text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
<div dir="rtl" style={{ textAlign: "right" }}>
# سوالات متداول
<hr />
## اوپن ام پی چست؟
اوپن ام پی یک مود جایگزین چند نفره برای سان اندریس در پاسخ به افزایش ناگوار مشکلات مربوط به بروزرسانی ها و مدیریت SA:MP است، نسخه اولیه فقط یک جایگزین برای سرور خواهد بود. کلاینت فعلی SA:MP میتواند به این سرور متصل شود. در آینده کلاینت جدید اوپن ام پی در دسترس قرار خواهد گرفت که اجازه میدهد آپدیت های جذاب بیشتری منتشر شود.
<hr />
## آیا این یک تقلید است؟
خیر، این یک بازنویسی کامل است با بهره گیری از دهه ها تجربه و دانش. قبلا تلاش هایی برای تقلید SA:MP بوده اما ما باور دارم آنها دو مشکل عمده داشتند :
1. آنها بر اساس سورس کد لو رفته SA:MP بودند. نویسندگان این مود ها هیچ حق قانونی روی این کد نداشتند و بدین ترتیب آنها همیشه عقب بودند، هم از نظر اخلاقی و هم از نظر قانونی
2. آنها سعی کردند یکباری چیز زیادی را بازآفرینی کنند. عوض کردن موتور تمام اسکریپت یا حذف کردن قابلیت در هنگام اضافه کردن قابلیت های جدید یا بهینه سازی کارها به روشهای ناسازگار. این از سرورهای موجود با کدهای بزرگ عظیم و از حرکت کردن بازیکنان جلوگیری می کند، همانطور که باید برخی را دوباره بنویسند. ما به طور کامل قصد داریم ویژگی ها را در طول زمان اضافه کرده و موارد را اصلاح کنیم اما ما روی پشتیبانی از سرور های فعلی تمرکز کرده ایم که به آنها اجازه دهیم از کد ما بدون تغییر در کد خودشان استفاده کنند.
<hr />
## چرا دارید این کار را میکنید؟
علی رغم تلاش های متعدد برای جلو بردن رسمی توسعه سمپ در قالب های پیشنهادات، جوانمردی و پیشنهادات کمک از طرف تیم بتا، در کنار یک اجتماع که برای هر چیز جدیدی گریه میکنند، هیچ پیشرفته دیده نشد در کل. اعتقاد عمومی بر این بود که این به خاطر عدم علاقه از طرف رهبر این مود است، چیزی که به خودی خود مشکل نیست اما هیچ چیز جانشینی وجود نداشت. بیانگذار به سادگی می خواست همه چیز را با خودش از بین ببرد. برخی ادعا می کنند که این امر به دلایل درآمد منفعل است اما هیچ مدرکی در مورد آن وجود ندارد. علی رغم علاقه زیاد او باور داشت که فقط 1-2 سال دیگر برای این مود مانده. و اینکه جامعه ای که برای ساخت سمپ بسیار سخت کار کرده است امروز شایسته ادامه نیست.
ما موافق نیستیم.
<hr />
## نظر شما درباره Kalcor/سمپ یا هرچیز چیست؟
ما عاشق سمپ هستیم، ما به همین دلیل است که اینجا هستیم در مرحله اول - و ما مدیون Kalcor هستیم برای ایجاد آن. او طی سالهای گذشته مبلغ بسیار زیادی را برای این مود هزینه کرده است و این مشارکت نباید فراموش شود یا نادیده گرفته شود.
<hr />
## آیا این اجتماع را جدا نمیکند؟
این قصد ما نیست. در حالت ایده آل به هیچ جداسازی نیازی نیست، اما مقداری جداسازی و نجات دادن آن قسمت بهتر از دیدن پژمرده شدن تمام آن است. تعهداد زیادی از مردم از انجمن رسمی سمپ بن شدند، اما Kalcor خودش اشاره کرده بود که انجمن های رسمی، سمپ نیستند، فقط قسمتی از سمپ هستند. تعداد زیادی از بازیکنان و سرور ها هیچوقت در آنجا مطلبی نذاشتند یا حتی وارد آن انجمن ها هم نشدند، پس صبحت با این مردم باعث متحد کردن دوباره قسمتی از اجتماع میشود.
<hr />
## آیا همانطور که اسم این مود _Open_ Multiplayer هست، متن باز خواهد بود؟
در نهایت این طرح هست، بله. برای الان ما داریم تلاش میکنیم که به صورت متن باز در مقررات ارتباطات و شفافیت(که به خودی خود یک پیشرفت است ) توسعه دهی، و ما هروقت که بتوانیم برای متن باز کردن اقدام خواهیم کرد، هنگامی که همه چیز مرتب و مستقر باشد.
<hr />
## چه زمانی منتشر میشود؟
این یک سوال قدیمی است، متاسفانه یک جواب قدیمی هم دارد: وقتی تمام شد. هیچ راهی وجود ندارد که فهمید چقدر یک پروژه مثل این طول میکشد.مدتی است که بی سر و صدا در حال اجرا است، قبلاً چند نوسان در سطح فعالیت دیده است، بستگی به میزان مشغله افراد دارد. اما مطمئن باشید که در راه است، و به لطف برخی تصمیمات اساسی در زمینه طراحی سریع پیشرفت می کند (ما بعدا درباره آن ها بیشتر خواهیم گفت).
<hr />
## من چطور میتوانم کمک کنم؟
به انجمن دقت داشته باشید. ما موضوع هایی دقیقا برای این داریم. در حالی که این پروژه کمی زودتر از آنچه در نظر گرفته شده فاش شد، ما در راه رسیدن به نسخه اولیه هستیم، اما آن به این معنی نیست که از کمک بیشتر همیشه قدردانی نمیشود. پیشاپیش از علاقه شما و باور داشتن به این پروژه متشکرم:
[موضوع "How to help"](https://forum.open.mp/showthread.php?tid=99)
<hr />
## burgershot.gg چیست؟
burgershot.gg یک انجمن گیمینگ است، دیگر هیچ. و بعضی از توسعه و آپدیت های اوپن ام پی در آنجا قرار میگیرد، اما آنها دو پروژه مستقل هستند، آنها فروم اوپن امم پی نیستند، و اوپن ام پی یک بخش از burgershot است. هنگامی که یک سایت برای اوپن ام پی کامل راه اندازی شد این دو میتوانند از یکدیگر جدا شوند (مثل انجمن سمپ که توسط GTAForums میزبانی میشد قبل از اینکه سایت خودش روشن شود).
<hr />
## OpenMP چطور؟
نام پروژه Open Multi-Proccessing، OpenMP است، ما open.mp هستیم. کاملا متفاوت است.
</div> | openmultiplayer/web/frontend/content/fa/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/fa/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 4746
} | 459 |
# Open Multiplayer
Open Multiplayer は _グランド・セフト・オート・サンアンドレアス_ のマルチプレイヤー MOD であり、今の _San Andreas Multiplayer_ というマルチプレイヤー MOD との互換性を持っています。
<br />
すなわち
**現在の SA:MP クライアントとすべてのサーバースクリプトは open.mp 上で使用されても問題なく動けます** 、しかもサーバー側の不具合は修正されます、もうプラグインやスクリプトからの修正は要らなくなります。
もしこのプロジェクトに興味があれば、いつリリースするのか、どうやって手伝えるのかなどの質問については <a href="https://forum.open.mp/showthread.php?tid=99">このトピック</a> から色々知るこ とができます。
# [よくある質問](/faq)
| openmultiplayer/web/frontend/content/ja/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/ja/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 364
} | 460 |
<h1>FAQ</h1>
<hr />
<h2>Что такое open.mp?</h2>
open.mp (Open Multiplayer, OMP) - мультиплеерный мод, разрабатываемый в качестве замены San Andreas
Multiplayer, созданный в ответ на проблемы с обновлениями и разработкой SA-MP. Изначальный релиз
обеспечит замену только для сервера. Игроки с клиентом SA-MP смогут подключаться к этому серверу. В
дальнейшем станет доступен новый клиент open.mp, что позволит выпускать больше интересных
обновлений.
<hr />
<h2>Это форк?</h2>
Нет, это полное переписывание с нуля, при котором учитываются знания и опыт, накопленные за
десятилетия. Попытки создать форк SA-MP имели место ранее, но мы убеждены, что у них у всех были две
основные проблемы:
<ol>
<li>
Они все были основаны на утекшем коде SA-MP. Авторы тех модов не имели законного права
использовать код SA-MP, и были в заведомо невыгодном положении, как с моральной, так и
с юридической точки зрения. Мы категорически отказываемся использовать этот код. Это слегка
затрудняет процесс разработки, но в долгосрочной перспективе это правильное решение.
</li>
<li>
Они пытались заново изобрести слишком много всего и сразу, добавляя новые скриптовые языки,
удаляя функционал и добавляя новый, или же просто изменяя что-либо несовместимым образом.
Это не позволяло серверам с крупными кодовыми базами и большим количеством игроков совершить
переход, т.к. для этого им требовалось переписать часть своего кода (если не весь код) - это
потенциально затратное дело. Мы собираемся со временем добавлять новый функционал и менять
существующий, но также сосредотачиваемся на поддержке существующих серверов, позволяя им
использовать наш код без нужды изменять свой.
</li>
</ol>
<hr />
<h2>С какой целью вы это делаете?</h2>
Несмотря на множественные попытки подтолкнуть вперёд развитие SA-MP официально (в виде советов,
просьб и предложений помочь со стороны команды бета-тестеров), а также просьб сообщества сделать
хоть что-то новое, не было абсолютно никакого прогресса в работе над модом. Было широко
распространено мнение, что причиной этому простое отсутствие интереса со стороны разработчиков мода,
что само по себе не проблема, однако не было никакого продвижения. Вместо того, чтобы передать
разработку мода заинтересованным в этом людям, основатель просто хотел уйти и утянуть всё за собой в
пропасть, при этом затягивая процесс как можно дольше для минимизации усилий. Также некоторые
утверждают, что причина этому - пассивный доход, но нет никаких доказательств этой версии. Несмотря
на большой интерес и крупное, слаженное сообщество, он был убеждён, что моду осталось всего 1-2
года, и что сообщество, вложившее много стараний, чтобы сделать SA-MP таким, какой он есть сейчас,
не заслуживает дальнейшего развития.
<br />
Мы не согласны.
<hr />
<h2>Каково ваше отношение к Kalcor'у/SA-MP/пр.?</h2>
Мы любим SA-MP и именно поэтому мы создали этот проект - и его созданием мы обязаны Kalcor'у. За
несколько лет он проделал большую работу над модом, и его вклад не следует забывать или
игнорировать. Однако, open.mp был создан потому, что мы не были согласны с несколькими из его
последних решений, и множественные попытки сменить вектор развития мода ни к чему не привели.
Поэтому для нас, к сожалению, оставалось только одно решение: попытаться создать проект, который
будет духовным наследником SA-MP, но без Kalcor'а. Наши действия не направлены против него лично,
и не должны восприниматься как попытка оскорбить или унизить его. Мы не собираемся терпеть
оскорбления против кого-либо, независимо от того, какое отношение они имеют к open.mp; мы считаем,
что обсуждения должны быть конструктивными и без переходов на личности.
<hr />
<h2>Разве то, что вы делаете, не разделяет сообщество?</h2>
Мы не добиваемся этого. В идеале никакого разделения не должно требоваться вообще, но лучше отделить
часть сообщества и спасти хотя бы её, чем просто наблюдать, как постепенно исчезает всё сообщество.
На самом деле с того момента, как этот мод был анонсирован, помимо участников англоязычного
сообщества к нам вернулись и представители многих неанглоязычных сообществ. В прошлом эти сообщества
постепенно вытеснялись и закрывались, поэтому тот факт, что они появились заново, на самом деле
возвращает прежний дух сообщества. Огромное количество людей были заблокированы на официальном
форуме SA-MP (в некоторых случаях с удалением всех их постов), но Kalcor сам некогда утверждал, что
официальный форум - это не SA-MP, это всего лишь часть SA-MP. Многие игроки и владельцы серверов
никогда на нём ничего не публиковали, не говоря уже о регистрации, поэтому общение с этими людьми
позволяет объединить ещё большее число участников сообщества.
<hr />
<h2>
Если это "Open" Multiplayer (пер.: "Открытый Мультиплеер"), это будет проект с открытым
исходным кодом?
</h2>
Да, в скором времени, таков наш план. Пока же мы стараемся обеспечить открытость в плане обратной
связи и прозрачности процесса разработки (что само по себе уже прогресс) и перейти к открытию
исходного кода, когда это будет возможно, как только будут решены другие значительные проблемы и
удастся добиться стабильного процесса разработки.
<hr />
<h2>Когда он будет выпущен?</h2>
Это извечный вопрос и, к сожалению, у нас такой же извечный ответ: когда он будет готов. Суть в том,
что попросту невозможно оценить, сколько займёт работа над подобного рода проектом. Разработка уже
велась втайне некоторое время с переменным уровнем активности, в зависимости от того, сколько у
людей было свободного времени. Но не беспокойтесь, работа идёт, причём идёт быстро, благодаря
фундаментальным архитектурным решениям (позже мы расскажем об архитектуре подробнее).
<hr />
<h2>Как я могу помочь?</h2>
Следите за форумом. У нас есть тема специально для этих целей и мы будем обновлять её, как только
появится больше работы. Несмотря на то, что о проекте стало известно немного раньше, чем
планировалось, мы уже на пути к первому релизу, но это не значит, что помощь не приветствуется.
Заранее спасибо за то, что интересуетесь и верите в успех проекта:
<br />
<a href="https://forum.open.mp/showthread.php?tid=361">
<u>Тема о том, как можно помочь</u>
</a>
<hr />
<h2>Что такое burgershot.gg?</h2>
burgershot.gg - это игровой форум, и ничего более. Многие люди связаны и с OMP, и с этим сайтом, а
также некоторый прогресс в разработке OMP публикуется там, но это два независимых друг от друга
проекта. У OMP нет своего форума, но OMP не является собственностью burgershot. Как только сайт OMP
будет введён в строй, мод и burgershot можно будет отделить друг от друга (примерно так же, как
разработка SA-MP когда-то базировалась на GTAForums, пока у мода не появился собственный сайт).
<hr />
<h2>Почему не "OpenMP"?</h2>
<a href="https://ru.wikipedia.org/wiki/OpenMP">Open Multiprocessing</a> - это "OpenMP", наш проект -
"open.mp". Это две совершенно разные вещи.
| openmultiplayer/web/frontend/content/ru/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/ru/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 6968
} | 461 |
# SSS
<hr />
## open.mp Nedir?
open.mp (Open Multiplayer, OMP) - SA:MP güncellemeleri ve geliştirilmesi ile ilgili sorunlara yanıt olarak oluşturulan San Andreas Multiplayer için yedek olarak geliştirilen çok oyunculu mod. İlk sürüm yalnızca sunucu için bir yedek sağlayacaktır. Sa:MP istemcisi olan oyuncular bu sunucuya bağlanabilir. open.mp, olarak daha ilginç güncellemeleri yayınlayacağız.
<hr />
## Bu bir kopya mı?
Hayır, bu proje yıllar boyunca biriken bilgi ve tecrübeyi dikkate alarak sıfırdan oluşturulmuştur. SA:MP kopyalama girişimleri daha önce gerçekleşti, ancak hepsinin iki ana problemi olduğuna inanıyoruz:
Hepsi SA:MP kaçak koduna dayanıyordu. Bu modların yazarları SA:MP kodunu kullanma hakkı yoktu ve hem ahlaki hem de hukuki açıdan açıkça savunmasızdı. Kesinlikle bu kodu kullanmayı reddediyoruz. Bu, geliştirme sürecini biraz zorlaştırıyor, ancak uzun vadede doğru karar verdiğimize inanıyoruz. Aynı anda çok fazla şeyi yeniden icat etmeye çalıştılar. Komut dosyası motorunu değiştirmeye, mevcut özellikleri silmeye ve yenilerini eklemeye ya da uyumsuz bir şekilde işleri optimize etmeye çalıştılar. Çünkü hepsi değilse de, bazı komut dosyalarınızı yeniden yazmanız gerekir. Ayrıca yeni özellikler eklemek ve değiştirmek istiyoruz, ancak sunucu sahiplerinin kendi kodlarını değiştirmek zorunda kalmadan kodumuzu kullanmalarına izin vermek için çalışıyoruz.
<hr />
## Bu işi neden yapıyorsunuz?
Her ne kadar topluluk üzerinden öneri sunarak, eleştirerek ve yardım sunarak resmi SA:MP gelişimini tekrar tekrar canlandırmaya çalışmış olsak da, hiçbir gelişme olmamıştır. Bu muhtemelen SA:MP geliştiricisinin ilgisizliğinden kaynaklanıyor. Kendinde, bu ilgi eksikliğinin farkında olmadı ve ne yazık ki hedefi olmadı ve bu nedenle daha fazla geliştirme olmadı. Kurucu, SA:MP geliştirmekyerine, her şeyi mezara götürmeye ve en az çabayla mümkün olduğunca uzun süre hayatta kalmaya karar verdi. Bazıları bunun sebebini gelir sebeplerinden dolayı olduğunu söylüyor, ancak herhangi bir kanıt yok. Güçlü ve aile temelli topluluğun yoğun ilgisine rağmen, kurucu, modifikasyonun sadece 1 veya 2 yıl daha devam edeceğine ve SA:MP’yi yapmak için çok çalışmış olduğu halde topluluğun gerekli değeri vermediğine inandı.
<br />
Biz katılmıyoruz
<hr />
## Kalcor / SAMP hakkında ne düşünüyorsunuz?
Sa:MP'yi seviyoruz, bu yüzden buradayız ve bunu Kalcor'a borçluyuz. Değişiklikler için yıllar boyunca çalıştı ve bu katkılar göz ardı edilmemeli veya unutulmamalıdır. Open.mp yol açma sebebimiz, son birkaç karara itiraz ettiğimiz için yapıldı.Bu yüzden, SA: MP'yi Kalcor'suz ruhu ile sürdürmeye çalışmak için talihsiz bir karar vermeye zorlandık.Bu bizzat kendisine karşı yapılan bir eylem değildir ve buna karşı bir saldırı olarak görülmemelidir. Kişilere karşı yapılan hakaretlere kim olduklarına bakılmaksızın tahammül etmeyeceğiz. open.mp; hakkında kişilere saldırı - hakaret etmeden makul bir tartışma yapabiliriz.
<hr />
## Bu toplumu bölmek değil midir?
Böyle bir niyetimiz yok. Ancak amaçımız bir kitleyi bölmek değil, her şeyin kaybolduğunu - silindiğini izlemek yerine bunu kurtarmak daha iyidir. SA:MP resmi forumundan çok sayıda insan yasaklandı (ve bazı durumlarda tüm emeklerini kaldırdılar), ancak Kalcor, resmi forumun SA:MP topluluğu değil, yalnızca bir kişi olduğunu belirtti.Birçok oyuncu ve sunucu sahibi foruma hiç katılmamış; bu yüzden bu insanlarla konuşmak toplumu daha da birleştirecek.
<hr />
## Bu "Open" Multiplayer olduğu için, bu proje açık kaynak kodlu olacak mı?
Evet, planımız bu. Bu arada, geliştirme sürecinin geri bildirimi ve şeffaflığı (kendi içinde ilerleyen) açısından açıklık sağlamaya çalışıyoruz ve mümkün olduğu zaman, diğer önemli sorunların çözüldüğünde ve istikrarlı bir gelişme süreci elde edilir edilmez açık kaynak koduna paylaşmaya çalışacağız.
<hr />
## Open.mp ne zaman çıkacak?
Bu eski bir sorudur ve ne yazık ki bunun için şu cevaba sahibiz; hazır olduğunda. Böyle bir projenin ne kadar süreceğini bilmek mümkün değil.
<hr />
## Nasıl yardımcı olabilirim?
Foruma bir göz atın. Sadece bunun için bir konumuz var ve daha fazla yardım ihtiyaçı mevcut olduğunda bu konuyu güncel tutacağız. Projenin planlanandan biraz daha erken bir şekilde ortaya çıkmasına rağmen, şimdiden ilk lansmana gidiyoruz, ancak bu daha fazla yardımın ihtiyaçımız olmadığı anlamına gelmiyor. Projeye ilgi duyduğunuz ve inandığınız için şimdiden teşekkür ederiz:
<br />
[Yardım Konusu](https://forum.open.mp/showthread.php?tid=99)
<hr />
## burgershot.gg nedir?
Burgershot.gg bir oyun forumudur, başka bir şey değildir. Birçok insan dahil olmuştur ve OMP'nin bazı güncellemeleri ve gelişmeleri orada yayınlanmaktadır, ancak bunlar iki bağımsız projedir.
<hr />
## "OpenMP" hakkında nedir?
[Open Multiprocessing](https://tr.wikipedia.org/wiki/OpenMP) - olarak bilinen "OpenMP", farklı projedir, bizim projemiz - "open.mp". olarak isimlendirilir. Bunlar ikisi tamamen farklı projelerdir.
| openmultiplayer/web/frontend/content/tr/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/tr/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 2428
} | 462 |
# Open Multiplayer
Một bản mod online cho _Grand Theft Auto: San Andreas_ sẽ hoàn toàn được tích hợp với chế độ chơi online hiện nay _San Andreas Multiplayer (SA-MP)._
<br />
Điều này có nghĩa là **hệ thống SA:MP cho máy khách và kịch bản (scripting) SA:MP sẽ hoạt động tương thích với open.mp** . Đồng thời, nhiều lỗi còn tồn đọng sẽ được sửa chửa mà không cần đến sự can thiệp của hacks và các bản vá không chính thống nữa.
Nếu bạn đang thắc mắc làm thế nào để có thể đóng góp vào dự án khi được phát hành công khai (public release), vui lòng truy cập <a href="https://forum.open.mp/showthread.php?tid=99">chuyên mục này</a> để biết thêm thông tin chi tiết.
# [FAQ (Câu hỏi thường gặp)](/faq)
| openmultiplayer/web/frontend/content/vi/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/vi/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 505
} | 463 |
import { useRouter } from "next/router";
import { NextPage } from "next";
import { useAuth } from "./hooks";
import LoadingBanner from "src/components/LoadingBanner";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export default function withAuthRedirect<CP = unknown, IP = CP>(
WrappedComponent: NextPage<CP, IP>,
expectedAuth: boolean,
location: string,
LoadingComponent = LoadingBanner
): NextPage<CP, IP> {
const WithAuthRedirectWrapper: NextPage<CP, IP> = (props) => {
const router = useRouter();
const { isLoading, isAuthenticated } = useAuth();
if (isLoading) {
return <LoadingComponent />;
}
if (isBrowser() && expectedAuth !== isAuthenticated) {
router.push(location);
return <></>;
}
return <WrappedComponent {...props} />;
};
return WithAuthRedirectWrapper;
}
| openmultiplayer/web/frontend/src/auth/withAuthRedirect.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/auth/withAuthRedirect.tsx",
"repo_id": "openmultiplayer",
"token_count": 294
} | 464 |
import React from "react";
const Issue = ({ fill = "white", display = "inline" }) => (
<svg
className="octicon octicon-issue-opened"
viewBox="0 0 14 16"
version="1.1"
width="14"
height="16"
aria-hidden="true"
focusable="false"
role="img"
xmlns="http://www.w3.org/2000/svg"
fill={fill}
display={display}
>
<path
fillRule="evenodd"
d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"
/>
</svg>
);
export default Issue;
| openmultiplayer/web/frontend/src/components/icons/Issue.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/icons/Issue.tsx",
"repo_id": "openmultiplayer",
"token_count": 336
} | 465 |
import { Box } from "@chakra-ui/layout";
import Image from "next/image";
import Link from "next/link";
import { FC } from "react";
import NavMenu, { NavItem } from "./NavMenu";
type Props = {
items: NavItem[];
route: string;
};
const Logo = () => (
<Box p="1">
<Link href="/">
<a>
<Image
src="https://assets.open.mp/assets/images/assets/logo-dark-trans.png"
alt="The open.mp logo"
width={50}
height={50}
unoptimized={true}
/>
</a>
</Link>
</Box>
);
const Nav: FC<Props> = ({ items, route }) => {
return (
<>
<Box
role="main"
as="nav"
minH="4em"
display="flex"
flexDirection="row"
justifyContent="space-between"
alignItems="center"
px={2}
>
<Logo />
<NavMenu items={items} route={route} />
</Box>
</>
);
};
export default Nav;
| openmultiplayer/web/frontend/src/components/site/Nav.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/site/Nav.tsx",
"repo_id": "openmultiplayer",
"token_count": 458
} | 466 |
import Admonition from "../../../Admonition";
export default function TipNpcCallback() {
return (
<Admonition type="tip">
<p>Esta callback também pode ser chamada por um NPC.</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/pt-BR/npc-callbacks-tip.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/pt-BR/npc-callbacks-tip.tsx",
"repo_id": "openmultiplayer",
"token_count": 83
} | 467 |
import { visit } from "unist-util-visit";
// Remark plugin for colours.
// Usage:
//
// {text}(#hexcode)
//
// This is {yellow}(#ffff00) text!
//
const colourPattern = /{(.+?)}\(#([a-f0-9]{6})\)/gm;
export const remarkColour = function attacher() {
return (tree: any) => {
visit(tree, "paragraph", (node) => {
const children: Array<any> = node.children as Array<any>;
const newChildren: Array<any> = node.children as Array<any>;
children.forEach((v: { value: string }, i: number) => {
let match: RegExpExecArray | null;
let insertions = 0;
let lastIndex = 0;
do {
match = colourPattern.exec(v.value);
if (match?.length !== 3) {
continue;
}
newChildren.splice(
i + insertions,
0,
{
type: "text",
value: v.value.slice(lastIndex, match.index),
},
{
type: "jsx",
value: `<span style={{color: "#${match[2]}"}}>`,
},
{
type: "text",
value: match[1],
},
{
type: "jsx",
value: `</span>`,
}
);
insertions += 4;
lastIndex = match.index + match[0].length;
} while (match);
if (insertions > 0) {
// remove the original text node and insert the remaining text
newChildren.splice(i + insertions, 1, {
type: "text",
value: v.value.slice(lastIndex, v.value.length),
});
}
});
node.children = newChildren;
});
};
};
| openmultiplayer/web/frontend/src/mdx-helpers/remark-colour.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/mdx-helpers/remark-colour.ts",
"repo_id": "openmultiplayer",
"token_count": 873
} | 468 |
//Icons
import { ArrowDownIcon, ChevronRightIcon } from "@chakra-ui/icons";
//Chakra Imports
import {
Box,
Button,
Center,
Flex,
Heading,
HStack,
Link,
Text,
useColorMode,
useColorModeValue,
VStack
} from "@chakra-ui/react";
import { GetStaticPropsContext } from "next";
import Head from "next/head";
import Image from "next/image";
import NextLink from "next/link";
import Announcement from "src/components/site/Announcement";
// Server side
import { markdownSSR } from "src/mdx-helpers/ssr";
import { MarkdownContent } from "src/mdx-helpers/types";
//Components
import Card from "../components/site/Card";
//Styles
import React from "react";
import Roads from "src/components/icons/Roads";
import heroStyles from "../styles/Hero.module.css";
const DownloadButton = (props: { link: string; title: string; tooltip: string}) => {
return (
<Link href={props.link} _hover={{ textDecoration: "none" }} isExternal>
<Button
bg="#9083D2"
color="white"
rightIcon={<ArrowDownIcon />}
_hover={{
bgColor: "#7466D4",
}}
_active={{
bgColor: "#5A4CBB",
}}
_focus={{
outline: "2px solid #695AD3",
transition: "outline 0.3s",
}}
title={props.tooltip}
>
{props.title}
</Button>
</Link>
);
};
const DocumentationButton = () => {
return (
<NextLink href="/docs" passHref>
<Link _hover={{ textDecoration: "none" }}>
<Button
rightIcon={<ChevronRightIcon />}
border="1px solid #9083D2"
bg="transparent"
color="#9083D2F2"
_hover={{
backgroundColor: "#9083D240",
}}
_active={{
backgroundColor: "#9083D240",
}}
_focus={{
outline: "2px solid #695AD3",
transition: "outline 0.3s",
}}
>
Documentation
</Button>
</Link>
</NextLink>
);
};
const Home = () => {
const { colorMode } = useColorMode();
const features = [
{
heading: "Fully backwards compatible with existing scripts and clients",
bodyText:
"Got an old AMX lying about? Load it up on the open.mp server straight out of the box and join your friends playing on the SA:MP client. Then when you want to enhance your code try our...",
buttonLink: "/docs",
buttonText: "Getting Started",
img: "/images/assets/f1.png",
imgAlt: "open.mp logo",
},
{
heading: "New and improved scripting system",
bodyText:
"We've stuck with pawn, but with a new compiler engineered to make your code more robust, and more functions to manipulate the server and client. If that's still not enough there's an...",
buttonLink:
"https://github.com/openmultiplayer/omp-stdlib/#openmp-includes",
buttonText: "Learn about the improvements",
img: "/images/assets/f5.png",
imgAlt: "pawn logo",
},
{
heading: "Extensible C++ API",
bodyText:
"Get access to all the server features available in pawn, plus the universe of C++ libraries and frameworks. Once you've mastered this why not help improve the server via our...",
buttonLink: "/docs",
buttonText: "Getting Started",
img: "/images/assets/f4.png",
imgAlt: "C++ logo",
},
{
heading: "Community driven development",
bodyText:
"The server is fully open source, and we welcome all contributions big or small. Help write the next version, or just post about any problems you find; despite our attempts to have...",
buttonLink: "https://github.com/openmultiplayer/open.mp",
buttonText: "Visit the GitHub repo",
img: "/images/assets/f2.png",
imgAlt: "Github stats illustration",
},
{
heading: "Age old SAMP bugs fixed",
bodyText:
"Many SA:MP bugs, well known and obscure, have been fixed. No more hacky work-arounds; no more community bug-fix projects; you have all the proper tools in your hands now.",
buttonLink: "/blog",
buttonText: "Read the blog post",
img: "/images/assets/f3.png",
imgAlt: "pawn code screen",
},
];
const socials = [
{
alt: "discord icon",
src: "/images/assets/discord-icon.svg",
href: "https://discord.com/invite/samp",
size: 45,
},
{
alt: "facebook icon",
src: "/images/assets/facebook.svg",
href: "https://www.facebook.com/openmultiplayer",
size: 33,
},
{
alt: "instagram icon",
src: "/images/assets/instagram.svg",
href: "https://instagram.com/openmultiplayer/",
size: 33,
},
{
alt: "twitch icon",
src: "/images/assets/twitch.svg",
href: "https://twitch.tv/openmultiplayer",
size: 29,
},
{
alt: "x icon",
src: "/images/assets/x.svg",
href: "https://x.com/openmultiplayer",
size: 29,
background: false,
},
{
alt: "youtube icon",
src: "/images/assets/youtube.svg",
href: "https://youtube.com/openmultiplayer",
size: 35,
},
];
return (
<Box fontFamily="Manrope, sans-serif">
<Head>
<title>open.mp | Open Multiplayer</title>
</Head>
<main>
<Box className={heroStyles.hero} py="2em" px="1em">
<Announcement />
{/* <Box
className={cardStyles.announcement}
align="center"
maxW="50em"
margin="auto"
>
Open.mp is under beta testing now, Read this{" "}
<strong>
<span style={{ color: "#5944EC" }}>
<Link>blog post</Link>
</span>
</strong>{" "}
to learn how to help us with testing.
</Box> */}
<Flex
align="center"
justifyContent={{ base: "center", md: "space-between" }}
margin="0 auto"
py="2em"
px={{ base: "0em", md: "2em" }}
maxW={"80em"}
gridGap="2em"
>
<VStack
maxW={{ base: "100%", md: "50em" }}
mt={{ base: "3em", md: "none" }}
align={{ base: "center", md: "start" }}
>
<Text
fontSize="xl"
fontWeight="500"
textAlign={{ base: "center", md: "left" }}
maxW="30em"
>
A multiplayer mod for Grand Theft Auto: San Andreas that is{" "}
<span style={{ fontWeight: 800 }}>
fully backwards compatible
</span>{" "}
with{" "}
<span style={{ fontWeight: 800 }}>San Andreas Multiplayer</span>
.
</Text>
<HStack spacing="1em" my="1.2em" align="top">
<Flex flexWrap="wrap" justifyContent="center" gridGap="1em">
<DownloadButton
title={"Download open.mp (server)"}
tooltip="open.mp is released!"
link={"https://github.com/openmultiplayer/open.mp/releases"}
/>
<DownloadButton
title={"Download open.mp launcher"}
tooltip="Download open.mp launcher"
link={"https://github.com/openmultiplayer/launcher/releases/latest"}
/>
<DocumentationButton />
</Flex>
</HStack>
</VStack>
<Box display={{ base: "none", md: "block" }} py="2em">
<Roads width="400" height="400" dark={colorMode === "dark"} />
</Box>
</Flex>
<Center>
<HStack
gridGap="0.5em"
color="#7466D4"
mt={{ base: "3em", md: "0" }}
style={{ justifyContent: "space-around" }}
>
{socials.map((social, index) => {
const iconSize = `${social.size}px`;
const style: React.CSSProperties = {
display: "flex",
justifyContent: "center",
...(social.background && {
backgroundColor: "#7466d4",
width: `${social.size + 12}px`,
height: `${social.size + 12}px`,
borderRadius: 5,
}),
};
return (
<Box
boxSize={10}
alignItems="center"
justifyContent={"center"}
display="flex"
>
<a
key={index}
href={social.href}
style={style}
target="__blank"
>
<Image
src={social.src}
alt={social.alt}
width={iconSize}
height={iconSize}
/>
</a>
</Box>
);
})}
</HStack>
</Center>
</Box>
<Box align="center" my="4em">
<Text color={useColorModeValue("#281685", "white")} fontSize="md">
Updates & Features
</Text>
<Text fontSize="3xl" fontWeight="900" mt="0">
What is improved and new?
</Text>
<VStack spacing="6em" my="3em" px="1em">
{features.map((feature, index) => (
<Card key={index} {...feature} />
))}
<Box maxW="60em">
<Heading>Ready to get started?</Heading>
<HStack spacing="1em" my="1.2em" align="top">
<Flex flexWrap="wrap" justifyContent="center" gridGap="1em">
<DownloadButton
title={"Download open.mp (server)"}
tooltip="open.mp is released!"
link={
"https://github.com/openmultiplayer/open.mp/releases"
}
/>
<DownloadButton
title={"Download open.mp launcher"}
tooltip="Download open.mp launcher"
link={
"https://github.com/openmultiplayer/launcher/releases/latest"
}
/>
<DocumentationButton />
</Flex>
</HStack>
</Box>
</VStack>
</Box>
</main>
</Box>
);
};
type Props = {
content: MarkdownContent;
};
const Page = ({ content }: Props) => (
<>
<Home />
</>
// <section className="pa0 ma0 center">
// <div className="mw8 center">
// <Image
// src="https://assets.open.mp/assets/images/assets/wordmark-light-mono.png"
// alt="The open.mp wordmark"
// width={1660}
// height={560}
// unoptimized={true}
// />
// </div>
// <article className="pa0 ma0">
// <div className="center measure pa4">{markdownCSR(content)}</div>
// </article>
// </section>
);
export const getStaticProps = async ({ locale }: GetStaticPropsContext) => ({
props: { content: await markdownSSR(locale || "en", "index") },
});
export default Page;
| openmultiplayer/web/frontend/src/pages/index.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/index.tsx",
"repo_id": "openmultiplayer",
"token_count": 5829
} | 469 |
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
| openmultiplayer/web/frontend/src/styles/globals.css/0 | {
"file_path": "openmultiplayer/web/frontend/src/styles/globals.css",
"repo_id": "openmultiplayer",
"token_count": 113
} | 470 |
import { useToast } from "@chakra-ui/toast";
import { APIError, APIErrorSchema } from "src/types/_generated_Error";
type HandleErrorFn = (e: unknown) => void;
const generic = "Unexpected error occurred";
export const useErrorHandler = (): HandleErrorFn => {
const toast = useToast();
const extractError = (e: unknown): APIError => {
const apiError = APIErrorSchema.safeParse(e);
if (apiError.success) {
return apiError.data;
}
if (e instanceof Error) {
return {
message: e.message,
error: e.name,
};
}
return {
message: generic,
};
};
const formatDescription = (e: APIError) => {
if (e.error && e.suggested) {
return `${e.suggested} (Error: ${e.error})`;
} else if (e.error) {
return `Error: ${e.error}`;
} else {
return generic;
}
};
const handleError = (e: unknown) => {
const err = extractError(e);
console.warn(err);
toast({
title: err.message,
description: formatDescription(err),
status: "error",
});
};
return handleError;
};
| openmultiplayer/web/frontend/src/utils/useErrorHandler.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/utils/useErrorHandler.ts",
"repo_id": "openmultiplayer",
"token_count": 438
} | 471 |
package seed
var Addresses = []string{
"101.100.143.138:28000",
"101.50.3.149:7777",
"101.50.3.61:7780",
"103.126.226.101:7777",
"103.195.100.59:7046",
"103.212.180.191:7776",
"103.212.180.191:7779",
"103.212.180.242:7777",
"103.27.203.107:3333",
"103.27.207.43:7777",
"103.62.48.149:7777",
"103.70.5.242:2000",
"103.91.205.141:7777",
"103.91.205.169:7777",
"103.91.206.144:7777",
"104.153.108.223:7777",
"104.168.141.28:7777",
"104.198.195.231:7778",
"104.215.118.194:7575",
"104.238.100.205:7026",
"104.248.4.140:7777",
"104.249.62.39:7777",
"104.40.224.213:7777",
"104.44.141.32:27315",
"105.101.83.27:7777",
"105.157.178.168:7777",
"106.160.3.200:7777",
"107.174.217.231:5555",
"107.174.217.231:8888",
"108.244.7.145:7777",
"108.61.168.254:7777",
"108.61.171.152:7777",
"109.165.216.192:7777",
"109.189.11.228:7777",
"109.195.87.124:7777",
"109.235.70.248:7777",
"109.254.19.113:7797",
"112.213.2.20:7777",
"114.72.10.190:7778",
"114.72.12.43:7778",
"114.72.36.29:7778",
"114.72.43.100:7778",
"114.72.44.126:7778",
"114.72.51.180:7778",
"114.72.93.182:7778",
"114.74.185.38:7777",
"116.202.140.147:7727",
"116.203.228.23:7777",
"116.203.36.6:7777",
"116.203.36.6:8888",
"116.203.37.18:7777",
"116.203.37.99:7777",
"116.203.39.41:7777",
"122.105.15.62:7778",
"122.105.225.225:7778",
"123.194.115.164:7777",
"13.76.161.131:7777",
"13.78.146.69:7777",
"13.82.174.211:7777",
"13.93.75.223:7777",
"130.211.60.233:7777",
"131.153.30.164:7777",
"131.196.199.230:7777",
"131.196.199.234:7777",
"131.221.35.50:7777",
"134.209.105.3:7777",
"134.255.220.169:7790",
"134.255.233.28:7790",
"136.243.39.248:7778",
"136.243.4.208:1201",
"136.243.4.208:1297",
"136.243.4.208:1337",
"136.243.4.208:1470",
"136.243.4.208:2525",
"136.243.4.208:7771",
"136.243.4.208:7777",
"136.243.4.208:8686",
"136.243.4.208:8895",
"136.243.4.208:8901",
"136.243.61.181:7777",
"136.243.89.49:7777",
"137.74.128.233:7777",
"137.74.148.228:7777",
"137.74.148.231:7777",
"137.74.148.239:7777",
"137.74.173.19:7777",
"137.74.179.193:7777",
"137.74.233.214:7777",
"137.74.4.167:5000",
"137.74.4.167:5001",
"137.74.4.167:5555",
"137.74.4.167:8806",
"137.74.4.44:7777",
"137.74.4.4:7777",
"137.74.6.199:4000",
"137.74.6.200:4008",
"137.74.60.209:7777",
"137.74.60.210:7777",
"138.118.173.137:7778",
"138.118.173.168:7777",
"138.118.173.240:7752",
"138.118.173.240:7753",
"138.118.174.48:7753",
"138.197.173.26:7777",
"138.201.111.58:7777",
"138.201.111.62:7777",
"138.201.30.108:7777",
"138.201.76.8:7776",
"138.68.138.56:7777",
"139.162.203.222:7777",
"139.162.233.137:7777",
"139.180.147.146:7777",
"139.180.186.156:7777",
"139.180.187.141:7777",
"139.180.190.89:7777",
"139.59.175.67:7777",
"139.99.125.54:7777",
"139.99.66.188:7792",
"139.99.89.111:1945",
"139.99.89.111:5555",
"139.99.89.111:7077",
"139.99.89.111:7777",
"14.1.30.52:7777",
"140.82.58.103:7777",
"141.136.47.116:7777",
"142.4.197.81:7777",
"142.4.197.82:7777",
"142.4.197.83:7777",
"142.4.203.26:7777",
"142.4.204.48:7780",
"142.4.206.115:8888",
"142.4.209.23:7777",
"142.4.209.23:7778",
"142.4.222.156:7777",
"142.4.223.194:7777",
"142.44.134.0:5555",
"142.44.134.0:8888",
"142.44.146.68:7777",
"142.44.149.163:7777",
"142.44.161.46:7777",
"142.44.162.82:7777",
"142.44.169.91:7777",
"142.44.170.47:7777",
"142.44.174.191:7777",
"142.44.189.82:7777",
"142.44.189.83:8001",
"142.44.189.87:7777",
"142.44.198.251:7777",
"142.44.198.251:8000",
"142.44.199.30:7777",
"142.44.199.30:7780",
"142.44.210.192:9999",
"142.44.218.199:7778",
"142.44.223.233:7777",
"142.44.223.79:7780",
"142.44.227.185:2036",
"142.44.227.185:7117",
"142.44.227.185:7777",
"142.44.227.185:7779",
"142.44.227.185:7878",
"142.44.227.185:8383",
"142.44.236.189:7777",
"142.44.236.191:7777",
"142.44.236.191:8000",
"142.44.240.130:7777",
"142.44.247.112:7777",
"142.44.247.112:8686",
"142.44.251.43:5555",
"142.44.251.43:8888",
"142.44.253.11:7753",
"142.44.253.11:7777",
"142.44.253.11:7797",
"142.44.253.18:7777",
"142.44.255.127:7777",
"142.93.13.204:7777",
"142.93.145.160:6666",
"142.93.150.170:8000",
"144.217.0.32:7777",
"144.217.0.32:7780",
"144.217.0.33:7777",
"144.217.0.35:7777",
"144.217.11.184:7778",
"144.217.112.12:5565",
"144.217.112.12:7790",
"144.217.112.12:7820",
"144.217.112.12:7830",
"144.217.112.12:7860",
"144.217.112.13:5585",
"144.217.112.14:7780",
"144.217.112.15:7780",
"144.217.112.15:7790",
"144.217.115.131:2000",
"144.217.115.131:3344",
"144.217.115.131:4444",
"144.217.115.131:5800",
"144.217.115.131:5900",
"144.217.115.131:6000",
"144.217.115.131:7300",
"144.217.115.131:7788",
"144.217.115.131:8700",
"144.217.115.131:8888",
"144.217.116.54:7777",
"144.217.12.169:7777",
"144.217.120.178:7777",
"144.217.13.190:27115",
"144.217.13.190:7770",
"144.217.148.20:7777",
"144.217.148.70:7777",
"144.217.158.86:7777",
"144.217.159.216:9355",
"144.217.159.217:7777",
"144.217.159.217:8888",
"144.217.159.218:7777",
"144.217.159.219:7777",
"144.217.161.32:7777",
"144.217.163.203:27515",
"144.217.163.203:7777",
"144.217.163.214:7777",
"144.217.171.5:7777",
"144.217.171.88:7777",
"144.217.171.89:8888",
"144.217.171.90:7777",
"144.217.171.91:7777",
"144.217.174.212:7777",
"144.217.174.213:2222",
"144.217.174.213:7777",
"144.217.174.213:7846",
"144.217.174.214:7021",
"144.217.174.214:7777",
"144.217.174.215:7651",
"144.217.174.215:7766",
"144.217.174.215:8001",
"144.217.178.56:7777",
"144.217.19.104:7776",
"144.217.19.104:7777",
"144.217.19.104:8888",
"144.217.19.105:5000",
"144.217.19.105:7117",
"144.217.19.105:7171",
"144.217.19.106:7770",
"144.217.19.106:7777",
"144.217.19.106:8888",
"144.217.19.107:4747",
"144.217.19.107:7777",
"144.217.19.107:7778",
"144.217.19.108:2020",
"144.217.19.108:6666",
"144.217.19.108:7777",
"144.217.19.108:7778",
"144.217.19.108:9999",
"144.217.19.109:7742",
"144.217.19.109:7777",
"144.217.19.109:8888",
"144.217.19.110:7766",
"144.217.19.110:7777",
"144.217.19.111:7777",
"144.217.19.111:7778",
"144.217.19.111:8888",
"144.217.190.194:7777",
"144.217.195.235:7777",
"144.217.201.28:7777",
"144.217.201.31:7777",
"144.217.206.4:7777",
"144.217.206.4:8000",
"144.217.217.212:7777",
"144.217.241.148:7777",
"144.217.248.194:7777",
"144.217.28.1:7777",
"144.217.29.21:7777",
"144.217.39.180:7777",
"144.217.40.119:2020",
"144.217.40.119:7777",
"144.217.51.253:7777",
"144.217.55.148:7777",
"144.217.58.128:7777",
"144.217.61.146:7777",
"144.217.62.158:2009",
"144.217.62.158:7777",
"144.217.62.159:7777",
"144.217.87.177:7777",
"144.217.92.54:8888",
"144.217.93.227:8888",
"144.217.95.117:8985",
"144.76.57.37:7777",
"144.76.68.79:10815",
"144.76.68.79:10835",
"144.76.68.79:13395",
"144.76.68.79:13615",
"144.76.68.79:13665",
"144.76.68.79:14185",
"144.76.68.79:14425",
"144.76.68.79:14705",
"144.76.68.79:15195",
"144.76.68.79:15365",
"144.76.68.79:7778",
"144.76.68.79:8575",
"144.76.68.79:9415",
"144.76.68.79:9775",
"144.76.69.104:7777",
"144.91.81.168:7777",
"145.14.134.124:7777",
"145.14.158.122:7777",
"145.239.136.61:7777",
"145.239.149.109:7777",
"145.239.149.25:7777",
"145.239.149.25:7852",
"145.239.149.25:7892",
"145.239.149.25:7902",
"145.239.149.3:7777",
"145.239.150.32:7802",
"145.239.150.32:7852",
"145.239.16.20:7777",
"145.239.172.232:7777",
"145.239.172.232:7817",
"145.239.172.233:7777",
"145.239.172.233:7787",
"145.239.172.234:7777",
"145.239.172.234:7797",
"145.239.172.234:7817",
"145.239.172.235:7777",
"145.239.172.235:7787",
"145.239.172.235:7797",
"145.239.183.130:7777",
"145.239.204.23:7817",
"145.239.204.23:7872",
"145.239.234.157:7777",
"145.239.235.184:7777",
"145.239.235.185:7777",
"145.239.235.187:7777",
"145.239.235.42:7777",
"145.239.3.225:7777",
"145.239.42.32:7777",
"147.135.118.159:7777",
"147.135.120.133:7777",
"147.135.127.113:7777",
"147.135.158.103:7777",
"147.135.158.113:7778",
"147.135.178.209:7800",
"147.135.199.44:7777",
"147.135.22.83:7787",
"147.135.248.251:7777",
"147.135.253.138:7777",
"147.135.27.141:7777",
"147.135.27.142:7777",
"147.135.3.14:7777",
"147.135.30.152:7778",
"147.135.30.88:7905",
"147.135.31.31:7842",
"147.135.44.55:7822",
"147.135.6.129:7872",
"147.135.6.129:7882",
"147.135.6.129:7912",
"147.135.6.129:7922",
"147.135.91.191:7777",
"147.135.99.134:1111",
"148.251.151.134:1237",
"148.251.229.224:1773",
"148.251.35.156:7797",
"149.202.115.144:7778",
"149.202.115.144:7790",
"149.202.115.144:7805",
"149.202.115.145:8476",
"149.202.198.161:7777",
"149.202.223.177:7777",
"149.202.223.59:7817",
"149.202.223.59:7847",
"149.202.223.59:7857",
"149.202.223.88:7777",
"149.202.225.137:7777",
"149.202.225.137:7799",
"149.202.24.250:7777",
"149.202.251.75:7777",
"149.202.251.88:7777",
"149.202.26.172:7777",
"149.202.37.10:7777",
"149.202.64.160:7777",
"149.202.64.55:1200",
"149.202.65.155:7777",
"149.202.65.205:1481",
"149.202.65.205:2361",
"149.202.65.205:2449",
"149.202.65.205:3333",
"149.202.65.205:8888",
"149.202.65.49:7777",
"149.202.65.49:8888",
"149.202.86.101:7777",
"149.202.86.34:7777",
"149.202.86.34:7787",
"149.202.86.34:7817",
"149.202.89.34:7776",
"149.28.132.249:7777",
"149.28.157.23:7777",
"149.56.1.116:7777",
"149.56.100.247:24615",
"149.56.100.247:28415",
"149.56.102.148:7771",
"149.56.102.148:7777",
"149.56.102.148:7790",
"149.56.103.90:27215",
"149.56.103.90:7778",
"149.56.103.90:8008",
"149.56.106.164:7777",
"149.56.107.94:1337",
"149.56.107.94:2018",
"149.56.107.94:6569",
"149.56.115.163:7777",
"149.56.115.164:7777",
"149.56.123.148:7777",
"149.56.13.226:1234",
"149.56.13.226:8686",
"149.56.131.205:7777",
"149.56.140.198:7111",
"149.56.140.198:7756",
"149.56.141.75:5255",
"149.56.141.75:7777",
"149.56.143.217:9099",
"149.56.149.202:7777",
"149.56.149.204:7777",
"149.56.149.78:7777",
"149.56.152.210:7777",
"149.56.175.170:1234",
"149.56.181.16:7777",
"149.56.185.84:7777",
"149.56.195.176:7777",
"149.56.195.4:7777",
"149.56.218.162:7777",
"149.56.218.168:7777",
"149.56.218.175:7777",
"149.56.218.191:7777",
"149.56.225.169:7777",
"149.56.226.91:7777",
"149.56.228.32:7777",
"149.56.232.185:7777",
"149.56.232.185:7780",
"149.56.237.59:7778",
"149.56.24.77:7777",
"149.56.255.17:7777",
"149.56.255.20:7777",
"149.56.255.23:7777",
"149.56.28.33:7777",
"149.56.28.52:8077",
"149.56.28.52:8087",
"149.56.28.52:8117",
"149.56.28.52:8127",
"149.56.28.52:8137",
"149.56.28.52:8147",
"149.56.35.132:7777",
"149.56.38.20:7777",
"149.56.41.22:7777",
"149.56.41.49:7776",
"149.56.41.49:7777",
"149.56.41.49:7787",
"149.56.41.50:7777",
"149.56.41.51:7772",
"149.56.41.52:7720",
"149.56.41.52:7730",
"149.56.41.52:7750",
"149.56.41.52:7776",
"149.56.41.52:7777",
"149.56.41.52:7780",
"149.56.41.52:7782",
"149.56.41.54:7770",
"149.56.41.54:7774",
"149.56.41.55:7770",
"149.56.41.55:7772",
"149.56.41.55:7776",
"149.56.41.55:7777",
"149.56.41.55:7778",
"149.56.45.135:7777",
"149.56.46.81:8686",
"149.56.46.81:9999",
"149.56.46.97:5555",
"149.56.46.97:7777",
"149.56.46.97:8888",
"149.56.84.10:7777",
"149.56.84.17:7777",
"149.56.84.1:7777",
"149.56.84.3:7777",
"149.56.84.5:7777",
"149.56.84.6:7777",
"149.56.84.7:7777",
"149.56.85.165:7777",
"149.56.85.79:7777",
"149.56.85.79:8686",
"149.56.96.88:9696",
"149.62.148.12:7777",
"151.72.45.53:7777",
"151.80.10.182:7782",
"151.80.108.105:3333",
"151.80.108.105:7777",
"151.80.108.109:8150",
"151.80.108.109:8540",
"151.80.108.109:8820",
"151.80.108.109:8830",
"151.80.108.109:8860",
"151.80.108.166:7777",
"151.80.108.209:7777",
"151.80.108.72:7777",
"151.80.240.80:7777",
"151.80.243.170:1998",
"151.80.243.170:7777",
"151.80.243.170:8800",
"151.80.42.90:9999",
"151.80.47.186:1121",
"151.80.47.186:1405",
"151.80.47.186:1657",
"151.80.47.186:3293",
"151.80.47.186:3487",
"151.80.47.186:4547",
"151.80.47.186:9999",
"151.80.47.231:7777",
"151.80.61.178:7777",
"155.138.132.201:7777",
"155.138.235.123:5550",
"155.138.237.154:5555",
"157.230.17.194:7777",
"157.230.41.118:7777",
"157.230.60.165:7777",
"157.245.241.4:2722",
"157.245.7.97:7777",
"158.58.189.38:7777",
"158.58.189.44:7777",
"158.69.0.131:7777",
"158.69.1.42:7777",
"158.69.1.97:7777",
"158.69.105.168:7777",
"158.69.12.207:7777",
"158.69.120.179:7777",
"158.69.120.41:7777",
"158.69.121.201:7777",
"158.69.121.214:7777",
"158.69.122.238:7777",
"158.69.123.27:7777",
"158.69.123.70:7777",
"158.69.128.125:7777",
"158.69.136.102:7777",
"158.69.137.214:7777",
"158.69.141.9:7777",
"158.69.142.70:7777",
"158.69.143.8:7777",
"158.69.148.101:7777",
"158.69.148.102:7777",
"158.69.149.216:7777",
"158.69.149.217:7777",
"158.69.149.222:7777",
"158.69.150.145:7777",
"158.69.153.221:7778",
"158.69.153.221:7781",
"158.69.153.221:7782",
"158.69.153.221:7783",
"158.69.153.221:7784",
"158.69.153.221:7785",
"158.69.153.221:7787",
"158.69.153.221:7788",
"158.69.153.221:7789",
"158.69.153.221:7792",
"158.69.153.221:7794",
"158.69.153.221:7816",
"158.69.153.222:7777",
"158.69.153.222:7778",
"158.69.16.230:7780",
"158.69.16.2:7777",
"158.69.16.6:7777",
"158.69.160.221:7777",
"158.69.160.223:7778",
"158.69.160.223:7787",
"158.69.160.223:7797",
"158.69.160.223:7799",
"158.69.175.163:7777",
"158.69.175.174:7777",
"158.69.175.175:7777",
"158.69.184.5:7777",
"158.69.184.6:7777",
"158.69.206.222:7117",
"158.69.206.222:7273",
"158.69.206.222:7337",
"158.69.206.222:7770",
"158.69.206.222:7778",
"158.69.206.222:7879",
"158.69.206.222:7897",
"158.69.209.255:7777",
"158.69.23.102:5555",
"158.69.23.102:7776",
"158.69.23.102:7777",
"158.69.23.102:8888",
"158.69.23.112:8006",
"158.69.234.232:7777",
"158.69.234.65:7777",
"158.69.235.116:7777",
"158.69.235.153:7777",
"158.69.28.206:7777",
"158.69.28.207:7777",
"158.69.39.115:7777",
"158.69.39.196:7777",
"158.69.5.116:7777",
"158.69.5.175:7777",
"158.69.5.63:7777",
"158.69.58.192:7777",
"158.69.58.203:7777",
"158.69.58.204:7777",
"158.69.58.205:7777",
"158.69.58.206:7777",
"158.69.58.207:7777",
"158.69.58.208:7777",
"158.69.58.209:7777",
"158.69.58.210:7777",
"158.69.60.107:5555",
"158.69.60.107:7777",
"158.69.60.107:8888",
"158.69.62.122:7777",
"158.69.63.223:7777",
"158.69.63.223:9999",
"159.100.29.63:7777",
"159.203.11.12:7777",
"159.255.43.32:7777",
"159.65.141.210:7777",
"159.69.100.189:7777",
"159.69.179.0:7777",
"159.69.37.76:7777",
"159.89.103.222:7777",
"159.89.90.34:27315",
"160.153.245.17:8015",
"160.202.164.27:7787",
"160.202.167.15:7777",
"161.35.11.142:8989",
"161.35.160.42:7777",
"162.248.93.147:7777",
"164.132.17.198:7777",
"164.132.181.181:7777",
"164.132.200.207:3377",
"164.132.200.207:7771",
"164.132.201.27:12000",
"164.132.202.4:7777",
"164.132.202.57:7777",
"164.132.204.150:7777",
"164.132.204.15:7777",
"164.132.204.183:7777",
"164.132.226.166:7777",
"164.132.241.101:7777",
"164.132.53.189:7776",
"164.132.53.189:7777",
"164.132.6.130:7777",
"164.132.69.65:7750",
"164.132.69.65:7777",
"164.132.69.66:7777",
"164.132.69.71:7750",
"164.132.69.71:7777",
"164.68.107.225:7777",
"164.68.120.209:7777",
"165.22.245.85:7777",
"167.114.104.51:7777",
"167.114.107.161:7777",
"167.114.107.163:7777",
"167.114.112.45:7777",
"167.114.113.211:7777",
"167.114.114.171:7775",
"167.114.114.198:27015",
"167.114.114.198:27116",
"167.114.115.163:2273",
"167.114.115.163:3665",
"167.114.115.163:5439",
"167.114.115.163:8888",
"167.114.127.16:7777",
"167.114.128.152:7810",
"167.114.128.152:9239",
"167.114.133.208:7777",
"167.114.137.124:7777",
"167.114.137.124:8888",
"167.114.138.28:7777",
"167.114.138.30:7777",
"167.114.144.248:7777",
"167.114.145.105:7777",
"167.114.145.122:7777",
"167.114.145.122:8888",
"167.114.147.191:7777",
"167.114.15.195:7777",
"167.114.165.161:7777",
"167.114.169.166:7777",
"167.114.195.237:7777",
"167.114.196.181:7777",
"167.114.196.182:7777",
"167.114.201.72:7777",
"167.114.201.74:7777",
"167.114.205.75:7777",
"167.114.32.175:7777",
"167.114.34.216:7777",
"167.114.36.179:1234",
"167.114.36.179:2222",
"167.114.36.179:8686",
"167.114.36.179:9696",
"167.114.42.236:7777",
"167.114.42.237:7777",
"167.114.56.2:5585",
"167.114.56.2:7777",
"167.114.56.2:7817",
"167.114.56.2:7827",
"167.114.56.2:7947",
"167.114.56.2:7997",
"167.114.56.3:7787",
"167.114.56.4:7777",
"167.114.56.4:7787",
"167.114.61.244:7777",
"167.114.61.245:7777",
"167.114.61.247:7777",
"167.114.68.13:7777",
"167.114.68.182:7777",
"167.114.73.110:7777",
"167.114.73.97:7777",
"167.114.8.129:7777",
"167.114.8.130:7777",
"167.114.8.248:7777",
"167.114.8.249:7777",
"167.114.8.250:7777",
"167.114.94.107:7777",
"167.114.97.111:7777",
"167.114.98.64:7777",
"167.114.99.243:7777",
"167.71.143.154:7777",
"167.71.81.49:7777",
"167.86.76.71:7783",
"167.88.15.123:7777",
"167.88.15.79:7777",
"167.99.200.117:7777",
"167.99.65.76:7777",
"168.63.236.247:7777",
"170.39.212.196:7777",
"170.81.41.183:7777",
"170.81.41.77:7777",
"170.81.42.237:7777",
"172.104.169.49:7777",
"172.105.153.194:8010",
"172.106.11.131:7777",
"172.106.11.132:7777",
"172.106.11.133:7777",
"172.106.11.134:7777",
"172.106.11.134:7781",
"172.106.11.135:7777",
"172.106.11.136:7777",
"172.106.11.137:7777",
"172.106.11.138:7777",
"172.106.11.139:7777",
"172.106.11.140:7777",
"172.106.11.141:7777",
"172.106.11.143:7777",
"172.106.11.146:7777",
"172.106.11.147:7777",
"172.106.11.150:7777",
"172.106.11.151:7777",
"172.106.11.156:7777",
"172.106.11.157:7777",
"172.107.2.27:7872",
"172.93.98.210:7777",
"172.93.98.210:8002",
"172.93.98.210:8006",
"173.212.215.174:7777",
"173.234.25.58:8542",
"173.234.31.222:7777",
"173.234.31.248:7777",
"173.234.31.34:7777",
"173.234.31.34:7912",
"173.234.31.34:8062",
"173.234.31.34:8152",
"173.234.31.34:8372",
"173.249.28.44:1222",
"173.249.28.44:1288",
"173.249.28.44:7740",
"173.249.49.62:7777",
"173.249.49.62:8006",
"176.107.131.5:7777",
"176.223.128.91:7777",
"176.31.163.212:7777",
"176.31.198.246:7777",
"176.31.5.10:7777",
"176.31.5.8:7777",
"176.32.36.100:7777",
"176.32.36.103:7777",
"176.32.36.105:7777",
"176.32.36.107:7777",
"176.32.36.108:7777",
"176.32.36.109:7777",
"176.32.36.10:7777",
"176.32.36.110:7777",
"176.32.36.112:7777",
"176.32.36.115:7777",
"176.32.36.119:7777",
"176.32.36.11:7777",
"176.32.36.122:7777",
"176.32.36.124:7777",
"176.32.36.128:7777",
"176.32.36.12:7777",
"176.32.36.130:7777",
"176.32.36.131:7777",
"176.32.36.135:7777",
"176.32.36.136:7777",
"176.32.36.13:7777",
"176.32.36.142:7777",
"176.32.36.144:7777",
"176.32.36.15:7777",
"176.32.36.17:7777",
"176.32.36.18:7777",
"176.32.36.19:7777",
"176.32.36.200:7777",
"176.32.36.202:7777",
"176.32.36.204:7777",
"176.32.36.209:7777",
"176.32.36.210:7777",
"176.32.36.211:7777",
"176.32.36.213:7777",
"176.32.36.216:7777",
"176.32.36.217:7777",
"176.32.36.218:7777",
"176.32.36.221:7777",
"176.32.36.223:7777",
"176.32.36.224:7777",
"176.32.36.225:7777",
"176.32.36.227:7777",
"176.32.36.228:7777",
"176.32.36.229:7777",
"176.32.36.22:7777",
"176.32.36.232:7777",
"176.32.36.233:7777",
"176.32.36.239:7777",
"176.32.36.23:7777",
"176.32.36.240:7777",
"176.32.36.246:7777",
"176.32.36.24:7777",
"176.32.36.252:7777",
"176.32.36.25:7777",
"176.32.36.28:7777",
"176.32.36.29:7777",
"176.32.36.31:7777",
"176.32.36.33:7777",
"176.32.36.34:7777",
"176.32.36.36:7777",
"176.32.36.37:7777",
"176.32.36.38:7777",
"176.32.36.41:7777",
"176.32.36.42:7777",
"176.32.36.43:7777",
"176.32.36.44:7777",
"176.32.36.45:7777",
"176.32.36.46:7777",
"176.32.36.47:7777",
"176.32.36.48:7777",
"176.32.36.49:7777",
"176.32.36.4:5555",
"176.32.36.50:7777",
"176.32.36.51:7777",
"176.32.36.52:7777",
"176.32.36.62:7777",
"176.32.36.6:7777",
"176.32.36.73:7777",
"176.32.36.80:7777",
"176.32.36.81:7777",
"176.32.36.83:7777",
"176.32.36.84:7777",
"176.32.36.85:7777",
"176.32.36.86:7777",
"176.32.36.87:7777",
"176.32.36.88:7777",
"176.32.36.89:7777",
"176.32.36.8:7777",
"176.32.36.90:7777",
"176.32.36.91:7777",
"176.32.36.92:7777",
"176.32.36.93:7777",
"176.32.36.94:7777",
"176.32.36.95:7777",
"176.32.36.96:7777",
"176.32.36.97:7777",
"176.32.36.98:7777",
"176.32.36.99:7777",
"176.32.37.100:7777",
"176.32.37.104:7777",
"176.32.37.10:7777",
"176.32.37.130:7777",
"176.32.37.137:7777",
"176.32.37.14:7777",
"176.32.37.15:7777",
"176.32.37.16:7777",
"176.32.37.17:7777",
"176.32.37.183:7777",
"176.32.37.184:7777",
"176.32.37.185:7777",
"176.32.37.186:7777",
"176.32.37.187:7777",
"176.32.37.189:7777",
"176.32.37.18:7777",
"176.32.37.190:7777",
"176.32.37.191:7777",
"176.32.37.192:7777",
"176.32.37.193:7777",
"176.32.37.194:7777",
"176.32.37.195:7777",
"176.32.37.196:7777",
"176.32.37.197:7777",
"176.32.37.198:7777",
"176.32.37.199:7777",
"176.32.37.19:7777",
"176.32.37.200:7777",
"176.32.37.201:7777",
"176.32.37.202:7777",
"176.32.37.203:7777",
"176.32.37.204:7777",
"176.32.37.205:7777",
"176.32.37.207:7777",
"176.32.37.208:7777",
"176.32.37.209:7777",
"176.32.37.20:7777",
"176.32.37.210:7777",
"176.32.37.21:7777",
"176.32.37.221:7777",
"176.32.37.22:7777",
"176.32.37.23:7777",
"176.32.37.243:7777",
"176.32.37.24:7777",
"176.32.37.251:7777",
"176.32.37.252:7777",
"176.32.37.25:7777",
"176.32.37.26:7777",
"176.32.37.27:7777",
"176.32.37.28:7777",
"176.32.37.29:7777",
"176.32.37.2:7777",
"176.32.37.30:7777",
"176.32.37.31:7777",
"176.32.37.32:7777",
"176.32.37.33:7777",
"176.32.37.34:7777",
"176.32.37.35:7777",
"176.32.37.36:7777",
"176.32.37.37:7777",
"176.32.37.38:7777",
"176.32.37.39:7777",
"176.32.37.3:7777",
"176.32.37.40:7777",
"176.32.37.41:7777",
"176.32.37.42:7777",
"176.32.37.43:7777",
"176.32.37.45:7777",
"176.32.37.49:7777",
"176.32.37.4:7777",
"176.32.37.50:7777",
"176.32.37.51:7777",
"176.32.37.52:7777",
"176.32.37.56:7777",
"176.32.37.57:7777",
"176.32.37.58:7777",
"176.32.37.5:7777",
"176.32.37.61:7777",
"176.32.37.62:7777",
"176.32.37.63:7777",
"176.32.37.65:7777",
"176.32.37.68:7777",
"176.32.37.6:7777",
"176.32.37.74:7777",
"176.32.37.75:7777",
"176.32.37.77:7777",
"176.32.37.7:7777",
"176.32.37.82:7777",
"176.32.37.8:7777",
"176.32.37.93:7777",
"176.32.37.9:7777",
"176.32.38.87:7777",
"176.32.39.10:7777",
"176.32.39.11:7777",
"176.32.39.128:7777",
"176.32.39.129:7777",
"176.32.39.130:7777",
"176.32.39.131:7777",
"176.32.39.132:7777",
"176.32.39.133:7777",
"176.32.39.134:7777",
"176.32.39.135:7777",
"176.32.39.136:7777",
"176.32.39.137:7777",
"176.32.39.138:7777",
"176.32.39.139:7777",
"176.32.39.13:7777",
"176.32.39.140:7777",
"176.32.39.141:7777",
"176.32.39.142:7777",
"176.32.39.143:7777",
"176.32.39.145:7777",
"176.32.39.146:7777",
"176.32.39.147:7777",
"176.32.39.148:7777",
"176.32.39.149:7777",
"176.32.39.14:7777",
"176.32.39.14:7778",
"176.32.39.150:7777",
"176.32.39.151:7777",
"176.32.39.152:7777",
"176.32.39.153:7777",
"176.32.39.154:7777",
"176.32.39.155:7777",
"176.32.39.156:7777",
"176.32.39.157:7777",
"176.32.39.158:7777",
"176.32.39.159:7777",
"176.32.39.15:7777",
"176.32.39.160:7777",
"176.32.39.162:7777",
"176.32.39.163:7777",
"176.32.39.164:7777",
"176.32.39.165:7777",
"176.32.39.166:7777",
"176.32.39.167:7777",
"176.32.39.168:7777",
"176.32.39.169:7777",
"176.32.39.16:7777",
"176.32.39.170:7777",
"176.32.39.171:7777",
"176.32.39.172:7777",
"176.32.39.173:7777",
"176.32.39.174:7777",
"176.32.39.175:7777",
"176.32.39.176:7777",
"176.32.39.177:7777",
"176.32.39.178:7777",
"176.32.39.179:7777",
"176.32.39.17:7777",
"176.32.39.180:7777",
"176.32.39.181:7777",
"176.32.39.182:7777",
"176.32.39.184:7777",
"176.32.39.185:7777",
"176.32.39.187:7777",
"176.32.39.188:7777",
"176.32.39.18:7777",
"176.32.39.190:7777",
"176.32.39.194:7777",
"176.32.39.198:7777",
"176.32.39.199:7777",
"176.32.39.19:7777",
"176.32.39.200:7777",
"176.32.39.20:7777",
"176.32.39.21:7777",
"176.32.39.22:7777",
"176.32.39.23:7777",
"176.32.39.24:7777",
"176.32.39.25:7777",
"176.32.39.27:7777",
"176.32.39.28:7777",
"176.32.39.29:7777",
"176.32.39.2:7777",
"176.32.39.30:7777",
"176.32.39.31:7777",
"176.32.39.32:7777",
"176.32.39.33:7777",
"176.32.39.34:7777",
"176.32.39.35:7777",
"176.32.39.36:7777",
"176.32.39.37:7777",
"176.32.39.38:7777",
"176.32.39.39:7777",
"176.32.39.3:7777",
"176.32.39.40:7777",
"176.32.39.41:7777",
"176.32.39.43:7777",
"176.32.39.44:7777",
"176.32.39.48:7777",
"176.32.39.4:7777",
"176.32.39.53:7777",
"176.32.39.56:7777",
"176.32.39.5:7777",
"176.32.39.69:7777",
"176.32.39.6:7777",
"176.32.39.7:7777",
"176.32.39.8:7777",
"176.32.39.9:7777",
"176.57.128.40:7780",
"176.57.188.16:7778",
"176.57.188.16:7779",
"176.9.142.5:7777",
"176.9.80.219:7777",
"176.96.238.230:7777",
"176.98.42.33:9980",
"176.98.42.6:7777",
"177.52.27.31:7777",
"177.54.146.169:7777",
"177.54.146.206:7777",
"177.54.146.208:7777",
"177.54.146.210:7777",
"177.54.146.216:7777",
"177.54.146.228:7777",
"177.54.146.231:7777",
"177.54.146.232:7777",
"177.54.146.235:7777",
"177.54.146.238:7777",
"177.54.147.143:7777",
"177.54.147.210:7777",
"177.54.152.149:7777",
"177.54.156.155:7777",
"177.54.156.191:7777",
"177.54.156.198:7777",
"178.128.114.122:7777",
"178.128.148.35:7777",
"178.128.220.86:7777",
"178.128.55.6:7777",
"178.128.82.211:7777",
"178.128.92.59:7777",
"178.128.94.134:7777",
"178.156.230.132:7777",
"178.170.189.155:7777",
"178.170.189.76:7777",
"178.218.215.106:7710",
"178.218.215.106:7711",
"178.218.215.106:7712",
"178.218.215.106:7713",
"178.218.215.106:7714",
"178.218.215.106:7715",
"178.218.215.106:7775",
"178.218.215.106:7776",
"178.218.215.106:7777",
"178.218.215.106:7778",
"178.254.20.141:7575",
"178.32.109.51:9792",
"178.32.114.245:7777",
"178.32.125.55:7778",
"178.32.147.55:7777",
"178.32.185.201:7777",
"178.32.234.16:7777",
"178.32.234.17:7777",
"178.32.234.18:7777",
"178.32.234.19:7777",
"178.32.26.67:7777",
"178.32.5.25:7777",
"178.32.55.41:7791",
"178.33.1.223:7777",
"178.33.221.210:2787",
"178.33.221.210:7776",
"178.33.221.210:7777",
"178.33.251.43:7777",
"178.33.26.240:7705",
"178.33.26.243:7780",
"178.33.37.70:7777",
"178.33.38.186:7793",
"178.33.45.249:7777",
"178.33.47.162:7777",
"178.33.53.113:4004",
"178.33.54.31:4000",
"178.33.54.31:4004",
"178.33.54.31:4088",
"178.33.54.32:4016",
"178.62.163.77:7777",
"178.63.13.143:16465",
"178.63.13.143:7777",
"178.63.13.186:15485",
"178.63.13.186:15655",
"178.63.13.186:15725",
"178.63.13.186:15735",
"178.63.13.186:15755",
"178.63.13.186:15765",
"18.141.162.39:7777",
"18.216.2.80:8084",
"18.218.115.196:7777",
"18.219.154.154:7777",
"18.229.131.36:7777",
"181.228.12.201:7777",
"181.30.26.27:7777",
"182.176.65.10:7777",
"185.101.95.199:7777",
"185.105.236.69:8888",
"185.107.96.114:7777",
"185.107.96.114:7779",
"185.107.96.190:2222",
"185.107.96.190:7777",
"185.107.96.190:7778",
"185.107.96.190:8888",
"185.107.96.207:7777",
"185.107.96.208:7777",
"185.107.96.218:3546",
"185.107.96.218:7777",
"185.107.96.218:8888",
"185.107.96.244:7777",
"185.107.96.246:7776",
"185.107.96.246:7777",
"185.11.146.93:7777",
"185.114.22.60:7777",
"185.12.178.71:7794",
"185.12.178.71:7813",
"185.134.29.180:7777",
"185.137.235.49:7777",
"185.137.235.68:7777",
"185.139.68.136:7777",
"185.144.157.50:7777",
"185.148.81.130:7777",
"185.158.115.142:7777",
"185.162.144.229:7777",
"185.169.132.171:7777",
"185.169.134.107:7777",
"185.169.134.109:7777",
"185.169.134.11:7777",
"185.169.134.126:7777",
"185.169.134.150:8904",
"185.169.134.164:7777",
"185.169.134.165:7777",
"185.169.134.166:7777",
"185.169.134.171:7777",
"185.169.134.172:7777",
"185.169.134.20:7777",
"185.169.134.22:7771",
"185.169.134.22:7773",
"185.169.134.22:7777",
"185.169.134.34:7777",
"185.169.134.3:7777",
"185.169.134.43:7777",
"185.169.134.44:7777",
"185.169.134.45:7777",
"185.169.134.4:7777",
"185.169.134.59:7777",
"185.169.134.5:7777",
"185.169.134.61:7777",
"185.169.134.67:7777",
"185.169.134.68:7777",
"185.169.134.83:7777",
"185.169.134.84:7777",
"185.169.134.85:7777",
"185.169.134.91:7777",
"185.169.135.86:7777",
"185.169.52.254:7777",
"185.17.144.64:7777",
"185.171.1.157:7777",
"185.171.1.69:7777",
"185.171.90.197:7777",
"185.172.145.147:8887",
"185.176.25.113:7777",
"185.181.9.198:7777",
"185.185.134.241:7777",
"185.195.27.232:7777",
"185.198.188.100:7777",
"185.198.188.101:7772",
"185.198.188.101:7777",
"185.198.188.101:7778",
"185.198.188.98:7279",
"185.198.188.98:7777",
"185.204.216.149:7777",
"185.208.174.33:7777",
"185.209.29.242:7779",
"185.211.247.111:7060",
"185.211.247.68:7777",
"185.223.28.164:7790",
"185.223.28.204:7777",
"185.223.30.232:7777",
"185.223.31.210:7790",
"185.224.249.76:7777",
"185.224.90.102:7777",
"185.228.136.67:7777",
"185.230.160.255:7777",
"185.231.153.48:7777",
"185.231.154.228:7882",
"185.231.155.185:6666",
"185.231.155.185:8888",
"185.238.136.54:7777",
"185.238.138.13:7777",
"185.243.152.120:7777",
"185.243.152.220:7777",
"185.244.173.82:7779",
"185.244.193.44:7777",
"185.249.196.95:7790",
"185.25.205.28:7777",
"185.25.207.73:7777",
"185.254.97.12:7777",
"185.255.91.183:7777",
"185.255.94.117:7777",
"185.28.18.218:7777",
"185.34.216.79:7777",
"185.34.52.200:7777",
"185.38.150.100:7777",
"185.41.163.72:7777",
"185.43.6.194:5825",
"185.50.69.206:7777",
"185.52.248.13:7777",
"185.53.130.171:1337",
"185.53.130.171:7777",
"185.53.131.51:7777",
"185.61.138.212:7777",
"185.61.138.98:7777",
"185.62.188.50:7777",
"185.69.55.140:7777",
"185.71.66.95:7771",
"185.71.66.95:7772",
"185.71.66.95:7773",
"185.71.66.95:7774",
"185.71.66.95:7775",
"185.71.66.95:7777",
"185.80.128.207:7777",
"185.81.152.54:7777",
"185.81.154.221:7777",
"185.87.199.12:7777",
"185.87.48.130:8386",
"185.87.48.252:7777",
"185.91.116.8:7780",
"185.91.116.8:7783",
"185.91.116.8:7784",
"185.91.116.8:7788",
"185.93.70.69:7777",
"185.97.255.46:7871",
"185.97.255.7:7777",
"185.98.61.228:7777",
"185.98.61.3:7777",
"186.14.176.109:7777",
"186.82.2.234:7777",
"186.93.117.91:7777",
"187.101.235.125:40120",
"187.108.193.225:2019",
"187.108.193.225:7777",
"187.172.160.125:6969",
"187.94.202.13:7777",
"188.120.248.118:7777",
"188.127.239.80:7777",
"188.165.127.145:7777",
"188.165.127.146:7777",
"188.165.138.147:7777",
"188.165.195.118:7778",
"188.165.210.34:7777",
"188.165.219.63:8800",
"188.165.236.19:7777",
"188.165.253.143:5001",
"188.165.253.143:7777",
"188.165.37.206:7777",
"188.165.4.14:7777",
"188.165.40.163:7777",
"188.165.57.58:7777",
"188.166.244.5:7770",
"188.166.88.79:7777",
"188.212.100.127:7777",
"188.212.100.239:7777",
"188.212.100.249:7777",
"188.212.100.79:7777",
"188.212.100.83:7777",
"188.212.101.131:7777",
"188.212.101.8:7777",
"188.212.101.91:7777",
"188.212.102.114:7777",
"188.212.102.163:7777",
"188.212.102.16:7777",
"188.212.102.184:7777",
"188.212.102.39:7777",
"188.212.102.94:7777",
"188.213.216.132:7777",
"188.214.88.251:7777",
"188.226.158.59:7777",
"188.254.144.231:9999",
"188.40.244.178:7777",
"189.127.164.28:7777",
"189.127.164.30:7777",
"189.127.164.34:7778",
"189.127.164.34:7780",
"190.0.164.181:7777",
"190.150.42.19:7797",
"190.16.41.101:7777",
"190.207.175.56:7777",
"190.207.178.52:7777",
"191.101.172.104:7777",
"191.114.189.10:7777",
"191.232.241.176:7777",
"191.252.109.154:2019",
"191.252.109.154:7777",
"192.162.242.65:7160",
"192.162.242.71:7777",
"192.162.244.115:7777",
"192.169.204.169:1111",
"192.169.205.77:9013",
"192.169.80.245:7770",
"192.169.80.245:7777",
"192.169.80.248:7777",
"192.223.24.100:7777",
"192.223.27.122:7777",
"192.223.27.165:7777",
"192.223.30.136:7777",
"192.249.126.77:7766",
"192.249.126.77:7777",
"192.71.245.204:7777",
"192.81.219.176:7777",
"192.95.10.16:5565",
"192.95.10.16:7777",
"192.95.10.16:7780",
"192.95.10.18:5565",
"192.95.10.19:5565",
"192.95.10.20:5565",
"192.95.12.96:7777",
"192.95.12.97:7777",
"192.95.12.98:7777",
"192.95.18.10:1234",
"192.95.18.10:2222",
"192.95.18.10:6677",
"192.95.18.10:7730",
"192.95.18.10:9696",
"192.95.19.27:7777",
"192.95.23.88:1234",
"192.95.23.88:7080",
"192.95.23.88:8820",
"192.95.40.20:7777",
"192.95.48.200:7777",
"192.95.49.249:7777",
"192.95.52.216:7777",
"192.95.55.65:7777",
"192.95.8.248:7777",
"192.95.8.249:8810",
"192.95.8.250:2222",
"192.95.8.250:7777",
"192.95.8.251:7777",
"192.95.8.252:7720",
"192.95.8.252:7777",
"192.95.8.253:6677",
"192.95.8.254:7720",
"192.99.0.187:2018",
"192.99.0.187:6569",
"192.99.110.161:7777",
"192.99.110.162:7777",
"192.99.110.164:7777",
"192.99.110.166:7777",
"192.99.119.136:7777",
"192.99.120.59:7777",
"192.99.127.220:7777",
"192.99.13.225:7777",
"192.99.135.246:7777",
"192.99.136.1:7778",
"192.99.140.196:7777",
"192.99.140.198:7777",
"192.99.154.239:27615",
"192.99.154.239:7776",
"192.99.159.168:7779",
"192.99.159.168:7782",
"192.99.159.168:7783",
"192.99.159.168:7784",
"192.99.159.168:7785",
"192.99.159.168:7786",
"192.99.159.168:7787",
"192.99.159.168:7788",
"192.99.159.168:7792",
"192.99.159.168:7800",
"192.99.159.168:7801",
"192.99.159.168:7808",
"192.99.159.168:7816",
"192.99.159.168:7824",
"192.99.168.16:7000",
"192.99.168.20:7777",
"192.99.169.16:7777",
"192.99.169.249:5555",
"192.99.169.249:7777",
"192.99.175.0:7777",
"192.99.175.2:7777",
"192.99.177.158:7777",
"192.99.177.253:7777",
"192.99.185.105:7777",
"192.99.185.110:7777",
"192.99.185.72:7777",
"192.99.185.73:8888",
"192.99.185.73:9999",
"192.99.185.80:7777",
"192.99.185.85:7777",
"192.99.185.98:7777",
"192.99.186.113:7777",
"192.99.197.9:7777",
"192.99.197.9:7787",
"192.99.197.9:7792",
"192.99.197.9:7797",
"192.99.2.6:22536",
"192.99.2.6:7749",
"192.99.207.139:7777",
"192.99.223.136:7777",
"192.99.223.143:7777",
"192.99.229.123:7777",
"192.99.231.128:7777",
"192.99.231.129:7777",
"192.99.231.133:7777",
"192.99.231.135:7777",
"192.99.231.138:7777",
"192.99.231.141:7777",
"192.99.237.23:7777",
"192.99.238.126:7777",
"192.99.244.184:7777",
"192.99.245.11:22222",
"192.99.247.153:7777",
"192.99.251.103:7792",
"192.99.251.103:7802",
"192.99.251.103:7852",
"192.99.251.110:7777",
"192.99.254.56:7777",
"192.99.54.104:7777",
"192.99.98.20:7777",
"193.107.74.227:7777",
"193.124.187.117:7878",
"193.124.187.117:8067",
"193.164.7.83:7777",
"193.200.74.220:7777",
"193.203.39.138:7777",
"193.203.39.141:7777",
"193.203.39.143:7777",
"193.203.39.154:7777",
"193.203.39.160:7777",
"193.203.39.166:7777",
"193.203.39.179:7777",
"193.203.39.205:7777",
"193.203.39.216:7777",
"193.203.39.250:7777",
"193.203.39.36:7777",
"193.203.39.37:7777",
"193.203.39.42:7777",
"193.203.39.46:7777",
"193.203.39.47:7777",
"193.203.39.49:7777",
"193.203.39.51:7777",
"193.203.39.74:7777",
"193.203.39.81:7777",
"193.23.126.55:7777",
"193.26.217.27:7777",
"193.31.25.28:7777",
"193.37.213.139:7777",
"193.70.125.136:7777",
"193.70.126.129:4016",
"193.70.126.129:4020",
"193.70.126.129:4028",
"193.70.126.129:4064",
"193.70.126.129:4072",
"193.70.126.136:4000",
"193.70.126.136:4004",
"193.70.126.136:4008",
"193.70.126.136:4020",
"193.70.126.136:4036",
"193.70.126.136:7777",
"193.70.18.81:7777",
"193.70.6.208:7777",
"193.70.65.226:7841",
"193.70.7.93:7777",
"193.70.72.240:7777",
"193.70.79.214:7777",
"193.70.81.128:7777",
"193.70.81.230:7777",
"193.70.81.80:7777",
"193.70.94.12:7777",
"193.70.96.17:7777",
"193.84.64.61:7777",
"193.84.64.67:7777",
"193.84.64.75:7777",
"194.135.88.18:7777",
"194.145.209.72:7777",
"194.28.212.120:7777",
"194.5.159.52:7777",
"194.5.159.52:7778",
"194.59.206.69:7777",
"194.61.44.21:7777",
"194.67.195.138:1145",
"194.67.195.138:1155",
"194.67.195.138:7777",
"194.67.223.254:7777",
"194.67.87.27:7777",
"194.93.2.106:7777",
"194.93.2.146:7777",
"194.93.2.198:7777",
"195.133.49.139:7777",
"195.154.184.235:7777",
"195.154.252.140:7897",
"195.178.103.31:7777",
"195.201.70.37:7777",
"195.201.81.254:7777",
"195.39.241.231:7812",
"198.100.144.190:1357",
"198.100.144.190:1359",
"198.100.144.190:2490",
"198.100.144.190:2493",
"198.100.144.190:2496",
"198.100.144.190:2498",
"198.100.144.190:2501",
"198.100.144.190:2502",
"198.100.144.190:2503",
"198.100.144.190:2505",
"198.100.144.190:2509",
"198.100.144.190:2511",
"198.100.144.190:2514",
"198.100.144.190:2517",
"198.100.144.190:2518",
"198.100.144.190:2519",
"198.100.144.190:2520",
"198.100.144.190:2522",
"198.100.144.190:2523",
"198.100.144.190:2527",
"198.100.144.190:2528",
"198.100.144.190:2529",
"198.100.144.190:2532",
"198.100.144.190:2533",
"198.100.144.190:2535",
"198.100.144.190:2538",
"198.100.144.190:2540",
"198.100.144.190:2542",
"198.100.144.190:2544",
"198.100.144.190:2545",
"198.100.144.190:2552",
"198.100.144.190:2553",
"198.100.144.190:2554",
"198.100.144.190:2557",
"198.100.144.190:2558",
"198.100.144.190:2560",
"198.100.144.190:2565",
"198.100.144.190:2567",
"198.100.144.190:2570",
"198.100.144.190:2572",
"198.100.144.190:2573",
"198.100.144.190:2575",
"198.100.144.190:2576",
"198.100.144.190:2580",
"198.100.144.190:2754",
"198.100.144.190:2757",
"198.100.144.190:2758",
"198.100.144.190:2759",
"198.100.144.190:2760",
"198.100.144.190:2761",
"198.100.144.190:2763",
"198.100.144.190:4015",
"198.100.144.190:4016",
"198.100.144.190:4018",
"198.100.144.190:4019",
"198.100.144.190:4020",
"198.100.144.190:4048",
"198.100.144.190:4049",
"198.100.144.190:5062",
"198.100.144.190:5068",
"198.100.144.190:5076",
"198.100.144.190:5088",
"198.100.144.190:5101",
"198.100.144.190:6540",
"198.100.144.190:6541",
"198.100.144.190:6542",
"198.100.144.190:6545",
"198.100.144.190:6549",
"198.100.144.190:6552",
"198.100.144.190:6553",
"198.100.144.190:6556",
"198.100.144.190:6557",
"198.100.144.190:6558",
"198.100.144.190:6560",
"198.100.144.190:6563",
"198.100.144.190:6565",
"198.100.144.190:6573",
"198.100.144.190:8000",
"198.100.144.190:8003",
"198.100.144.190:8006",
"198.100.144.190:9547",
"198.100.144.190:9856",
"198.100.144.190:9858",
"198.100.144.190:9859",
"198.100.144.190:9861",
"198.100.144.190:9862",
"198.100.144.190:9863",
"198.100.144.190:9865",
"198.100.144.190:9866",
"198.100.144.190:9868",
"198.100.144.190:9873",
"198.100.144.190:9876",
"198.100.144.190:9880",
"198.100.144.190:9883",
"198.100.144.190:9885",
"198.100.144.190:9886",
"198.100.144.190:9887",
"198.100.144.190:9888",
"198.100.144.190:9889",
"198.100.144.190:9891",
"198.100.154.124:7777",
"198.100.154.62:7777",
"198.100.157.124:7777",
"198.100.157.55:7777",
"198.100.159.61:7777",
"198.199.89.24:7777",
"198.24.160.229:7777",
"198.24.188.213:7777",
"198.245.51.214:1337",
"198.245.51.214:1997",
"198.245.51.214:2018",
"198.245.51.214:2019",
"198.245.51.214:3322",
"198.245.51.214:5551",
"198.245.51.214:5555",
"198.245.51.214:6567",
"198.245.51.214:6569",
"198.245.51.214:7676",
"198.245.51.214:7775",
"198.245.51.214:7776",
"198.245.51.214:7778",
"198.245.51.214:7779",
"198.245.51.214:7878",
"198.245.51.214:7888",
"198.245.51.214:8698",
"198.245.51.214:8888",
"198.245.53.41:7777",
"198.245.55.219:7777",
"198.245.55.2:27315",
"198.245.55.2:27587",
"198.245.55.2:27615",
"198.245.55.2:28715",
"198.245.55.2:34567",
"198.245.55.2:5896",
"198.251.81.177:7777",
"198.251.82.14:7777",
"198.251.83.76:7777",
"198.27.105.21:7777",
"198.27.118.123:27215",
"198.27.121.241:7777",
"198.27.66.115:7777",
"198.27.76.170:7777",
"198.27.77.130:7777",
"198.27.77.131:7842",
"198.27.77.133:7777",
"198.27.91.212:7777",
"198.27.95.178:7777",
"198.46.242.8:8888",
"198.50.134.212:7777",
"198.50.137.231:7777",
"198.50.158.121:7797",
"198.50.159.113:7721",
"198.50.159.113:7738",
"198.50.159.146:7778",
"198.50.184.105:7777",
"198.50.187.240:7777",
"198.50.187.241:7777",
"198.50.187.243:7777",
"198.50.187.247:7777",
"198.50.194.236:7777",
"198.50.194.238:7777",
"198.50.195.140:7771",
"198.50.195.140:7772",
"198.50.195.140:7774",
"198.50.195.140:7776",
"198.50.195.140:7778",
"198.50.195.140:7780",
"198.50.195.140:7782",
"198.50.195.140:7784",
"198.50.195.140:7786",
"198.50.195.140:7790",
"198.50.195.140:7794",
"198.50.195.140:7800",
"198.50.195.141:7770",
"198.50.195.141:7772",
"198.50.195.141:7774",
"198.50.195.141:7776",
"198.50.195.141:7780",
"198.50.195.141:7784",
"198.50.195.141:7786",
"198.50.195.141:7790",
"198.50.195.141:7792",
"198.50.195.141:7798",
"198.50.195.141:7800",
"198.50.195.141:7804",
"198.50.195.142:7770",
"198.50.195.142:7774",
"198.50.195.142:7776",
"198.50.195.142:7778",
"198.50.195.142:7780",
"198.50.195.142:7782",
"198.50.195.142:7784",
"198.50.195.142:7788",
"198.50.195.142:7790",
"198.50.195.142:7796",
"198.50.195.143:7770",
"198.50.195.143:7772",
"198.50.195.143:7774",
"198.50.195.143:7776",
"198.50.195.143:7777",
"198.50.195.143:7778",
"198.50.195.143:7780",
"198.50.195.143:7782",
"198.50.195.143:7784",
"198.50.195.143:7786",
"198.50.195.143:7790",
"198.50.195.143:7792",
"198.50.195.143:7794",
"198.50.195.143:7798",
"198.50.195.143:7800",
"198.50.195.77:7777",
"198.50.205.100:7777",
"198.50.205.103:7777",
"198.50.206.176:7777",
"198.50.206.177:7777",
"198.50.207.32:7777",
"198.50.217.189:7777",
"198.50.222.113:7777",
"198.50.224.188:7777",
"198.50.224.189:7777",
"198.50.224.191:7777",
"198.50.224.47:7777",
"198.50.224.47:7779",
"198.50.224.47:7791",
"198.50.224.79:7777",
"198.50.231.216:7777",
"198.50.236.65:7777",
"198.50.236.67:7777",
"198.50.236.67:7779",
"198.50.241.211:7777",
"198.50.244.204:7777",
"198.50.244.205:7777",
"198.50.244.207:7778",
"198.50.246.132:7777",
"198.50.246.50:7777",
"198.50.246.51:7777",
"198.50.246.52:7777",
"198.50.246.53:7777",
"198.50.246.55:7777",
"198.50.246.56:7777",
"198.50.246.59:7777",
"198.50.247.159:1121",
"198.50.253.42:7777",
"198.50.253.42:8127",
"2.229.191.204:5001",
"2.229.191.204:7777",
"2.56.152.29:7777",
"2.56.155.155:7777",
"2.56.155.55:7777",
"2.56.242.138:7777",
"2.59.119.236:7777",
"2.59.119.86:7777",
"2.59.134.136:7777",
"2.59.40.80:7777",
"200.9.154.49:7777",
"203.137.180.130:7777",
"206.189.149.142:7777",
"206.189.37.2:7777",
"206.72.193.184:6666",
"206.81.7.77:1111",
"206.81.7.77:7777",
"207.244.241.196:7791",
"207.244.241.196:7801",
"207.244.251.24:8006",
"207.246.71.180:7777",
"207.246.83.73:4500",
"208.73.200.220:27015",
"209.126.106.34:7777",
"209.222.97.160:7777",
"209.97.190.183:7777",
"212.109.217.243:7777",
"212.129.39.234:7777",
"212.129.40.4:7777",
"212.22.77.119:7777",
"212.22.77.247:2019",
"212.22.77.247:9999",
"212.22.93.101:7777",
"212.22.93.13:7787",
"212.22.93.13:7807",
"212.22.93.37:7777",
"212.22.93.37:7817",
"212.22.93.45:7777",
"212.22.93.49:7777",
"212.22.93.49:7787",
"212.22.93.6:7777",
"212.237.35.69:7777",
"212.24.104.246:7777",
"212.32.240.167:7777",
"213.108.241.25:7777",
"213.108.243.8:7777",
"213.159.211.115:7026",
"213.159.211.75:7006",
"213.159.211.87:7777",
"213.226.225.109:7777",
"213.227.140.26:7777",
"213.227.154.203:7777",
"213.238.178.98:7777",
"213.239.198.139:7777",
"213.32.112.224:7777",
"213.32.116.163:7777",
"213.32.116.166:7777",
"213.32.116.168:7777",
"213.32.116.170:7777",
"213.32.116.173:7777",
"213.32.120.119:7777",
"213.32.120.176:7777",
"213.32.120.191:7777",
"213.32.59.213:7777",
"213.32.6.232:7777",
"213.5.229.25:7777",
"213.5.229.33:7777",
"213.5.229.34:7777",
"213.5.229.35:7777",
"213.5.229.4:7777",
"216.98.221.25:7777",
"217.106.104.102:7777",
"217.106.104.104:7777",
"217.106.104.105:7777",
"217.106.104.107:7777",
"217.106.104.114:7777",
"217.106.104.115:7777",
"217.106.104.11:7777",
"217.106.104.120:7777",
"217.106.104.125:7777",
"217.106.104.12:7777",
"217.106.104.13:7777",
"217.106.104.140:7777",
"217.106.104.14:7777",
"217.106.104.175:7777",
"217.106.104.17:7777",
"217.106.104.18:7777",
"217.106.104.199:7777",
"217.106.104.200:7777",
"217.106.104.217:7777",
"217.106.104.21:7777",
"217.106.104.228:7777",
"217.106.104.22:7777",
"217.106.104.233:7777",
"217.106.104.23:7777",
"217.106.104.24:7777",
"217.106.104.26:7777",
"217.106.104.27:7777",
"217.106.104.28:7777",
"217.106.104.30:7777",
"217.106.104.32:7777",
"217.106.104.35:7777",
"217.106.104.41:7777",
"217.106.104.42:7777",
"217.106.104.43:7777",
"217.106.104.44:7777",
"217.106.104.47:7777",
"217.106.104.48:7777",
"217.106.104.49:7777",
"217.106.104.50:7777",
"217.106.104.55:7777",
"217.106.104.66:7777",
"217.106.104.74:7777",
"217.106.104.84:7777",
"217.106.104.85:7777",
"217.106.104.91:7777",
"217.106.106.101:7777",
"217.106.106.102:7777",
"217.106.106.107:7092",
"217.106.106.116:7035",
"217.106.106.116:7037",
"217.106.106.116:7050",
"217.106.106.116:7052",
"217.106.106.116:7062",
"217.106.106.116:7073",
"217.106.106.116:7079",
"217.106.106.116:7087",
"217.106.106.116:7120",
"217.106.106.116:7121",
"217.106.106.116:7132",
"217.106.106.116:7144",
"217.106.106.116:7166",
"217.106.106.116:7178",
"217.106.106.116:7202",
"217.106.106.116:7228",
"217.106.106.116:7261",
"217.106.106.116:7277",
"217.106.106.116:7297",
"217.106.106.116:7409",
"217.106.106.116:7495",
"217.106.106.116:7524",
"217.106.106.116:7540",
"217.106.106.116:7620",
"217.106.106.116:7762",
"217.106.106.136:7061",
"217.106.106.136:7137",
"217.106.106.155:7777",
"217.106.106.166:7777",
"217.106.106.170:7777",
"217.106.106.178:7020",
"217.106.106.178:7023",
"217.106.106.178:7031",
"217.106.106.178:7044",
"217.106.106.178:7052",
"217.106.106.178:7057",
"217.106.106.178:7063",
"217.106.106.178:7093",
"217.106.106.178:7118",
"217.106.106.178:7135",
"217.106.106.178:7139",
"217.106.106.178:7154",
"217.106.106.178:7155",
"217.106.106.178:7165",
"217.106.106.178:7175",
"217.106.106.178:7185",
"217.106.106.178:7188",
"217.106.106.178:7192",
"217.106.106.178:7219",
"217.106.106.178:7261",
"217.106.106.178:7314",
"217.106.106.178:7324",
"217.106.106.178:7340",
"217.106.106.178:7366",
"217.106.106.178:7496",
"217.106.106.178:8888",
"217.106.106.180:7777",
"217.106.106.197:7777",
"217.106.106.200:7777",
"217.106.106.202:7777",
"217.106.106.75:7777",
"217.106.106.79:7777",
"217.106.106.82:7777",
"217.106.106.87:7017",
"217.106.106.87:7032",
"217.106.106.87:7036",
"217.106.106.87:7059",
"217.106.106.87:7067",
"217.106.106.87:7074",
"217.106.106.87:7080",
"217.106.106.87:7091",
"217.106.106.87:7113",
"217.106.106.87:7116",
"217.106.106.87:7118",
"217.106.106.87:7147",
"217.106.106.87:7158",
"217.106.106.87:7241",
"217.106.106.87:7317",
"217.106.106.87:7422",
"217.106.106.87:8146",
"217.182.199.106:7787",
"217.182.36.95:7777",
"217.182.46.69:7777",
"217.182.56.101:7777",
"217.182.66.106:7778",
"217.182.9.124:7777",
"217.198.138.142:7777",
"217.25.236.7:7777",
"217.61.0.193:7777",
"217.88.178.66:7777",
"23.101.22.59:7777",
"23.235.228.205:7771",
"23.235.228.205:7777",
"23.254.165.234:7777",
"23.92.85.250:7777",
"23.94.136.135:8888",
"23.94.96.153:5555",
"23.98.65.16:7777",
"23.99.206.196:7777",
"24.54.82.76:7777",
"24.72.7.71:7777",
"3.16.154.255:7777",
"3.236.43.125:7777",
"31.133.0.47:7777",
"31.172.86.143:7777",
"31.186.250.240:7777",
"31.202.128.69:7777",
"31.214.141.122:7777",
"31.214.160.4:7777",
"31.214.235.113:7777",
"31.220.31.19:7777",
"31.220.31.19:7778",
"31.220.31.19:7779",
"31.220.31.19:7787",
"31.220.31.19:7797",
"31.220.31.19:7799",
"31.220.31.90:7777",
"31.220.59.47:7777",
"31.31.77.202:8888",
"31.46.101.174:5732",
"34.248.18.237:7777",
"34.65.234.41:7777",
"34.67.213.27:7777",
"34.68.188.86:5454",
"34.68.188.86:7777",
"34.85.54.220:7777",
"34.89.51.255:7777",
"34.94.219.229:7777",
"34.95.182.165:7777",
"34.95.191.144:7777",
"34.95.205.24:7777",
"34.95.248.13:7777",
"35.175.66.2:7777",
"35.196.228.74:2009",
"35.197.153.168:7777",
"35.198.11.64:7777",
"35.198.152.25:7777",
"35.198.214.92:7777",
"35.198.23.149:7777",
"35.198.24.26:7777",
"35.198.25.24:7797",
"35.198.33.205:7777",
"35.198.35.234:7777",
"35.198.35.234:7778",
"35.198.40.171:7777",
"35.198.48.138:7777",
"35.198.54.9:7777",
"35.198.55.151:7777",
"35.198.56.127:7777",
"35.198.56.135:7777",
"35.198.59.66:7777",
"35.199.125.12:7778",
"35.199.125.193:7777",
"35.199.126.240:7777",
"35.199.57.88:7777",
"35.199.65.234:7777",
"35.199.80.83:7777",
"35.199.83.133:7777",
"35.199.93.109:7777",
"35.199.93.135:7777",
"35.199.99.95:7777",
"35.203.0.219:7777",
"35.203.100.13:7777",
"35.215.127.66:6666",
"35.215.127.66:7777",
"35.215.246.36:7777",
"35.234.110.110:7777",
"35.236.42.144:7777",
"35.240.140.8:7777",
"35.240.186.33:1234",
"35.240.196.165:7777",
"35.243.233.12:6666",
"35.243.233.12:9999",
"35.246.160.17:7776",
"35.246.228.44:7777",
"35.247.196.137:7777",
"35.247.199.42:7777",
"35.247.199.42:7778",
"35.247.211.67:7777",
"35.247.213.11:7777",
"35.247.215.0:7777",
"35.247.217.185:7778",
"35.247.242.210:7777",
"35.247.251.93:7777",
"35.247.92.160:7777",
"36.77.27.229:7777",
"37.120.189.179:7777",
"37.123.98.94:7777",
"37.123.98.94:7778",
"37.143.10.154:7777",
"37.143.10.154:8904",
"37.143.8.138:7777",
"37.157.197.55:7778",
"37.187.154.36:8801",
"37.187.178.96:7762",
"37.187.196.107:7777",
"37.187.205.20:7777",
"37.187.205.21:7777",
"37.187.205.25:7777",
"37.187.205.27:7777",
"37.187.222.168:7777",
"37.187.222.170:7777",
"37.187.222.170:7847",
"37.187.7.227:7777",
"37.187.7.227:7778",
"37.187.77.206:7775",
"37.187.77.206:7777",
"37.205.9.208:7777",
"37.221.193.189:7777",
"37.221.209.129:7793",
"37.221.209.216:7785",
"37.221.209.216:7817",
"37.221.209.97:7779",
"37.230.137.57:7777",
"37.230.139.37:7777",
"37.230.139.41:7777",
"37.230.139.43:7777",
"37.230.139.44:7777",
"37.230.139.49:7777",
"37.230.139.50:7777",
"37.230.139.54:7777",
"37.230.139.55:5555",
"37.230.139.55:7777",
"37.230.139.56:7777",
"37.230.139.58:7777",
"37.230.139.60:7777",
"37.230.139.61:7777",
"37.230.162.110:7777",
"37.230.162.111:7777",
"37.230.162.123:7777",
"37.230.162.179:7777",
"37.230.162.185:7777",
"37.230.162.217:7777",
"37.230.162.223:7777",
"37.230.162.232:7777",
"37.230.162.30:7777",
"37.230.162.48:7777",
"37.230.210.146:7777",
"37.230.210.174:7777",
"37.230.210.186:7777",
"37.230.210.196:7777",
"37.230.210.210:7777",
"37.230.210.231:7777",
"37.230.210.237:7777",
"37.230.210.49:7777",
"37.230.228.104:7777",
"37.230.228.106:7777",
"37.230.228.116:7777",
"37.230.228.42:7777",
"37.230.228.44:7777",
"37.252.189.76:7777",
"37.48.87.211:7777",
"37.59.130.224:7777",
"37.59.183.141:7777",
"37.59.30.67:7777",
"37.59.45.199:2460",
"37.59.45.199:2517",
"37.59.45.199:5384",
"37.59.45.199:8762",
"37.59.72.96:7777",
"37.59.72.97:7777",
"37.59.88.84:7777",
"37.59.88.85:7777",
"37.59.88.86:7777",
"37.59.88.87:7777",
"37.75.99.101:7777",
"38.107.214.212:7777",
"39.41.224.245:7777",
"40.117.98.87:28015",
"40.117.98.87:28115",
"40.83.166.238:7777",
"41.98.108.12:7777",
"43.225.188.186:7777",
"43.242.73.85:7777",
"45.11.24.100:7777",
"45.11.24.22:7777",
"45.121.211.137:7777",
"45.121.211.137:7778",
"45.121.211.18:7787",
"45.125.66.107:7711",
"45.125.66.107:7777",
"45.125.66.107:8000",
"45.125.66.151:3030",
"45.125.66.167:9955",
"45.125.66.167:9966",
"45.125.66.75:8007",
"45.125.66.77:5522",
"45.125.66.77:7722",
"45.125.66.77:7755",
"45.125.66.77:7772",
"45.125.66.77:7781",
"45.125.66.77:7799",
"45.125.66.77:8002",
"45.125.66.77:8005",
"45.125.66.77:8043",
"45.125.66.77:8855",
"45.125.66.77:9955",
"45.125.66.97:1111",
"45.125.66.97:2211",
"45.125.66.97:2233",
"45.125.66.97:4455",
"45.125.66.97:6655",
"45.125.66.97:7000",
"45.125.66.97:7710",
"45.125.66.97:7744",
"45.125.66.97:7773",
"45.125.66.97:7775",
"45.125.66.97:7777",
"45.125.66.97:7779",
"45.129.2.83:7777",
"45.162.229.208:7777",
"45.224.129.190:7777",
"45.235.98.30:28815",
"45.235.98.62:7777",
"45.235.98.65:7777",
"45.32.106.255:7777",
"45.32.145.13:7777",
"45.32.252.31:7777",
"45.35.57.217:7777",
"45.43.14.49:1111",
"45.43.14.49:2222",
"45.43.14.49:4444",
"45.43.14.49:6666",
"45.58.127.130:7780",
"45.58.127.130:7849",
"45.63.109.27:7771",
"45.63.109.77:2009",
"45.76.160.236:7777",
"45.76.183.165:7777",
"45.76.184.154:7777",
"45.77.136.23:7777",
"45.77.146.67:17771",
"45.77.163.220:7777",
"45.77.193.199:7777",
"45.77.246.240:7777",
"45.77.250.15:7777",
"45.77.55.3:7777",
"45.77.67.63:7777",
"45.77.74.59:7777",
"45.79.54.131:6666",
"45.80.172.231:7777",
"45.90.216.177:7777",
"46.101.108.221:7777",
"46.101.108.221:7778",
"46.102.116.140:7777",
"46.102.116.159:7777",
"46.102.116.166:7777",
"46.102.116.19:7777",
"46.102.116.235:7777",
"46.102.116.247:7777",
"46.102.116.248:7777",
"46.102.116.33:7777",
"46.102.116.42:7777",
"46.102.116.95:7777",
"46.105.102.97:7777",
"46.105.109.59:7777",
"46.105.109.59:7812",
"46.105.123.39:7777",
"46.105.169.128:7777",
"46.105.179.105:7777",
"46.105.180.204:7777",
"46.105.180.204:7778",
"46.105.180.204:7779",
"46.105.212.150:7775",
"46.105.212.150:7777",
"46.105.215.115:7797",
"46.105.233.108:7777",
"46.105.41.177:7777",
"46.105.43.212:1420",
"46.105.43.212:7777",
"46.105.43.212:8000",
"46.105.49.123:7777",
"46.105.52.100:7777",
"46.105.54.3:7777",
"46.105.73.83:7777",
"46.105.79.141:7777",
"46.17.44.8:7777",
"46.174.48.107:7777",
"46.174.48.119:7777",
"46.174.48.126:7777",
"46.174.48.131:7777",
"46.174.48.140:7777",
"46.174.48.149:7777",
"46.174.48.184:7777",
"46.174.48.185:7777",
"46.174.48.188:7777",
"46.174.48.194:7777",
"46.174.48.216:7777",
"46.174.48.235:7777",
"46.174.48.46:7781",
"46.174.48.46:7783",
"46.174.48.46:7792",
"46.174.48.46:7818",
"46.174.48.46:7861",
"46.174.48.50:7785",
"46.174.48.50:7789",
"46.174.48.50:7792",
"46.174.48.50:7795",
"46.174.48.50:7813",
"46.174.48.50:7816",
"46.174.48.50:7867",
"46.174.48.57:7777",
"46.174.48.88:7777",
"46.174.48.90:7777",
"46.174.48.93:7777",
"46.174.49.109:7777",
"46.174.49.113:7777",
"46.174.49.142:7777",
"46.174.49.143:7777",
"46.174.49.170:7777",
"46.174.49.224:7777",
"46.174.49.225:7777",
"46.174.49.227:7777",
"46.174.49.252:7777",
"46.174.49.47:7782",
"46.174.49.47:7783",
"46.174.49.47:7790",
"46.174.49.47:7799",
"46.174.49.47:7818",
"46.174.49.47:7835",
"46.174.49.47:7838",
"46.174.49.47:7935",
"46.174.49.48:7800",
"46.174.49.48:7907",
"46.174.49.62:7777",
"46.174.50.193:7777",
"46.174.50.20:7787",
"46.174.50.20:7795",
"46.174.50.20:7797",
"46.174.50.20:7810",
"46.174.50.20:7812",
"46.174.50.20:7820",
"46.174.50.20:7833",
"46.174.50.211:7777",
"46.174.50.223:7777",
"46.174.50.41:7788",
"46.174.50.41:7791",
"46.174.50.41:7793",
"46.174.50.41:7801",
"46.174.50.41:7884",
"46.174.50.41:7893",
"46.174.50.42:7781",
"46.174.50.42:7782",
"46.174.50.42:7790",
"46.174.50.42:7791",
"46.174.50.42:7792",
"46.174.50.42:7838",
"46.174.50.42:7847",
"46.174.50.42:7871",
"46.174.50.45:7791",
"46.174.50.45:7802",
"46.174.50.45:7814",
"46.174.50.45:7828",
"46.174.50.45:7831",
"46.174.50.45:7834",
"46.174.50.45:7845",
"46.174.50.45:7867",
"46.174.50.46:7786",
"46.174.50.46:7793",
"46.174.50.46:7811",
"46.174.50.46:7820",
"46.174.50.46:7979",
"46.174.50.48:7785",
"46.174.50.48:7800",
"46.174.50.48:7859",
"46.174.50.52:7789",
"46.174.50.52:7798",
"46.174.50.52:7820",
"46.174.50.52:7823",
"46.174.50.52:7891",
"46.174.51.123:7777",
"46.174.51.153:7777",
"46.174.51.182:7771",
"46.174.51.182:7772",
"46.174.51.189:7777",
"46.174.52.144:7777",
"46.174.52.154:7777",
"46.174.52.176:7777",
"46.174.52.219:7777",
"46.174.52.234:7777",
"46.174.52.246:7777",
"46.174.52.89:7777",
"46.174.52.96:7777",
"46.174.53.100:7777",
"46.174.53.13:7777",
"46.174.53.171:7777",
"46.174.53.176:7777",
"46.174.53.214:7777",
"46.174.53.218:7777",
"46.174.53.22:7777",
"46.174.53.247:7777",
"46.174.53.63:7777",
"46.174.53.91:7777",
"46.174.54.102:7777",
"46.174.54.113:7777",
"46.174.54.117:7777",
"46.174.54.124:7777",
"46.174.54.140:7777",
"46.174.54.167:7777",
"46.174.54.175:7777",
"46.174.54.184:7777",
"46.174.54.189:7777",
"46.174.54.18:7777",
"46.174.54.192:7777",
"46.174.54.239:7777",
"46.174.54.72:7777",
"46.174.55.11:7777",
"46.174.55.120:7777",
"46.174.55.139:7777",
"46.174.55.149:7777",
"46.174.55.168:7777",
"46.174.55.182:7777",
"46.174.55.186:7777",
"46.174.55.190:7777",
"46.174.55.203:7777",
"46.174.55.20:7777",
"46.174.55.212:7777",
"46.174.55.245:7777",
"46.174.55.30:7777",
"46.174.55.41:7777",
"46.174.55.47:7777",
"46.174.55.85:7777",
"46.174.55.87:7777",
"46.183.163.152:7777",
"46.249.47.13:7777",
"46.252.16.73:7777",
"46.254.17.211:7777",
"46.254.19.163:7700",
"46.254.19.163:7777",
"46.35.196.79:7823",
"46.39.225.193:7777",
"46.39.225.193:7778",
"46.39.225.193:7779",
"46.39.225.193:7780",
"46.39.225.193:8888",
"46.39.225.193:9999",
"46.4.154.100:7777",
"46.4.197.64:7777",
"46.4.32.36:7777",
"46.51.217.138:7777",
"46.55.3.17:7704",
"49.12.104.8:7777",
"49.12.9.20:7777",
"49.176.64.114:7778",
"49.192.59.137:7777",
"49.192.59.137:7778",
"5.1.81.104:7777",
"5.101.165.176:10380",
"5.101.165.35:10030",
"5.12.8.41:7777",
"5.133.9.55:7777",
"5.135.112.213:7777",
"5.135.112.214:7777",
"5.135.112.219:7777",
"5.135.141.7:2600",
"5.135.179.214:7777",
"5.135.202.29:7777",
"5.135.209.89:7777",
"5.135.24.181:2341",
"5.135.24.181:6666",
"5.135.24.181:7777",
"5.135.24.181:8888",
"5.152.161.49:1285",
"5.152.161.49:7777",
"5.160.103.166:7777",
"5.180.136.16:7771",
"5.188.238.52:7777",
"5.189.164.37:7777",
"5.196.112.104:7714",
"5.196.112.104:7728",
"5.196.112.105:7717",
"5.196.124.215:7777",
"5.196.143.96:7807",
"5.196.143.97:7777",
"5.196.143.97:7787",
"5.196.143.97:7797",
"5.196.143.98:7777",
"5.196.143.98:7787",
"5.196.143.98:7797",
"5.196.143.98:7807",
"5.196.143.99:7777",
"5.196.143.99:7807",
"5.196.162.103:7777",
"5.196.171.87:7777",
"5.196.214.76:7777",
"5.196.39.58:7777",
"5.196.72.69:7602",
"5.196.72.69:7777",
"5.196.72.69:7778",
"5.2.65.164:7777",
"5.206.227.177:7777",
"5.230.69.187:7777",
"5.252.116.63:7771",
"5.252.193.240:7777",
"5.253.115.3:7777",
"5.253.86.232:4581",
"5.253.86.232:4710",
"5.254.102.168:7777",
"5.254.104.131:7777",
"5.254.104.132:7777",
"5.254.104.133:7777",
"5.254.104.134:7777",
"5.254.104.135:7777",
"5.254.104.136:7777",
"5.254.104.137:7777",
"5.254.104.138:7777",
"5.254.104.139:7777",
"5.254.123.3:7777",
"5.254.123.4:7777",
"5.254.123.6:7777",
"5.254.124.35:8904",
"5.254.124.44:8904",
"5.254.124.45:8904",
"5.254.56.103:7777",
"5.254.59.112:7777",
"5.254.59.118:7777",
"5.254.59.90:7777",
"5.254.59.94:7777",
"5.254.66.104:7777",
"5.39.105.66:7777",
"5.39.27.218:7777",
"5.39.42.252:9999",
"5.39.90.156:5568",
"5.39.90.156:7101",
"5.39.90.38:7777",
"5.63.153.193:7777",
"5.63.153.193:8888",
"5.63.155.149:7777",
"5.79.70.156:7777",
"5.83.162.5:7777",
"5.83.163.101:7777",
"5.83.173.59:10040",
"5.83.173.91:10100",
"5.83.43.171:7777",
"5.83.43.215:7777",
"5.83.43.7:7777",
"5.83.43.8:7777",
"5.9.115.244:7777",
"5.9.115.244:7778",
"50.7.70.210:7777",
"51.15.43.164:7777",
"51.161.100.131:7777",
"51.161.101.199:7777",
"51.161.110.10:7777",
"51.161.31.157:7777",
"51.161.31.159:7777",
"51.161.32.214:7777",
"51.161.33.113:8888",
"51.161.34.108:7777",
"51.161.45.224:7777",
"51.161.45.225:7777",
"51.161.50.218:7777",
"51.161.50.219:7777",
"51.161.50.249:7777",
"51.161.56.254:7817",
"51.161.56.254:7827",
"51.161.57.8:6262",
"51.161.57.8:6666",
"51.161.73.168:7777",
"51.161.76.45:7777",
"51.161.76.46:7777",
"51.178.138.254:7777",
"51.178.150.134:7777",
"51.178.150.135:7777",
"51.178.170.134:7777",
"51.178.170.255:7777",
"51.178.185.230:7777",
"51.178.26.227:7771",
"51.178.50.29:7777",
"51.195.133.169:7777",
"51.195.143.132:7777",
"51.195.143.155:7777",
"51.195.143.168:7777",
"51.195.144.92:7777",
"51.195.39.72:7777",
"51.195.39.73:7777",
"51.195.39.76:7777",
"51.195.39.76:7778",
"51.195.39.77:7777",
"51.195.39.78:7777",
"51.195.39.79:7777",
"51.195.45.190:7777",
"51.195.68.248:7777",
"51.210.180.137:7777",
"51.210.182.91:7777",
"51.210.222.45:7777",
"51.222.12.20:7777",
"51.222.12.20:7878",
"51.222.12.92:7777",
"51.222.13.11:2108",
"51.222.21.128:7777",
"51.222.21.129:7777",
"51.222.21.131:7777",
"51.222.21.132:7777",
"51.222.21.133:7812",
"51.222.21.134:7777",
"51.222.21.137:7777",
"51.222.21.140:7777",
"51.222.21.141:7777",
"51.222.21.142:7777",
"51.222.31.169:7778",
"51.222.31.3:9999",
"51.222.33.112:7777",
"51.222.39.135:7777",
"51.222.50.2:7777",
"51.222.56.168:7777",
"51.222.56.175:7777",
"51.222.57.91:7777",
"51.222.9.103:7777",
"51.222.9.103:7887",
"51.222.9.103:8888",
"51.254.101.103:7777",
"51.254.120.148:7770",
"51.254.127.12:7777",
"51.254.128.21:7777",
"51.254.130.14:7777",
"51.254.139.106:7777",
"51.254.139.153:7777",
"51.254.143.231:7777",
"51.254.175.221:7777",
"51.254.175.223:7777",
"51.254.178.238:7777",
"51.254.181.90:7777",
"51.254.181.91:7777",
"51.254.21.21:7777",
"51.254.21.27:7777",
"51.254.218.50:6000",
"51.254.219.139:7777",
"51.254.31.0:7777",
"51.254.31.1:7777",
"51.254.85.134:7776",
"51.254.99.14:7777",
"51.255.131.130:7777",
"51.255.146.121:1122",
"51.255.146.121:7314",
"51.255.146.121:7777",
"51.255.175.64:7777",
"51.255.209.52:7777",
"51.255.21.243:6666",
"51.255.215.208:7817",
"51.255.238.197:7777",
"51.255.28.110:7777",
"51.255.61.5:9999",
"51.38.106.136:7777",
"51.38.114.36:7777",
"51.38.115.231:7777",
"51.38.122.59:2222",
"51.38.122.59:5555",
"51.38.122.59:7778",
"51.38.134.52:8904",
"51.38.156.218:7777",
"51.38.163.69:7777",
"51.38.188.160:7777",
"51.38.205.40:7777",
"51.38.70.254:6135",
"51.38.70.254:8888",
"51.38.87.81:7777",
"51.38.93.198:7777",
"51.68.126.166:7777",
"51.68.139.97:7777",
"51.68.173.152:7777",
"51.68.175.6:7777",
"51.68.185.100:7777",
"51.68.185.166:7777",
"51.68.188.119:7777",
"51.68.190.121:6666",
"51.68.190.121:7777",
"51.68.199.90:4500",
"51.68.204.178:7777",
"51.68.207.204:7777",
"51.68.208.47:7777",
"51.68.208.5:7777",
"51.68.70.233:7777",
"51.75.140.86:7777",
"51.75.23.114:7777",
"51.75.248.237:7777",
"51.75.26.120:7777",
"51.75.33.152:7777",
"51.75.33.153:7777",
"51.75.33.154:7777",
"51.75.37.32:7777",
"51.75.66.106:7777",
"51.75.69.199:7777",
"51.75.71.41:7777",
"51.75.72.243:7777",
"51.75.72.243:8888",
"51.77.145.120:7777",
"51.77.150.211:7777",
"51.77.150.212:7777",
"51.77.200.63:7777",
"51.77.202.171:7777",
"51.77.214.190:7777",
"51.77.214.204:7947",
"51.77.238.94:7777",
"51.77.245.129:7777",
"51.77.27.234:7718",
"51.77.52.212:7777",
"51.77.66.168:7777",
"51.79.1.168:7777",
"51.79.111.147:7777",
"51.79.111.97:7777",
"51.79.156.147:7777",
"51.79.160.215:9448",
"51.79.160.47:7777",
"51.79.161.101:7777",
"51.79.189.81:7777",
"51.79.33.245:7777",
"51.79.35.114:7777",
"51.79.35.201:7777",
"51.79.35.250:7777",
"51.79.37.19:7777",
"51.79.37.97:7777",
"51.79.49.59:7777",
"51.79.54.125:7777",
"51.79.55.156:7777",
"51.79.63.248:7777",
"51.79.65.222:7777",
"51.79.67.227:7777",
"51.79.67.236:7777",
"51.79.67.72:7777",
"51.79.67.93:7777",
"51.79.68.188:6767",
"51.79.68.250:5555",
"51.79.69.122:7777",
"51.79.69.32:7015",
"51.79.69.48:4444",
"51.79.69.48:5555",
"51.79.69.48:8888",
"51.79.7.144:7777",
"51.79.7.144:7787",
"51.79.7.144:7797",
"51.79.74.28:2501",
"51.79.8.226:7777",
"51.81.0.158:7777",
"51.81.0.6:7777",
"51.81.1.59:7787",
"51.81.101.100:7777",
"51.81.101.101:7777",
"51.81.102.79:7777",
"51.81.105.220:7807",
"51.81.105.220:7817",
"51.81.105.222:7777",
"51.81.116.125:7790",
"51.81.117.16:7777",
"51.81.117.19:7777",
"51.81.21.128:7777",
"51.81.34.116:9000",
"51.81.35.65:7777",
"51.81.48.32:4500",
"51.81.80.41:7777",
"51.81.80.66:7777",
"51.81.81.145:7750",
"51.81.81.145:7777",
"51.81.9.232:7777",
"51.81.9.233:7777",
"51.83.146.9:7777",
"51.83.166.48:4040",
"51.83.207.240:7777",
"51.83.207.241:7777",
"51.83.207.242:7777",
"51.83.207.243:7777",
"51.83.33.176:7777",
"51.83.78.208:7777",
"51.89.108.148:7777",
"51.89.108.149:7777",
"51.89.15.69:7777",
"51.89.150.180:7777",
"51.89.188.188:7777",
"51.89.188.190:7777",
"51.89.188.191:7777",
"51.89.22.60:7777",
"51.89.22.60:9999",
"51.89.235.154:7790",
"51.89.25.168:7777",
"51.89.3.96:7777",
"51.89.30.32:7777",
"51.89.33.21:7777",
"51.89.33.22:7777",
"51.89.39.177:7777",
"51.91.109.247:7777",
"51.91.122.18:7778",
"51.91.157.114:7777",
"51.91.203.177:7777",
"51.91.203.178:7777",
"51.91.203.180:7777",
"51.91.45.25:7777",
"51.91.45.28:7777",
"51.91.77.179:7777",
"51.91.8.97:9999",
"51.91.9.125:7777",
"51.91.91.91:7777",
"52.170.252.96:8080",
"52.220.35.54:7777",
"52.228.64.186:8107",
"52.230.64.200:7777",
"52.67.16.2:7777",
"52.67.201.89:7777",
"52.67.232.91:7777",
"54.169.241.45:7777",
"54.183.53.198:7777",
"54.188.53.29:7777",
"54.207.71.204:7777",
"54.233.238.62:7778",
"54.36.124.11:7777",
"54.36.126.214:7777",
"54.36.127.43:7777",
"54.36.138.181:7777",
"54.36.145.29:7777",
"54.36.188.222:7777",
"54.36.19.104:7788",
"54.36.218.100:7777",
"54.36.223.51:7777",
"54.36.223.54:7777",
"54.36.223.60:7777",
"54.36.225.202:7777",
"54.36.232.6:7777",
"54.36.239.252:7777",
"54.36.24.227:7777",
"54.36.24.231:7777",
"54.36.24.255:7777",
"54.36.90.74:7777",
"54.37.137.231:7777",
"54.37.142.72:7777",
"54.37.142.73:7777",
"54.37.142.74:7777",
"54.37.142.75:7777",
"54.37.165.60:7777",
"54.37.200.135:7777",
"54.37.201.47:7777",
"54.37.204.73:7777",
"54.37.204.73:8888",
"54.37.207.119:7777",
"54.37.244.163:7777",
"54.37.245.112:7777",
"54.37.245.170:7802",
"54.37.65.40:7777",
"54.37.75.104:420",
"54.37.75.104:7777",
"54.37.84.120:4500",
"54.37.93.28:7777",
"54.37.93.29:7777",
"54.37.93.77:7777",
"54.37.93.77:8888",
"54.38.10.194:7777",
"54.38.156.123:7777",
"54.38.156.202:7777",
"54.38.157.139:7777",
"54.38.159.56:7777",
"54.38.201.18:3502",
"54.38.201.18:5514",
"54.38.201.18:7777",
"54.38.201.18:8062",
"54.38.205.64:7777",
"54.38.205.65:7777",
"54.38.205.66:7777",
"54.38.213.75:7777",
"54.38.218.181:7777",
"54.38.219.137:7777",
"54.38.219.138:7777",
"54.38.220.134:7777",
"54.38.221.209:7777",
"54.38.221.222:7777",
"54.38.49.117:7777",
"54.38.76.81:7777",
"54.38.76.83:7777",
"54.39.105.204:7777",
"54.39.115.101:17771",
"54.39.115.96:7797",
"54.39.118.146:6666",
"54.39.118.146:7777",
"54.39.123.144:7777",
"54.39.123.144:7787",
"54.39.125.4:7777",
"54.39.125.4:7797",
"54.39.131.35:7777",
"54.39.131.45:7777",
"54.39.131.45:9999",
"54.39.137.88:7777",
"54.39.145.16:7720",
"54.39.145.16:7777",
"54.39.145.16:9999",
"54.39.147.226:7777",
"54.39.147.51:27715",
"54.39.150.197:7777",
"54.39.151.217:8888",
"54.39.167.233:7777",
"54.39.167.89:7777",
"54.39.173.43:7777",
"54.39.175.190:7787",
"54.39.175.190:7793",
"54.39.194.88:7777",
"54.39.196.70:7777",
"54.39.196.70:7797",
"54.39.196.88:7777",
"54.39.209.234:7777",
"54.39.211.121:7787",
"54.39.22.173:6666",
"54.39.22.173:7777",
"54.39.226.91:7777",
"54.39.233.83:7777",
"54.39.233.84:7777",
"54.39.233.87:7777",
"54.39.245.93:5555",
"54.39.247.141:7777",
"54.39.248.255:7777",
"54.39.248.255:7787",
"54.39.249.15:7777",
"54.39.249.1:7777",
"54.39.249.223:7777",
"54.39.249.2:7777",
"54.39.249.3:7777",
"54.39.250.53:7797",
"54.39.252.64:7780",
"54.39.252.65:7777",
"54.39.38.83:7777",
"54.39.38.83:8888",
"54.39.38.85:7676",
"54.39.38.85:8888",
"54.39.40.109:7777",
"54.39.48.124:7777",
"54.39.52.114:7777",
"54.39.68.190:6001",
"54.39.75.223:7777",
"54.39.81.56:7777",
"54.39.81.58:6666",
"54.39.81.60:5555",
"54.39.84.13:7777",
"54.39.85.166:4444",
"54.39.85.166:7777",
"54.39.85.166:8888",
"54.39.87.195:7777",
"54.39.92.28:7777",
"54.39.92.28:7787",
"54.39.92.28:7797",
"54.39.92.28:7807",
"54.39.92.29:7777",
"54.39.92.29:7787",
"54.39.92.29:7807",
"54.39.95.71:7790",
"54.39.96.30:6665",
"54.39.96.30:7775",
"54.39.98.195:7777",
"62.109.1.10:7777",
"62.113.114.7:7777",
"62.122.213.109:7777",
"62.122.213.161:7777",
"62.122.213.221:7777",
"62.122.213.28:7777",
"62.122.213.57:7777",
"62.122.213.70:7777",
"62.122.213.73:7777",
"62.122.214.12:7777",
"62.122.214.156:7777",
"62.122.214.159:7777",
"62.122.214.182:7777",
"62.122.214.204:7777",
"62.122.214.252:7777",
"62.122.214.40:7777",
"62.122.215.162:7777",
"62.122.215.207:7777",
"62.122.215.40:7777",
"62.122.215.6:7777",
"62.122.215.87:7777",
"62.122.215.92:7777",
"62.141.46.200:7777",
"62.141.46.58:7777",
"62.152.39.65:7184",
"62.152.39.65:7188",
"62.152.39.65:7261",
"62.171.132.71:7777",
"62.171.159.22:7777",
"62.171.159.22:7848",
"62.210.130.147:7777",
"62.210.56.139:7777",
"62.4.28.184:7777",
"62.72.239.64:7777",
"64.110.27.130:8152",
"64.225.47.248:1501",
"64.227.21.208:7777",
"64.44.139.110:7777",
"64.44.139.116:7777",
"64.94.101.247:7777",
"64.94.238.239:7778",
"64.94.95.244:7777",
"65.52.20.100:7777",
"66.150.121.136:7777",
"66.23.205.132:7777",
"66.70.128.207:7777",
"66.70.128.207:8787",
"66.70.132.32:7780",
"66.70.141.135:7777",
"66.70.142.121:7777",
"66.70.142.129:7777",
"66.70.142.132:7780",
"66.70.142.133:7777",
"66.70.142.133:7780",
"66.70.142.133:8000",
"66.70.156.209:7777",
"66.70.156.72:7777",
"66.70.157.100:7776",
"66.70.157.100:7777",
"66.70.157.100:7779",
"66.70.157.101:7777",
"66.70.157.103:7777",
"66.70.165.233:7780",
"66.70.165.235:7777",
"66.70.180.192:7842",
"66.70.180.192:7862",
"66.70.181.167:7777",
"66.70.181.167:7778",
"66.70.191.87:7771",
"66.70.194.206:7777",
"66.70.194.206:7787",
"66.70.199.97:7777",
"66.70.203.214:7777",
"66.70.206.195:7777",
"66.70.206.197:7777",
"66.70.206.69:7777",
"66.70.207.114:7785",
"66.70.212.84:7777",
"66.70.212.87:7777",
"66.70.212.92:27315",
"66.70.212.93:5555",
"66.70.233.112:7777",
"66.70.235.13:7777",
"66.70.242.213:7777",
"66.70.242.221:7776",
"66.70.248.36:7777",
"66.85.80.64:7777",
"67.205.162.53:7777",
"68.183.190.8:7777",
"68.183.71.48:7777",
"68.183.96.193:4444",
"69.30.193.42:7777",
"69.30.193.42:7778",
"69.85.84.14:7777",
"70.163.250.25:7777",
"74.122.192.101:7777",
"74.63.199.12:7777",
"74.91.112.121:1718",
"74.91.112.121:8002",
"74.91.112.121:8004",
"74.91.112.121:9002",
"74.91.112.121:9003",
"74.91.112.14:27115",
"74.91.112.14:7476",
"74.91.112.242:9355",
"74.91.113.51:7777",
"74.91.115.35:7777",
"74.91.119.65:8787",
"74.91.120.171:7777",
"74.91.121.214:7777",
"74.91.121.214:7787",
"74.91.122.124:7777",
"74.91.123.46:7777",
"74.91.123.58:7777",
"74.91.124.243:6262",
"74.91.124.243:9355",
"74.91.125.78:7777",
"74.91.125.78:7778",
"74.91.125.87:7777",
"74.91.127.147:7777",
"74.91.127.150:7777",
"74.91.127.178:7777",
"74.91.127.239:7777",
"74.91.127.98:6262",
"74.91.127.98:8888",
"74.91.127.98:9355",
"77.122.52.135:7777",
"77.173.155.246:7777",
"77.220.180.151:7777",
"77.220.180.161:7777",
"77.220.180.162:7777",
"77.220.180.56:7777",
"77.232.152.56:7777",
"77.83.200.47:7777",
"77.83.200.6:7777",
"77.83.201.162:7777",
"77.83.201.163:7777",
"77.83.201.166:7777",
"77.83.201.169:7777",
"77.83.201.171:7777",
"77.83.201.175:7777",
"77.83.201.180:7777",
"77.83.201.212:7777",
"77.83.201.226:7777",
"77.83.201.227:7777",
"77.83.201.229:7777",
"77.83.201.230:7777",
"77.83.201.232:7777",
"77.83.201.234:7777",
"77.83.201.245:7777",
"77.83.202.149:7777",
"77.83.202.150:7777",
"77.83.202.160:7777",
"77.83.202.169:7777",
"78.108.216.35:7777",
"78.131.88.88:7777",
"78.31.66.195:7777",
"78.47.105.1:7777",
"78.47.49.90:7777",
"78.63.38.34:7777",
"78.67.214.40:7777",
"79.133.194.18:7750",
"79.133.194.18:7756",
"79.133.194.18:7759",
"79.133.194.18:7767",
"79.133.194.18:7777",
"79.137.97.17:7777",
"79.137.97.20:7777",
"79.137.97.50:7777",
"79.137.97.55:7777",
"79.143.20.120:7777",
"79.98.29.132:7777",
"80.211.10.17:7777",
"80.211.132.171:7777",
"80.211.196.21:7777",
"80.211.40.206:7777",
"80.66.82.11:7777",
"80.72.41.158:7714",
"80.72.41.158:7751",
"80.72.41.158:7753",
"80.72.41.158:7754",
"80.72.41.158:7755",
"80.72.41.158:7756",
"80.72.41.158:7757",
"80.72.41.158:7759",
"80.72.41.158:7762",
"80.72.41.158:7763",
"80.72.41.158:7764",
"80.72.41.158:7765",
"80.72.41.158:7769",
"80.72.41.158:7770",
"80.72.41.158:7773",
"80.72.41.158:7775",
"80.72.41.158:7777",
"80.72.41.158:7778",
"80.72.41.158:7780",
"80.72.41.158:7782",
"80.72.41.158:7785",
"80.72.41.158:7786",
"80.72.41.158:7791",
"80.72.41.158:7793",
"81.169.243.167:7777",
"81.169.244.108:7777",
"81.176.176.11:7777",
"81.176.176.13:7777",
"81.176.176.15:7777",
"81.176.176.16:7777",
"81.176.176.17:7777",
"81.176.176.19:7777",
"81.176.176.20:7777",
"81.176.176.30:7777",
"81.176.176.35:7777",
"81.176.176.66:7777",
"81.176.176.68:7777",
"81.176.176.76:7777",
"81.176.176.77:7777",
"81.176.176.81:7777",
"81.4.103.173:7777",
"81.7.7.56:7777",
"82.137.5.217:7777",
"82.146.53.77:7024",
"82.146.56.85:7777",
"82.192.76.193:7777",
"82.192.76.193:7778",
"82.202.249.78:7777",
"82.208.16.132:1337",
"82.208.16.132:27996",
"82.208.16.132:28001",
"82.208.16.132:7777",
"82.208.17.10:27023",
"82.208.17.10:27066",
"82.208.17.10:27087",
"82.208.17.10:27141",
"82.208.17.10:27182",
"82.208.17.10:27255",
"82.208.17.10:27490",
"82.208.17.10:27655",
"82.208.17.10:27708",
"82.208.17.10:27787",
"82.208.17.10:27932",
"82.208.17.10:27976",
"82.208.17.192:7777",
"82.208.17.192:8888",
"82.208.17.209:7777",
"82.208.17.218:7777",
"82.208.17.47:27544",
"83.166.241.215:7777",
"83.166.245.119:7777",
"83.166.245.90:7777",
"83.222.104.6:7788",
"83.222.105.142:7660",
"83.222.105.54:9900",
"83.222.105.60:8863",
"83.222.105.60:9539",
"83.222.116.222:1111",
"83.222.116.222:3333",
"84.200.73.39:7777",
"84.239.11.44:7777",
"84.54.13.11:7777",
"84.54.13.39:7777",
"84.54.13.8:7777",
"84.54.144.144:7777",
"85.10.202.200:28017",
"85.119.149.164:7777",
"85.119.149.82:7771",
"85.119.149.82:7772",
"85.119.149.82:7773",
"85.119.149.82:7774",
"85.119.149.82:7777",
"85.131.148.71:7777",
"85.138.100.26:7777",
"85.17.194.133:8904",
"85.190.171.225:7777",
"85.214.116.25:7777",
"85.214.127.60:7777",
"85.214.255.86:7777",
"85.214.33.44:7777",
"85.25.177.15:7777",
"85.25.177.15:7778",
"85.25.177.15:7779",
"85.25.210.246:7777",
"85.48.161.226:7777",
"85.93.91.168:7777",
"86.25.40.245:7777",
"87.125.36.129:7777",
"87.229.71.245:7777",
"87.79.117.33:7777",
"87.98.132.123:7777",
"87.98.156.115:7777",
"87.98.168.44:7777",
"87.98.176.242:8388",
"87.98.176.242:8788",
"87.98.219.111:7777",
"87.98.236.108:4004",
"87.98.236.108:4028",
"87.98.236.108:7777",
"87.98.241.207:3333",
"87.98.241.207:4444",
"87.98.241.207:6666",
"87.98.241.207:7000",
"87.98.241.207:7002",
"87.98.241.207:7013",
"87.98.241.207:7771",
"87.98.241.207:7780",
"87.98.243.201:1337",
"87.98.243.201:6969",
"87.98.243.201:7006",
"87.98.243.201:7007",
"87.98.243.201:7500",
"87.98.243.201:7770",
"87.98.243.201:7777",
"87.98.243.201:7779",
"87.98.243.201:8888",
"87.98.243.201:9999",
"87.98.244.35:4444",
"87.98.244.35:5555",
"87.98.244.35:5566",
"87.98.244.35:7000",
"87.98.244.35:7003",
"87.98.244.35:8888",
"88.118.163.63:7777",
"88.198.131.209:7776",
"88.214.58.220:7777",
"88.99.185.152:7777",
"88.99.185.152:7781",
"88.99.185.152:7784",
"88.99.72.203:7777",
"88.99.85.49:7777",
"89.108.123.217:7777",
"89.108.64.164:7777",
"89.163.206.160:7777",
"89.163.227.181:7777",
"89.203.248.214:7777",
"89.215.87.57:1998",
"89.34.24.180:7777",
"89.34.24.207:7777",
"89.34.24.212:7777",
"89.34.24.214:7777",
"89.34.24.228:7777",
"89.34.25.104:7777",
"89.34.25.21:7777",
"89.34.25.30:7777",
"89.34.25.41:7777",
"89.34.25.6:7777",
"89.34.25.72:7777",
"89.38.149.148:7777",
"89.38.149.148:7778",
"89.39.14.106:7781",
"89.39.14.130:7777",
"89.39.14.24:7777",
"89.39.14.25:7777",
"89.39.14.26:7777",
"89.40.70.173:7777",
"89.40.70.176:7777",
"89.40.70.177:7777",
"89.40.70.210:7777",
"89.41.176.86:7777",
"89.42.178.202:7777",
"89.45.94.185:7777",
"89.46.123.23:7777",
"90.191.51.236:7777",
"91.121.154.28:7797",
"91.121.165.7:7777",
"91.121.174.61:7777",
"91.121.174.61:8888",
"91.121.176.53:7777",
"91.121.223.142:1222",
"91.121.223.142:1235",
"91.121.223.142:1337",
"91.121.223.142:3333",
"91.121.223.142:7575",
"91.121.223.142:7772",
"91.121.223.142:7773",
"91.121.223.142:7775",
"91.121.223.142:7777",
"91.121.223.142:7779",
"91.121.223.142:7780",
"91.121.223.142:7878",
"91.121.223.142:8085",
"91.121.223.142:8877",
"91.121.223.142:8882",
"91.121.223.142:8886",
"91.121.223.142:8887",
"91.121.223.142:8889",
"91.121.226.97:7777",
"91.121.237.128:6666",
"91.121.237.128:7777",
"91.121.237.128:7778",
"91.121.237.128:8071",
"91.121.237.128:9797",
"91.121.237.129:7777",
"91.121.237.129:7778",
"91.121.237.129:8085",
"91.121.237.130:7000",
"91.121.237.130:7772",
"91.121.237.130:7777",
"91.121.237.131:7777",
"91.121.237.131:7898",
"91.121.43.1:7777",
"91.121.54.164:7777",
"91.121.55.3:7777",
"91.121.60.15:7777",
"91.121.87.14:3462",
"91.121.87.14:3624",
"91.121.87.14:4012",
"91.121.87.14:4213",
"91.121.87.14:5482",
"91.121.87.14:5772",
"91.121.87.14:6331",
"91.121.87.14:6718",
"91.121.87.14:6808",
"91.121.87.14:6871",
"91.121.87.14:7355",
"91.121.87.14:7579",
"91.121.87.14:9057",
"91.121.87.14:9369",
"91.121.90.218:7777",
"91.121.90.218:8888",
"91.121.96.146:7777",
"91.134.127.215:7777",
"91.134.127.217:7777",
"91.134.147.154:1255",
"91.134.147.154:8800",
"91.134.156.46:7777",
"91.134.156.47:7777",
"91.134.166.72:7777",
"91.134.166.73:1333",
"91.134.166.74:7000",
"91.134.166.74:8888",
"91.134.166.76:7777",
"91.134.166.76:7778",
"91.134.166.76:8084",
"91.134.166.76:8085",
"91.134.166.77:7777",
"91.134.166.78:1337",
"91.134.166.78:7777",
"91.134.166.79:7777",
"91.134.182.88:7777",
"91.134.193.97:7799",
"91.134.207.174:7777",
"91.134.209.13:7777",
"91.134.209.21:7777",
"91.134.209.24:7777",
"91.134.209.4:7777",
"91.134.209.6:7777",
"91.134.211.177:7777",
"91.134.240.193:7777",
"91.134.250.81:7777",
"91.134.250.87:7777",
"91.134.250.93:7777",
"91.193.253.153:1719",
"91.193.253.153:7777",
"91.199.118.197:4500",
"91.210.224.23:7777",
"91.211.118.80:27700",
"91.211.244.140:7777",
"91.211.245.57:7777",
"91.227.18.55:7777",
"91.234.254.133:4500",
"91.240.85.12:7026",
"91.83.93.42:7766",
"92.115.160.228:7777",
"92.222.146.52:7777",
"92.222.193.236:7777",
"92.222.49.112:7729",
"92.222.9.64:7777",
"92.222.94.164:7777",
"92.42.44.25:7777",
"92.42.46.151:7796",
"92.42.47.106:7777",
"92.62.57.66:7777",
"92.63.203.203:7777",
"93.104.211.106:7945",
"93.114.82.101:7777",
"93.114.82.161:7777",
"93.114.82.168:7777",
"93.114.82.188:7777",
"93.114.82.189:7777",
"93.114.82.21:7777",
"93.114.82.225:7777",
"93.114.82.227:7777",
"93.114.82.235:7777",
"93.119.25.160:7777",
"93.119.25.161:7777",
"93.119.25.162:7777",
"93.119.25.163:7777",
"93.119.25.164:7777",
"93.119.25.165:7777",
"93.119.25.166:7777",
"93.119.25.167:7777",
"93.119.25.168:7777",
"93.119.25.179:7777",
"93.119.25.183:7777",
"93.119.25.184:7777",
"93.119.25.187:7777",
"93.119.25.188:7777",
"93.119.25.189:7777",
"93.119.25.190:7777",
"93.119.25.191:7777",
"93.119.25.197:7777",
"93.119.25.199:7777",
"93.119.25.31:7777",
"93.119.25.66:7777",
"93.119.26.134:7777",
"93.119.26.179:7777",
"93.119.26.203:7777",
"93.119.26.206:7777",
"93.119.26.208:7777",
"93.119.26.212:7777",
"93.119.26.214:7777",
"93.119.26.217:7777",
"93.119.26.226:7777",
"93.119.26.22:7777",
"93.119.26.230:7777",
"93.119.26.232:7777",
"93.119.26.236:7777",
"93.119.26.243:7777",
"93.119.26.249:7777",
"93.119.26.251:7777",
"93.119.26.252:7777",
"93.119.26.42:7777",
"93.119.26.90:7777",
"93.119.26.9:7777",
"93.125.121.223:7777",
"93.125.54.10:7777",
"93.157.172.40:27100",
"93.170.123.133:7810",
"93.170.123.133:7822",
"93.170.123.133:7966",
"93.170.76.34:7777",
"93.170.76.34:7778",
"93.171.179.75:1111",
"93.186.200.63:7777",
"93.190.141.69:7777",
"94.103.83.11:7777",
"94.103.83.158:7777",
"94.103.84.140:7125",
"94.103.89.35:7777",
"94.103.93.77:7777",
"94.103.94.41:7777",
"94.130.120.130:7777",
"94.130.213.170:7778",
"94.130.29.75:7777",
"94.142.139.11:7771",
"94.177.160.14:2346",
"94.177.235.195:7777",
"94.177.235.195:7778",
"94.23.111.203:6666",
"94.23.162.0:7777",
"94.23.165.138:7777",
"94.23.203.159:7715",
"94.23.208.199:1357",
"94.23.208.199:1358",
"94.23.208.199:1360",
"94.23.208.199:2457",
"94.23.208.199:2463",
"94.23.208.199:2464",
"94.23.208.199:2465",
"94.23.208.199:2466",
"94.23.208.199:2469",
"94.23.208.199:2471",
"94.23.208.199:2472",
"94.23.208.199:2473",
"94.23.208.199:2474",
"94.23.208.199:2475",
"94.23.208.199:2476",
"94.23.208.199:2478",
"94.23.208.199:2480",
"94.23.208.199:2481",
"94.23.208.199:2486",
"94.23.208.199:2488",
"94.23.208.199:2491",
"94.23.208.199:2492",
"94.23.208.199:2493",
"94.23.208.199:2494",
"94.23.208.199:2496",
"94.23.208.199:2501",
"94.23.208.199:2504",
"94.23.208.199:2506",
"94.23.208.199:2507",
"94.23.208.199:2510",
"94.23.208.199:2511",
"94.23.208.199:2512",
"94.23.208.199:2515",
"94.23.208.199:2516",
"94.23.208.199:2517",
"94.23.208.199:2518",
"94.23.208.199:2521",
"94.23.208.199:2522",
"94.23.208.199:2524",
"94.23.208.199:2527",
"94.23.208.199:2528",
"94.23.208.199:2530",
"94.23.208.199:2532",
"94.23.208.199:2533",
"94.23.208.199:2535",
"94.23.208.199:2536",
"94.23.208.199:2537",
"94.23.208.199:2538",
"94.23.208.199:2539",
"94.23.208.199:2540",
"94.23.208.199:2543",
"94.23.208.199:2550",
"94.23.208.199:2551",
"94.23.208.199:2552",
"94.23.208.199:2554",
"94.23.208.199:2555",
"94.23.208.199:2556",
"94.23.208.199:2557",
"94.23.208.199:2558",
"94.23.208.199:2560",
"94.23.208.199:2561",
"94.23.208.199:2562",
"94.23.208.199:2565",
"94.23.208.199:2566",
"94.23.208.199:2568",
"94.23.208.199:2569",
"94.23.208.199:2573",
"94.23.208.199:2574",
"94.23.208.199:2578",
"94.23.208.199:2579",
"94.23.208.199:4013",
"94.23.208.199:4015",
"94.23.208.199:4016",
"94.23.208.199:4017",
"94.23.208.199:4019",
"94.23.208.199:4045",
"94.23.208.199:4048",
"94.23.208.199:5062",
"94.23.208.199:5072",
"94.23.208.199:5074",
"94.23.208.199:5101",
"94.23.208.199:7011",
"94.23.208.199:7026",
"94.23.208.199:8002",
"94.23.208.199:8003",
"94.23.208.199:8005",
"94.23.208.199:8007",
"94.23.208.199:9547",
"94.23.208.199:9859",
"94.23.208.199:9866",
"94.23.208.199:9867",
"94.23.208.199:9868",
"94.23.208.199:9869",
"94.23.208.199:9870",
"94.23.208.199:9871",
"94.23.208.199:9873",
"94.23.208.199:9874",
"94.23.208.199:9875",
"94.23.208.199:9876",
"94.23.208.199:9877",
"94.23.208.199:9878",
"94.23.208.199:9880",
"94.23.208.199:9882",
"94.23.208.199:9883",
"94.23.208.199:9885",
"94.23.208.199:9888",
"94.23.208.199:9891",
"94.23.208.199:9892",
"94.23.208.199:9893",
"94.23.208.199:9900",
"94.23.208.199:9901",
"94.23.208.199:9904",
"94.23.208.199:9908",
"94.23.208.199:9909",
"94.23.212.191:7777",
"94.23.212.191:8085",
"94.23.252.145:7777",
"94.23.255.30:7777",
"94.23.85.133:10200",
"94.23.85.133:6611",
"94.23.85.133:7799",
"95.128.168.224:7777",
"95.148.77.240:7777",
"95.168.191.50:7777",
"95.172.92.165:7777",
"95.181.152.163:7777",
"95.181.152.198:7777",
"95.181.156.70:7777",
"95.181.158.20:7777",
"95.182.122.115:7777",
"95.213.203.74:7777",
"95.213.227.20:7777",
"95.213.236.203:7777",
"95.213.255.83:7773",
"95.213.255.83:7774",
"95.216.171.141:7776",
"95.216.171.141:7777",
"95.216.182.60:7777",
"95.216.249.153:7776",
"95.216.6.122:7042",
"95.216.6.122:7542",
"95.216.6.122:7556",
"95.217.127.169:1139",
"95.217.147.192:7777",
"95.46.199.20:7777",
"95.46.8.196:1248",
"95.46.99.190:7777",
"95.78.119.118:7777",
"96.44.147.154:7777",
"99.8.182.62:7777",
"Agsa.arsacia.ir:7777",
"amanecerzombie.es:7777",
"Amanecerzombie.es:7777",
"basdon.net:7777",
"bcv.xjgames.com.br:7777",
"Black.bugged.ro:7777",
"blue.bugged.ro:7777",
"bpg.brasilplaygames.com.br:7777",
"br.botzone.ml:7777",
"br.kestzone.cf:7777",
"br.s1.fenixzone.com:7777",
"br.s1.omegazone.net:7777",
"brp.phoenixhost.com.br:7777",
"bullzonerp.com:7777",
"ca01.heavyhost.com.br:7778",
"ca01.heavyhost.com.br:7784",
"ca01.heavyhost.com.br:7790",
"ca03.heavyhost.com.br:7792",
"ca04.heavyhost.com.br:7778",
"ca04.heavyhost.com.br:7780",
"ca04.heavyhost.com.br:7796",
"cj.crew.sk:7780",
"cj.crew.sk:7789",
"cnbderby.net:7777",
"Crimegta.com:7777",
"dm.bewz.net:7777",
"dm.fenixzone.tv:7777",
"dsz-rl.de:7777",
"ec-rp.com:7777",
"ec2-18-228-188-66.sa-east-1.compute.amazonaws.com:7777",
"eslgremoryn.xyz:7777",
"ESLGremoryN.xyz:7777",
"et.b1g.best:7777",
"Ffsg2.fun:7777",
"Flin-rp.su:7771",
"Flin-rp.su:7772",
"game.eserv.co.il:8877",
"game.samp-mobile.com:7777",
"gamers-il.com:7777",
"gra.ls-rp.net:7777",
"graj.server-pps.com:7777",
"gta-irz.com:7777",
"GTA.BLACKGUN.RO:7777",
"gta.brasil-tl.com.br:7777",
"gta.brasilnewlife.com.br:7777",
"gta.for-umm.pt:7777",
"gta.fugados.net:7812",
"gta.nebulos.net:7777",
"gta.ru:7777",
"Gta.zuldazar-realms.tk:7777",
"gtamp.world:7777",
"igtasamp.cn:7778",
"intranet.pdglobal.app:7777",
"ip.entserv.ru:7777",
"ip.legacysamp.com.br:7777",
"IP.LEGACYSAMP.COM.BR:7777",
"ip.npsamp.com.br:7777",
"IP.npsamp.com.br:7777",
"ip.sa-mp.lt:7777",
"jade.nephrite.ro:7777",
"jg-gta.com:7777",
"justnowmovie.sparrow.moe:7777",
"kingsofsa.cz:8888",
"Klingenpeitschling2.myonlineportal.at:7777",
"life-of-sa.de:7777",
"Linux4.de:7777",
"ls-stories.pl:7777",
"n32.ultra-h.com:7777",
"neucomx.com:7777",
"performancecraft.ddns.net:7777",
"play.evonix-rp.com:7777",
"play.gangwar.xyz:7777",
"play.gtamultigames.com:7777",
"play.lasventuras.net:7777",
"play.ls-rcr.com:7777",
"PLAY.LS-RCR.COM:7777",
"Play.ls-rcr.com:7777",
"play.lvcnr.xyz:7777",
"play.metropolitancityrpg.xyz:7778",
"play.mikescnr.com:7777",
"play.reborn-city.net:7777",
"play.sa-mp.nl:7777",
"play.sag.gs:7777",
"play.sfdfd.cz:7777",
"play.social-rp.org:7777",
"play.strawberries-dm.com:7777",
"play.streetzofls.com:7777",
"play.sumoserv.com:7777",
"PLAY.SUPERPARBA.EU:7777",
"play.thepilotslife.com:7777",
"play.uifserver.net:7776",
"pol-samp.com:7777",
"redzoneserver.com:7777",
"rgame.vn:7777",
"rnt.hype-zone.ro:7777",
"rp.brightsunrp.com:7777",
"rp.centerside.ga:7770",
"rp.comugamers.com:7777",
"rp.croherze.com:7777",
"rp.lawlessrp.com:7777",
"rp.nsrp.es:7777",
"rp.superdanova.com:7777",
"rp.zona0.ga:7777",
"rp2.superdanova.com:7777",
"rpg.b-hood.ro:7777",
"RPG.B-HOOD.RO:7777",
"Rpg.b-zone.ro:7777",
"rpg.b-zone.ro:7777",
"rpg.crowland.ro:7777",
"rpg.csblackdevil.com:7777",
"rpg.droll.ro:7777",
"rpg.dty.ro:7777",
"RPG.DTY.RO:7777",
"Rpg.grown.ro:7777",
"rpg.nwdgames.net:7777",
"rpg.og-times.ro:7777",
"rpg.redtimes.eu:7777",
"Rpg.starland.ro:7777",
"rpg.starland.ro:7777",
"rpg4.b-zone.ro:7777",
"ruby.nephrite.ro:7777",
"s1.deluxzone.net:7777",
"s1.dixel-rp.com:7777",
"S1.dixel-rp.com:7777",
"S1.DIXEL-RP.COM:7777",
"S1.fenixzone.com:7777",
"s1.fenixzone.com:7777",
"s1.fenixzone.tv:7777",
"s1.gta-multiplayer.cz:7777",
"s1.highwaylife.pl:7777",
"s1.kestzonebr.tk:7777",
"s1.omegazone.net:7777",
"s1.redzonerp.ga:7777",
"s2.fenixzone.com:7777",
"s2.fenixzone.tv:7777",
"s2.flin-rp.com:7772",
"s2.gta-multiplayer.cz:7777",
"s2.omegazone.net:7777",
"s3.fenixzone.com:7777",
"s3.gta-mp.cz:7777",
"s3.gta-multiplayer.cz:7777",
"s4.fenixzone.com:7777",
"S4.fenixzone.com:7777",
"s4.gta-multiplayer.cz:7777",
"s5k.fenixzone.com:7777",
"sa-arp.net:7777",
"sa-mp.me:2182",
"sa-mp.me:2201",
"sa-mp.me:2981",
"sa-mp.me:4258",
"sa-mp.me:4286",
"sa-mp.me:4641",
"sa-mp.me:5169",
"sa-mp.me:6394",
"sa-mp.me:8455",
"samp-s1.rsrl.ru:7777",
"samp-sk.com:7777",
"samp.advanced-roleplay.com.br:7777",
"samp.balkan-exclusive.com:7777",
"samp.blacklagoon.biz:7777",
"samp.bu-rp.com:7777",
"samp.ccroleplay.com:7777",
"samp.ciudad-aventura.net:7777",
"samp.csagames.com.br:7777",
"samp.daylilife.com:7777",
"samp.gotham-rp.com:7777",
"samp.grandpursuit.in:7777",
"samp.greenside.lt:7777",
"samp.gtabase.net:7777",
"samp.hellsins.xyz:7778",
"samp.hzgaming.net:7777",
"samp.juzni-vetar.tk:7777",
"samp.la-gl.com:7777",
"samp.las-venturas.lt:7777",
"samp.lawlessrp.com:7777",
"samp.liberty-reallife.de:7777",
"samp.libertycity.lt:7777",
"samp.lmg.lt:7777",
"samp.lrg.lt:7777",
"samp.ls-stories.pl:7777",
"samp.lsantos.lt:7777",
"samp.lsgyvenimas.lt:7777",
"samp.lstown.lt:7777",
"samp.luxusroleplay.com:7720",
"samp.magoslatinos.ml:7777",
"samp.mrucznik-rp.pl:7777",
"samp.neucomx.com:7777",
"samp.newgamersrp.com:7777",
"samp.ng-gaming.com:7777",
"samp.ngg.network:7777",
"samp.okplayers.com:7777",
"samp.partyserver.net:7777",
"samp.ph-rp.net:7777",
"samp.plastilino.tk:7777",
"samp.r7-rp.com:7777",
"samp.rgn.gr:7777",
"samp.rl-rp.info:7777",
"samp.rls.lt:7777",
"samp.rpg-city.de:7777",
"samp.rss-ro.com:7777",
"samp.sampmega.xyz:7777",
"samp.sanandreas.club:7777",
"samp.santosgaming.pl:7777",
"samp.sarg.lt:7777",
"Samp.saunited.net:7777",
"samp.saunited.net:7777",
"samp.sf-gaming.net:7777",
"samp.skilledg.com:7777",
"samp.sona-gaming.com:7777",
"samp.superdanova.com:8888",
"samp.teamshrimp.com:7777",
"samp.theultimateroleplay.com:7777",
"samp.turbogamingrp.com:7777",
"samp.u-rp.net:7777",
"Samp.u-rp.net:7777",
"SAMP.UK-RP.COM:7777",
"samp.uk-rp.com:7777",
"samp.union-gamers.com:7777",
"samp.unplayer.com:7777",
"samp.ustunting.com:7777",
"samp.vienna-rp.ga:7777",
"samp.xmovieserver.com:7777",
"samp.xsfserver.com:7777",
"samp.zara-rpg.com:7777",
"Samp1.net4game.com:7777",
"samp1.net4game.com:7777",
"samp1.sampmega.xyz:7777",
"samp121.samphost.com.br:8686",
"sampza.net:7777",
"Sandesmadre.com:7777",
"sasinosoft.com:7777",
"sbcsamp.com:7777",
"server.atlantis-world.net:7777",
"server.cmlv-rp.com:2600",
"server.equipetl.com:7777",
"server.evonix-rp.com:7777",
"server.garudaindonations.net:7777",
"Server.greenfieldrpg.net:7777",
"server.gsroleplay.com:7777",
"server.gtatorcidas.net:2009",
"server.hyaxe.com:7777",
"server.iorp.in:7777",
"server.kokysdm.com:7777",
"server.life-of-sa.de:7777",
"server.ls-cc.info:7777",
"server.ls-roleplay.org:7777",
"server.ls-rp.com:7777",
"server.ls-rp.es:7777",
"server.ls-rp.io:7777",
"server.lvcnr.net:7777",
"server.lyd-roleplay.de:7777",
"server.mundohispanorp.com:7777",
"server.na-rp.ro:7777",
"server.nc-roleplay.com:7777",
"server.nemesus-roleplay.de:7777",
"server.nemesus-roleplay.net:7777",
"Server.nemesus-roleplay.net:7777",
"server.nes-newlife.de:7777",
"server.nineteen-roleplay.com:7777",
"server.pursuits.xyz:7777",
"server.redcountyrp.com:7777",
"server.ro-rp.ro:7777",
"server.sa-mp.im:7777",
"server.sa-rpg.com:7777",
"server.sacnr.com:7777",
"server.sampdroid.com:7777",
"Server.sampdroid.com:7777",
"server.starrp.es:7777",
"server.wc-rp.com:7777",
"server1.loskatchorros.com.br:7777",
"server2.loskatchorros.com.br:7777",
"server28.clans.hu:7807",
"server4.loskatchorros.com.br:7777",
"serveur.gtrp.fr:3400",
"serveur.lm-rp.fr:2600",
"sf-se.net:7777",
"shrill.biz:1337",
"sod.complicit.xyz:7777",
"sp-rp.life:7777",
"svgta.me:7779",
"tircilarmekani.com:7777",
"titanhosting.ml:1111",
"titaniumgamers.es:7777",
"Tmp0.hyaxe.com:7777",
"tmp0.hyaxe.com:7777",
"topoland.zapto.org:7777",
"ulclan.com:1420",
"valakas.ru:7777",
"vn-rp.org:7777",
"vz.playserver.pro:8000",
"Wars.samp.vip:7777",
"white.bugged.ro:7777",
"White.bugged.ro:7777",
"x.gtamultigames.com:3333",
}
| openmultiplayer/web/internal/seed/seed.go/0 | {
"file_path": "openmultiplayer/web/internal/seed/seed.go",
"repo_id": "openmultiplayer",
"token_count": 63604
} | 472 |
-- RenameIndex
ALTER INDEX "Discord_accountId_key" RENAME TO "Discord.accountId_unique";
-- RenameIndex
ALTER INDEX "Discord_email_key" RENAME TO "Discord.email_unique";
-- RenameIndex
ALTER INDEX "Discord_username_key" RENAME TO "Discord.username_unique";
-- RenameIndex
ALTER INDEX "GitHub_accountId_key" RENAME TO "GitHub.accountId_unique";
-- RenameIndex
ALTER INDEX "GitHub_email_key" RENAME TO "GitHub.email_unique";
-- RenameIndex
ALTER INDEX "GitHub_username_key" RENAME TO "GitHub.username_unique";
-- RenameIndex
ALTER INDEX "Rule_name_serverId_key" RENAME TO "Rule_serverId_rule_name_index";
-- RenameIndex
ALTER INDEX "Server_ip_key" RENAME TO "Server.ip_unique";
-- RenameIndex
ALTER INDEX "User_email_key" RENAME TO "User.email_unique";
| openmultiplayer/web/prisma/migrations/20211026111831_full_text_search_indexing/migration.sql/0 | {
"file_path": "openmultiplayer/web/prisma/migrations/20211026111831_full_text_search_indexing/migration.sql",
"repo_id": "openmultiplayer",
"token_count": 290
} | 473 |
.sidebar-container a[title='Overleaf'] {
max-width: 100px;
}
| overleaf/web/.storybook/global.css/0 | {
"file_path": "overleaf/web/.storybook/global.css",
"repo_id": "overleaf",
"token_count": 25
} | 474 |
const settings = require('@overleaf/settings')
const Errors = require('../Errors/Errors')
const httpProxy = require('express-http-proxy')
const URL = require('url')
module.exports = {
call(basePath) {
if (!settings.apis.analytics) {
return (req, res, next) =>
next(
new Errors.ServiceNotConfiguredError(
'Analytics service not configured'
)
)
}
return httpProxy(settings.apis.analytics.url, {
proxyReqPathResolver(req) {
const requestPath = URL.parse(req.url).path
return `${basePath}${requestPath}`
},
proxyReqOptDecorator(proxyReqOpts, srcReq) {
proxyReqOpts.headers = {} // unset all headers
return proxyReqOpts
},
})
},
}
| overleaf/web/app/src/Features/Analytics/AnalyticsProxy.js/0 | {
"file_path": "overleaf/web/app/src/Features/Analytics/AnalyticsProxy.js",
"repo_id": "overleaf",
"token_count": 325
} | 475 |
/* 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
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let CaptchaMiddleware
const request = require('request')
const logger = require('logger-sharelatex')
const Settings = require('@overleaf/settings')
module.exports = CaptchaMiddleware = {
validateCaptcha(action) {
return function (req, res, next) {
if (
(Settings.recaptcha != null ? Settings.recaptcha.siteKey : undefined) ==
null
) {
return next()
}
if (Settings.recaptcha.disabled[action]) {
return next()
}
const response = req.body['g-recaptcha-response']
const options = {
form: {
secret: Settings.recaptcha.secretKey,
response,
},
json: true,
}
return request.post(
'https://www.google.com/recaptcha/api/siteverify',
options,
function (error, response, body) {
if (error != null) {
return next(error)
}
if (!(body != null ? body.success : undefined)) {
logger.warn(
{ statusCode: response.statusCode, body },
'failed recaptcha siteverify request'
)
return res.status(400).send({
errorReason: 'cannot_verify_user_not_robot',
message: {
text:
'Sorry, we could not verify that you are not a robot. Please check that Google reCAPTCHA is not being blocked by an ad blocker or firewall.',
},
})
} else {
return next()
}
}
)
}
},
}
| overleaf/web/app/src/Features/Captcha/CaptchaMiddleware.js/0 | {
"file_path": "overleaf/web/app/src/Features/Captcha/CaptchaMiddleware.js",
"repo_id": "overleaf",
"token_count": 853
} | 476 |
/* 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__
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let CompileManager
const Settings = require('@overleaf/settings')
const RedisWrapper = require('../../infrastructure/RedisWrapper')
const rclient = RedisWrapper.client('clsi_recently_compiled')
const ProjectGetter = require('../Project/ProjectGetter')
const ProjectRootDocManager = require('../Project/ProjectRootDocManager')
const UserGetter = require('../User/UserGetter')
const ClsiManager = require('./ClsiManager')
const Metrics = require('@overleaf/metrics')
const rateLimiter = require('../../infrastructure/RateLimiter')
module.exports = CompileManager = {
compile(project_id, user_id, options, _callback) {
if (options == null) {
options = {}
}
if (_callback == null) {
_callback = function (error) {}
}
const timer = new Metrics.Timer('editor.compile')
const callback = function (...args) {
timer.done()
return _callback(...Array.from(args || []))
}
return CompileManager._checkIfRecentlyCompiled(
project_id,
user_id,
function (error, recentlyCompiled) {
if (error != null) {
return callback(error)
}
if (recentlyCompiled) {
return callback(null, 'too-recently-compiled', [])
}
return CompileManager._checkIfAutoCompileLimitHasBeenHit(
options.isAutoCompile,
'everyone',
function (err, canCompile) {
if (!canCompile) {
return callback(null, 'autocompile-backoff', [])
}
return ProjectRootDocManager.ensureRootDocumentIsSet(
project_id,
function (error) {
if (error != null) {
return callback(error)
}
return CompileManager.getProjectCompileLimits(
project_id,
function (error, limits) {
if (error != null) {
return callback(error)
}
for (const key in limits) {
const value = limits[key]
options[key] = value
}
// Put a lower limit on autocompiles for free users, based on compileGroup
return CompileManager._checkCompileGroupAutoCompileLimit(
options.isAutoCompile,
limits.compileGroup,
function (err, canCompile) {
if (!canCompile) {
return callback(null, 'autocompile-backoff', [])
}
// only pass user_id down to clsi if this is a per-user compile
const compileAsUser = Settings.disablePerUserCompiles
? undefined
: user_id
return ClsiManager.sendRequest(
project_id,
compileAsUser,
options,
function (
error,
status,
outputFiles,
clsiServerId,
validationProblems,
stats,
timings
) {
if (error != null) {
return callback(error)
}
return callback(
null,
status,
outputFiles,
clsiServerId,
limits,
validationProblems,
stats,
timings
)
}
)
}
)
}
)
}
)
}
)
}
)
},
stopCompile(project_id, user_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return CompileManager.getProjectCompileLimits(
project_id,
function (error, limits) {
if (error != null) {
return callback(error)
}
return ClsiManager.stopCompile(project_id, user_id, limits, callback)
}
)
},
deleteAuxFiles(project_id, user_id, clsiserverid, callback) {
if (callback == null) {
callback = function (error) {}
}
return CompileManager.getProjectCompileLimits(
project_id,
function (error, limits) {
if (error != null) {
return callback(error)
}
ClsiManager.deleteAuxFiles(
project_id,
user_id,
limits,
clsiserverid,
callback
)
}
)
},
getProjectCompileLimits(project_id, callback) {
if (callback == null) {
callback = function (error, limits) {}
}
return ProjectGetter.getProject(
project_id,
{ owner_ref: 1 },
function (error, project) {
if (error != null) {
return callback(error)
}
return UserGetter.getUser(
project.owner_ref,
{ alphaProgram: 1, betaProgram: 1, features: 1 },
function (err, owner) {
if (error != null) {
return callback(error)
}
const ownerFeatures = (owner && owner.features) || {}
// put alpha users into their own compile group
if (owner && owner.alphaProgram) {
ownerFeatures.compileGroup = 'alpha'
}
return callback(null, {
timeout:
ownerFeatures.compileTimeout ||
Settings.defaultFeatures.compileTimeout,
compileGroup:
ownerFeatures.compileGroup ||
Settings.defaultFeatures.compileGroup,
})
}
)
}
)
},
COMPILE_DELAY: 1, // seconds
_checkIfRecentlyCompiled(project_id, user_id, callback) {
if (callback == null) {
callback = function (error, recentlyCompiled) {}
}
const key = `compile:${project_id}:${user_id}`
return rclient.set(
key,
true,
'EX',
this.COMPILE_DELAY,
'NX',
function (error, ok) {
if (error != null) {
return callback(error)
}
if (ok === 'OK') {
return callback(null, false)
} else {
return callback(null, true)
}
}
)
},
_checkCompileGroupAutoCompileLimit(isAutoCompile, compileGroup, callback) {
if (callback == null) {
callback = function (err, canCompile) {}
}
if (!isAutoCompile) {
return callback(null, true)
}
if (compileGroup === 'standard') {
// apply extra limits to the standard compile group
return CompileManager._checkIfAutoCompileLimitHasBeenHit(
isAutoCompile,
compileGroup,
callback
)
} else {
Metrics.inc(`auto-compile-${compileGroup}`)
return callback(null, true)
}
}, // always allow priority group users to compile
_checkIfAutoCompileLimitHasBeenHit(isAutoCompile, compileGroup, callback) {
if (callback == null) {
callback = function (err, canCompile) {}
}
if (!isAutoCompile) {
return callback(null, true)
}
Metrics.inc(`auto-compile-${compileGroup}`)
const opts = {
endpointName: 'auto_compile',
timeInterval: 20,
subjectName: compileGroup,
throttle: Settings.rateLimit.autoCompile[compileGroup] || 25,
}
return rateLimiter.addCount(opts, function (err, canCompile) {
if (err != null) {
canCompile = false
}
if (!canCompile) {
Metrics.inc(`auto-compile-${compileGroup}-limited`)
}
return callback(err, canCompile)
})
},
wordCount(project_id, user_id, file, clsiserverid, callback) {
if (callback == null) {
callback = function (error) {}
}
return CompileManager.getProjectCompileLimits(
project_id,
function (error, limits) {
if (error != null) {
return callback(error)
}
ClsiManager.wordCount(
project_id,
user_id,
file,
limits,
clsiserverid,
callback
)
}
)
},
}
| overleaf/web/app/src/Features/Compile/CompileManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Compile/CompileManager.js",
"repo_id": "overleaf",
"token_count": 4570
} | 477 |
const _ = require('underscore')
module.exports = _.template(`\
<table class="row" style="border-collapse: collapse; border-spacing: 0; display: table; padding: 0; position: relative; text-align: left; vertical-align: top; width: 100%;">
<tbody>
<tr style="padding: 0; vertical-align: top;">
<th class="small-12 columns" style="line-height: 1.3; margin: 0 auto; padding: 0; padding-bottom: 16px; padding-left: 16px; padding-right: 16px; text-align: left; width: 564px;">
<table style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3;">
<tr style="padding: 0; text-align: left; vertical-align: top;">
<th style="margin: 0; padding: 0; text-align: left;">
<% if (title) { %>
<h3 class="force-overleaf-style" style="margin: 0; color: #5D6879; font-family: Georgia, serif; font-size: 24px; font-weight: normal; line-height: 1.3; padding: 0; text-align: left; word-wrap: normal;">
<%= title %>
</h3>
<% } %>
</th>
<tr>
<td>
<p style="height: 20px; margin: 0; padding: 0;"> </p>
<% if (greeting) { %>
<p style="margin: 0 0 10px 0; padding: 0;">
<%= greeting %>
</p>
<% } %>
<% (message).forEach(function(paragraph) { %>
<p class="force-overleaf-style" style="margin: 0 0 10px 0; padding: 0;">
<%= paragraph %>
</p>
<% }) %>
</td>
</tr>
</tr>
</table>
</th>
</tr>
</tbody>
</table>
\
`)
| overleaf/web/app/src/Features/Email/Bodies/NoCTAEmailBody.js/0 | {
"file_path": "overleaf/web/app/src/Features/Email/Bodies/NoCTAEmailBody.js",
"repo_id": "overleaf",
"token_count": 809
} | 478 |
const _ = require('underscore')
const logger = require('logger-sharelatex')
const fs = require('fs')
const request = require('request')
const settings = require('@overleaf/settings')
const Async = require('async')
const FileHashManager = require('./FileHashManager')
const { File } = require('../../models/File')
const Errors = require('../Errors/Errors')
const OError = require('@overleaf/o-error')
const { promisifyAll } = require('../../util/promises')
const ONE_MIN_IN_MS = 60 * 1000
const FIVE_MINS_IN_MS = ONE_MIN_IN_MS * 5
const FileStoreHandler = {
RETRY_ATTEMPTS: 3,
uploadFileFromDisk(projectId, fileArgs, fsPath, callback) {
fs.lstat(fsPath, function (err, stat) {
if (err) {
logger.warn({ err, projectId, fileArgs, fsPath }, 'error stating file')
callback(err)
}
if (!stat) {
logger.warn(
{ projectId, fileArgs, fsPath },
'stat is not available, can not check file from disk'
)
return callback(new Error('error getting stat, not available'))
}
if (!stat.isFile()) {
logger.log(
{ projectId, fileArgs, fsPath },
'tried to upload symlink, not continuing'
)
return callback(new Error('can not upload symlink'))
}
Async.retry(
FileStoreHandler.RETRY_ATTEMPTS,
(cb, results) =>
FileStoreHandler._doUploadFileFromDisk(
projectId,
fileArgs,
fsPath,
cb
),
function (err, result) {
if (err) {
OError.tag(err, 'Error uploading file, retries failed', {
projectId,
fileArgs,
})
return callback(err)
}
callback(err, result.url, result.fileRef)
}
)
})
},
_doUploadFileFromDisk(projectId, fileArgs, fsPath, callback) {
const callbackOnce = _.once(callback)
FileHashManager.computeHash(fsPath, function (err, hashValue) {
if (err) {
return callbackOnce(err)
}
const fileRef = new File(Object.assign({}, fileArgs, { hash: hashValue }))
const fileId = fileRef._id
const readStream = fs.createReadStream(fsPath)
readStream.on('error', function (err) {
logger.warn(
{ err, projectId, fileId, fsPath },
'something went wrong on the read stream of uploadFileFromDisk'
)
callbackOnce(err)
})
readStream.on('open', function () {
const url = FileStoreHandler._buildUrl(projectId, fileId)
const opts = {
method: 'post',
uri: url,
timeout: FIVE_MINS_IN_MS,
headers: {
'X-File-Hash-From-Web': hashValue,
}, // send the hash to the filestore as a custom header so it can be checked
}
const writeStream = request(opts)
writeStream.on('error', function (err) {
logger.warn(
{ err, projectId, fileId, fsPath },
'something went wrong on the write stream of uploadFileFromDisk'
)
callbackOnce(err)
})
writeStream.on('response', function (response) {
if (![200, 201].includes(response.statusCode)) {
err = new OError(
`non-ok response from filestore for upload: ${response.statusCode}`,
{ statusCode: response.statusCode }
)
return callbackOnce(err)
}
callbackOnce(null, { url, fileRef })
}) // have to pass back an object because async.retry only accepts a single result argument
readStream.pipe(writeStream)
})
})
},
getFileStream(projectId, fileId, query, callback) {
let queryString = ''
if (query != null && query.format != null) {
queryString = `?format=${query.format}`
}
const opts = {
method: 'get',
uri: `${this._buildUrl(projectId, fileId)}${queryString}`,
timeout: FIVE_MINS_IN_MS,
headers: {},
}
if (query != null && query.range != null) {
const rangeText = query.range
if (rangeText && rangeText.match != null && rangeText.match(/\d+-\d+/)) {
opts.headers.range = `bytes=${query.range}`
}
}
const readStream = request(opts)
readStream.on('error', err =>
logger.err(
{ err, projectId, fileId, query, opts },
'error in file stream'
)
)
return callback(null, readStream)
},
getFileSize(projectId, fileId, callback) {
const url = this._buildUrl(projectId, fileId)
request.head(url, (err, res) => {
if (err) {
OError.tag(err, 'failed to get file size from filestore', {
projectId,
fileId,
})
return callback(err)
}
if (res.statusCode === 404) {
return callback(new Errors.NotFoundError('file not found in filestore'))
}
if (res.statusCode !== 200) {
logger.warn(
{ projectId, fileId, statusCode: res.statusCode },
'filestore returned non-200 response'
)
return callback(new Error('filestore returned non-200 response'))
}
const fileSize = res.headers['content-length']
callback(null, fileSize)
})
},
deleteFile(projectId, fileId, callback) {
logger.log({ projectId, fileId }, 'telling file store to delete file')
const opts = {
method: 'delete',
uri: this._buildUrl(projectId, fileId),
timeout: FIVE_MINS_IN_MS,
}
return request(opts, function (err, response) {
if (err) {
logger.warn(
{ err, projectId, fileId },
'something went wrong deleting file from filestore'
)
}
return callback(err)
})
},
deleteProject(projectId, callback) {
request(
{
method: 'delete',
uri: this._buildUrl(projectId),
timeout: FIVE_MINS_IN_MS,
},
err => {
if (err) {
return callback(
OError.tag(
err,
'something went wrong deleting a project in filestore',
{ projectId }
)
)
}
callback()
}
)
},
copyFile(oldProjectId, oldFileId, newProjectId, newFileId, callback) {
logger.log(
{ oldProjectId, oldFileId, newProjectId, newFileId },
'telling filestore to copy a file'
)
const opts = {
method: 'put',
json: {
source: {
project_id: oldProjectId,
file_id: oldFileId,
},
},
uri: this._buildUrl(newProjectId, newFileId),
timeout: FIVE_MINS_IN_MS,
}
return request(opts, function (err, response) {
if (err) {
OError.tag(
err,
'something went wrong telling filestore api to copy file',
{
oldProjectId,
oldFileId,
newProjectId,
newFileId,
}
)
return callback(err)
} else if (response.statusCode >= 200 && response.statusCode < 300) {
// successful response
return callback(null, opts.uri)
} else {
err = new OError(
`non-ok response from filestore for copyFile: ${response.statusCode}`,
{
uri: opts.uri,
statusCode: response.statusCode,
}
)
return callback(err)
}
})
},
_buildUrl(projectId, fileId) {
return (
`${settings.apis.filestore.url}/project/${projectId}` +
(fileId ? `/file/${fileId}` : '')
)
},
}
module.exports = FileStoreHandler
module.exports.promises = promisifyAll(FileStoreHandler, {
multiResult: {
uploadFileFromDisk: ['url', 'fileRef'],
},
})
| overleaf/web/app/src/Features/FileStore/FileStoreHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/FileStore/FileStoreHandler.js",
"repo_id": "overleaf",
"token_count": 3523
} | 479 |
const OError = require('@overleaf/o-error')
const logger = require('logger-sharelatex')
const metrics = require('@overleaf/metrics')
const settings = require('@overleaf/settings')
const request = require('request')
const { promisifyAll } = require('../../util/promises')
const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
const {
V1ConnectionError,
InvalidInstitutionalEmailError,
} = require('../Errors/Errors')
const InstitutionsAPI = {
getInstitutionAffiliations(institutionId, callback) {
makeAffiliationRequest(
{
method: 'GET',
path: `/api/v2/institutions/${institutionId.toString()}/affiliations`,
defaultErrorMessage: "Couldn't get institution affiliations",
},
(error, body) => callback(error, body || [])
)
},
getInstitutionAffiliationsCounts(institutionId, callback) {
makeAffiliationRequest(
{
method: 'GET',
path: `/api/v2/institutions/${institutionId.toString()}/affiliations_counts`,
defaultErrorMessage: "Couldn't get institution counts",
},
(error, body) => callback(error, body || [])
)
},
getLicencesForAnalytics(lag, queryDate, callback) {
makeAffiliationRequest(
{
method: 'GET',
path: `/api/v2/institutions/institutions_licences`,
body: { query_date: queryDate, lag },
defaultErrorMessage: 'Could not get institutions licences',
},
callback
)
},
getInstitutionLicences(institutionId, startDate, endDate, lag, callback) {
makeAffiliationRequest(
{
method: 'GET',
path: `/api/v2/institutions/${institutionId.toString()}/institution_licences`,
body: { start_date: startDate, end_date: endDate, lag },
defaultErrorMessage: "Couldn't get institution licences",
},
callback
)
},
getInstitutionNewLicences(institutionId, startDate, endDate, lag, callback) {
makeAffiliationRequest(
{
method: 'GET',
path: `/api/v2/institutions/${institutionId.toString()}/new_institution_licences`,
body: { start_date: startDate, end_date: endDate, lag },
defaultErrorMessage: "Couldn't get institution new licences",
},
callback
)
},
getUserAffiliations(userId, callback) {
makeAffiliationRequest(
{
method: 'GET',
path: `/api/v2/users/${userId.toString()}/affiliations`,
defaultErrorMessage: "Couldn't get user affiliations",
},
(error, body) => callback(error, body || [])
)
},
getUsersNeedingReconfirmationsLapsedProcessed(callback) {
makeAffiliationRequest(
{
method: 'GET',
path: '/api/v2/institutions/need_reconfirmation_lapsed_processed',
defaultErrorMessage:
'Could not get users that need reconfirmations lapsed processed',
},
(error, body) => callback(error, body || [])
)
},
addAffiliation(userId, email, affiliationOptions, callback) {
if (!callback) {
// affiliationOptions is optional
callback = affiliationOptions
affiliationOptions = {}
}
const {
university,
department,
role,
confirmedAt,
entitlement,
rejectIfBlocklisted,
} = affiliationOptions
makeAffiliationRequest(
{
method: 'POST',
path: `/api/v2/users/${userId.toString()}/affiliations`,
body: {
email,
university,
department,
role,
confirmedAt,
entitlement,
rejectIfBlocklisted,
},
defaultErrorMessage: "Couldn't create affiliation",
},
function (error, body) {
if (error) {
if (error.info && error.info.statusCode === 422) {
return callback(
new InvalidInstitutionalEmailError(error.message).withCause(error)
)
}
return callback(error)
}
if (!university) {
return callback(null, body)
}
// have notifications delete any ip matcher notifications for this university
NotificationsBuilder.ipMatcherAffiliation(userId).read(
university.id,
function (err) {
if (err) {
// log and ignore error
logger.err(
{ err },
'Something went wrong marking ip notifications read'
)
}
callback(null, body)
}
)
}
)
},
removeAffiliation(userId, email, callback) {
makeAffiliationRequest(
{
method: 'POST',
path: `/api/v2/users/${userId.toString()}/affiliations/remove`,
body: { email },
extraSuccessStatusCodes: [404], // `Not Found` responses are considered successful
defaultErrorMessage: "Couldn't remove affiliation",
},
callback
)
},
endorseAffiliation(userId, email, role, department, callback) {
makeAffiliationRequest(
{
method: 'POST',
path: `/api/v2/users/${userId.toString()}/affiliations/endorse`,
body: { email, role, department },
defaultErrorMessage: "Couldn't endorse affiliation",
},
callback
)
},
deleteAffiliations(userId, callback) {
makeAffiliationRequest(
{
method: 'DELETE',
path: `/api/v2/users/${userId.toString()}/affiliations`,
defaultErrorMessage: "Couldn't delete affiliations",
},
callback
)
},
addEntitlement(userId, email, callback) {
makeAffiliationRequest(
{
method: 'POST',
path: `/api/v2/users/${userId}/affiliations/add_entitlement`,
body: { email },
defaultErrorMessage: "Couldn't add entitlement",
},
callback
)
},
removeEntitlement(userId, email, callback) {
makeAffiliationRequest(
{
method: 'POST',
path: `/api/v2/users/${userId}/affiliations/remove_entitlement`,
body: { email },
defaultErrorMessage: "Couldn't remove entitlement",
extraSuccessStatusCodes: [404],
},
callback
)
},
sendUsersWithReconfirmationsLapsedProcessed(users, callback) {
makeAffiliationRequest(
{
method: 'POST',
path: '/api/v2/institutions/reconfirmation_lapsed_processed',
body: { users },
defaultErrorMessage:
'Could not update reconfirmation_lapsed_processed_at',
},
(error, body) => callback(error, body || [])
)
},
}
var makeAffiliationRequest = function (requestOptions, callback) {
if (!settings.apis.v1.url) {
return callback(null)
} // service is not configured
if (!requestOptions.extraSuccessStatusCodes) {
requestOptions.extraSuccessStatusCodes = []
}
request(
{
method: requestOptions.method,
url: `${settings.apis.v1.url}${requestOptions.path}`,
body: requestOptions.body,
auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass },
json: true,
timeout: 20 * 1000,
},
function (error, response, body) {
if (error) {
return callback(
new V1ConnectionError('error getting affiliations from v1').withCause(
error
)
)
}
if (response && response.statusCode >= 500) {
return callback(
new V1ConnectionError({
message: 'error getting affiliations from v1',
info: {
status: response.statusCode,
body: body,
},
})
)
}
let isSuccess = response.statusCode >= 200 && response.statusCode < 300
if (!isSuccess) {
isSuccess = requestOptions.extraSuccessStatusCodes.includes(
response.statusCode
)
}
if (!isSuccess) {
let errorMessage
if (body && body.errors) {
errorMessage = `${response.statusCode}: ${body.errors}`
} else {
errorMessage = `${requestOptions.defaultErrorMessage}: ${response.statusCode}`
}
logger.warn(
{ path: requestOptions.path, body: requestOptions.body },
errorMessage
)
return callback(
new OError(errorMessage, { statusCode: response.statusCode })
)
}
callback(null, body)
}
)
}
;[
'getInstitutionAffiliations',
'getUserAffiliations',
'addAffiliation',
'removeAffiliation',
].map(method =>
metrics.timeAsyncMethod(
InstitutionsAPI,
method,
'mongo.InstitutionsAPI',
logger
)
)
InstitutionsAPI.promises = promisifyAll(InstitutionsAPI)
module.exports = InstitutionsAPI
| overleaf/web/app/src/Features/Institutions/InstitutionsAPI.js/0 | {
"file_path": "overleaf/web/app/src/Features/Institutions/InstitutionsAPI.js",
"repo_id": "overleaf",
"token_count": 3685
} | 480 |
const { callbackify } = require('util')
const logger = require('logger-sharelatex')
const Settings = require('@overleaf/settings')
const crypto = require('crypto')
const Mailchimp = require('mailchimp-api-v3')
const OError = require('@overleaf/o-error')
const provider = getProvider()
module.exports = {
subscribe: callbackify(provider.subscribe),
unsubscribe: callbackify(provider.unsubscribe),
changeEmail: callbackify(provider.changeEmail),
promises: provider,
}
class NonFatalEmailUpdateError extends OError {
constructor(message, oldEmail, newEmail) {
super(message, { oldEmail, newEmail })
}
}
function getProvider() {
if (mailchimpIsConfigured()) {
logger.info('Using newsletter provider: mailchimp')
return makeMailchimpProvider()
} else {
logger.info('Using newsletter provider: none')
return makeNullProvider()
}
}
function mailchimpIsConfigured() {
return Settings.mailchimp != null && Settings.mailchimp.api_key != null
}
function makeMailchimpProvider() {
const mailchimp = new Mailchimp(Settings.mailchimp.api_key)
const MAILCHIMP_LIST_ID = Settings.mailchimp.list_id
return {
subscribe,
unsubscribe,
changeEmail,
}
async function subscribe(user) {
try {
const path = getSubscriberPath(user.email)
await mailchimp.put(path, {
email_address: user.email,
status: 'subscribed',
status_if_new: 'subscribed',
merge_fields: getMergeFields(user),
})
logger.info({ user }, 'finished subscribing user to newsletter')
} catch (err) {
throw OError.tag(err, 'error subscribing user to newsletter', {
userId: user._id,
})
}
}
async function unsubscribe(user, options = {}) {
try {
const path = getSubscriberPath(user.email)
if (options.delete) {
await mailchimp.delete(path)
} else {
await mailchimp.patch(path, {
status: 'unsubscribed',
merge_fields: getMergeFields(user),
})
}
logger.info(
{ user, options },
'finished unsubscribing user from newsletter'
)
} catch (err) {
if (err.status === 404 || err.status === 405) {
// silently ignore users who were never subscribed (404) or previously deleted (405)
return
}
if (err.message.includes('looks fake or invalid')) {
logger.info(
{ err, user, options },
'Mailchimp declined to unsubscribe user because it finds the email looks fake'
)
return
}
throw OError.tag(err, 'error unsubscribing user from newsletter', {
userId: user._id,
})
}
}
async function changeEmail(user, newEmail) {
const oldEmail = user.email
try {
await updateEmailInMailchimp(user, newEmail)
} catch (updateError) {
// if we failed to update the user, delete their old email address so that
// we don't leave it stuck in mailchimp
logger.info(
{ oldEmail, newEmail, updateError },
'unable to change email in newsletter, removing old mail'
)
try {
await unsubscribe(user, { delete: true })
} catch (unsubscribeError) {
// something went wrong removing the user's address
throw OError.tag(
unsubscribeError,
'error unsubscribing old email in response to email change failure',
{ oldEmail, newEmail, updateError }
)
}
if (!(updateError instanceof NonFatalEmailUpdateError)) {
throw updateError
}
}
}
async function updateEmailInMailchimp(user, newEmail) {
const oldEmail = user.email
// mailchimp doesn't give us error codes, so we have to parse the message :'(
const errors = {
'merge fields were invalid': 'user has never subscribed',
'could not be validated':
'user has previously unsubscribed or new email already exist on list',
'is already a list member': 'new email is already on mailing list',
'looks fake or invalid': 'mail looks fake to mailchimp',
}
try {
const path = getSubscriberPath(oldEmail)
await mailchimp.patch(path, {
email_address: newEmail,
merge_fields: getMergeFields(user),
})
logger.info('finished changing email in the newsletter')
} catch (err) {
// silently ignore users who were never subscribed
if (err.status === 404) {
return
}
// look through expected mailchimp errors and log if we find one
Object.keys(errors).forEach(key => {
if (err.message.includes(key)) {
const message = `unable to change email in newsletter, ${errors[key]}`
logger.info({ oldEmail, newEmail }, message)
throw new NonFatalEmailUpdateError(
message,
oldEmail,
newEmail
).withCause(err)
}
})
// if we didn't find an expected error, generate something to throw
throw OError.tag(err, 'error changing email in newsletter', {
oldEmail,
newEmail,
})
}
}
function getSubscriberPath(email) {
const emailHash = hashEmail(email)
return `/lists/${MAILCHIMP_LIST_ID}/members/${emailHash}`
}
function hashEmail(email) {
return crypto.createHash('md5').update(email.toLowerCase()).digest('hex')
}
function getMergeFields(user) {
return {
FNAME: user.first_name,
LNAME: user.last_name,
MONGO_ID: user._id.toString(),
}
}
}
function makeNullProvider() {
return {
subscribe,
unsubscribe,
changeEmail,
}
async function subscribe(user) {
logger.info(
{ user },
'Not subscribing user to newsletter because no newsletter provider is configured'
)
}
async function unsubscribe(user) {
logger.info(
{ user },
'Not unsubscribing user from newsletter because no newsletter provider is configured'
)
}
async function changeEmail(oldEmail, newEmail) {
logger.info(
{ oldEmail, newEmail },
'Not changing email in newsletter for user because no newsletter provider is configured'
)
}
}
| overleaf/web/app/src/Features/Newsletter/NewsletterManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Newsletter/NewsletterManager.js",
"repo_id": "overleaf",
"token_count": 2344
} | 481 |
const { callbackify } = require('util')
const Path = require('path')
const OError = require('@overleaf/o-error')
const { promiseMapWithLimit } = require('../../util/promises')
const { Doc } = require('../../models/Doc')
const { File } = require('../../models/File')
const DocstoreManager = require('../Docstore/DocstoreManager')
const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
const FileStoreHandler = require('../FileStore/FileStoreHandler')
const ProjectCreationHandler = require('./ProjectCreationHandler')
const ProjectDeleter = require('./ProjectDeleter')
const ProjectEntityMongoUpdateHandler = require('./ProjectEntityMongoUpdateHandler')
const ProjectEntityUpdateHandler = require('./ProjectEntityUpdateHandler')
const ProjectGetter = require('./ProjectGetter')
const ProjectLocator = require('./ProjectLocator')
const ProjectOptionsHandler = require('./ProjectOptionsHandler')
const SafePath = require('./SafePath')
const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
module.exports = {
duplicate: callbackify(duplicate),
promises: {
duplicate,
},
}
async function duplicate(owner, originalProjectId, newProjectName) {
await DocumentUpdaterHandler.promises.flushProjectToMongo(originalProjectId)
const originalProject = await ProjectGetter.promises.getProject(
originalProjectId,
{
compiler: true,
rootFolder: true,
rootDoc_id: true,
}
)
const { path: rootDocPath } = await ProjectLocator.promises.findRootDoc({
project_id: originalProjectId,
})
const originalEntries = _getFolderEntries(originalProject.rootFolder[0])
// Now create the new project, cleaning it up on failure if necessary
const newProject = await ProjectCreationHandler.promises.createBlankProject(
owner._id,
newProjectName
)
try {
await ProjectOptionsHandler.promises.setCompiler(
newProject._id,
originalProject.compiler
)
const [docEntries, fileEntries] = await Promise.all([
_copyDocs(originalEntries.docEntries, originalProject, newProject),
_copyFiles(originalEntries.fileEntries, originalProject, newProject),
])
const projectVersion = await ProjectEntityMongoUpdateHandler.promises.createNewFolderStructure(
newProject._id,
docEntries,
fileEntries
)
// Silently ignore the rootDoc in case it's not valid per the new limits.
if (
rootDocPath &&
ProjectEntityUpdateHandler.isPathValidForRootDoc(rootDocPath.fileSystem)
) {
await _setRootDoc(newProject._id, rootDocPath.fileSystem)
}
await _notifyDocumentUpdater(newProject, owner._id, {
newFiles: fileEntries,
newDocs: docEntries,
newProject: { version: projectVersion },
})
await TpdsProjectFlusher.promises.flushProjectToTpds(newProject._id)
} catch (err) {
// Clean up broken clone on error.
// Make sure we delete the new failed project, not the original one!
await ProjectDeleter.promises.deleteProject(newProject._id)
throw OError.tag(err, 'error cloning project, broken clone deleted', {
originalProjectId,
newProjectName,
newProjectId: newProject._id,
})
}
return newProject
}
function _getFolderEntries(folder, folderPath = '/') {
const docEntries = []
const fileEntries = []
const docs = folder.docs || []
const files = folder.fileRefs || []
const subfolders = folder.folders || []
for (const doc of docs) {
if (doc == null || doc._id == null) {
continue
}
const path = Path.join(folderPath, doc.name)
docEntries.push({ doc, path })
}
for (const file of files) {
if (file == null || file._id == null) {
continue
}
const path = Path.join(folderPath, file.name)
fileEntries.push({ file, path })
}
for (const subfolder of subfolders) {
if (subfolder == null || subfolder._id == null) {
continue
}
const subfolderPath = Path.join(folderPath, subfolder.name)
const subfolderEntries = _getFolderEntries(subfolder, subfolderPath)
for (const docEntry of subfolderEntries.docEntries) {
docEntries.push(docEntry)
}
for (const fileEntry of subfolderEntries.fileEntries) {
fileEntries.push(fileEntry)
}
}
return { docEntries, fileEntries }
}
async function _copyDocs(sourceEntries, sourceProject, targetProject) {
const docLinesById = await _getDocLinesForProject(sourceProject._id)
const targetEntries = []
for (const sourceEntry of sourceEntries) {
const sourceDoc = sourceEntry.doc
const path = sourceEntry.path
const doc = new Doc({ name: sourceDoc.name })
const docLines = docLinesById.get(sourceDoc._id.toString())
await DocstoreManager.promises.updateDoc(
targetProject._id.toString(),
doc._id.toString(),
docLines,
0,
{}
)
targetEntries.push({ doc, path, docLines: docLines.join('\n') })
}
return targetEntries
}
async function _getDocLinesForProject(projectId) {
const docs = await DocstoreManager.promises.getAllDocs(projectId)
const docLinesById = new Map(docs.map(doc => [doc._id, doc.lines]))
return docLinesById
}
async function _copyFiles(sourceEntries, sourceProject, targetProject) {
const targetEntries = await promiseMapWithLimit(
5,
sourceEntries,
async sourceEntry => {
const sourceFile = sourceEntry.file
const path = sourceEntry.path
const file = new File({ name: SafePath.clean(sourceFile.name) })
if (sourceFile.linkedFileData != null) {
file.linkedFileData = sourceFile.linkedFileData
}
if (sourceFile.hash != null) {
file.hash = sourceFile.hash
}
const url = await FileStoreHandler.promises.copyFile(
sourceProject._id,
sourceFile._id,
targetProject._id,
file._id
)
return { file, path, url }
}
)
return targetEntries
}
async function _setRootDoc(projectId, path) {
const { element: rootDoc } = await ProjectLocator.promises.findElementByPath({
project_id: projectId,
path,
exactCaseMatch: true,
})
await ProjectEntityUpdateHandler.promises.setRootDoc(projectId, rootDoc._id)
}
async function _notifyDocumentUpdater(project, userId, changes) {
const projectHistoryId =
project.overleaf && project.overleaf.history && project.overleaf.history.id
await DocumentUpdaterHandler.promises.updateProjectStructure(
project._id,
projectHistoryId,
userId,
changes
)
}
| overleaf/web/app/src/Features/Project/ProjectDuplicator.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectDuplicator.js",
"repo_id": "overleaf",
"token_count": 2255
} | 482 |
const ReferalHandler = require('./ReferalHandler')
const SessionManager = require('../Authentication/SessionManager')
module.exports = {
bonus(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
ReferalHandler.getReferedUsers(
userId,
(err, referedUsers, referedUserCount) => {
if (err) {
next(err)
} else {
res.render('referal/bonus', {
title: 'bonus_please_recommend_us',
refered_users: referedUsers,
refered_user_count: referedUserCount,
})
}
}
)
},
}
| overleaf/web/app/src/Features/Referal/ReferalController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Referal/ReferalController.js",
"repo_id": "overleaf",
"token_count": 277
} | 483 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-path-concat,
no-unused-vars,
node/no-deprecated-api,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* 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 HomeController
const Features = require('../../infrastructure/Features')
const Path = require('path')
const fs = require('fs')
const ErrorController = require('../Errors/ErrorController')
const SessionManager = require('../Authentication/SessionManager')
const homepageExists = fs.existsSync(
Path.resolve(__dirname + '/../../../views/external/home/v2.pug')
)
module.exports = HomeController = {
index(req, res) {
if (SessionManager.isUserLoggedIn(req.session)) {
if (req.query.scribtex_path != null) {
return res.redirect(`/project?scribtex_path=${req.query.scribtex_path}`)
} else {
return res.redirect('/project')
}
} else {
return HomeController.home(req, res)
}
},
home(req, res, next) {
if (Features.hasFeature('homepage') && homepageExists) {
return res.render('external/home/v2')
} else {
return res.redirect('/login')
}
},
externalPage(page, title) {
return function (req, res, next) {
if (next == null) {
next = function (error) {}
}
const path = Path.resolve(
__dirname + `/../../../views/external/${page}.pug`
)
return fs.exists(path, function (exists) {
// No error in this callback - old method in Node.js!
if (exists) {
return res.render(`external/${page}.pug`, { title })
} else {
return ErrorController.notFound(req, res, next)
}
})
}
},
}
| overleaf/web/app/src/Features/StaticPages/HomeController.js/0 | {
"file_path": "overleaf/web/app/src/Features/StaticPages/HomeController.js",
"repo_id": "overleaf",
"token_count": 752
} | 484 |
const async = require('async')
const RecurlyWrapper = require('./RecurlyWrapper')
const RecurlyClient = require('./RecurlyClient')
const { User } = require('../../models/User')
const { promisifyAll } = require('../../util/promises')
const logger = require('logger-sharelatex')
const SubscriptionUpdater = require('./SubscriptionUpdater')
const LimitationsManager = require('./LimitationsManager')
const EmailHandler = require('../Email/EmailHandler')
const PlansLocator = require('./PlansLocator')
const SubscriptionHelper = require('./SubscriptionHelper')
const SubscriptionHandler = {
validateNoSubscriptionInRecurly(userId, callback) {
if (callback == null) {
callback = function () {}
}
RecurlyWrapper.listAccountActiveSubscriptions(
userId,
function (error, subscriptions) {
if (subscriptions == null) {
subscriptions = []
}
if (error != null) {
return callback(error)
}
if (subscriptions.length > 0) {
SubscriptionUpdater.syncSubscription(
subscriptions[0],
userId,
function (error) {
if (error != null) {
return callback(error)
}
callback(null, false)
}
)
} else {
callback(null, true)
}
}
)
},
createSubscription(user, subscriptionDetails, recurlyTokenIds, callback) {
SubscriptionHandler.validateNoSubscriptionInRecurly(
user._id,
function (error, valid) {
if (error != null) {
return callback(error)
}
if (!valid) {
return callback(new Error('user already has subscription in recurly'))
}
RecurlyWrapper.createSubscription(
user,
subscriptionDetails,
recurlyTokenIds,
function (error, recurlySubscription) {
if (error != null) {
return callback(error)
}
return SubscriptionUpdater.syncSubscription(
recurlySubscription,
user._id,
function (error) {
if (error != null) {
return callback(error)
}
return callback()
}
)
}
)
}
)
},
updateSubscription(user, planCode, couponCode, callback) {
LimitationsManager.userHasV2Subscription(
user,
function (err, hasSubscription, subscription) {
if (err) {
logger.warn(
{ err, user_id: user._id, hasSubscription },
'there was an error checking user v2 subscription'
)
}
if (!hasSubscription) {
return callback()
} else {
return async.series(
[
function (cb) {
if (couponCode == null) {
return cb()
}
RecurlyWrapper.getSubscription(
subscription.recurlySubscription_id,
{ includeAccount: true },
function (err, usersSubscription) {
if (err != null) {
return cb(err)
}
RecurlyWrapper.redeemCoupon(
usersSubscription.account.account_code,
couponCode,
cb
)
}
)
},
function (cb) {
let changeAtTermEnd
const currentPlan = PlansLocator.findLocalPlanInSettings(
subscription.planCode
)
const newPlan = PlansLocator.findLocalPlanInSettings(planCode)
if (currentPlan && newPlan) {
changeAtTermEnd = SubscriptionHelper.shouldPlanChangeAtTermEnd(
currentPlan,
newPlan
)
} else {
logger.error(
{ currentPlan: subscription.planCode, newPlan: planCode },
'unable to locate both plans in settings'
)
return cb(
new Error('unable to locate both plans in settings')
)
}
const timeframe = changeAtTermEnd ? 'term_end' : 'now'
RecurlyClient.changeSubscriptionByUuid(
subscription.recurlySubscription_id,
{ planCode: planCode, timeframe: timeframe },
function (error, subscriptionChange) {
if (error != null) {
return cb(error)
}
// v2 recurly API wants a UUID, but UUID isn't included in the subscription change response
// we got the UUID from the DB using userHasV2Subscription() - it is the only property
// we need to be able to build a 'recurlySubscription' object for syncSubscription()
SubscriptionHandler.syncSubscription(
{ uuid: subscription.recurlySubscription_id },
user._id,
cb
)
}
)
},
],
callback
)
}
}
)
},
cancelPendingSubscriptionChange(user, callback) {
LimitationsManager.userHasV2Subscription(
user,
function (err, hasSubscription, subscription) {
if (err) {
return callback(err)
}
if (hasSubscription) {
RecurlyClient.removeSubscriptionChangeByUuid(
subscription.recurlySubscription_id,
function (error) {
if (error != null) {
return callback(error)
}
callback()
}
)
} else {
callback()
}
}
)
},
cancelSubscription(user, callback) {
LimitationsManager.userHasV2Subscription(
user,
function (err, hasSubscription, subscription) {
if (err) {
logger.warn(
{ err, user_id: user._id, hasSubscription },
'there was an error checking user v2 subscription'
)
}
if (hasSubscription) {
RecurlyClient.cancelSubscriptionByUuid(
subscription.recurlySubscription_id,
function (error) {
if (error != null) {
return callback(error)
}
const emailOpts = {
to: user.email,
first_name: user.first_name,
}
const ONE_HOUR_IN_MS = 1000 * 60 * 60
setTimeout(
() =>
EmailHandler.sendEmail(
'canceledSubscription',
emailOpts,
err => {
if (err != null) {
logger.warn(
{ err },
'failed to send confirmation email for subscription cancellation'
)
}
}
),
ONE_HOUR_IN_MS
)
callback()
}
)
} else {
callback()
}
}
)
},
reactivateSubscription(user, callback) {
LimitationsManager.userHasV2Subscription(
user,
function (err, hasSubscription, subscription) {
if (err) {
logger.warn(
{ err, user_id: user._id, hasSubscription },
'there was an error checking user v2 subscription'
)
}
if (hasSubscription) {
RecurlyClient.reactivateSubscriptionByUuid(
subscription.recurlySubscription_id,
function (error) {
if (error != null) {
return callback(error)
}
EmailHandler.sendEmail(
'reactivatedSubscription',
{ to: user.email },
err => {
if (err != null) {
logger.warn(
{ err },
'failed to send reactivation confirmation email'
)
}
}
)
callback()
}
)
} else {
callback()
}
}
)
},
syncSubscription(recurlySubscription, requesterData, callback) {
RecurlyWrapper.getSubscription(
recurlySubscription.uuid,
{ includeAccount: true },
function (error, recurlySubscription) {
if (error != null) {
return callback(error)
}
User.findById(
recurlySubscription.account.account_code,
{ _id: 1 },
function (error, user) {
if (error != null) {
return callback(error)
}
if (user == null) {
return callback(new Error('no user found'))
}
SubscriptionUpdater.syncSubscription(
recurlySubscription,
user != null ? user._id : undefined,
requesterData,
callback
)
}
)
}
)
},
// attempt to collect past due invoice for customer. Only do that when a) the
// customer is using Paypal and b) there is only one past due invoice.
// This is used because Recurly doesn't always attempt collection of paast due
// invoices after Paypal billing info were updated.
attemptPaypalInvoiceCollection(recurlyAccountCode, callback) {
RecurlyWrapper.getBillingInfo(recurlyAccountCode, (error, billingInfo) => {
if (error) {
return callback(error)
}
if (!billingInfo.paypal_billing_agreement_id) {
// this is not a Paypal user
return callback()
}
RecurlyWrapper.getAccountPastDueInvoices(
recurlyAccountCode,
(error, pastDueInvoices) => {
if (error) {
return callback(error)
}
if (pastDueInvoices.length !== 1) {
// no past due invoices, or more than one. Ignore.
return callback()
}
RecurlyWrapper.attemptInvoiceCollection(
pastDueInvoices[0].invoice_number,
callback
)
}
)
})
},
extendTrial(subscription, daysToExend, callback) {
return RecurlyWrapper.extendTrial(
subscription.recurlySubscription_id,
daysToExend,
callback
)
},
}
SubscriptionHandler.promises = promisifyAll(SubscriptionHandler)
module.exports = SubscriptionHandler
| overleaf/web/app/src/Features/Subscription/SubscriptionHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionHandler.js",
"repo_id": "overleaf",
"token_count": 5647
} | 485 |
/* eslint-disable
camelcase,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { Project } = require('../../models/Project')
const OError = require('@overleaf/o-error')
const ProjectDetailsHandler = require('../Project/ProjectDetailsHandler')
const ProjectOptionsHandler = require('../Project/ProjectOptionsHandler')
const ProjectRootDocManager = require('../Project/ProjectRootDocManager')
const ProjectUploadManager = require('../Uploads/ProjectUploadManager')
const FileWriter = require('../../infrastructure/FileWriter')
const async = require('async')
const fs = require('fs')
const util = require('util')
const logger = require('logger-sharelatex')
const request = require('request')
const requestPromise = require('request-promise-native')
const settings = require('@overleaf/settings')
const uuid = require('uuid')
const Errors = require('../Errors/Errors')
const _ = require('underscore')
const TemplatesManager = {
createProjectFromV1Template(
brandVariationId,
compiler,
mainFile,
templateId,
templateName,
templateVersionId,
user_id,
imageName,
_callback
) {
const callback = _.once(_callback)
const zipUrl = `${settings.apis.v1.url}/api/v1/sharelatex/templates/${templateVersionId}`
const zipReq = request(zipUrl, {
auth: {
user: settings.apis.v1.user,
pass: settings.apis.v1.pass,
},
timeout: 60 * 1000,
})
zipReq.on('error', function (err) {
logger.warn({ err }, 'error getting zip from template API')
return callback(err)
})
return FileWriter.ensureDumpFolderExists(function (err) {
if (err != null) {
return callback(err)
}
const projectName = ProjectDetailsHandler.fixProjectName(templateName)
const dumpPath = `${settings.path.dumpFolder}/${uuid.v4()}`
const writeStream = fs.createWriteStream(dumpPath)
const attributes = {
fromV1TemplateId: templateId,
fromV1TemplateVersionId: templateVersionId,
}
writeStream.on('close', function () {
if (zipReq.response.statusCode !== 200) {
logger.warn(
{ uri: zipUrl, statusCode: zipReq.response.statusCode },
'non-success code getting zip from template API'
)
return callback(new Error('get zip failed'))
}
return ProjectUploadManager.createProjectFromZipArchiveWithName(
user_id,
projectName,
dumpPath,
attributes,
function (err, project) {
if (err != null) {
OError.tag(err, 'problem building project from zip', {
zipReq,
})
return callback(err)
}
return async.series(
[
cb => TemplatesManager._setCompiler(project._id, compiler, cb),
cb => TemplatesManager._setImage(project._id, imageName, cb),
cb => TemplatesManager._setMainFile(project._id, mainFile, cb),
cb =>
TemplatesManager._setBrandVariationId(
project._id,
brandVariationId,
cb
),
],
function (err) {
if (err != null) {
return callback(err)
}
fs.unlink(dumpPath, function (err) {
if (err != null) {
return logger.err({ err }, 'error unlinking template zip')
}
})
const update = {
fromV1TemplateId: templateId,
fromV1TemplateVersionId: templateVersionId,
}
return Project.updateOne(
{ _id: project._id },
update,
{},
function (err) {
if (err != null) {
return callback(err)
}
return callback(null, project)
}
)
}
)
}
)
})
return zipReq.pipe(writeStream)
})
},
_setCompiler(project_id, compiler, callback) {
if (compiler == null) {
return callback()
}
return ProjectOptionsHandler.setCompiler(project_id, compiler, callback)
},
_setImage(project_id, imageName, callback) {
if (!imageName) {
imageName = 'wl_texlive:2018.1'
}
return ProjectOptionsHandler.setImageName(project_id, imageName, callback)
},
_setMainFile(project_id, mainFile, callback) {
if (mainFile == null) {
return callback()
}
return ProjectRootDocManager.setRootDocFromName(
project_id,
mainFile,
callback
)
},
_setBrandVariationId(project_id, brandVariationId, callback) {
if (brandVariationId == null) {
return callback()
}
return ProjectOptionsHandler.setBrandVariationId(
project_id,
brandVariationId,
callback
)
},
promises: {
async fetchFromV1(templateId) {
const { body, statusCode } = await requestPromise({
baseUrl: settings.apis.v1.url,
url: `/api/v2/templates/${templateId}`,
method: 'GET',
auth: {
user: settings.apis.v1.user,
pass: settings.apis.v1.pass,
sendImmediately: true,
},
resolveWithFullResponse: true,
simple: false,
json: true,
timeout: 60 * 1000,
})
if (statusCode === 404) {
throw new Errors.NotFoundError()
}
if (statusCode !== 200) {
logger.warn(
{ templateId },
"[TemplateMetrics] Couldn't fetch template data from v1"
)
throw new Error("Couldn't fetch template data from v1")
}
return body
},
},
}
TemplatesManager.fetchFromV1 = util.callbackify(
TemplatesManager.promises.fetchFromV1
)
module.exports = TemplatesManager
| overleaf/web/app/src/Features/Templates/TemplatesManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Templates/TemplatesManager.js",
"repo_id": "overleaf",
"token_count": 2831
} | 486 |
/* 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
*/
let ProjectUploadController
const logger = require('logger-sharelatex')
const metrics = require('@overleaf/metrics')
const fs = require('fs')
const Path = require('path')
const FileSystemImportManager = require('./FileSystemImportManager')
const ProjectUploadManager = require('./ProjectUploadManager')
const SessionManager = require('../Authentication/SessionManager')
const Settings = require('@overleaf/settings')
const { InvalidZipFileError } = require('./ArchiveErrors')
const multer = require('multer')
const upload = multer({
dest: Settings.path.uploadFolder,
limits: {
fileSize: Settings.maxUploadSize,
},
})
module.exports = ProjectUploadController = {
uploadProject(req, res, next) {
const timer = new metrics.Timer('project-upload')
const user_id = SessionManager.getLoggedInUserId(req.session)
const { originalname, path } = req.file
const name = Path.basename(originalname, '.zip')
return ProjectUploadManager.createProjectFromZipArchive(
user_id,
name,
path,
function (error, project) {
fs.unlink(path, function () {})
timer.done()
if (error != null) {
logger.error(
{ err: error, filePath: path, fileName: name },
'error uploading project'
)
if (error instanceof InvalidZipFileError) {
return res.status(422).json({
success: false,
error: req.i18n.translate(error.message),
})
} else {
return res.status(500).json({
success: false,
error: req.i18n.translate('upload_failed'),
})
}
} else {
return res.send({ success: true, project_id: project._id })
}
}
)
},
uploadFile(req, res, next) {
const timer = new metrics.Timer('file-upload')
const name = req.file != null ? req.file.originalname : undefined
const path = req.file != null ? req.file.path : undefined
const project_id = req.params.Project_id
const { folder_id } = req.query
if (name == null || name.length === 0 || name.length > 150) {
logger.err(
{ projectId: project_id, fileName: name },
'bad name when trying to upload file'
)
return res.status(422).send({
success: false,
error: 'invalid_filename',
})
}
const user_id = SessionManager.getLoggedInUserId(req.session)
return FileSystemImportManager.addEntity(
user_id,
project_id,
folder_id,
name,
path,
true,
function (error, entity) {
fs.unlink(path, function () {})
timer.done()
if (error != null) {
logger.error(
{
err: error,
projectId: project_id,
filePath: path,
fileName: name,
folderId: folder_id,
},
'error uploading file'
)
if (error.name === 'InvalidNameError') {
return res.status(422).send({
success: false,
error: 'invalid_filename',
})
} else if (error.message === 'project_has_too_many_files') {
return res.status(422).send({
success: false,
error: 'project_has_too_many_files',
})
} else {
return res.status(422).send({ success: false })
}
} else {
return res.send({
success: true,
entity_id: entity != null ? entity._id : undefined,
entity_type: entity != null ? entity.type : undefined,
})
}
}
)
},
multerMiddleware(req, res, next) {
if (upload == null) {
return res
.status(500)
.json({ success: false, error: req.i18n.translate('upload_failed') })
}
return upload.single('qqfile')(req, res, function (err) {
if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') {
return res
.status(422)
.json({ success: false, error: req.i18n.translate('file_too_large') })
}
return next(err)
})
},
}
| overleaf/web/app/src/Features/Uploads/ProjectUploadController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Uploads/ProjectUploadController.js",
"repo_id": "overleaf",
"token_count": 1994
} | 487 |
const UserGetter = require('./UserGetter')
const OError = require('@overleaf/o-error')
const UserSessionsManager = require('./UserSessionsManager')
const logger = require('logger-sharelatex')
const Settings = require('@overleaf/settings')
const AuthenticationController = require('../Authentication/AuthenticationController')
const SessionManager = require('../Authentication/SessionManager')
const _ = require('lodash')
const UserPagesController = {
registerPage(req, res) {
const sharedProjectData = {
project_name: req.query.project_name,
user_first_name: req.query.user_first_name,
}
const newTemplateData = {}
if (req.session.templateData != null) {
newTemplateData.templateName = req.session.templateData.templateName
}
res.render('user/register', {
title: 'register',
sharedProjectData,
newTemplateData,
samlBeta: req.session.samlBeta,
})
},
loginPage(req, res) {
// if user is being sent to /login with explicit redirect (redir=/foo),
// such as being sent from the editor to /login, then set the redirect explicitly
if (
req.query.redir != null &&
AuthenticationController._getRedirectFromSession(req) == null
) {
AuthenticationController.setRedirectInSession(req, req.query.redir)
}
res.render('user/login', {
title: 'login',
})
},
/**
* Landing page for users who may have received one-time login
* tokens from the read-only maintenance site.
*
* We tell them that Overleaf is back up and that they can login normally.
*/
oneTimeLoginPage(req, res, next) {
res.render('user/one_time_login')
},
logoutPage(req, res) {
res.render('user/logout')
},
renderReconfirmAccountPage(req, res) {
const pageData = {
reconfirm_email: req.session.reconfirm_email,
}
// when a user must reconfirm their account
res.render('user/reconfirm', pageData)
},
settingsPage(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const reconfirmationRemoveEmail = req.query.remove
// SSO
const ssoError = req.session.ssoError
if (ssoError) {
delete req.session.ssoError
}
// Institution SSO
let institutionLinked = _.get(req.session, ['saml', 'linked'])
if (institutionLinked) {
// copy object if exists because _.get does not
institutionLinked = Object.assign(
{
hasEntitlement: _.get(req.session, ['saml', 'hasEntitlement']),
},
institutionLinked
)
}
const samlError = _.get(req.session, ['saml', 'error'])
const institutionEmailNonCanonical = _.get(req.session, [
'saml',
'emailNonCanonical',
])
const institutionRequestedEmail = _.get(req.session, [
'saml',
'requestedEmail',
])
const reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
delete req.session.saml
let shouldAllowEditingDetails = true
if (Settings.ldap && Settings.ldap.updateUserDetailsOnLogin) {
shouldAllowEditingDetails = false
}
if (Settings.saml && Settings.saml.updateUserDetailsOnLogin) {
shouldAllowEditingDetails = false
}
const oauthProviders = Settings.oauthProviders || {}
UserGetter.getUser(userId, (err, user) => {
if (err != null) {
return next(err)
}
res.render('user/settings', {
title: 'account_settings',
user,
hasPassword: !!user.hashedPassword,
shouldAllowEditingDetails,
languages: Settings.languages,
accountSettingsTabActive: true,
oauthProviders: UserPagesController._translateProviderDescriptions(
oauthProviders,
req
),
oauthUseV2: Settings.oauthUseV2 || false,
institutionLinked,
samlError,
institutionEmailNonCanonical:
institutionEmailNonCanonical && institutionRequestedEmail
? institutionEmailNonCanonical
: undefined,
reconfirmedViaSAML,
reconfirmationRemoveEmail,
samlBeta: req.session.samlBeta,
ssoError: ssoError,
thirdPartyIds: UserPagesController._restructureThirdPartyIds(user),
})
})
},
sessionsPage(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
logger.log({ userId: user._id }, 'loading sessions page')
UserSessionsManager.getAllUserSessions(
user,
[req.sessionID],
(err, sessions) => {
if (err != null) {
OError.tag(err, 'error getting all user sessions', {
userId: user._id,
})
return next(err)
}
res.render('user/sessions', {
title: 'sessions',
sessions,
})
}
)
},
_restructureThirdPartyIds(user) {
// 3rd party identifiers are an array of objects
// this turn them into a single object, which
// makes data easier to use in template
if (
!user.thirdPartyIdentifiers ||
user.thirdPartyIdentifiers.length === 0
) {
return null
}
return user.thirdPartyIdentifiers.reduce((obj, identifier) => {
obj[identifier.providerId] = identifier.externalUserId
return obj
}, {})
},
_translateProviderDescriptions(providers, req) {
const result = {}
if (providers) {
for (const provider in providers) {
const data = providers[provider]
data.description = req.i18n.translate(
data.descriptionKey,
Object.assign({}, data.descriptionOptions)
)
result[provider] = data
}
}
return result
},
}
module.exports = UserPagesController
| overleaf/web/app/src/Features/User/UserPagesController.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserPagesController.js",
"repo_id": "overleaf",
"token_count": 2243
} | 488 |
const bodyParser = require('body-parser')
const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler')
function isBodyParserError(nextArg) {
if (nextArg instanceof Error) {
return (
nextArg.statusCode &&
nextArg.statusCode >= 400 &&
nextArg.statusCode < 600
)
}
return false
}
const wrapBodyParser = method => opts => {
const middleware = bodyParser[method](opts)
return (req, res, next) => {
middleware(req, res, nextArg => {
if (isBodyParserError(nextArg)) {
return HttpErrorHandler.handleErrorByStatusCode(
req,
res,
nextArg,
nextArg.statusCode
)
}
next(nextArg)
})
}
}
module.exports = {
urlencoded: wrapBodyParser('urlencoded'),
json: wrapBodyParser('json'),
}
| overleaf/web/app/src/infrastructure/BodyParserWrapper.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/BodyParserWrapper.js",
"repo_id": "overleaf",
"token_count": 326
} | 489 |
const Queue = require('bull')
const Settings = require('@overleaf/settings')
// Bull will keep a fixed number of the most recently completed jobs. This is
// useful to inspect recently completed jobs. The bull prometheus exporter also
// uses the completed job records to report on job duration.
const MAX_COMPLETED_JOBS_RETAINED = 10000
const MAX_FAILED_JOBS_RETAINED = 50000
const queues = {}
function getAnalyticsEventsQueue() {
if (Settings.analytics.enabled) {
return getOrCreateQueue('analytics-events')
}
}
function getAnalyticsEditingSessionsQueue() {
if (Settings.analytics.enabled) {
return getOrCreateQueue('analytics-editing-sessions')
}
}
function getAnalyticsUserPropertiesQueue() {
if (Settings.analytics.enabled) {
return getOrCreateQueue('analytics-user-properties')
}
}
function getOnboardingEmailsQueue() {
return getOrCreateQueue('emails-onboarding')
}
function getPostRegistrationAnalyticsQueue() {
return getOrCreateQueue('post-registration-analytics')
}
function getOrCreateQueue(queueName, defaultJobOptions) {
if (!queues[queueName]) {
queues[queueName] = new Queue(queueName, {
redis: Settings.redis.queues,
defaultJobOptions: {
removeOnComplete: MAX_COMPLETED_JOBS_RETAINED,
removeOnFail: MAX_FAILED_JOBS_RETAINED,
attempts: 11,
backoff: {
type: 'exponential',
delay: 3000,
},
},
})
}
return queues[queueName]
}
module.exports = {
getAnalyticsEventsQueue,
getAnalyticsEditingSessionsQueue,
getAnalyticsUserPropertiesQueue,
getOnboardingEmailsQueue,
getPostRegistrationAnalyticsQueue,
}
| overleaf/web/app/src/infrastructure/Queues.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/Queues.js",
"repo_id": "overleaf",
"token_count": 566
} | 490 |
const mongoose = require('../infrastructure/Mongoose')
const { SubscriptionSchema } = require('./Subscription')
const { Schema } = mongoose
const { ObjectId } = Schema
const DeleterDataSchema = new Schema(
{
deleterId: { type: ObjectId, ref: 'User' },
deleterIpAddress: { type: String },
deletedAt: {
type: Date,
default() {
return new Date()
},
},
},
{ _id: false }
)
const DeletedSubscriptionSchema = new Schema(
{
deleterData: DeleterDataSchema,
subscription: SubscriptionSchema,
},
{ collection: 'deletedSubscriptions' }
)
exports.DeletedSubscription = mongoose.model(
'DeletedSubscription',
DeletedSubscriptionSchema
)
exports.DeletedSubscriptionSchema = DeletedSubscriptionSchema
| overleaf/web/app/src/models/DeletedSubscription.js/0 | {
"file_path": "overleaf/web/app/src/models/DeletedSubscription.js",
"repo_id": "overleaf",
"token_count": 279
} | 491 |
const mongoose = require('../infrastructure/Mongoose')
const { Schema } = mongoose
const _ = require('lodash')
const MIN_NAME_LENGTH = 3
const MAX_NAME_LENGTH = 200
const MIN_VARIANT_NAME_LENGTH = 3
const MAX_VARIANT_NAME_LENGTH = 255
const NAME_REGEX = /^[a-zA-Z0-9\-_]+$/
const RolloutPercentType = {
type: Number,
default: 0,
min: [0, 'Rollout percentage must be between 0 and 100, got {VALUE}'],
max: [100, 'Rollout percentage must be between 0 and 100, got {VALUE}'],
required: true,
}
const VariantSchema = new Schema(
{
name: {
type: String,
minLength: MIN_VARIANT_NAME_LENGTH,
maxLength: MAX_VARIANT_NAME_LENGTH,
required: true,
validate: {
validator: function (input) {
return input !== null && input !== 'default' && NAME_REGEX.test(input)
},
message: `invalid, cannot be 'default' and must match: ${NAME_REGEX}, got {VALUE}`,
},
},
active: {
type: Boolean,
default: true,
required: true,
},
rolloutPercent: RolloutPercentType,
rolloutStripes: [
{
start: RolloutPercentType,
end: RolloutPercentType,
},
],
},
{ _id: false }
)
const VersionSchema = new Schema(
{
versionNumber: {
type: Number,
default: 1,
min: [1, 'must be 1 or higher, got {VALUE}'],
required: true,
},
phase: {
type: String,
default: 'alpha',
enum: ['alpha', 'beta', 'release'],
required: true,
},
active: {
type: Boolean,
default: true,
required: true,
},
variants: [VariantSchema],
},
{ _id: false }
)
const SplitTestSchema = new Schema({
name: {
type: String,
minLength: MIN_NAME_LENGTH,
maxlength: MAX_NAME_LENGTH,
required: true,
unique: true,
validate: {
validator: function (input) {
return input !== null && NAME_REGEX.test(input)
},
message: `invalid, must match: ${NAME_REGEX}`,
},
},
versions: [VersionSchema],
forbidReleasePhase: {
type: Boolean,
required: false,
},
})
SplitTestSchema.methods.getCurrentVersion = function () {
if (this.versions && this.versions.length > 0) {
return _.maxBy(this.versions, 'versionNumber')
} else {
return undefined
}
}
SplitTestSchema.methods.getVersion = function (versionNumber) {
return _.find(this.versions || [], {
versionNumber,
})
}
module.exports = {
SplitTest: mongoose.model('SplitTest', SplitTestSchema),
SplitTestSchema,
}
| overleaf/web/app/src/models/SplitTest.js/0 | {
"file_path": "overleaf/web/app/src/models/SplitTest.js",
"repo_id": "overleaf",
"token_count": 1050
} | 492 |
//- Title
if (metadata && metadata.title)
title= metadata.title + ' - ' + settings.appName + ', ' + translate("online_latex_editor")
meta(name="twitter:title", content=metadata.title)
meta(name="og:title", content=metadata.title)
else if (typeof(title) == "undefined")
title= settings.appName + ', '+ translate("online_latex_editor")
meta(name="twitter:title", content=settings.appName + ', '+ translate("online_latex_editor"))
meta(name="og:title", content=settings.appName + ', '+ translate("online_latex_editor"))
else
title= translate(title) + ' - ' + settings.appName + ', ' + translate("online_latex_editor")
//- to do - not translate?
meta(name="twitter:title", content=translate(title))
meta(name="og:title", content=translate(title))
//- Description
if (metadata && metadata.description)
meta(name="description" , content=metadata.description)
meta(itemprop="description" , content=metadata.description)
//-twitter and og descriptions handeled in their sections below
else
meta(name="description", content=translate("site_description"))
meta(itemprop="description", content=translate("site_description"))
//- Image
if (metadata && metadata.image && metadata.image.fields)
//- from the CMS
meta(itemprop="image", content=metadata.image.fields.file.url)
meta(name="image", content=metadata.image.fields.file.url)
else if (metadata && metadata.image_src)
//- pages with custom metadata images, metadata.image_src is the full image URL
meta(itemprop="image", content=metadata.image_src)
meta(name="image", content=metadata.image_src)
else if (settings.overleaf)
//- the default image for Overleaf
meta(itemprop="image", content=buildImgPath('ol-brand/overleaf_og_logo.png'))
meta(name="image", content=buildImgPath('ol-brand/overleaf_og_logo.png'))
else
//- the default image for ShareLaTeX
meta(itemprop="image", content='/touch-icon-192x192.png')
meta(name="image", content='/touch-icon-192x192.png')
//- Keywords
if (metadata && metadata.keywords)
meta(name="keywords" content=metadata.keywords)
//- Misc
meta(itemprop="name", content=settings.appName + ", the Online LaTeX Editor")
if (metadata && metadata.robotsNoindexNofollow)
meta(name="robots" content="noindex, nofollow")
//- Twitter
meta(name="twitter:card", content=metadata && metadata.twitterCardType ? metadata.twitterCardType : 'summary')
if (settings.social && settings.social.twitter && settings.social.twitter.handle)
meta(name="twitter:site", content="@" + settings.social.twitter.handle)
if (metadata && metadata.twitterDescription)
meta(name="twitter:description", content=metadata.twitterDescription)
else
meta(name="twitter:description", content=translate("site_description"))
if (metadata && metadata.twitterImage && metadata.twitterImage.fields)
//- from the CMS
meta(name="twitter:image", content=metadata.twitterImage.fields.file.url)
meta(name="twitter:image:alt", content=metadata.twitterImage.fields.title)
else if (settings.overleaf)
//- the default image for Overleaf
meta(name="twitter:image", content=buildImgPath('ol-brand/overleaf_og_logo.png'))
else
//- the default image for ShareLaTeX
meta(name="twitter:image", content='/touch-icon-192x192.png')
//- Open Graph
//- to do - add og:url
if (settings.social && settings.social.facebook && settings.social.facebook.appId)
meta(property="fb:app_id", content=settings.social.facebook.appId)
if (metadata && metadata.openGraphDescription)
meta(property="og:description", content=metadata.openGraphDescription)
else
meta(property="og:description", content=translate("site_description"))
if (metadata && metadata.openGraphImage && metadata.openGraphImage.fields)
//- from the CMS
meta(property="og:image", content=metadata.openGraphImage.fields.file.url)
else if (settings.overleaf)
//- the default image for Overleaf
meta(property="og:image", content=buildImgPath('ol-brand/overleaf_og_logo.png'))
else
//- the default image for ShareLaTeX
meta(property="og:image", content='/touch-icon-192x192.png')
if (metadata && metadata.openGraphType)
meta(property="og:type", metadata.openGraphType)
else
meta(property="og:type", content="website")
if (metadata && metadata.openGraphVideo)
//- from the CMS
meta(property="og:video", content=metadata.openGraphVideo)
//- Viewport
if metadata && metadata.viewport
meta(name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes")
//- Noindex
if settings.robotsNoindex
meta(name="robots" content="noindex")
//- Icons
link(rel="icon", href="/favicon.ico")
link(rel="icon", sizes="192x192", href="/touch-icon-192x192.png")
link(rel="apple-touch-icon-precomposed", href="/apple-touch-icon-precomposed.png")
link(rel="mask-icon", href="/mask-favicon.svg", color="#138A07")
| overleaf/web/app/views/_metadata.pug/0 | {
"file_path": "overleaf/web/app/views/_metadata.pug",
"repo_id": "overleaf",
"token_count": 1493
} | 493 |
doctype html
html(
lang=(currentLngCode || 'en')
)
- metadata = metadata || {}
block vars
head
include ./_metadata.pug
if (typeof(gaExperiments) != "undefined")
|!{gaExperiments}
//- Stylesheet
link(rel='stylesheet', href=buildCssPath(getCssThemeModifier(userSettings, brandVariation)), id="main-stylesheet")
link(rel='stylesheet', href=buildStylesheetPath("libraries.css"))
block _headLinks
if settings.i18n.subdomainLang
each subdomainDetails in settings.i18n.subdomainLang
if !subdomainDetails.hide
link(rel="alternate", href=subdomainDetails.url+currentUrl, hreflang=subdomainDetails.lngCode)
//- Scripts
//- Google Analytics
if (typeof(gaToken) != "undefined")
script(type="text/javascript", nonce=scriptNonce).
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
script(type="text/javascript", nonce=scriptNonce).
ga('create', '#{gaToken}', '#{settings.cookieDomain.replace(/^\./, "")}');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
try {
ga.isBlocked = localStorage.getItem('gaBlocked') === 'true'
if (!ga.isBlocked) {
window.addEventListener('load', function () {
setTimeout(function () {
if (!ga.loaded) localStorage.setItem('gaBlocked', 'true')
}, 4000)
})
}
} catch (e) {}
if gaOptimize === true && typeof(gaOptimizeId) != "undefined"
//- Anti-flicker snippet
style(type='text/css') .async-hide { opacity: 0 !important}
script(type="text/javascript", nonce=scriptNonce).
if (!ga.isBlocked) {
ga('require', '#{gaOptimizeId}');
ga('send', 'event', 'pageview', document.title.substring(0, 499), window.location.href.substring(0, 499));
(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'#{gaOptimizeId}':true});
}
else
script(type="text/javascript", nonce=scriptNonce).
window.ga = function() { console.log("would send to GA", arguments) };
block meta
meta(name="ol-csrfToken" content=csrfToken)
//- Configure dynamically loaded assets (via webpack) to be downloaded from CDN
//- See: https://webpack.js.org/guides/public-path/#on-the-fly
meta(name="ol-baseAssetPath" content=buildBaseAssetPath())
meta(name="ol-usersEmail" content=getUserEmail())
meta(name="ol-sharelatex" data-type="json" content={
siteUrl: settings.siteUrl,
wsUrl,
})
meta(name="ol-ab" data-type="json" content={})
meta(name="ol-user_id" content=getLoggedInUserId())
//- Internationalisation settings
meta(name="ol-i18n" data-type="json" content={
currentLangCode: currentLngCode
})
//- Expose some settings globally to the frontend
meta(name="ol-ExposedSettings" data-type="json" content=ExposedSettings)
if (typeof(settings.algolia) != "undefined")
meta(name="ol-algolia" data-type="json" content={
appId: settings.algolia.app_id,
apiKey: settings.algolia.read_only_api_key,
indexes: settings.algolia.indexes
})
if (typeof(settings.templates) != "undefined")
meta(name="ol-sharelatex.templates" data-type="json" content={
user_id : settings.templates.user_id,
cdnDomain : settings.templates.cdnDomain,
indexName : settings.templates.indexName
})
block head-scripts
body(ng-csp=(cspEnabled ? "no-unsafe-eval" : false))
if(settings.recaptcha && settings.recaptcha.siteKeyV3)
script(type="text/javascript", nonce=scriptNonce, src="https://www.recaptcha.net/recaptcha/api.js?render="+settings.recaptcha.siteKeyV3)
if (typeof(suppressSkipToContent) == "undefined")
a(class="skip-to-content" href="#main-content") #{translate('skip_to_content')}
if (typeof(suppressNavbar) == "undefined")
include layout/navbar
block content
if (typeof(suppressFooter) == "undefined")
include layout/footer
!= moduleIncludes("contactModal", locals)
block foot-scripts
script(type="text/javascript", nonce=scriptNonce, src=buildJsPath('libraries.js'))
script(type="text/javascript", nonce=scriptNonce, src=buildJsPath('main.js'))
script(type="text/javascript", nonce=scriptNonce).
//- Look for bundle
var cdnBlocked = typeof Frontend === 'undefined'
//- Prevent loops
var noCdnAlreadyInUrl = window.location.href.indexOf("nocdn=true") != -1
if (cdnBlocked && !noCdnAlreadyInUrl && navigator.userAgent.indexOf("Googlebot") == -1) {
//- Set query param, server will not set CDN url
window.location.search += "&nocdn=true";
}
if hasFeature('saas')
script(type="text/javascript", nonce=scriptNonce).
//- Test for CDN availability and report to sentry if loading failed
var cdnLoadTest = document.createElement('img')
cdnLoadTest.addEventListener('error', function () {
throw new Error('CDN test image load error (cdn.overleaf.net)')
})
cdnLoadTest.src = 'https://cdn.overleaf.net/img/1p.gif'
| overleaf/web/app/views/layout.pug/0 | {
"file_path": "overleaf/web/app/views/layout.pug",
"repo_id": "overleaf",
"token_count": 2189
} | 494 |
.diff-panel.full-size(ng-if="!history.isV2", ng-controller="HistoryDiffController")
.diff(
ng-if="!!history.diff && !history.diff.loading && !history.diff.deleted && !history.diff.error && !history.diff.binary"
)
.toolbar.toolbar-alt
span.name
| <strong>{{history.diff.highlights.length}} </strong>
ng-pluralize(
count="history.diff.highlights.length",
when="{\
'one': 'change',\
'other': 'changes'\
}"
)
| in <strong>{{history.diff.pathname}}</strong>
.toolbar-right(ng-if="permissions.write")
a.btn.btn-danger.btn-xs(
href,
ng-click="openRestoreDiffModal()"
) #{translate("restore_to_before_these_changes")}
.diff-editor.hide-ace-cursor(
ace-editor="history",
theme="settings.editorTheme",
font-size="settings.fontSize",
text="history.diff.text",
highlights="history.diff.highlights",
read-only="true",
resize-on="layout:main:resize",
navigate-highlights="true"
)
.diff-deleted.text-centered(
ng-show="history.diff.deleted && !history.diff.restoreDeletedSuccess"
)
p.text-serif #{translate("file_has_been_deleted", {filename:"{{ history.diff.doc.name }} "})}
p
a.btn.btn-primary.btn-lg(
href,
ng-click="restoreDeletedDoc()",
ng-disabled="history.diff.restoreInProgress"
) #{translate("restore")}
.diff-deleted.text-centered(
ng-show="history.diff.deleted && history.diff.restoreDeletedSuccess"
)
p.text-serif #{translate("file_restored", {filename:"{{ history.diff.doc.name }} "})}
p.text-serif #{translate("file_restored_back_to_editor")}
p
a.btn.btn-default(
href,
ng-click="backToEditorAfterRestore()",
) #{translate("file_restored_back_to_editor_btn")}
.loading-panel(ng-show="history.diff.loading")
i.fa.fa-spin.fa-refresh
| #{translate("loading")}…
.error-panel(ng-show="history.diff.error")
.alert.alert-danger #{translate("generic_something_went_wrong")}
| overleaf/web/app/views/project/editor/history/diffPanelV1.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/history/diffPanelV1.pug",
"repo_id": "overleaf",
"token_count": 832
} | 495 |
extends ../layout
block vars
- var suppressNavContentLinks = true
block append meta
meta(name="ol-projects" data-type="json" content=projects)
meta(name="ol-tags" data-type="json" content=tags)
meta(name="ol-notifications" data-type="json" content=notifications)
meta(name="ol-notificationsInstitution" data-type="json" content=notificationsInstitution)
meta(name="ol-userAffiliations" data-type="json" content=userAffiliations)
meta(name="ol-userEmails" data-type="json" content=userEmails)
meta(name="ol-userHasNoSubscription" data-type="boolean" content=!!(settings.enableSubscriptions && !hasSubscription))
meta(name="ol-allInReconfirmNotificationPeriods" data-type="json" content=allInReconfirmNotificationPeriods)
meta(name="ol-reconfirmedViaSAML" content=reconfirmedViaSAML)
block content
main.content.content-alt.project-list-page#main-content(
ng-controller="ProjectPageController"
role="main"
)
.system-messages(
ng-cloak
ng-controller="SystemMessagesController"
)
.system-message(
ng-repeat="message in messages"
ng-controller="SystemMessageController"
ng-hide="hidden"
)
button(ng-hide="protected",ng-click="hide()").close.pull-right
span(aria-hidden="true") ×
span.sr-only #{translate("close")}
.system-message-content(ng-bind-html="htmlContent")
include ../translations/translation_message
.project-list-content(event-tracking=settings.overleaf ? "loads_v2_dash" : "", onboard=settings.overleaf ? "true" : "", event-tracking-trigger=settings.overleaf ? "load" : "", event-tracking-mb="true", event-segmentation="{location: 'dash', v2_onboard: true}")
.project-list-row(ng-cloak)
.project-list-container.row(ng-if="projects.length > 0")
.project-list-sidebar-wrapper.col-md-2.col-xs-3
aside.project-list-sidebar
include ./list/side-bar
.project-list-main.col-md-10.col-xs-9
include ./list/notifications
include ./list/project-list
.project-list-empty.row(ng-if="projects.length === 0")
.project-list-empty-col.col-md-offset-2.col-md-8.col-md-offset-2.col-xs-8.col-xs-offset-2
include ./list/empty-project-list
.row.row-spaced
.col-sm-12
include ./list/notifications
include ./list/modals
| overleaf/web/app/views/project/list.pug/0 | {
"file_path": "overleaf/web/app/views/project/list.pug",
"repo_id": "overleaf",
"token_count": 868
} | 496 |
extends ../layout
include ./dashboard/_team_name_mixin
block head-scripts
script(type="text/javascript", nonce=scriptNonce, src="https://js.recurly.com/v4/recurly.js")
block append meta
meta(name="ol-managedInstitutions", data-type="json", content=managedInstitutions)
meta(name="ol-planCodesChangingAtTermEnd", data-type="json", content=plans.planCodesChangingAtTermEnd)
if (personalSubscription && personalSubscription.recurly)
meta(name="ol-recurlyApiKey" content=settings.apis.recurly.publicKey)
meta(name="ol-subscription" data-type="json" content=personalSubscription)
meta(name="ol-recomendedCurrency" content=personalSubscription.recurly.currency)
block content
main.content.content-alt#main-content(ng-cloak)
.container
.row
.col-md-8.col-md-offset-2
if (fromPlansPage)
.alert.alert-warning
p You already have a subscription
.card
.page-header
h1 #{translate("your_subscription")}
-var hasDisplayedSubscription = false
if (personalSubscription)
-hasDisplayedSubscription = true
include ./dashboard/_personal_subscription
if (managedGroupSubscriptions && managedGroupSubscriptions.length > 0)
include ./dashboard/_managed_groups
if (managedInstitutions && managedInstitutions.length > 0)
include ./dashboard/_managed_institutions
if (managedPublishers && managedPublishers.length > 0)
include ./dashboard/_managed_publishers
if (memberGroupSubscriptions && memberGroupSubscriptions.length > 0)
-hasDisplayedSubscription = true
include ./dashboard/_group_memberships
if (confirmedMemberAffiliations && confirmedMemberAffiliations.length > 0)
include ./dashboard/_institution_memberships
if (v1SubscriptionStatus)
include ./dashboard/_v1_subscription_status
if (!hasDisplayedSubscription)
if (hasSubscription)
-hasDisplayedSubscription = true
p(ng-non-bindable) You're on an #{settings.appName} Paid plan. Contact
a(href="mailto:support@overleaf.com") support@overleaf.com
| to find out more.
else
if (subscriptionCopy === 'new')
p(ng-non-bindable) You are on the #{settings.appName} Free plan. Upgrade to access these Premium Features:
ul
li Invite more collaborators
for feature in ['realtime_track_changes', 'full_doc_history', 'reference_search', 'reference_sync', 'dropbox_integration_lowercase', 'github_integration_lowercase', 'priority_support']
li #{translate(feature)}
a(ng-controller="UpgradeSubscriptionController" href="/user/subscription/plans" ng-click="upgradeSubscription()").btn.btn-primary Upgrade now
else
p(ng-non-bindable) You're on the #{settings.appName} Free plan.
|
a(ng-controller="UpgradeSubscriptionController" href="/user/subscription/plans" ng-click="upgradeSubscription()").btn.btn-primary Upgrade now
| overleaf/web/app/views/subscriptions/dashboard.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard.pug",
"repo_id": "overleaf",
"token_count": 1131
} | 497 |
extends ../../layout
block append meta
meta(name="ol-hasIndividualRecurlySubscription" data-type="boolean" content=hasIndividualRecurlySubscription)
meta(name="ol-inviteToken" content=inviteToken)
block content
main.content.content-alt.team-invite#main-content
.container
.row
.col-md-8.col-md-offset-2
if (expired)
.alert.alert-warning #{translate("email_link_expired")}
.row.row-spaced
.col-md-8.col-md-offset-2.text-center(ng-cloak)
.card(ng-controller="TeamInviteController")
.page-header
h1.text-centered(ng-non-bindable) #{translate("invited_to_group", {inviterName: inviterName, appName: appName})}
div(ng-show="view =='hasIndividualRecurlySubscription'")
p #{translate("cancel_personal_subscription_first")}
.alert.alert-danger(ng-show="cancel_error" ng-cloak) #{translate("something_went_wrong_canceling_your_subscription")}
p
a.btn.btn.btn-default(ng-click="keepPersonalSubscription()", ng-disabled="inflight") #{translate("not_now")}
|
a.btn.btn.btn-primary(ng-click="cancelPersonalSubscription()", ng-disabled="inflight") #{translate("cancel_your_subscription")}
div(ng-show="view =='teamInvite'")
p #{translate("join_team_explanation", {appName: appName})}
p
a.btn.btn-default(href="/project") #{translate("not_now")}
|
a.btn.btn.btn-primary(ng-click="joinTeam()", ng-disabled="inflight") #{translate("accept_invitation")}
div(ng-show="view =='inviteAccepted'")
p(ng-non-bindable) #{translate("joined_team", {inviterName: inviterName})}
p
a.btn.btn.btn-primary(href="/project") #{translate("done")}
| overleaf/web/app/views/subscriptions/team/invite.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/team/invite.pug",
"repo_id": "overleaf",
"token_count": 740
} | 498 |
include ../../_mixins/reconfirm_affiliation
mixin aboutInstitutionLink()
a(href="/learn/how-to/Institutional_Login") #{translate("find_out_more_about_institution_login")}.
mixin btnMakePrimaryDisabled(tooltip)
div(
tooltip=tooltip
tooltip-enable="!ui.isMakingRequest"
)
button.btn.btn-sm.btn-success.affiliations-table-inline-action(
disabled
type="button"
) #{translate("make_primary")}
mixin btnRemoveEmail()
.affiliations-table-inline-action-disabled-wrapper(ng-if="userEmail.default")
div(
tooltip=translate("please_change_primary_to_remove")
tooltip-enable="!ui.isMakingRequest"
tooltip-placement="left"
)
button.btn.btn-sm.btn-danger(disabled)
i.fa.fa-fw.fa-trash(aria-hidden="true")
span.sr-only #{translate("please_change_primary_to_remove")}
button.btn.btn-sm.btn-danger.affiliations-table-inline-action(
ng-if="!userEmail.default"
ng-click="removeUserEmail(userEmail)"
ng-disabled="ui.isMakingRequest"
tooltip=translate("remove")
type="button"
)
i.fa.fa-fw.fa-trash(aria-hidden="true")
span.sr-only #{translate("remove")}
form.row(
ng-controller="UserAffiliationsController"
name="affiliationsForm"
)
.col-md-12
h3 #{translate("emails_and_affiliations_title")}
p.small #{translate("emails_and_affiliations_explanation")}
table.table.affiliations-table
thead
tr
th.affiliations-table-email #{translate("email")}
th.affiliations-table-institution #{translate("institution_and_role")}
th.affiliations-table-inline-actions
tbody
tr(
ng-repeat-start="userEmail in userEmails"
)
td
| {{ userEmail.email + (userEmail.default ? ' (primary)' : '') }}
div(ng-if="!userEmail.confirmedAt").small
strong #{translate('unconfirmed')}.
span(ng-if="!userEmail.ssoAvailable") #{translate('please_check_your_inbox')}.
br
a(
href,
ng-click="resendConfirmationEmail(userEmail)",
ng-if="!userEmail.ssoAvailable"
) #{translate('resend_confirmation_email')}
div(ng-if="userEmail.confirmedAt && userEmail.affiliation.institution && userEmail.affiliation.institution.confirmed && userEmail.affiliation.licence && userEmail.affiliation.licence != 'free'").small
span.label.label-primary #{translate("professional")}
td
div(ng-if="userEmail.affiliation.institution")
div {{ userEmail.affiliation.institution.name }}
span.small
a(
href
ng-if="!isChangingAffiliation(userEmail.email) && !userEmail.affiliation.role && !userEmail.affiliation.department"
ng-click="changeAffiliation(userEmail);"
) #{translate("add_role_and_department")}
div.small(
ng-if="!isChangingAffiliation(userEmail.email) && (userEmail.affiliation.role || userEmail.affiliation.department)"
)
span(ng-if="userEmail.affiliation.role") {{ userEmail.affiliation.role }}
span(ng-if="userEmail.affiliation.role && userEmail.affiliation.department") , 
span(ng-if="userEmail.affiliation.department") {{ userEmail.affiliation.department }}
br
a(
href
ng-click="changeAffiliation(userEmail);"
) #{translate("change")}
.affiliation-change-container(
ng-if="isChangingAffiliation(userEmail.email)"
)
affiliation-form(
affiliation-data="affiliationToChange"
show-university-and-country="false"
show-role-and-department="true"
)
.affiliation-change-actions.small
button.btn.btn-sm.btn-success(
ng-click="saveAffiliationChange(userEmail);"
ng-disabled="!(affiliationToChange.role && affiliationToChange.department)"
type="button"
) #{translate("save_or_cancel-save")}
|  #{translate("save_or_cancel-or" )} 
a(
href
ng-click="cancelAffiliationChange();"
) #{translate("save_or_cancel-cancel")}
td.affiliations-table-inline-actions
// Disabled buttons don't work with tooltips, due to pointer-events: none,
// so create a wrapper for the tooltip
span(ng-if="!userEmail.default && (!userEmail.confirmedAt || ui.isMakingRequest) && !institutionAlreadyLinked(userEmail) && !inReconfirmNotificationPeriod(userEmail)")
.affiliations-table-inline-action-disabled-wrapper(ng-if="userEmail.ssoAvailable")
+btnMakePrimaryDisabled(translate("please_link_before_making_primary"))
.affiliations-table-inline-action-disabled-wrapper(ng-if="!userEmail.ssoAvailable")
+btnMakePrimaryDisabled(translate("please_confirm_your_email_before_making_it_default"))
.affiliations-table-inline-action-disabled-wrapper(ng-if="!userEmail.default && inReconfirmNotificationPeriod(userEmail)")
+btnMakePrimaryDisabled(translate("please_reconfirm_your_affiliation_before_making_this_primary"))
button.btn.btn-sm.btn-success.affiliations-table-inline-action(
tooltip=translate("make_email_primary_description")
ng-if="!userEmail.default && (userEmail.confirmedAt && !ui.isMakingRequest) && !inReconfirmNotificationPeriod(userEmail)"
ng-click="setDefaultUserEmail(userEmail)"
type="button"
) #{translate("make_primary")}
|
+btnRemoveEmail()
tr.affiliations-table-saml-row(ng-if="userEmail.affiliation && userEmail.affiliation && userEmail.ssoAvailable")
td
td(ng-attr-colspan="{{userEmail.samlProviderId ? '2' : '1'}}" ng-class="institutionAlreadyLinked(userEmail) ? '' : 'with-border'")
p.small(ng-if="userEmail.samlProviderId")
| !{translate("acct_linked_to_institution_acct", {institutionName: '{{userEmail.affiliation.institution.name}}'})}
div(ng-if="!userEmail.samlProviderId && !institutionAlreadyLinked(userEmail)")
//- this email is not linked to institution login but
//- cannot have multiple emails at same institution linked for "institution login"
//- so check if institution is already linked
p.small
| !{translate("can_link_your_institution_acct", {institutionName: '{{userEmail.affiliation.institution.name}}'})}
p.small
| !{translate("doing_this_allow_log_in_through_institution")}
+aboutInstitutionLink()
td.with-border.affiliations-table-inline-actions(ng-if="!userEmail.samlProviderId && !institutionAlreadyLinked(userEmail)")
button.btn-sm.btn.btn-info(
ng-click="linkInstitutionAcct(userEmail.email, userEmail.affiliation.institution.id)"
ng-disabled="ui.isMakingRequest"
type="button"
)
| #{translate("link_accounts")}
tr(
class="reconfirm-row"
ng-if="userEmail.samlIdentifier && userEmail.samlIdentifier.providerId === reconfirmedViaSAML"
)
td(colspan="3")
+reconfirmedAffiliationNotification()
tr(
class="reconfirm-row"
ng-repeat-end
)
td(
colspan="3"
ng-if="userEmail.affiliation && userEmail.affiliation.inReconfirmNotificationPeriod"
)
div(ng-class="{'alert alert-info': reconfirmationRemoveEmail === userEmail.email}")
+reconfirmAffiliationNotification('/user/settings')
tr.affiliations-table-highlighted-row(
ng-if="!ui.showAddEmailUI && !ui.isMakingRequest"
)
td(colspan="3")
a(
href
ng-click="showAddEmailForm()"
) #{translate("add_another_email")}
tr.affiliations-table-highlighted-row(
ng-if="ui.showAddEmailUI && !ui.isLoadingEmails"
)
td
.affiliations-form-group
input-suggestions(
ng-model="newAffiliation.email"
ng-model-options="{ allowInvalid: true }"
get-suggestion="getEmailSuggestion(userInput)"
on-blur="handleEmailInputBlur()"
input-id="affilitations-email"
input-name="affilitationsEmail"
input-placeholder="e.g. johndoe@mit.edu"
input-type="email"
input-required="true"
)
td(
colspan="2"
ng-if="newAffiliation.ssoAvailable"
)
p.affiliations-table-label {{ newAffiliation.university.name }}
p !{translate("to_add_email_accounts_need_to_be_linked", {institutionName: "{{newAffiliation.university.name}}"})}
p !{translate("doing_this_will_verify_affiliation_and_allow_log_in", {institutionName: "{{newAffiliation.university.name}}"})}
+aboutInstitutionLink()
button.btn-sm.btn.btn-primary.btn-link-accounts(
ng-click="linkInstitutionAcct(newAffiliation.email, newAffiliation.university.id)"
ng-disabled="ui.isMakingRequest"
type="button"
)
| #{translate("link_accounts_and_add_email")}
td(
ng-if="!newAffiliation.ssoAvailable"
)
p.affiliations-table-label(
ng-if="newAffiliation.university && !ui.showManualUniversitySelectionUI"
)
| {{ newAffiliation.university.name }}
span.small
| (
a(
href
ng-click="selectUniversityManually();"
) #{translate("change")}
| )
.affiliations-table-label(
ng-if="!newAffiliation.university && !ui.isValidEmail && !ui.showManualUniversitySelectionUI"
) #{translate("start_by_adding_your_email")}
.affiliations-table-label(
ng-if="!newAffiliation.university && ui.isValidEmail && !ui.isBlacklistedEmail && !ui.showManualUniversitySelectionUI"
)
| #{translate("is_email_affiliated")}
br
a(
href
ng-click="selectUniversityManually();"
) #{translate("let_us_know")}
affiliation-form(
affiliation-data="newAffiliation"
show-university-and-country="ui.showManualUniversitySelectionUI"
show-role-and-department="ui.isValidEmail && newAffiliation.university"
)
td(
ng-if="!newAffiliation.ssoAvailable"
)
button.btn.btn-sm.btn-primary(
ng-disabled="affiliationsForm.$invalid || ui.isMakingRequest"
ng-click="addNewEmail()"
)
| #{translate("add_new_email")}
tr.affiliations-table-highlighted-row(
ng-if="ui.isMakingRequest"
)
td.text-center(colspan="3", ng-if="ui.isLoadingEmails")
i.fa.fa-fw.fa-spin.fa-refresh(aria-hidden="true")
| #{translate("loading")}…
td.text-center(colspan="3", ng-if="ui.isResendingConfirmation")
i.fa.fa-fw.fa-spin.fa-refresh(aria-hidden="true")
| #{translate("sending")}…
td.text-center.text-capitalize(colspan="3", ng-if="ui.isProcessing")
i.fa.fa-fw.fa-spin.fa-refresh(aria-hidden="true")
| #{translate("processing")}
td.text-center(colspan="3", ng-if="!ui.isLoadingEmails && !ui.isResendingConfirmation && !ui.isProcessing")
i.fa.fa-fw.fa-spin.fa-refresh(aria-hidden="true")
| #{translate("saving")}
tr.affiliations-table-error-row(
ng-if="ui.hasError"
)
td.text-center(colspan="3")
div
i.fa.fa-fw.fa-exclamation-triangle(aria-hidden="true")
span(ng-if="!ui.errorMessage") #{translate("error_performing_request")}
span(ng-if="ui.errorMessage") {{ui.errorMessage}}
if institutionLinked
tr.affiliations-table-info-row(ng-if="!hideInstitutionNotifications.info")
td.text-center(aria-live="assertive" colspan="3")
button.close(
type="button"
data-dismiss="modal"
ng-click="closeInstitutionNotification('info')"
aria-label=translate("close")
)
span(aria-hidden="true") ×
.small(ng-non-bindable) !{translate("institution_acct_successfully_linked", {institutionName: institutionLinked.universityName})}
if institutionLinked.hasEntitlement
.small !{translate("this_grants_access_to_features", {featureType: translate("professional")})}
if institutionEmailNonCanonical
tr.affiliations-table-warning-row(ng-if="!hideInstitutionNotifications.warning")
td.text-center(aria-live="assertive" colspan="3")
button.close(
type="button"
data-dismiss="modal"
ng-click="closeInstitutionNotification('warning')"
aria-label=translate("close")
)
span(aria-hidden="true") ×
.small
i.fa.fa-exclamation-triangle(aria-hidden="true")
|
| !{translate("in_order_to_match_institutional_metadata", {email: institutionEmailNonCanonical})}
if samlError
tr.affiliations-table-error-row(ng-if="!hideInstitutionNotifications.linkError")
td.text-center(aria-live="assertive" colspan="3")
button.close(
type="button"
data-dismiss="modal"
ng-click="closeInstitutionNotification('linkError')"
aria-label=translate("close")
)
span(aria-hidden="true") ×
.small
i.fa.fa-fw.fa-exclamation-triangle(aria-hidden="true")
| #{translate("generic_something_went_wrong")}.
br
if samlError.translatedMessage
span(ng-non-bindable) !{samlError.translatedMessage}
else if samlError.message
span(ng-non-bindable) #{samlError.message}
if samlError.tryAgain
br
| #{translate("try_again")}.
script(type="text/ng-template", id="affiliationFormTpl")
.affiliations-form-group(
ng-if="$ctrl.showUniversityAndCountry"
)
ui-select(
ng-model="$ctrl.affiliationData.country"
)
ui-select-match(
placeholder="Country"
) {{ $select.selected.name }}
ui-select-choices(
repeat="country in $ctrl.countries | filter: $select.search"
)
span(
ng-bind="country.name"
)
.affiliations-form-group(
ng-if="$ctrl.showUniversityAndCountry"
)
ui-select(
ng-model="$ctrl.affiliationData.university"
ng-disabled="!$ctrl.affiliationData.country"
tagging="$ctrl.addUniversityToSelection"
tagging-label="false"
)
ui-select-match(
placeholder="Institution"
) {{ $select.selected.name }}
ui-select-choices(
repeat="university in $ctrl.universities | filter: $select.search"
refresh="$ctrl.handleFreeformInputChange($select, 'name');"
refresh-delay="10"
)
span(
ng-bind="university.name"
)
.affiliations-form-group(
ng-if="$ctrl.showRoleAndDepartment"
)
ui-select(
ng-model="$ctrl.affiliationData.role"
tagging
tagging-label="false"
)
ui-select-match(
placeholder="Role"
) {{ $select.selected }}
ui-select-choices(
repeat="role in $ctrl.roles | filter: $select.search"
refresh="$ctrl.handleFreeformInputChange($select);"
refresh-delay="10"
)
span(
ng-bind="role"
)
.affiliations-form-group(
ng-if="$ctrl.showRoleAndDepartment"
)
ui-select(
ng-model="$ctrl.affiliationData.department"
tagging
tagging-label="false"
)
ui-select-match(
placeholder="Department"
) {{ $select.selected }}
ui-select-choices(
repeat="department in $ctrl.departments | filter: $select.search"
refresh="$ctrl.handleFreeformInputChange($select);"
refresh-delay="10"
)
span(
ng-bind="department"
)
| overleaf/web/app/views/user/settings/user-affiliations.pug/0 | {
"file_path": "overleaf/web/app/views/user/settings/user-affiliations.pug",
"repo_id": "overleaf",
"token_count": 6720
} | 499 |
// 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('equals', () => ({
require: 'ngModel',
link(scope, elem, attrs, ctrl) {
const firstField = `#${attrs.equals}`
return elem.add(firstField).on('keyup', () =>
scope.$apply(function () {
const equal = elem.val() === $(firstField).val()
return ctrl.$setValidity('areEqual', equal)
})
)
},
}))
| overleaf/web/frontend/js/directives/equals.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/equals.js",
"repo_id": "overleaf",
"token_count": 244
} | 500 |
import { useRef, useEffect } from 'react'
import PropTypes from 'prop-types'
import Linkify from 'react-linkify'
function MessageContent({ content }) {
const root = useRef(null)
useEffect(() => {
if (!(window.MathJax && window.MathJax.Hub)) {
return
}
const MJHub = window.MathJax.Hub
const inlineMathConfig =
(MJHub.config &&
MJHub.config.tex2jax &&
MJHub.config.tex2jax.inlineMath) ||
[]
const alreadyConfigured = inlineMathConfig.some(
c => c[0] === '$' && c[1] === '$'
)
if (!alreadyConfigured) {
MJHub.Config({
tex2jax: {
inlineMath: inlineMathConfig.concat([['$', '$']]),
},
})
}
}, [])
useEffect(() => {
// adds attributes to all the links generated by <Linkify/>, required due to https://github.com/tasti/react-linkify/issues/99
for (const a of root.current.getElementsByTagName('a')) {
a.setAttribute('target', '_blank')
a.setAttribute('rel', 'noreferrer noopener')
}
// MathJax typesetting
const MJHub = window.MathJax.Hub
const timeoutHandler = setTimeout(() => {
MJHub.Queue(['Typeset', MJHub, root.current])
}, 0)
return () => clearTimeout(timeoutHandler)
}, [content])
return (
<p ref={root}>
<Linkify>{content}</Linkify>
</p>
)
}
MessageContent.propTypes = {
content: PropTypes.string.isRequired,
}
export default MessageContent
| overleaf/web/frontend/js/features/chat/components/message-content.js/0 | {
"file_path": "overleaf/web/frontend/js/features/chat/components/message-content.js",
"repo_id": "overleaf",
"token_count": 589
} | 501 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import Icon from '../../../shared/components/icon'
function MenuButton({ onClick }) {
const { t } = useTranslation()
return (
// eslint-disable-next-line jsx-a11y/anchor-is-valid
<a role="button" className="btn btn-full-height" href="#" onClick={onClick}>
<Icon type="fw" modifier="bars" classes={{ icon: 'editor-menu-icon' }} />
<p className="toolbar-label">{t('menu')}</p>
</a>
)
}
MenuButton.propTypes = {
onClick: PropTypes.func.isRequired,
}
export default MenuButton
| overleaf/web/frontend/js/features/editor-navigation-toolbar/components/menu-button.js/0 | {
"file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/menu-button.js",
"repo_id": "overleaf",
"token_count": 218
} | 502 |
import { useCallback, useEffect } from 'react'
import FileTreeCreateNameInput from '../file-tree-create-name-input'
import { useFileTreeActionable } from '../../../contexts/file-tree-actionable'
import { useFileTreeCreateName } from '../../../contexts/file-tree-create-name'
import { useFileTreeCreateForm } from '../../../contexts/file-tree-create-form'
import ErrorMessage from '../error-message'
export default function FileTreeCreateNewDoc() {
const { name, validName } = useFileTreeCreateName()
const { setValid } = useFileTreeCreateForm()
const { error, finishCreatingDoc } = useFileTreeActionable()
// form validation: name is valid
useEffect(() => {
setValid(validName)
}, [setValid, validName])
// form submission: create an empty doc with this name
const handleSubmit = useCallback(
event => {
event.preventDefault()
finishCreatingDoc({ name })
},
[finishCreatingDoc, name]
)
return (
<form noValidate id="create-file" onSubmit={handleSubmit}>
<FileTreeCreateNameInput focusName error={error} />
{error && <ErrorMessage error={error} />}
</form>
)
}
| overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-create-new-doc.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/modes/file-tree-create-new-doc.js",
"repo_id": "overleaf",
"token_count": 362
} | 503 |
import { Modal } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import { useFileTreeActionable } from '../../contexts/file-tree-actionable'
import FileTreeCreateFormProvider from '../../contexts/file-tree-create-form'
import FileTreeModalCreateFileBody from '../file-tree-create/file-tree-modal-create-file-body'
import FileTreeModalCreateFileFooter from '../file-tree-create/file-tree-modal-create-file-footer'
import AccessibleModal from '../../../../shared/components/accessible-modal'
export default function FileTreeModalCreateFile() {
const { t } = useTranslation()
const { isCreatingFile, cancel } = useFileTreeActionable()
if (!isCreatingFile) {
return null
}
return (
<FileTreeCreateFormProvider>
<AccessibleModal bsSize="large" onHide={cancel} show>
<Modal.Header closeButton>
<Modal.Title>{t('add_files')}</Modal.Title>
</Modal.Header>
<Modal.Body className="modal-new-file">
<FileTreeModalCreateFileBody />
</Modal.Body>
<Modal.Footer>
<FileTreeModalCreateFileFooter />
</Modal.Footer>
</AccessibleModal>
</FileTreeCreateFormProvider>
)
}
| overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-file.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/modals/file-tree-modal-create-file.js",
"repo_id": "overleaf",
"token_count": 450
} | 504 |
import { useEffect, useState } from 'react'
import { getJSON } from '../../../infrastructure/fetch-json'
import { fileCollator } from '../util/file-collator'
import useAbortController from '../../../shared/hooks/use-abort-controller'
const alphabetical = (a, b) => fileCollator.compare(a.name, b.name)
export function useUserProjects() {
const [loading, setLoading] = useState(true)
const [data, setData] = useState(null)
const [error, setError] = useState(false)
const { signal } = useAbortController()
useEffect(() => {
getJSON('/user/projects', { signal })
.then(data => {
setData(data.projects.sort(alphabetical))
})
.catch(error => setError(error))
.finally(() => setLoading(false))
}, [signal])
return { loading, data, error }
}
| overleaf/web/frontend/js/features/file-tree/hooks/use-user-projects.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/hooks/use-user-projects.js",
"repo_id": "overleaf",
"token_count": 281
} | 505 |
import { useState, useEffect, createRef, useRef } from 'react'
import PropTypes from 'prop-types'
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
import classNames from 'classnames'
import { useTranslation } from 'react-i18next'
import OutlineList from './outline-list'
import Icon from '../../../shared/components/icon'
function getChildrenLines(children) {
return (children || [])
.map(child => {
return getChildrenLines(child.children).concat(child.line)
})
.flat()
}
function OutlineItem({ outlineItem, jumpToLine, highlightedLine }) {
const { t } = useTranslation()
const [expanded, setExpanded] = useState(true)
const titleElementRef = createRef()
const isHighlightedRef = useRef(false)
const mainItemClasses = classNames('outline-item', {
'outline-item-no-children': !outlineItem.children,
})
const hasHighlightedChild =
!expanded &&
getChildrenLines(outlineItem.children).includes(highlightedLine)
const isHighlighted =
highlightedLine === outlineItem.line || hasHighlightedChild
const itemLinkClasses = classNames('outline-item-link', {
'outline-item-link-highlight': isHighlighted,
})
function handleExpandCollapseClick() {
setExpanded(!expanded)
}
function handleOutlineItemLinkClick() {
jumpToLine(outlineItem.line, false)
}
function handleOutlineItemLinkDoubleClick() {
jumpToLine(outlineItem.line, true)
}
useEffect(() => {
const wasHighlighted = isHighlightedRef.current
isHighlightedRef.current = isHighlighted
if (!wasHighlighted && isHighlighted) {
scrollIntoViewIfNeeded(titleElementRef.current, {
scrollMode: 'if-needed',
block: 'center',
})
}
}, [isHighlighted, titleElementRef, isHighlightedRef])
// don't set the aria-expanded attribute when there are no children
const ariaExpandedValue = outlineItem.children ? expanded : undefined
return (
<li
className={mainItemClasses}
aria-expanded={ariaExpandedValue}
role="treeitem"
aria-current={isHighlighted}
aria-label={outlineItem.title}
>
<div className="outline-item-row">
{outlineItem.children ? (
<button
className="outline-item-expand-collapse-btn"
onClick={handleExpandCollapseClick}
aria-label={expanded ? t('collapse') : t('expand')}
>
<Icon
type={expanded ? 'angle-down' : 'angle-right'}
classes={{ icon: 'outline-caret-icon' }}
/>
</button>
) : null}
<button
className={itemLinkClasses}
onClick={handleOutlineItemLinkClick}
onDoubleClick={handleOutlineItemLinkDoubleClick}
ref={titleElementRef}
>
{outlineItem.title}
</button>
</div>
{expanded && outlineItem.children ? (
<OutlineList
outline={outlineItem.children}
jumpToLine={jumpToLine}
isRoot={false}
highlightedLine={highlightedLine}
/>
) : null}
</li>
)
}
OutlineItem.propTypes = {
outlineItem: PropTypes.exact({
line: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
level: PropTypes.number,
children: PropTypes.array,
}).isRequired,
jumpToLine: PropTypes.func.isRequired,
highlightedLine: PropTypes.number,
}
export default OutlineItem
| overleaf/web/frontend/js/features/outline/components/outline-item.js/0 | {
"file_path": "overleaf/web/frontend/js/features/outline/components/outline-item.js",
"repo_id": "overleaf",
"token_count": 1356
} | 506 |
import { useRef, useState } from 'react'
import PropTypes from 'prop-types'
import { OverlayTrigger, Tooltip } from 'react-bootstrap'
import { useTranslation } from 'react-i18next'
import PreviewDownloadButton from './preview-download-button'
import PreviewRecompileButton from './preview-recompile-button'
import PreviewLogsToggleButton from './preview-logs-toggle-button'
import useResizeObserver from '../../../shared/hooks/use-resize-observer'
import Icon from '../../../shared/components/icon'
function _getElementWidth(element) {
if (!element) return 0
return Math.ceil(element.getBoundingClientRect().width)
}
function PreviewToolbar({
compilerState,
logsState,
onRecompileFromScratch,
onRecompile,
onRunSyntaxCheckNow,
onSetAutoCompile,
onSetDraftMode,
onSetSyntaxCheck,
onToggleLogs,
onSetSplitLayout,
onSetFullLayout,
onStopCompilation,
outputFiles,
pdfDownloadUrl,
showLogs,
splitLayout,
}) {
const showTextRef = useRef(true)
const showToggleTextRef = useRef(true)
const toolbarRef = useRef()
const recompileWidthDifferenceRef = useRef()
const recompileLongerTextRef = useRef()
const [showText, setShowText] = useState(showTextRef.current)
const [showToggleText, setShowToggleText] = useState(
showToggleTextRef.current
)
const { t } = useTranslation()
function checkCanShowText(observedElement) {
// toolbar items can be in 3 states:
// all text, only toggle logs w/text and icons on others, all icons
// states depend on available space in the toolbar
const toolbarWidth =
observedElement &&
observedElement.contentRect &&
observedElement.contentRect.width
if (!toolbarWidth) return
_checkRecompileStateWidths()
let textWidths = 0
let itemsWidth = _getItemsWidth() // could be with or without text
// get widths of text only
// required for _checkToggleText, even if currently showing text
const textElements = toolbarRef.current.querySelectorAll('.toolbar-text')
textElements.forEach(item => {
if (item.getAttribute('aria-hidden') !== 'true') {
textWidths += _getElementWidth(item)
}
})
const logsToggleText = toolbarRef.current.querySelector(
'#logs-toggle .toolbar-text'
)
const logsToggleTextWidth = _getElementWidth(logsToggleText)
if (!showTextRef.current && !showToggleTextRef.current) {
// itemsWidth was calculated without any text shown
itemsWidth += textWidths
} else if (!showTextRef.current && showToggleTextRef.current) {
// itemsWidth was calculated with toggle text but no other text
// only add text width for other items and then
// subtract toggle text width, since it is already in itemsWidth
itemsWidth += parseInt(textWidths - logsToggleTextWidth, 10)
}
// only add extra if recompile button is in state with smaller length
if (
recompileWidthDifferenceRef.current &&
recompileLongerTextRef.current &&
((!compilerState.isCompiling &&
recompileLongerTextRef.current === 'compiling') ||
(compilerState.isCompiling &&
recompileLongerTextRef.current === 'recompile'))
) {
itemsWidth += recompileWidthDifferenceRef.current
}
itemsWidth += 10 // add extra for some spacing between items
const canShowText = itemsWidth < toolbarWidth
if (!canShowText) {
_checkToggleText(
toolbarWidth,
logsToggleTextWidth,
itemsWidth,
textWidths
)
} else if (showToggleTextRef.current !== true) {
setShowToggleText(true)
showToggleTextRef.current = true
}
setShowText(canShowText)
showTextRef.current = canShowText
}
function _checkRecompileStateWidths() {
// check recompile/compiling button text.
// Do not want to hide and then show text when recompiling
if (
recompileWidthDifferenceRef.current ||
recompileWidthDifferenceRef.current === 0
)
return
const textCompiling = toolbarRef.current.querySelector('#text-compiling')
const textRecompile = toolbarRef.current.querySelector('#text-recompile')
const textCompilingWidth = _getElementWidth(textCompiling)
const textRecompileWidth = _getElementWidth(textRecompile)
const textLengthDifference = Math.abs(
parseInt(textCompilingWidth - textRecompileWidth, 10)
)
recompileWidthDifferenceRef.current = textLengthDifference
// ignore if equal
if (textRecompileWidth > textCompilingWidth) {
recompileLongerTextRef.current = 'recompile'
} else if (textRecompileWidth < textCompilingWidth) {
recompileLongerTextRef.current = 'compiling'
}
}
function _checkToggleText(
toolbarWidth,
logsToggleTextWidth,
itemsWithTextWidth,
textWidths
) {
// check to see if we can still show the toggle button text
let toggleWithTextWidth = 0
let toggleWithoutTextWidth = 0
const itemsWithoutTextWidth = parseInt(itemsWithTextWidth - textWidths, 10)
const logsToggle = toolbarRef.current.querySelector('#logs-toggle')
const logsToggleWidth = _getElementWidth(logsToggle)
// logsToggleWidth could be with or without text
if (showToggleTextRef.current) {
toggleWithTextWidth = logsToggleWidth
toggleWithoutTextWidth = parseInt(
logsToggleWidth - logsToggleTextWidth,
10
)
} else {
toggleWithTextWidth = parseInt(logsToggleWidth + logsToggleTextWidth, 10)
toggleWithoutTextWidth = logsToggleWidth
}
const itemsWithoutTextAndToggleWidth = parseInt(
itemsWithoutTextWidth - toggleWithoutTextWidth,
10
)
const itemsWithIconsExceptToggleWidth = parseInt(
itemsWithoutTextAndToggleWidth + toggleWithTextWidth,
10
)
const canShowToggleText = itemsWithIconsExceptToggleWidth < toolbarWidth
if (canShowToggleText !== showToggleTextRef.current) {
setShowToggleText(canShowToggleText)
showToggleTextRef.current = canShowToggleText
}
}
function _getItemsWidth() {
const toolbarItems = toolbarRef.current.querySelectorAll('.toolbar-item')
let itemWidth = 0
toolbarItems.forEach(item => {
itemWidth += _getElementWidth(item)
})
return itemWidth
}
const pdfExpandLabel = splitLayout ? t('full_screen') : t('split_screen')
const pdfExpandIconType = splitLayout ? 'expand' : 'compress'
const pdfExpandTooltip = (
<Tooltip id="expand-pdf-btn">{pdfExpandLabel}</Tooltip>
)
function handlePdfExpandBtnClick() {
if (splitLayout) {
onSetFullLayout()
} else {
onSetSplitLayout()
}
}
useResizeObserver(toolbarRef, logsState, checkCanShowText)
return (
<div
className="toolbar toolbar-pdf"
id="toolbar-preview"
data-testid="toolbar-preview"
ref={toolbarRef}
>
<div className="toolbar-pdf-left">
<PreviewRecompileButton
compilerState={compilerState}
onRecompile={onRecompile}
onRecompileFromScratch={onRecompileFromScratch}
onRunSyntaxCheckNow={onRunSyntaxCheckNow}
onSetAutoCompile={onSetAutoCompile}
onSetDraftMode={onSetDraftMode}
onSetSyntaxCheck={onSetSyntaxCheck}
onStopCompilation={onStopCompilation}
showText={showText}
/>
<PreviewDownloadButton
isCompiling={compilerState.isCompiling}
outputFiles={outputFiles}
pdfDownloadUrl={pdfDownloadUrl}
showText={showText}
/>
</div>
<div className="toolbar-pdf-right">
<PreviewLogsToggleButton
logsState={logsState}
showLogs={showLogs}
autoCompileLintingError={
compilerState.isAutoCompileOn &&
compilerState.autoCompileHasLintingError
}
compileFailed={compilerState.compileFailed}
onToggle={onToggleLogs}
showText={showToggleText}
/>
<OverlayTrigger placement="left" overlay={pdfExpandTooltip}>
<button
onClick={handlePdfExpandBtnClick}
className="toolbar-pdf-expand-btn toolbar-item"
aria-label={pdfExpandLabel}
>
<Icon type={pdfExpandIconType} />
</button>
</OverlayTrigger>
</div>
</div>
)
}
PreviewToolbar.propTypes = {
compilerState: PropTypes.shape({
autoCompileHasLintingError: PropTypes.bool,
isAutoCompileOn: PropTypes.bool.isRequired,
isCompiling: PropTypes.bool.isRequired,
isDraftModeOn: PropTypes.bool.isRequired,
isSyntaxCheckOn: PropTypes.bool.isRequired,
compileFailed: PropTypes.bool,
logEntries: PropTypes.object.isRequired,
}),
logsState: PropTypes.shape({
nErrors: PropTypes.number.isRequired,
nWarnings: PropTypes.number.isRequired,
}),
showLogs: PropTypes.bool.isRequired,
splitLayout: PropTypes.bool.isRequired,
onRecompile: PropTypes.func.isRequired,
onRecompileFromScratch: PropTypes.func.isRequired,
onRunSyntaxCheckNow: PropTypes.func.isRequired,
onSetAutoCompile: PropTypes.func.isRequired,
onSetDraftMode: PropTypes.func.isRequired,
onSetSyntaxCheck: PropTypes.func.isRequired,
onToggleLogs: PropTypes.func.isRequired,
onSetSplitLayout: PropTypes.func.isRequired,
onSetFullLayout: PropTypes.func.isRequired,
onStopCompilation: PropTypes.func.isRequired,
pdfDownloadUrl: PropTypes.string,
outputFiles: PropTypes.array,
}
export default PreviewToolbar
| overleaf/web/frontend/js/features/preview/components/preview-toolbar.js/0 | {
"file_path": "overleaf/web/frontend/js/features/preview/components/preview-toolbar.js",
"repo_id": "overleaf",
"token_count": 3555
} | 507 |
import PropTypes from 'prop-types'
import { Col, Row } from 'react-bootstrap'
import MemberPrivileges from './member-privileges'
export default function ViewMember({ member }) {
return (
<Row className="project-member">
<Col xs={7}>{member.email}</Col>
<Col xs={3}>
<MemberPrivileges privileges={member.privileges} />
</Col>
</Row>
)
}
ViewMember.propTypes = {
member: PropTypes.shape({
_id: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
privileges: PropTypes.string.isRequired,
}).isRequired,
}
| overleaf/web/frontend/js/features/share-project-modal/components/view-member.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/components/view-member.js",
"repo_id": "overleaf",
"token_count": 216
} | 508 |
import symbols from '../data/symbols.json'
export function createCategories(t) {
return [
{
id: 'Greek',
label: t('category_greek'),
},
{
id: 'Arrows',
label: t('category_arrows'),
},
{
id: 'Operators',
label: t('category_operators'),
},
{
id: 'Relations',
label: t('category_relations'),
},
{
id: 'Misc',
label: t('category_misc'),
},
]
}
export function buildCategorisedSymbols(categories) {
const output = {}
for (const category of categories) {
output[category.id] = []
}
for (const item of symbols) {
if (item.category in output) {
item.character = String.fromCodePoint(
parseInt(item.codepoint.replace(/^U\+0*/, ''), 16)
)
output[item.category].push(item)
}
}
return output
}
| overleaf/web/frontend/js/features/symbol-palette/utils/categories.js/0 | {
"file_path": "overleaf/web/frontend/js/features/symbol-palette/utils/categories.js",
"repo_id": "overleaf",
"token_count": 369
} | 509 |
/* 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.controller(
'CloneProjectModalController',
function ($scope, $modalInstance, $timeout, $http, ide) {
$scope.inputs = { projectName: ide.$scope.project.name + ' (Copy)' }
$scope.state = {
inflight: false,
error: false,
}
$modalInstance.opened.then(() =>
$timeout(() => $scope.$broadcast('open'), 200)
)
const cloneProject = cloneName =>
$http.post(`/project/${ide.$scope.project._id}/clone`, {
_csrf: window.csrfToken,
projectName: cloneName,
})
$scope.clone = function () {
$scope.state.inflight = true
$scope.state.error = false
return cloneProject($scope.inputs.projectName)
.then(function (response) {
const { data } = response
return (window.location = `/project/${data.project_id}`)
})
.catch(function (response) {
const { data, status } = response
$scope.state.inflight = false
if (status === 400) {
return ($scope.state.error = { message: data })
} else {
return ($scope.state.error = true)
}
})
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
| overleaf/web/frontend/js/ide/clone/controllers/CloneProjectModalController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/clone/controllers/CloneProjectModalController.js",
"repo_id": "overleaf",
"token_count": 656
} | 510 |
/* eslint-disable
camelcase,
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'
import Document from '../Document'
export default App.controller(
'SavingNotificationController',
function ($scope, $interval, ide) {
let warnAboutUnsavedChanges
setInterval(() => pollSavedStatus(), 1000)
$(window).bind('beforeunload', () => {
return warnAboutUnsavedChanges()
})
let lockEditorModal = null // modal showing "connection lost"
let originalPermissionsLevel
const MAX_UNSAVED_SECONDS = 15 // lock the editor after this time if unsaved
$scope.docSavingStatus = {}
var pollSavedStatus = function () {
let t
const oldStatus = $scope.docSavingStatus
const oldUnsavedCount = $scope.docSavingStatusCount
const newStatus = {}
let newUnsavedCount = 0
let maxUnsavedSeconds = 0
for (const doc_id in Document.openDocs) {
const doc = Document.openDocs[doc_id]
const saving = doc.pollSavedStatus()
if (!saving) {
newUnsavedCount++
if (oldStatus[doc_id] != null) {
newStatus[doc_id] = oldStatus[doc_id]
t = newStatus[doc_id].unsavedSeconds += 1
if (t > maxUnsavedSeconds) {
maxUnsavedSeconds = t
}
} else {
newStatus[doc_id] = {
unsavedSeconds: 0,
doc: ide.fileTreeManager.findEntityById(doc_id),
}
}
}
}
if (newUnsavedCount > 0 && t > MAX_UNSAVED_SECONDS && !lockEditorModal) {
lockEditorModal = ide.showLockEditorMessageModal(
'Connection lost',
'Sorry, the connection to the server is down.'
)
// put editor in readOnly mode
originalPermissionsLevel = ide.$scope.permissionsLevel
ide.$scope.permissionsLevel = 'readOnly'
lockEditorModal.result.finally(() => {
lockEditorModal = null // unset the modal if connection comes back
// restore original permissions
ide.$scope.permissionsLevel = originalPermissionsLevel
})
}
if (lockEditorModal && newUnsavedCount === 0) {
lockEditorModal.dismiss('connection back up')
// restore original permissions if they were changed
if (originalPermissionsLevel) {
ide.$scope.permissionsLevel = originalPermissionsLevel
}
}
// for performance, only update the display if the old or new
// counts of unsaved files are nonzeror. If both old and new
// unsaved counts are zero then we know we are in a good state
// and don't need to do anything to the UI.
if (newUnsavedCount || oldUnsavedCount) {
$scope.docSavingStatus = newStatus
$scope.docSavingStatusCount = newUnsavedCount
return $scope.$apply()
}
}
return (warnAboutUnsavedChanges = function () {
if (Document.hasUnsavedChanges()) {
return 'You have unsaved changes. If you leave now they will not be saved.'
}
})
}
)
| overleaf/web/frontend/js/ide/editor/controllers/SavingNotificationController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/controllers/SavingNotificationController.js",
"repo_id": "overleaf",
"token_count": 1369
} | 511 |
/* eslint-disable
camelcase
*/
import EditorShareJsCodec from '../../../EditorShareJsCodec'
import 'ace/ace'
const { Range } = ace.require('ace/range')
class TrackChangesAdapter {
constructor(editor) {
this.editor = editor
this.changeIdToMarkerIdMap = {}
}
tearDown() {
this.changeIdToMarkerIdMap = {}
}
clearAnnotations() {
const session = this.editor.getSession()
for (const change_id in this.changeIdToMarkerIdMap) {
const markers = this.changeIdToMarkerIdMap[change_id]
for (const marker_name in markers) {
const marker_id = markers[marker_name]
session.removeMarker(marker_id)
}
}
this.changeIdToMarkerIdMap = {}
}
onInsertAdded(change) {
const start = this.shareJsOffsetToRowColumn(change.op.p)
const end = this.shareJsOffsetToRowColumn(change.op.p + change.op.i.length)
const session = this.editor.getSession()
const background_range = new Range(
start.row,
start.column,
end.row,
end.column
)
const background_marker_id = session.addMarker(
background_range,
'track-changes-marker track-changes-added-marker',
'text'
)
const callout_marker_id = this.createCalloutMarker(
start,
'track-changes-added-marker-callout'
)
this.changeIdToMarkerIdMap[change.id] = {
background_marker_id,
callout_marker_id,
}
}
onDeleteAdded(change) {
const position = this.shareJsOffsetToRowColumn(change.op.p)
const session = this.editor.getSession()
const markerLayer = this.editor.renderer.$markerBack
const klass = 'track-changes-marker track-changes-deleted-marker'
const background_range = this.makeZeroWidthRange(position)
const background_marker_id = session.addMarker(
background_range,
klass,
(html, range, left, top, config) =>
markerLayer.drawSingleLineMarker(
html,
range,
`${klass} ace_start`,
config,
0,
''
)
)
const callout_marker_id = this.createCalloutMarker(
position,
'track-changes-deleted-marker-callout'
)
this.changeIdToMarkerIdMap[change.id] = {
background_marker_id,
callout_marker_id,
}
}
onInsertRemoved(change) {
if (this.changeIdToMarkerIdMap[change.id] == null) {
return
}
const {
background_marker_id,
callout_marker_id,
} = this.changeIdToMarkerIdMap[change.id]
delete this.changeIdToMarkerIdMap[change.id]
const session = this.editor.getSession()
session.removeMarker(background_marker_id)
session.removeMarker(callout_marker_id)
}
onDeleteRemoved(change) {
if (this.changeIdToMarkerIdMap[change.id] == null) {
return
}
const {
background_marker_id,
callout_marker_id,
} = this.changeIdToMarkerIdMap[change.id]
delete this.changeIdToMarkerIdMap[change.id]
const session = this.editor.getSession()
session.removeMarker(background_marker_id)
session.removeMarker(callout_marker_id)
}
onChangeMoved(change) {
let end
const start = this.shareJsOffsetToRowColumn(change.op.p)
if (change.op.i != null) {
end = this.shareJsOffsetToRowColumn(change.op.p + change.op.i.length)
} else {
end = start
}
this.updateMarker(change.id, start, end)
}
onCommentAdded(comment) {
if (this.changeIdToMarkerIdMap[comment.id] == null) {
// Only create new markers if they don't already exist
const start = this.shareJsOffsetToRowColumn(comment.op.p)
const end = this.shareJsOffsetToRowColumn(
comment.op.p + comment.op.c.length
)
const session = this.editor.getSession()
const background_range = new Range(
start.row,
start.column,
end.row,
end.column
)
const background_marker_id = session.addMarker(
background_range,
'track-changes-marker track-changes-comment-marker',
'text'
)
const callout_marker_id = this.createCalloutMarker(
start,
'track-changes-comment-marker-callout'
)
this.changeIdToMarkerIdMap[comment.id] = {
background_marker_id,
callout_marker_id,
}
}
}
onCommentMoved(comment) {
const start = this.shareJsOffsetToRowColumn(comment.op.p)
const end = this.shareJsOffsetToRowColumn(
comment.op.p + comment.op.c.length
)
this.updateMarker(comment.id, start, end)
}
onCommentRemoved(comment) {
if (this.changeIdToMarkerIdMap[comment.id] != null) {
// Resolved comments may not have marker ids
const {
background_marker_id,
callout_marker_id,
} = this.changeIdToMarkerIdMap[comment.id]
delete this.changeIdToMarkerIdMap[comment.id]
const session = this.editor.getSession()
session.removeMarker(background_marker_id)
session.removeMarker(callout_marker_id)
}
}
updateMarker(change_id, start, end) {
if (this.changeIdToMarkerIdMap[change_id] == null) {
return
}
const session = this.editor.getSession()
const markers = session.getMarkers()
const {
background_marker_id,
callout_marker_id,
} = this.changeIdToMarkerIdMap[change_id]
if (background_marker_id != null && markers[background_marker_id] != null) {
const background_marker = markers[background_marker_id]
background_marker.range.start = start
background_marker.range.end = end
}
if (callout_marker_id != null && markers[callout_marker_id] != null) {
const callout_marker = markers[callout_marker_id]
callout_marker.range.start = start
callout_marker.range.end = start
}
}
shareJsOffsetToRowColumn(offset) {
const lines = this.editor.getSession().getDocument().getAllLines()
return EditorShareJsCodec.shareJsOffsetToRowColumn(offset, lines)
}
createCalloutMarker(position, klass) {
const session = this.editor.getSession()
const callout_range = this.makeZeroWidthRange(position)
const markerLayer = this.editor.renderer.$markerBack
return session.addMarker(
callout_range,
klass,
(html, range, left, top, config) =>
markerLayer.drawSingleLineMarker(
html,
range,
`track-changes-marker-callout ${klass} ace_start`,
config,
0,
'width: auto; right: 0;'
)
)
}
makeZeroWidthRange(position) {
const ace_range = new Range(
position.row,
position.column,
position.row,
position.column
)
// Our delete marker is zero characters wide, but Ace doesn't draw ranges
// that are empty. So we monkey patch the range to tell Ace it's not empty
// We do want to claim to be empty if we're off screen after clipping rows
// though. This is the code we need to trick:
// var range = marker.range.clipRows(config.firstRow, config.lastRow);
// if (range.isEmpty()) continue;
ace_range.clipRows = function (first_row, last_row) {
this.isEmpty = function () {
return first_row > this.end.row || last_row < this.start.row
}
return this
}
return ace_range
}
}
export default TrackChangesAdapter
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/track-changes/TrackChangesAdapter.js",
"repo_id": "overleaf",
"token_count": 3017
} | 512 |
/* 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'
const historyEntriesListController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.$entryListViewportEl = null
ctrl.isDragging = false
const _isEntryElVisible = function ($entryEl) {
const entryElTop = $entryEl.offset().top
const entryElBottom = entryElTop + $entryEl.outerHeight()
const entryListViewportElTop = ctrl.$entryListViewportEl.offset().top
const entryListViewportElBottom =
entryListViewportElTop + ctrl.$entryListViewportEl.height()
return (
entryElTop >= entryListViewportElTop &&
entryElBottom <= entryListViewportElBottom
)
}
const _getScrollTopPosForEntry = function ($entryEl) {
const halfViewportElHeight = ctrl.$entryListViewportEl.height() / 2
return $entryEl.offset().top - halfViewportElHeight
}
ctrl.onEntryLinked = function (entry, $entryEl) {
if (
!ctrl.rangeSelectionEnabled &&
entry.toV === ctrl.selectedHistoryVersion
) {
$scope.$applyAsync(() => {
if (!_isEntryElVisible($entryEl)) {
ctrl.$entryListViewportEl.scrollTop(
_getScrollTopPosForEntry($entryEl)
)
}
})
}
}
ctrl.handleEntrySelect = entry => {
if (ctrl.rangeSelectionEnabled) {
ctrl.onRangeSelect({
selectedToV: entry.toV,
selectedFromV: entry.fromV,
})
} else {
ctrl.onVersionSelect({ version: entry.toV })
}
}
ctrl.setRangeToV = toV => {
if (toV > ctrl.selectedHistoryRange.fromV) {
ctrl.onRangeSelect({
selectedToV: toV,
selectedFromV: ctrl.selectedHistoryRange.fromV,
})
}
}
ctrl.setRangeFromV = fromV => {
if (fromV < ctrl.selectedHistoryRange.toV) {
ctrl.onRangeSelect({
selectedToV: ctrl.selectedHistoryRange.toV,
selectedFromV: fromV,
})
}
}
ctrl.initHoveredRange = () => {
ctrl.hoveredHistoryRange = {
toV: ctrl.selectedHistoryRange.toV,
fromV: ctrl.selectedHistoryRange.fromV,
}
}
ctrl.resetHoveredRange = () => {
ctrl.hoveredHistoryRange = { toV: null, fromV: null }
}
ctrl.setHoveredRangeToV = toV => {
if (toV > ctrl.hoveredHistoryRange.fromV) {
$scope.$applyAsync(() => (ctrl.hoveredHistoryRange.toV = toV))
}
}
ctrl.setHoveredRangeFromV = fromV => {
if (fromV < ctrl.hoveredHistoryRange.toV) {
$scope.$applyAsync(() => (ctrl.hoveredHistoryRange.fromV = fromV))
}
}
ctrl.onDraggingStart = () => {
$scope.$applyAsync(() => {
ctrl.isDragging = true
ctrl.initHoveredRange()
})
}
ctrl.onDraggingStop = (isValidDrop, boundary) => {
$scope.$applyAsync(() => {
ctrl.isDragging = false
if (!isValidDrop) {
if (boundary === 'toV') {
ctrl.setRangeToV(ctrl.hoveredHistoryRange.toV)
} else if (boundary === 'fromV') {
ctrl.setRangeFromV(ctrl.hoveredHistoryRange.fromV)
}
}
ctrl.resetHoveredRange()
})
}
ctrl.$onInit = () => {
ctrl.$entryListViewportEl = $element.find('> .history-entries')
ctrl.resetHoveredRange()
}
}
export default App.component('historyEntriesList', {
bindings: {
entries: '<',
users: '<',
loadEntries: '&',
loadDisabled: '<',
loadInitialize: '<',
isLoading: '<',
currentUser: '<',
freeHistoryLimitHit: '<',
currentUserIsOwner: '<',
rangeSelectionEnabled: '<',
selectedHistoryVersion: '<?',
selectedHistoryRange: '<?',
onVersionSelect: '&',
onRangeSelect: '&',
onLabelDelete: '&',
},
controller: historyEntriesListController,
templateUrl: 'historyEntriesListTpl',
})
| overleaf/web/frontend/js/ide/history/components/historyEntriesList.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/components/historyEntriesList.js",
"repo_id": "overleaf",
"token_count": 1654
} | 513 |
/* eslint-disable
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
*/
let HistoryViewModes
export default HistoryViewModes = {
POINT_IN_TIME: 'point_in_time',
COMPARE: 'compare',
}
| overleaf/web/frontend/js/ide/history/util/HistoryViewModes.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/util/HistoryViewModes.js",
"repo_id": "overleaf",
"token_count": 158
} | 514 |
/* eslint-disable
max-len,
no-cond-assign,
no-return-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
*/
import App from '../../../base'
import './pdfViewer'
export default App.directive('pdfng', ($timeout, localStorage) => ({
scope: {
pdfSrc: '=',
highlights: '=',
position: '=',
dblClickCallback: '=',
firstRenderDone: '=',
updateConsumedBandwidth: '=',
},
link(scope, element, attrs) {
scope.loading = false
scope.pleaseJumpTo = null
scope.scale = null
let initializedPosition = false
const initializePosition = function () {
let position, scale
if (initializedPosition) {
return
}
initializedPosition = true
if ((scale = localStorage('pdf.scale')) != null) {
scope.scale = { scaleMode: scale.scaleMode, scale: +scale.scale }
} else {
scope.scale = { scaleMode: 'scale_mode_fit_width' }
}
if ((position = localStorage(`pdf.position.${attrs.key}`))) {
scope.position = {
page: +position.page,
offset: {
top: +position.offset.top,
left: +position.offset.left,
},
}
}
scope.$on('$destroy', () => {
localStorage('pdf.scale', scope.scale)
return localStorage(`pdf.position.${attrs.key}`, scope.position)
})
return $(window).unload(() => {
localStorage('pdf.scale', scope.scale)
return localStorage(`pdf.position.${attrs.key}`, scope.position)
})
}
const flashControls = () =>
scope.$evalAsync(function () {
scope.flashControls = true
return $timeout(() => (scope.flashControls = false), 1000)
})
scope.$on('pdfDoubleClick', (event, e) =>
typeof scope.dblClickCallback === 'function'
? scope.dblClickCallback({
page: e.page - 1,
offset: { top: e.y, left: e.x },
})
: undefined
)
scope.$on('flash-controls', () => flashControls())
scope.$watch('pdfSrc', function (url) {
if (url) {
scope.loading = true
scope.loaded = false
scope.progress = 1
initializePosition()
return flashControls()
}
})
scope.$on('loaded', function () {
scope.loaded = true
scope.progress = 100
return $timeout(function () {
scope.loading = false
return delete scope.progress
}, 500)
})
scope.fitToHeight = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_fit_height'
return (scope.scale = scale)
}
scope.fitToWidth = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_fit_width'
return (scope.scale = scale)
}
scope.zoomIn = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_value'
scale.scale = scale.scale * 1.2
return (scope.scale = scale)
}
scope.zoomOut = function () {
const scale = angular.copy(scope.scale)
scale.scaleMode = 'scale_mode_value'
scale.scale = scale.scale / 1.2
return (scope.scale = scale)
}
if (attrs.resizeOn != null) {
for (const event of Array.from(attrs.resizeOn.split(','))) {
scope.$on(event, function (e) {})
}
}
// console.log 'got a resize event', event, e
scope.$on('progress', (event, progress) =>
scope.$apply(function () {
if (scope.loaded) {
return
}
scope.progress = Math.floor((progress.loaded / progress.total) * 100)
if (scope.progress > 100) {
scope.progress = 100
}
if (scope.progress < 0) {
return (scope.progress = 0)
}
})
)
return scope.$on('$destroy', function () {})
},
// console.log 'pdfjs destroy event'
template: `\
<div
data-pdf-viewer
class="pdfjs-viewer"
pdf-src='pdfSrc'
position='position'
scale='scale'
highlights='highlights'
please-jump-to='pleaseJumpTo'
first-render-done="firstRenderDone"
update-consumed-bandwidth="updateConsumedBandwidth"
>
</div>
<div class="pdfjs-controls" ng-class="{'flash': flashControls }">
<div class="btn-group">
<a href
class="btn btn-info btn-lg"
ng-click="fitToWidth()"
tooltip="Fit to Width"
tooltip-append-to-body="true"
tooltip-placement="bottom"
>
<i class="fa fa-fw fa-arrows-h"></i>
</a>
<a href
class="btn btn-info btn-lg"
ng-click="fitToHeight()"
tooltip="Fit to Height"
tooltip-append-to-body="true"
tooltip-placement="bottom"
>
<i class="fa fa-fw fa-arrows-v"></i>
</a>
<a href
class="btn btn-info btn-lg"
ng-click="zoomIn()"
tooltip="Zoom In"
tooltip-append-to-body="true"
tooltip-placement="bottom"
>
<i class="fa fa-fw fa-search-plus"></i>
</a>
<a href
class="btn btn-info btn-lg"
ng-click="zoomOut()"
tooltip="Zoom Out"
tooltip-append-to-body="true"
tooltip-placement="bottom"
>
<i class="fa fa-fw fa-search-minus"></i>
</a>
</div>
</div>
<div class="progress-thin" ng-show="loading">
<div class="progress-bar" ng-style="{ 'width': progress + '%' }"></div>
</div>\
`,
}))
| overleaf/web/frontend/js/ide/pdfng/directives/pdfJs.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/pdfng/directives/pdfJs.js",
"repo_id": "overleaf",
"token_count": 2566
} | 515 |
import App from '../../../base'
let content = ''
App.directive('addCommentEntry', () => ({
restrict: 'E',
templateUrl: 'addCommentEntryTemplate',
scope: {
onStartNew: '&',
onSubmit: '&',
onCancel: '&',
},
link(scope, element, attrs) {
scope.state = {
isAdding: false,
content: content,
}
scope.$on('comment:start_adding', () => scope.startNewComment())
scope.$on('$destroy', function () {
content = scope.state.content
})
scope.startNewComment = function () {
scope.state.isAdding = true
scope.onStartNew()
setTimeout(() => scope.$broadcast('comment:new:open'))
}
scope.cancelNewComment = function () {
scope.state.isAdding = false
scope.state.content = ''
scope.onCancel()
}
scope.handleCommentKeyPress = function (ev) {
if (ev.keyCode === 13 && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey) {
ev.preventDefault()
if (scope.state.content.length > 0) {
scope.submitNewComment()
}
}
}
scope.submitNewComment = function (event) {
scope.onSubmit({ content: scope.state.content })
content = scope.state.content
scope.state.isAdding = false
scope.state.content = ''
}
},
}))
| overleaf/web/frontend/js/ide/review-panel/directives/addCommentEntry.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/directives/addCommentEntry.js",
"repo_id": "overleaf",
"token_count": 519
} | 516 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
import './services/settings'
import './controllers/SettingsController'
import './controllers/ProjectNameController'
| overleaf/web/frontend/js/ide/settings/index.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/settings/index.js",
"repo_id": "overleaf",
"token_count": 58
} | 517 |
import _ from 'lodash'
/* 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'
const affiliationFormController = function (
$scope,
$element,
$attrs,
UserAffiliationsDataService
) {
const ctrl = this
ctrl.roles = []
ctrl.departments = []
ctrl.countries = []
ctrl.universities = []
let _defaultDepartments = []
ctrl.addUniversityToSelection = universityName => ({
name: universityName,
isUserSuggested: true,
})
ctrl.handleFreeformInputChange = function ($select, propertyToMatch) {
if ($select.search == null || $select.search === '') {
return
}
let resultingItem = $select.search
if (($select.tagging != null ? $select.tagging.fct : undefined) != null) {
resultingItem = $select.tagging.fct($select.search)
}
if (propertyToMatch != null) {
const matchingItem = _.find(
$select.items,
item => item[propertyToMatch] === $select.search
)
if (matchingItem != null) {
resultingItem = matchingItem
}
}
return $select.searchInput.scope().$broadcast('uis:select', resultingItem)
}
// Populates the countries dropdown
UserAffiliationsDataService.getCountries().then(
countries => (ctrl.countries = countries)
)
// Populates the roles dropdown
UserAffiliationsDataService.getDefaultRoleHints().then(
roles => (ctrl.roles = roles)
)
// Fetches the default department hints
UserAffiliationsDataService.getDefaultDepartmentHints().then(
departments => (_defaultDepartments = departments)
)
// Populates the universities dropdown (after selecting a country)
$scope.$watch(
'$ctrl.affiliationData.country',
function (newSelectedCountry, prevSelectedCountry) {
if (
newSelectedCountry != null &&
newSelectedCountry !== prevSelectedCountry
) {
ctrl.affiliationData.university = null
ctrl.affiliationData.role = null
ctrl.affiliationData.department = null
return UserAffiliationsDataService.getUniversitiesFromCountry(
newSelectedCountry
).then(universities => (ctrl.universities = universities))
}
}
)
// Populates the departments dropdown (after selecting a university)
$scope.$watch(
'$ctrl.affiliationData.university',
function (newSelectedUniversity, prevSelectedUniversity) {
if (
newSelectedUniversity != null &&
newSelectedUniversity !== prevSelectedUniversity &&
(newSelectedUniversity.departments != null
? newSelectedUniversity.departments.length
: undefined) > 0
) {
return (ctrl.departments = _.uniq(newSelectedUniversity.departments))
} else {
return (ctrl.departments = _defaultDepartments)
}
}
)
}
export default App.component('affiliationForm', {
bindings: {
affiliationData: '=',
showUniversityAndCountry: '<',
showRoleAndDepartment: '<',
},
controller: affiliationFormController,
templateUrl: 'affiliationFormTpl',
})
| overleaf/web/frontend/js/main/affiliations/components/affiliationForm.js/0 | {
"file_path": "overleaf/web/frontend/js/main/affiliations/components/affiliationForm.js",
"repo_id": "overleaf",
"token_count": 1191
} | 518 |
import App from '../base'
export default App.controller('PostGatewayController', function ($scope) {
$scope.handleGateway = function () {
const { params } = JSON.parse($('#gateway-data').text())
params.viaGateway = 'true'
Object.keys(params).forEach(param => {
$('<input>')
.attr({
type: 'hidden',
name: param,
value: params[param],
})
.appendTo('#gateway')
})
$('#gateway').submit()
}
})
| overleaf/web/frontend/js/main/post-gateway.js/0 | {
"file_path": "overleaf/web/frontend/js/main/post-gateway.js",
"repo_id": "overleaf",
"token_count": 204
} | 519 |
import _ from 'lodash'
/* 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:
* 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
*/
import App from '../base'
App.controller('UserMembershipController', function ($scope, queuedHttp) {
$scope.users = window.users
$scope.groupSize = window.groupSize
$scope.paths = window.paths
$scope.selectedUsers = []
$scope.inputs = {
addMembers: {
content: '',
error: false,
errorMessage: null,
inflightCount: 0,
},
removeMembers: {
error: false,
errorMessage: null,
},
}
const parseEmails = function (emailsString) {
const regexBySpaceOrComma = /[\s,]+/
let emails = emailsString.split(regexBySpaceOrComma)
emails = _.map(emails, email => (email = email.trim()))
emails = _.filter(emails, email => email.indexOf('@') !== -1)
return emails
}
$scope.addMembers = function () {
$scope.inputs.addMembers.error = false
$scope.inputs.addMembers.errorMessage = null
$scope.inputs.addMembers.inflightCount = 0
const emails = parseEmails($scope.inputs.addMembers.content)
return Array.from(emails).map(email => {
$scope.inputs.addMembers.inflightCount += 1
return queuedHttp
.post(window.paths.addMember, {
email,
_csrf: window.csrfToken,
})
.then(function (response) {
$scope.inputs.addMembers.inflightCount -= 1
const { data } = response
if (data.user != null) {
$scope.users.push(data.user)
}
return ($scope.inputs.addMembers.content = '')
})
.catch(function (response) {
$scope.inputs.addMembers.inflightCount -= 1
const { data } = response
$scope.inputs.addMembers.error = true
return ($scope.inputs.addMembers.errorMessage =
data.error != null ? data.error.message : undefined)
})
})
}
$scope.removeMembers = function () {
$scope.inputs.removeMembers.error = false
$scope.inputs.removeMembers.errorMessage = null
for (const user of Array.from($scope.selectedUsers)) {
;(function (user) {
let url
if (window.paths.removeInvite && user.invite && user._id == null) {
url = `${window.paths.removeInvite}/${encodeURIComponent(user.email)}`
} else if (window.paths.removeMember && user._id != null) {
url = `${window.paths.removeMember}/${user._id}`
} else {
return
}
return queuedHttp({
method: 'DELETE',
url,
headers: {
'X-Csrf-Token': window.csrfToken,
},
})
.then(function () {
const index = $scope.users.indexOf(user)
if (index === -1) {
return
}
return $scope.users.splice(index, 1)
})
.catch(function (response) {
const { data } = response
$scope.inputs.removeMembers.error = true
return ($scope.inputs.removeMembers.errorMessage =
data.error != null ? data.error.message : undefined)
})
})(user)
}
return $scope.updateSelectedUsers
}
return ($scope.updateSelectedUsers = () =>
($scope.selectedUsers = $scope.users.filter(user => user.selected)))
})
export default App.controller('UserMembershipListItemController', $scope =>
$scope.$watch('user.selected', function (value) {
if (value != null) {
return $scope.updateSelectedUsers()
}
})
)
| overleaf/web/frontend/js/main/user-membership.js/0 | {
"file_path": "overleaf/web/frontend/js/main/user-membership.js",
"repo_id": "overleaf",
"token_count": 1635
} | 520 |
import { useMemo } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { useTranslation } from 'react-i18next'
function Pagination({ currentPage, totalPages, handlePageClick }) {
const { t } = useTranslation()
const maxOtherPageButtons = useMemo(() => {
let maxOtherPageButtons = 4 // does not include current page, prev/next buttons
if (totalPages < maxOtherPageButtons + 1) {
maxOtherPageButtons = totalPages - 1
}
return maxOtherPageButtons
}, [totalPages])
const pageButtons = useMemo(() => {
const result = []
let nextPage = currentPage + 1
let prevPage = currentPage - 1
function calcPages() {
if (nextPage && nextPage <= totalPages) {
result.push(nextPage)
nextPage++
} else {
nextPage = undefined
}
if (prevPage && prevPage > 0) {
result.push(prevPage)
prevPage--
} else {
prevPage = undefined
}
}
while (result.length < maxOtherPageButtons) {
calcPages()
}
result.push(currentPage) // wait until prev/next calculated to add current
result.sort((a, b) => a - b) // sort numerically
return result
}, [currentPage, totalPages, maxOtherPageButtons])
const morePrevPages = useMemo(() => {
return pageButtons[0] !== 1 && currentPage - maxOtherPageButtons / 2 > 1
}, [pageButtons, currentPage, maxOtherPageButtons])
const moreNextPages = useMemo(() => {
return pageButtons[pageButtons.length - 1] < totalPages
}, [pageButtons, totalPages])
return (
<nav role="navigation" aria-label={t('pagination_navigation')}>
<ul className="pagination">
{currentPage > 1 && (
<li>
<button
onClick={event => handlePageClick(event, currentPage - 1)}
aria-label={t('go_prev_page')}
>
«
</button>
</li>
)}
{morePrevPages && (
<li>
<span className="ellipses">…</span>
</li>
)}
{pageButtons.map(page => (
<PaginationItem
key={`prev-page-${page}`}
page={page}
currentPage={currentPage}
handlePageClick={handlePageClick}
/>
))}
{moreNextPages && (
<li>
<span className="ellipses">…</span>
</li>
)}
{currentPage < totalPages && (
<li>
<button
onClick={event => handlePageClick(event, currentPage + 1)}
aria-label={t('go_next_page')}
>
»
</button>
</li>
)}
</ul>
</nav>
)
}
function PaginationItem({ page, currentPage, handlePageClick }) {
const { t } = useTranslation()
const itemClassName = classNames({ active: currentPage === page })
const ariaCurrent = currentPage === page
const ariaLabel =
currentPage === page ? t('page_current', { page }) : t('go_page', { page })
return (
<li className={itemClassName}>
<button
aria-current={ariaCurrent}
onClick={event => handlePageClick(event, page)}
aria-label={ariaLabel}
>
{page}
</button>
</li>
)
}
function isPositiveNumber(value) {
return typeof value === 'number' && value > 0
}
function isCurrentPageWithinTotalPages(currentPage, totalPages) {
return currentPage <= totalPages
}
Pagination.propTypes = {
currentPage: function (props, propName, componentName) {
if (
!isPositiveNumber(props[propName]) ||
!isCurrentPageWithinTotalPages(props.currentPage, props.totalPages)
) {
return new Error(
'Invalid prop `' +
propName +
'` supplied to' +
' `' +
componentName +
'`. Validation failed.'
)
}
},
totalPages: function (props, propName, componentName) {
if (!isPositiveNumber(props[propName])) {
return new Error(
'Invalid prop `' +
propName +
'` supplied to' +
' `' +
componentName +
'`. Validation failed.'
)
}
},
handlePageClick: PropTypes.func.isRequired,
}
PaginationItem.propTypes = {
currentPage: PropTypes.number.isRequired,
page: PropTypes.number.isRequired,
handlePageClick: PropTypes.func.isRequired,
}
export default Pagination
| overleaf/web/frontend/js/shared/components/pagination.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/components/pagination.js",
"repo_id": "overleaf",
"token_count": 1926
} | 521 |
import { useCallback, useEffect, useRef, useState } from 'react'
import { findDOMNode } from 'react-dom'
export default function useDropdown(defaultOpen = false) {
const [open, setOpen] = useState(defaultOpen)
// store the dropdown node for use in the "click outside" event listener
const ref = useRef(null)
// react-bootstrap v0.x passes `component` instead of `node` to the ref callback
const handleRef = useCallback(
component => {
if (component) {
// eslint-disable-next-line react/no-find-dom-node
ref.current = findDOMNode(component)
}
},
[ref]
)
// prevent a click on the dropdown toggle propagating to the original handler
const handleClick = useCallback(event => {
event.stopPropagation()
}, [])
// handle dropdown toggle
const handleToggle = useCallback(value => {
setOpen(value)
}, [])
// close the dropdown on click outside the dropdown
const handleDocumentClick = useCallback(
event => {
if (ref.current && !ref.current.contains(event.target)) {
setOpen(false)
}
},
[ref]
)
// add/remove listener for click anywhere in document
useEffect(() => {
if (open) {
document.addEventListener('mousedown', handleDocumentClick)
}
return () => {
document.removeEventListener('mousedown', handleDocumentClick)
}
}, [open, handleDocumentClick])
// return props for the Dropdown component
return { ref: handleRef, onClick: handleClick, onToggle: handleToggle, open }
}
| overleaf/web/frontend/js/shared/hooks/use-dropdown.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/hooks/use-dropdown.js",
"repo_id": "overleaf",
"token_count": 512
} | 522 |
/*!
* jquery.storage.js 0.0.3 - https://github.com/yckart/jquery.storage.js
* The client-side storage for every browser, on any device.
*
* Copyright (c) 2012 Yannick Albert (http://yckart.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
* 2013/02/10
**/
;(function($, window, document) {
'use strict';
$.map(['localStorage', 'sessionStorage'], function( method ) {
var defaults = {
cookiePrefix : 'fallback:' + method + ':',
cookieOptions : {
path : '/',
domain : document.domain,
expires : ('localStorage' === method) ? { expires: 365 } : undefined
}
};
try {
$.support[method] = method in window && window[method] !== null;
} catch (e) {
$.support[method] = false;
}
$[method] = function(key, value) {
var options = $.extend({}, defaults, $[method].options);
this.getItem = function( key ) {
var returns = function(key){
return JSON.parse($.support[method] ? window[method].getItem(key) : $.cookie(options.cookiePrefix + key));
};
if(typeof key === 'string') return returns(key);
var arr = [],
i = key.length;
while(i--) arr[i] = returns(key[i]);
return arr;
};
this.setItem = function( key, value ) {
value = JSON.stringify(value);
return $.support[method] ? window[method].setItem(key, value) : $.cookie(options.cookiePrefix + key, value, options.cookieOptions);
};
this.removeItem = function( key ) {
return $.support[method] ? window[method].removeItem(key) : $.cookie(options.cookiePrefix + key, null, $.extend(options.cookieOptions, {
expires: -1
}));
};
this.clear = function() {
if($.support[method]) {
return window[method].clear();
} else {
var reg = new RegExp('^' + options.cookiePrefix, ''),
opts = $.extend(options.cookieOptions, {
expires: -1
});
if(document.cookie && document.cookie !== ''){
$.map(document.cookie.split(';'), function( cookie ){
if(reg.test(cookie = $.trim(cookie))) {
$.cookie( cookie.substr(0,cookie.indexOf('=')), null, opts);
}
});
}
}
};
if (typeof key !== "undefined") {
return typeof value !== "undefined" ? ( value === null ? this.removeItem(key) : this.setItem(key, value) ) : this.getItem(key);
}
return this;
};
$[method].options = defaults;
});
}(jQuery, window, document));
| overleaf/web/frontend/js/vendor/libs/jquery.storage.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/jquery.storage.js",
"repo_id": "overleaf",
"token_count": 1596
} | 523 |
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/* eslint-disable
camelcase,
max-len,
no-class-assign,
no-return-assign,
no-undef,
no-unused-vars,
no-use-before-define,
standard/object-curly-even-spacing,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
define(['ace/ace','crypto-js/sha1'], function (_ignore, CryptoJSSHA1) {
var append = void 0,
bootstrapTransform = void 0,
exports = void 0,
transformComponent = void 0;
var WEB = true;
window.sharejs = exports = {};
var types = exports.types = {};
// These methods let you build a transform function from a transformComponent function
// for OT types like text and JSON in which operations are lists of components
// and transforming them requires N^2 work.
// Add transform and transformX functions for an OT type which has transformComponent defined.
// transformComponent(destination array, component, other component, side)
exports['_bt'] = bootstrapTransform = function bootstrapTransform(type, transformComponent, checkValidOp, append) {
var _transformX = void 0;
var transformComponentX = function transformComponentX(left, right, destLeft, destRight) {
transformComponent(destLeft, left, right, 'left');
return transformComponent(destRight, right, left, 'right');
};
// Transforms rightOp by leftOp. Returns ['rightOp', clientOp']
type.transformX = type['transformX'] = _transformX = function transformX(leftOp, rightOp) {
checkValidOp(leftOp);
checkValidOp(rightOp);
var newRightOp = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Array.from(rightOp)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var rightComponent = _step.value;
// Generate newLeftOp by composing leftOp by rightComponent
var newLeftOp = [];
var k = 0;
while (k < leftOp.length) {
var l;
var nextC = [];
transformComponentX(leftOp[k], rightComponent, newLeftOp, nextC);
k++;
if (nextC.length === 1) {
rightComponent = nextC[0];
} else if (nextC.length === 0) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = Array.from(leftOp.slice(k))[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
l = _step2.value;
append(newLeftOp, l);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
rightComponent = null;
break;
} else {
// Recurse.
var _Array$from = Array.from(_transformX(leftOp.slice(k), nextC)),
_Array$from2 = _slicedToArray(_Array$from, 2),
l_ = _Array$from2[0],
r_ = _Array$from2[1];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = Array.from(l_)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
l = _step3.value;
append(newLeftOp, l);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = Array.from(r_)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var r = _step4.value;
append(newRightOp, r);
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
rightComponent = null;
break;
}
}
if (rightComponent != null) {
append(newRightOp, rightComponent);
}
leftOp = newLeftOp;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return [leftOp, newRightOp];
};
// Transforms op with specified type ('left' or 'right') by otherOp.
return type.transform = type['transform'] = function (op, otherOp, type) {
var _ = void 0;
if (type !== 'left' && type !== 'right') {
throw new Error("type must be 'left' or 'right'");
}
if (otherOp.length === 0) {
return op;
}
// TODO: Benchmark with and without this line. I _think_ it'll make a big difference...?
if (op.length === 1 && otherOp.length === 1) {
return transformComponent([], op[0], otherOp[0], type);
}
if (type === 'left') {
var left = void 0;
var _Array$from3 = Array.from(_transformX(op, otherOp));
var _Array$from4 = _slicedToArray(_Array$from3, 2);
left = _Array$from4[0];
_ = _Array$from4[1];
return left;
} else {
var right = void 0;
var _Array$from5 = Array.from(_transformX(otherOp, op));
var _Array$from6 = _slicedToArray(_Array$from5, 2);
_ = _Array$from6[0];
right = _Array$from6[1];
return right;
}
};
};
// A simple text implementation
//
// Operations are lists of components.
// Each component either inserts or deletes at a specified position in the document.
//
// Components are either:
// {i:'str', p:100}: Insert 'str' at position 100 in the document
// {d:'str', p:100}: Delete 'str' at position 100 in the document
//
// Components in an operation are executed sequentially, so the position of components
// assumes previous components have already executed.
//
// Eg: This op:
// [{i:'abc', p:0}]
// is equivalent to this op:
// [{i:'a', p:0}, {i:'b', p:1}, {i:'c', p:2}]
// NOTE: The global scope here is shared with other sharejs files when built with closure.
// Be careful what ends up in your namespace.
var text = {};
text.name = 'text';
text.create = function () {
return '';
};
var strInject = function strInject(s1, pos, s2) {
return s1.slice(0, pos) + s2 + s1.slice(pos);
};
var checkValidComponent = function checkValidComponent(c) {
if (typeof c.p !== 'number') {
throw new Error('component missing position field');
}
var i_type = _typeof(c.i);
var d_type = _typeof(c.d);
var c_type = _typeof(c.c);
if (!(i_type === 'string' ^ d_type === 'string' ^ c_type === 'string')) {
throw new Error('component needs an i, d or c field');
}
if (!(c.p >= 0)) {
throw new Error('position cannot be negative');
}
};
var checkValidOp = function checkValidOp(op) {
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = Array.from(op)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var c = _step5.value;
checkValidComponent(c);
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
return true;
};
text.apply = function (snapshot, op) {
checkValidOp(op);
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = Array.from(op)[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var component = _step6.value;
if (component.i != null) {
snapshot = strInject(snapshot, component.p, component.i);
} else if (component.d != null) {
var deleted = snapshot.slice(component.p, component.p + component.d.length);
if (component.d !== deleted) {
throw new Error('Delete component \'' + component.d + '\' does not match deleted text \'' + deleted + '\'');
}
snapshot = snapshot.slice(0, component.p) + snapshot.slice(component.p + component.d.length);
} else if (component.c != null) {
var comment = snapshot.slice(component.p, component.p + component.c.length);
if (component.c !== comment) {
throw new Error('Comment component \'' + component.c + '\' does not match commented text \'' + comment + '\'');
}
} else {
throw new Error('Unknown op type');
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
return snapshot;
};
var cloneAndModify = function cloneAndModify(op, modifications) {
var v = void 0;
var newOp = {};
for (var k in op) {
v = op[k];
newOp[k] = v;
}
for (k in modifications) {
v = modifications[k];
newOp[k] = v;
}
return newOp;
};
// Exported for use by the random op generator.
//
// For simplicity, this version of append does not compress adjacent inserts and deletes of
// the same text. It would be nice to change that at some stage.
text._append = append = function append(newOp, c) {
if (c.i === '' || c.d === '') {
return;
}
if (newOp.length === 0) {
return newOp.push(c);
} else {
var last = newOp[newOp.length - 1];
// Compose the insert into the previous insert if possible
if (last.i != null && c.i != null && last.p <= c.p && c.p <= last.p + last.i.length && last.u === c.u) {
return newOp[newOp.length - 1] = cloneAndModify(last, { i: strInject(last.i, c.p - last.p, c.i) });
} else if (last.d != null && c.d != null && c.p <= last.p && last.p <= c.p + c.d.length && last.u === c.u) {
return newOp[newOp.length - 1] = cloneAndModify(last, { d: strInject(c.d, last.p - c.p, last.d), p: c.p });
} else {
return newOp.push(c);
}
}
};
text.compose = function (op1, op2) {
checkValidOp(op1);
checkValidOp(op2);
var newOp = op1.slice();
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = Array.from(op2)[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var c = _step7.value;
append(newOp, c);
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
return newOp;
};
// Attempt to compress the op components together 'as much as possible'.
// This implementation preserves order and preserves create/delete pairs.
text.compress = function (op) {
return text.compose([], op);
};
text.normalize = function (op) {
var newOp = [];
// Normalize should allow ops which are a single (unwrapped) component:
// {i:'asdf', p:23}.
// There's no good way to test if something is an array:
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
// so this is probably the least bad solution.
if (op.i != null || op.p != null) {
op = [op];
}
var _iteratorNormalCompletion8 = true;
var _didIteratorError8 = false;
var _iteratorError8 = undefined;
try {
for (var _iterator8 = Array.from(op)[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
var c = _step8.value;
if (c.p == null) {
c.p = 0;
}
append(newOp, c);
}
} catch (err) {
_didIteratorError8 = true;
_iteratorError8 = err;
} finally {
try {
if (!_iteratorNormalCompletion8 && _iterator8.return) {
_iterator8.return();
}
} finally {
if (_didIteratorError8) {
throw _iteratorError8;
}
}
}
return newOp;
};
// This helper method transforms a position by an op component.
//
// If c is an insert, insertAfter specifies whether the transform
// is pushed after the insert (true) or before it (false).
//
// insertAfter is optional for deletes.
var transformPosition = function transformPosition(pos, c, insertAfter) {
if (c.i != null) {
if (c.p < pos || c.p === pos && insertAfter) {
return pos + c.i.length;
} else {
return pos;
}
} else if (c.d != null) {
// I think this could also be written as: Math.min(c.p, Math.min(c.p - otherC.p, otherC.d.length))
// but I think its harder to read that way, and it compiles using ternary operators anyway
// so its no slower written like this.
if (pos <= c.p) {
return pos;
} else if (pos <= c.p + c.d.length) {
return c.p;
} else {
return pos - c.d.length;
}
} else if (c.c != null) {
return pos;
} else {
throw new Error('unknown op type');
}
};
// Helper method to transform a cursor position as a result of an op.
//
// Like transformPosition above, if c is an insert, insertAfter specifies whether the cursor position
// is pushed after an insert (true) or before it (false).
text.transformCursor = function (position, op, side) {
var insertAfter = side === 'right';
var _iteratorNormalCompletion9 = true;
var _didIteratorError9 = false;
var _iteratorError9 = undefined;
try {
for (var _iterator9 = Array.from(op)[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
var c = _step9.value;
position = transformPosition(position, c, insertAfter);
}
} catch (err) {
_didIteratorError9 = true;
_iteratorError9 = err;
} finally {
try {
if (!_iteratorNormalCompletion9 && _iterator9.return) {
_iterator9.return();
}
} finally {
if (_didIteratorError9) {
throw _iteratorError9;
}
}
}
return position;
};
// Transform an op component by another op component. Asymmetric.
// The result will be appended to destination.
//
// exported for use in JSON type
text._tc = transformComponent = function transformComponent(dest, c, otherC, side) {
var cIntersect = void 0,
intersectEnd = void 0,
intersectStart = void 0,
newC = void 0,
otherIntersect = void 0;
checkValidOp([c]);
checkValidOp([otherC]);
if (c.i != null) {
append(dest, cloneAndModify(c, { p: transformPosition(c.p, otherC, side === 'right') }));
} else if (c.d != null) {
// Delete
if (otherC.i != null) {
// delete vs insert
var s = c.d;
if (c.p < otherC.p) {
append(dest, cloneAndModify(c, { d: s.slice(0, otherC.p - c.p) }));
s = s.slice(otherC.p - c.p);
}
if (s !== '') {
append(dest, cloneAndModify(c, { d: s, p: c.p + otherC.i.length }));
}
} else if (otherC.d != null) {
// Delete vs delete
if (c.p >= otherC.p + otherC.d.length) {
append(dest, cloneAndModify(c, { p: c.p - otherC.d.length }));
} else if (c.p + c.d.length <= otherC.p) {
append(dest, c);
} else {
// They overlap somewhere.
newC = cloneAndModify(c, { d: '' });
if (c.p < otherC.p) {
newC.d = c.d.slice(0, otherC.p - c.p);
}
if (c.p + c.d.length > otherC.p + otherC.d.length) {
newC.d += c.d.slice(otherC.p + otherC.d.length - c.p);
}
// This is entirely optional - just for a check that the deleted
// text in the two ops matches
intersectStart = Math.max(c.p, otherC.p);
intersectEnd = Math.min(c.p + c.d.length, otherC.p + otherC.d.length);
cIntersect = c.d.slice(intersectStart - c.p, intersectEnd - c.p);
otherIntersect = otherC.d.slice(intersectStart - otherC.p, intersectEnd - otherC.p);
if (cIntersect !== otherIntersect) {
throw new Error('Delete ops delete different text in the same region of the document');
}
if (newC.d !== '') {
// This could be rewritten similarly to insert v delete, above.
newC.p = transformPosition(newC.p, otherC);
append(dest, newC);
}
}
} else if (otherC.c != null) {
append(dest, c);
} else {
throw new Error('unknown op type');
}
} else if (c.c != null) {
// Comment
if (otherC.i != null) {
if (c.p < otherC.p && otherC.p < c.p + c.c.length) {
var offset = otherC.p - c.p;
var new_c = c.c.slice(0, +(offset - 1) + 1 || undefined) + otherC.i + c.c.slice(offset);
append(dest, cloneAndModify(c, { c: new_c }));
} else {
append(dest, cloneAndModify(c, { p: transformPosition(c.p, otherC, true) }));
}
} else if (otherC.d != null) {
if (c.p >= otherC.p + otherC.d.length) {
append(dest, cloneAndModify(c, { p: c.p - otherC.d.length }));
} else if (c.p + c.c.length <= otherC.p) {
append(dest, c);
} else {
// Delete overlaps comment
// They overlap somewhere.
newC = cloneAndModify(c, { c: '' });
if (c.p < otherC.p) {
newC.c = c.c.slice(0, otherC.p - c.p);
}
if (c.p + c.c.length > otherC.p + otherC.d.length) {
newC.c += c.c.slice(otherC.p + otherC.d.length - c.p);
}
// This is entirely optional - just for a check that the deleted
// text in the two ops matches
intersectStart = Math.max(c.p, otherC.p);
intersectEnd = Math.min(c.p + c.c.length, otherC.p + otherC.d.length);
cIntersect = c.c.slice(intersectStart - c.p, intersectEnd - c.p);
otherIntersect = otherC.d.slice(intersectStart - otherC.p, intersectEnd - otherC.p);
if (cIntersect !== otherIntersect) {
throw new Error('Delete ops delete different text in the same region of the document');
}
newC.p = transformPosition(newC.p, otherC);
append(dest, newC);
}
} else if (otherC.c != null) {
append(dest, c);
} else {
throw new Error('unknown op type');
}
}
return dest;
};
var invertComponent = function invertComponent(c) {
if (c.i != null) {
return { d: c.i, p: c.p };
} else {
return { i: c.d, p: c.p };
}
};
// No need to use append for invert, because the components won't be able to
// cancel with one another.
text.invert = function (op) {
return Array.from(op.slice().reverse()).map(function (c) {
return invertComponent(c);
});
};
if (WEB != null) {
if (!exports.types) {
exports.types = {};
}
// This is kind of awful - come up with a better way to hook this helper code up.
bootstrapTransform(text, transformComponent, checkValidOp, append);
// [] is used to prevent closure from renaming types.text
exports.types.text = text;
}
// Text document API for text
text.api = {
provides: { text: true },
// The number of characters in the string
getLength: function getLength() {
return this.snapshot.length;
},
// Get the text contents of a document
getText: function getText() {
return this.snapshot;
},
insert: function insert(pos, text, fromUndo, callback) {
var op = { p: pos, i: text };
if (fromUndo) {
op.u = true;
}
op = [op];
this.submitOp(op, callback);
return op;
},
del: function del(pos, length, fromUndo, callback) {
var op = { p: pos, d: this.snapshot.slice(pos, pos + length) };
if (fromUndo) {
op.u = true;
}
op = [op];
this.submitOp(op, callback);
return op;
},
_register: function _register() {
return this.on('remoteop', function (op) {
var _this = this;
return function () {
var result = [];
var _iteratorNormalCompletion10 = true;
var _didIteratorError10 = false;
var _iteratorError10 = undefined;
try {
for (var _iterator10 = Array.from(op)[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
var component = _step10.value;
if (component.i !== undefined) {
result.push(_this.emit('insert', component.p, component.i));
} else if (component.d !== undefined) {
result.push(_this.emit('delete', component.p, component.d));
} else {
result.push(undefined);
}
}
} catch (err) {
_didIteratorError10 = true;
_iteratorError10 = err;
} finally {
try {
if (!_iteratorNormalCompletion10 && _iterator10.return) {
_iterator10.return();
}
} finally {
if (_didIteratorError10) {
throw _iteratorError10;
}
}
}
return result;
}();
});
}
};
// This is a simple port of microevent.js to Coffeescript. I've changed the
// function names to be consistent with node.js EventEmitter.
//
// microevent.js is copyright Jerome Etienne, and licensed under the MIT license:
// https://github.com/jeromeetienne/microevent.js
var nextTick = WEB != null ? function (fn) {
return setTimeout(fn, 0);
} : process['nextTick'];
var MicroEvent = function () {
function MicroEvent() {
_classCallCheck(this, MicroEvent);
}
_createClass(MicroEvent, [{
key: 'on',
value: function on(event, fct) {
if (!this._events) {
this._events = {};
}
if (!this._events[event]) {
this._events[event] = [];
}
this._events[event].push(fct);
return this;
}
}, {
key: 'removeListener',
value: function removeListener(event, fct) {
var _this2 = this;
if (!this._events) {
this._events = {};
}
var listeners = this._events[event] || (this._events[event] = []);
// Sadly, there's no IE8- support for indexOf.
var i = 0;
while (i < listeners.length) {
if (listeners[i] === fct) {
listeners[i] = undefined;
}
i++;
}
nextTick(function () {
return _this2._events[event] = Array.from(_this2._events[event]).filter(function (x) {
return x;
});
});
return this;
}
}, {
key: 'emit',
value: function emit(event) {
if (!(this._events != null ? this._events[event] : undefined)) {
return this;
}
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var _iteratorNormalCompletion11 = true;
var _didIteratorError11 = false;
var _iteratorError11 = undefined;
try {
for (var _iterator11 = Array.from(this._events[event])[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
var fn = _step11.value;
if (fn) {
fn.apply(this, args);
}
}
} catch (err) {
_didIteratorError11 = true;
_iteratorError11 = err;
} finally {
try {
if (!_iteratorNormalCompletion11 && _iterator11.return) {
_iterator11.return();
}
} finally {
if (_didIteratorError11) {
throw _iteratorError11;
}
}
}
return this;
}
}]);
return MicroEvent;
}();
// mixin will delegate all MicroEvent.js function in the destination object
MicroEvent.mixin = function (obj) {
var proto = obj.prototype || obj;
// Damn closure compiler :/
proto.on = MicroEvent.prototype.on;
proto.removeListener = MicroEvent.prototype.removeListener;
proto.emit = MicroEvent.prototype.emit;
return obj;
};
if (WEB == null) {
module.exports = MicroEvent;
}
if (WEB != null) {
exports.extendDoc = function (name, fn) {
return Doc.prototype[name] = fn;
};
}
// A Doc is a client's view on a sharejs document.
//
// Documents are created by calling Connection.open().
//
// Documents are event emitters - use doc.on(eventname, fn) to subscribe.
//
// Documents get mixed in with their type's API methods. So, you can .insert('foo', 0) into
// a text document and stuff like that.
//
// Events:
// - remoteop (op)
// - changed (op)
// - acknowledge (op)
// - error
// - open, closing, closed. 'closing' is not guaranteed to fire before closed.
var Doc = function () {
// connection is a Connection object.
// name is the documents' docName.
// data can optionally contain known document data, and initial open() call arguments:
// {v[erson], snapshot={...}, type, create=true/false/undefined}
// callback will be called once the document is first opened.
function Doc(connection, name, openData) {
_classCallCheck(this, Doc);
// Any of these can be null / undefined at this stage.
this.flush = this.flush.bind(this);
this.setFlushDelay = this.setFlushDelay.bind(this);
this.shout = this.shout.bind(this);
this.connection = connection;
this.name = name;
if (!openData) {
openData = {};
}
this.version = openData.v;
this.snapshot = openData.snaphot;
if (openData.type) {
this._setType(openData.type);
}
this.state = 'closed';
this.autoOpen = false;
// Has the document already been created?
this._create = openData.create;
// The op that is currently roundtripping to the server, or null.
//
// When the connection reconnects, the inflight op is resubmitted.
this.inflightOp = null;
this.inflightCallbacks = [];
// The auth ids which the client has previously used to attempt to send inflightOp. This is
// usually empty.
this.inflightSubmittedIds = [];
// All ops that are waiting for the server to acknowledge @inflightOp
this.pendingOp = null;
this.pendingCallbacks = [];
// Some recent ops, incase submitOp is called with an old op version number.
this.serverOps = {};
}
// Transform a server op by a client op, and vice versa.
_createClass(Doc, [{
key: '_xf',
value: function _xf(client, server) {
if (this.type.transformX) {
return this.type.transformX(client, server);
} else {
var client_ = this.type.transform(client, server, 'left');
var server_ = this.type.transform(server, client, 'right');
return [client_, server_];
}
}
}, {
key: '_otApply',
value: function _otApply(docOp, isRemote, msg) {
var oldSnapshot = this.snapshot;
this.snapshot = this.type.apply(this.snapshot, docOp);
// Its important that these event handlers are called with oldSnapshot.
// The reason is that the OT type APIs might need to access the snapshots to
// determine information about the received op.
this.emit('change', docOp, oldSnapshot, msg);
if (isRemote) {
return this.emit('remoteop', docOp, oldSnapshot, msg);
}
}
}, {
key: '_connectionStateChanged',
value: function _connectionStateChanged(state, data) {
switch (state) {
case 'disconnected':
this.state = 'closed';
// This is used by the server to make sure that when an op is resubmitted it
// doesn't end up getting applied twice.
if (this.inflightOp) {
this.inflightSubmittedIds.push(this.connection.id);
}
this.emit('closed');
break;
case 'ok':
// Might be able to do this when we're connecting... that would save a roundtrip.
if (this.autoOpen) {
this.open();
}
break;
case 'stopped':
if (typeof this._openCallback === 'function') {
this._openCallback(data);
}
break;
}
return this.emit(state, data);
}
}, {
key: '_setType',
value: function _setType(type) {
if (typeof type === 'string') {
type = types[type];
}
if (!type || !type.compose) {
throw new Error('Support for types without compose() is not implemented');
}
this.type = type;
if (type.api) {
for (var k in type.api) {
var v = type.api[k];this[k] = v;
}
return typeof this._register === 'function' ? this._register() : undefined;
} else {
return this.provides = {};
}
}
}, {
key: '_onMessage',
value: function _onMessage(msg) {
// console.warn 's->c', msg
if (msg.open === true) {
// The document has been successfully opened.
this.state = 'open';
this._create = false; // Don't try and create the document again next time open() is called.
if (this.created == null) {
this.created = !!msg.create;
}
if (msg.type) {
this._setType(msg.type);
}
if (msg.create) {
this.created = true;
this.snapshot = this.type.create();
} else {
if (this.created !== true) {
this.created = false;
}
if (msg.snapshot !== undefined) {
this.snapshot = msg.snapshot;
}
}
if (msg.v != null) {
this.version = msg.v;
}
// Resend any previously queued operation.
if (this.inflightOp) {
var response = {
doc: this.name,
op: this.inflightOp,
v: this.version
};
if (this.inflightSubmittedIds.length) {
response.dupIfSource = this.inflightSubmittedIds;
}
this.connection.send(response);
} else {
this.flush();
}
this.emit('open');
return typeof this._openCallback === 'function' ? this._openCallback(null) : undefined;
} else if (msg.open === false) {
// The document has either been closed, or an open request has failed.
if (msg.error) {
// An error occurred opening the document.
if (typeof console !== 'undefined' && console !== null) {
console.error('Could not open document: ' + msg.error);
}
this.emit('error', msg.error);
if (typeof this._openCallback === 'function') {
this._openCallback(msg.error);
}
}
this.state = 'closed';
this.emit('closed');
if (typeof this._closeCallback === 'function') {
this._closeCallback();
}
return this._closeCallback = null;
} else if (msg.op === null && error === 'Op already submitted') {
// We've tried to resend an op to the server, which has already been received successfully. Do nothing.
// The op will be confirmed normally when we get the op itself was echoed back from the server
// (handled below).
} else if (msg.op === undefined && msg.v !== undefined || msg.op && Array.from(this.inflightSubmittedIds).includes(msg.meta.source)) {
// Our inflight op has been acknowledged.
var callback = void 0;
var oldInflightOp = this.inflightOp;
this.inflightOp = null;
this.inflightSubmittedIds.length = 0;
if (this.pendingOp === null) {
// All ops are acked
this.emit('saved');
}
var error = msg.error;
if (error) {
// The server has rejected an op from the client for some reason.
// We'll send the error message to the user and roll back the change.
//
// If the server isn't going to allow edits anyway, we should probably
// figure out some way to flag that (readonly:true in the open request?)
if (this.type.invert) {
var undo = this.type.invert(oldInflightOp);
// Now we have to transform the undo operation by any server ops & pending ops
if (this.pendingOp) {
var _Array$from7 = Array.from(this._xf(this.pendingOp, undo));
var _Array$from8 = _slicedToArray(_Array$from7, 2);
this.pendingOp = _Array$from8[0];
undo = _Array$from8[1];
}
// ... and apply it locally, reverting the changes.
//
// This call will also call @emit 'remoteop'. I'm still not 100% sure about this
// functionality, because its really a local op. Basically, the problem is that
// if the client's op is rejected by the server, the editor window should update
// to reflect the undo.
this._otApply(undo, true, msg);
} else {
this.emit('error', 'Op apply failed (' + error + ') and the op could not be reverted');
}
var _iteratorNormalCompletion12 = true;
var _didIteratorError12 = false;
var _iteratorError12 = undefined;
try {
for (var _iterator12 = Array.from(this.inflightCallbacks)[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
callback = _step12.value;
callback(error);
}
} catch (err) {
_didIteratorError12 = true;
_iteratorError12 = err;
} finally {
try {
if (!_iteratorNormalCompletion12 && _iterator12.return) {
_iterator12.return();
}
} finally {
if (_didIteratorError12) {
throw _iteratorError12;
}
}
}
} else {
// The op applied successfully.
// We may get multiple acks of the same message if we retried it,
// so its ok if we receive an ack for a version that we've already gone past.
// If so, just ignore it
if (msg.v < this.version) {
return;
}
if (msg.v !== this.version) {
throw new Error('Invalid version from server');
}
this.serverOps[this.version] = oldInflightOp;
this.version++;
this.emit('acknowledge', oldInflightOp);
var _iteratorNormalCompletion13 = true;
var _didIteratorError13 = false;
var _iteratorError13 = undefined;
try {
for (var _iterator13 = Array.from(this.inflightCallbacks)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
callback = _step13.value;
callback(null, oldInflightOp);
}
} catch (err) {
_didIteratorError13 = true;
_iteratorError13 = err;
} finally {
try {
if (!_iteratorNormalCompletion13 && _iterator13.return) {
_iterator13.return();
}
} finally {
if (_didIteratorError13) {
throw _iteratorError13;
}
}
}
}
// Send the next op.
return this.delayedFlush();
} else if (msg.op) {
// We got a new op from the server.
// msg is {doc:, op:, v:}
// There is a bug in socket.io (produced on firefox 3.6) which causes messages
// to be duplicated sometimes.
// We'll just silently drop subsequent messages.
if (msg.v < this.version) {
return;
}
if (msg.doc !== this.name) {
return this.emit('error', 'Expected docName \'' + this.name + '\' but got ' + msg.doc);
}
if (msg.v !== this.version) {
return this.emit('error', 'Expected version ' + this.version + ' but got ' + msg.v);
}
// p "if: #{i @inflightOp} pending: #{i @pendingOp} doc '#{@snapshot}' op: #{i msg.op}"
var op = msg.op;
this.serverOps[this.version] = op;
var docOp = op;
if (this.inflightOp !== null) {
var _Array$from9 = Array.from(this._xf(this.inflightOp, docOp));
var _Array$from10 = _slicedToArray(_Array$from9, 2);
this.inflightOp = _Array$from10[0];
docOp = _Array$from10[1];
}
if (this.pendingOp !== null) {
var _Array$from11 = Array.from(this._xf(this.pendingOp, docOp));
var _Array$from12 = _slicedToArray(_Array$from11, 2);
this.pendingOp = _Array$from12[0];
docOp = _Array$from12[1];
}
this.version++;
// Finally, apply the op to @snapshot and trigger any event listeners
return this._otApply(docOp, true, msg);
} else if (msg.meta) {
var _msg$meta = msg.meta,
path = _msg$meta.path,
value = _msg$meta.value;
switch (path != null ? path[0] : undefined) {
case 'shout':
return this.emit('shout', value);
default:
return typeof console !== 'undefined' && console !== null ? console.warn('Unhandled meta op:', msg) : undefined;
}
} else {
return typeof console !== 'undefined' && console !== null ? console.warn('Unhandled document message:', msg) : undefined;
}
}
// Send ops to the server, if appropriate.
//
// Only one op can be in-flight at a time, so if an op is already on its way then
// this method does nothing.
}, {
key: 'flush',
value: function flush() {
this.flushTimeout = null;
// console.log "CALLED FLUSH"
if (this.connection.state !== 'ok' || this.inflightOp !== null || this.pendingOp === null) {
return;
}
// Rotate null -> pending -> inflight
this.inflightOp = this.pendingOp;
this.inflightCallbacks = this.pendingCallbacks;
this.pendingOp = null;
this.pendingCallbacks = [];
this.emit('flipped_pending_to_inflight');
if (window.useShareJsHash || window.sl_debugging) {
var now = Date.now()
var age = this.__lastSubmitTimestamp && (now - this.__lastSubmitTimestamp)
var RECOMPUTE_HASH_INTERVAL = 5000
// check the document hash regularly (but not if we have checked in the last 5 seconds)
var needToRecomputeHash = !this.__lastSubmitTimestamp || (age > RECOMPUTE_HASH_INTERVAL) || (age < 0)
if (needToRecomputeHash || window.sl_debugging) {
// send git hash of current snapshot
var sha1 = CryptoJSSHA1("blob " + this.snapshot.length + "\x00" + this.snapshot).toString()
this.__lastSubmitTimestamp = now;
}
}
// console.log "SENDING OP TO SERVER", @inflightOp, @version
var lastVersion = this.__lastVersion;
this.__lastVersion = this.version;
return this.connection.send({ doc: this.name, op: this.inflightOp, v: this.version, lastV: lastVersion, hash: sha1});
}
// Submit an op to the server. The op maybe held for a little while before being sent, as only one
// op can be inflight at any time.
}, {
key: 'submitOp',
value: function submitOp(op, callback) {
if (this.type.normalize != null) {
op = this.type.normalize(op);
}
var oldSnapshot = this.snapshot;
// If this throws an exception, no changes should have been made to the doc
this.snapshot = this.type.apply(this.snapshot, op);
if (this.pendingOp !== null) {
this.pendingOp = this.type.compose(this.pendingOp, op);
} else {
this.pendingOp = op;
}
if (callback) {
this.pendingCallbacks.push(callback);
}
this.emit('change', op, oldSnapshot);
return this.delayedFlush();
}
}, {
key: 'delayedFlush',
value: function delayedFlush() {
if (this.flushTimeout == null) {
return this.flushTimeout = setTimeout(this.flush, this._flushDelay || 0);
}
}
}, {
key: 'setFlushDelay',
value: function setFlushDelay(delay) {
return this._flushDelay = delay;
}
}, {
key: 'shout',
value: function shout(msg) {
// Meta ops don't have to queue, they can go direct. Good/bad idea?
return this.connection.send({ doc: this.name, meta: { path: ['shout'], value: msg } });
}
// Open a document. The document starts closed.
}, {
key: 'open',
value: function open(callback) {
var _this3 = this;
this.autoOpen = true;
if (this.state !== 'closed') {
return;
}
var message = {
doc: this.name,
open: true
};
if (this.snapshot === undefined) {
message.snapshot = null;
}
if (this.type) {
message.type = this.type.name;
}
if (this.version != null) {
message.v = this.version;
}
if (this._create) {
message.create = true;
}
this.connection.send(message);
this.state = 'opening';
return this._openCallback = function (error) {
_this3._openCallback = null;
return typeof callback === 'function' ? callback(error) : undefined;
};
}
// Close a document.
}, {
key: 'close',
value: function close(callback) {
this.autoOpen = false;
if (this.state === 'closed') {
return typeof callback === 'function' ? callback() : undefined;
}
this.connection.send({ doc: this.name, open: false });
// Should this happen immediately or when we get open:false back from the server?
this.state = 'closed';
this.emit('closing');
return this._closeCallback = callback;
}
}]);
return Doc;
}();
// Make documents event emitters
MicroEvent.mixin(Doc);
exports.Doc = Doc;
// This is some utility code to connect an ace editor to a sharejs document.
var _ace$require = ace.require('ace/range'),
Range = _ace$require.Range;
// Convert an ace delta into an op understood by share.js
var applyAceToShareJS = function applyAceToShareJS(editorDoc, delta, doc, fromUndo) {
// Get the start position of the range, in no. of characters
var getStartOffsetPosition = function getStartOffsetPosition(start) {
// This is quite inefficient - getLines makes a copy of the entire
// lines array in the document. It would be nice if we could just
// access them directly.
var lines = editorDoc.getLines(0, start.row);
var offset = 0;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
offset += i < start.row ? line.length : start.column;
}
// Add the row number to include newlines.
return offset + start.row;
};
var pos = getStartOffsetPosition(delta.start);
// NOTE: Keep in sync with EditorWatchdogManager.
switch (delta.action) {
case 'insert':
text = delta.lines.join('\n');
doc.insert(pos, text, fromUndo);
break;
case 'remove':
text = delta.lines.join('\n');
doc.del(pos, text.length, fromUndo);
break;
default:
throw new Error('unknown action: ' + delta.action);
}
};
// Attach an ace editor to the document. The editor's contents are replaced
// with the document's contents unless keepEditorContents is true. (In which case the document's
// contents are nuked and replaced with the editor's).
window.sharejs.extendDoc('attach_ace', function (editor, keepEditorContents, maxDocLength) {
if (!this.provides['text']) {
throw new Error('Only text documents can be attached to ace');
}
var doc = this;
var editorDoc = editor.getSession().getDocument();
editorDoc.setNewLineMode('unix');
function check() {
return window.setTimeout(function () {
var editorText = editorDoc.getValue();
var otText = doc.getText();
if (editorText !== otText) {
doc.emit('error','Text does not match in ace')
console.error('Text does not match!');
console.error('editor: ' + editorText);
return console.error('ot: ' + otText);
}
}
// Should probably also replace the editor text with the doc snapshot.
, 0);
};
onDelete(0, editorDoc.getValue());
onInsert(0, doc.getText());
check();
// Listen for edits in ace
function editorListener(change) {
if (change.origin === 'remote') {
// this change has been injected via sharejs
return;
}
if (maxDocLength != null && editorDoc.getValue().length > maxDocLength) {
doc.emit('error', new Error('document length is greater than maxDocLength'));
return;
}
var fromUndo = !!(editor.getSession().$fromUndo || editor.getSession().$fromReject);
applyAceToShareJS(editorDoc, change, doc, fromUndo);
return check();
};
editorDoc.on('change', editorListener);
// Horribly inefficient.
function offsetToPos(offset) {
// Again, very inefficient.
var lines = editorDoc.getAllLines();
var row = 0;
for (row = 0; row < lines.length; row++) {
var line = lines[row];
if (offset <= line.length) {
break;
}
// +1 for the newline.
offset -= lines[row].length + 1;
}
return { row: row, column: offset };
};
// We want to insert the flag `origin: 'remote'` into the delta if the op
// is the initial document write or comes from the underlying sharejs doc
// (which means it is from a remote op), so we have to do the work of
// editorDoc.insert and editorDoc.remove manually.
// These methods are copied from ace.js doc#insert and #remove, and then
// inject the `origin: 'remote'` flag into the delta.
function onInsert(pos, text) {
if (editorDoc.getLength() <= 1) {
editorDoc.$detectNewLine(text);
}
var lines = editorDoc.$split(text);
var position = offsetToPos(pos);
var start = editorDoc.clippedPos(position.row, position.column);
var end = {
row: start.row + lines.length - 1,
column: (lines.length === 1 ? start.column : 0) + lines[lines.length - 1].length
};
editorDoc.applyDelta({
start: start,
end: end,
action: 'insert',
lines: lines,
origin: 'remote'
});
return check();
};
function onDelete(pos, text) {
var range = Range.fromPoints(offsetToPos(pos), offsetToPos(pos + text.length));
var start = editorDoc.clippedPos(range.start.row, range.start.column);
var end = editorDoc.clippedPos(range.end.row, range.end.column);
editorDoc.applyDelta({
start: start,
end: end,
action: 'remove',
lines: editorDoc.getLinesForRange({ start: start, end: end }),
origin: 'remote'
});
return check();
};
doc.on('insert', onInsert);
doc.on('delete', onDelete);
doc.detach_ace = function () {
doc.removeListener('insert', onInsert);
doc.removeListener('delete', onDelete);
editorDoc.removeListener('change', editorListener);
return delete doc.detach_ace;
};
});
// This is some utility code to connect a CodeMirror editor
// to a sharejs document.
// It is heavily inspired from the Ace editor hook.
// Convert a CodeMirror delta into an op understood by share.js
var applyCMToShareJS = function applyCMToShareJS(editorDoc, delta, doc, fromUndo) {
// CodeMirror deltas give a text replacement.
// I tuned this operation a little bit, for speed.
var startPos = 0; // Get character position from # of chars in each line.
var i = 0; // i goes through all lines.
// Compute the position from the shareJS snapshot because we are in the CodeMirror
// change event, where the change has already been applied to the editorDoc
var docLines = doc.snapshot.split('\n', delta.from.line) // only split the document as far as we need to
while (i < delta.from.line) {
startPos += docLines[i].length + 1; // Add 1 for '\n'
i++;
}
startPos += delta.from.ch;
// NOTE: Keep in sync with EditorWatchdogManager.
if (delta.removed) {
doc.del(startPos, delta.removed.join('\n').length, fromUndo);
}
if (delta.text) {
return doc.insert(startPos, delta.text.join('\n'), fromUndo);
}
};
// Attach a CodeMirror editor to the document. The editor's contents are replaced
// with the document's contents unless keepEditorContents is true. (In which case
// the document's contents are nuked and replaced with the editor's).
// NOTE: When upgrading CM, make sure to check for new special cases of
// origin prefixes as documented for `doc.setSelection`. We are using
// a custom `origin: 'remote'` which may conflict.
// Perma link of the docs at the time of writing this note:
// https://web.archive.org/web/20201029163528/https://codemirror.net/doc/manual.html#selection_origin
window.sharejs.extendDoc('attach_cm', function (editor, keepEditorContents) {
if (!this.provides.text) {
throw new Error('Only text documents can be attached to CodeMirror2');
}
var sharedoc = this;
var editorDoc = editor.getDoc();
function check() {
return window.setTimeout(function () {
var editorText = editor.getValue();
var otText = sharedoc.getText();
if (editorText !== otText) {
sharedoc.emit('error','Text does not match in CodeMirror')
console.error('Text does not match!');
console.error('editor: ' + editorText);
return console.error('ot: ' + otText);
}
}
// Removed editor.setValue here as it would cause recursive loops if
// consistency check failed - because setting the value would trigger
// the change event
, 0);
};
onDelete(0, editor.getValue());
onInsert(0, sharedoc.getText());
check();
// Listen for edits in CodeMirror.
function editorListener(ed, change) {
if (change.origin === 'remote') {
// this change has been injected via sharejs
return;
}
var fromUndo = (change.origin === 'undo')
applyCMToShareJS(editorDoc, change, sharedoc, fromUndo);
return check();
};
editorDoc.on('change', editorListener);
function onInsert(pos, text) {
// All the primitives we need are already in CM's API.
// call signature: editor.replaceRange(text, from, to, origin)
editor.replaceRange(text, editor.posFromIndex(pos), undefined, 'remote');
// Clear CM's undo/redo history on remote edit. This prevents issues where
// a user can accidentally remove another user's edits
editor.clearHistory();
return check();
};
function onDelete(pos, text) {
var from = editor.posFromIndex(pos);
var to = editor.posFromIndex(pos + text.length);
editor.replaceRange('', from, to, 'remote');
// Clear CM's undo/redo history on remote edit. This prevents issues where
// a user can accidentally remove another user's edits
editor.clearHistory()
return check();
};
this.on('insert', onInsert);
this.on('delete', onDelete);
this.detach_cm = function () {
this.removeListener('insert', onInsert);
this.removeListener('delete', onDelete);
editorDoc.off('change', editorListener);
return delete this.detach_cm;
};
});
return window.sharejs;
});
| overleaf/web/frontend/js/vendor/libs/sharejs.js/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/sharejs.js",
"repo_id": "overleaf",
"token_count": 25010
} | 524 |
import { ContextRoot } from '../js/shared/context/root-context'
import { setupContext } from './fixtures/context'
import importOverleafModules from '../macros/import-overleaf-module.macro'
import useFetchMock from './hooks/use-fetch-mock'
const [
{
import: { default: GitBridgeModal },
},
] = importOverleafModules('gitBridge')
setupContext()
export const GitBridgeUrlModal = args => <GitBridgeModal {...args} />
GitBridgeUrlModal.args = {
type: 'show_url',
}
export const CollaboratorModal = args => <GitBridgeModal {...args} />
CollaboratorModal.args = {
type: 'collaborator',
}
export const TeaserModal = args => {
useFetchMock(fetchMock => fetchMock.post('express:/event/:key', 202))
return <GitBridgeModal {...args} />
}
TeaserModal.args = {
type: 'teaser',
}
export default {
title: 'Modals / Git Bridge',
component: GitBridgeModal,
args: {
show: true,
},
argTypes: {
handleHide: { action: 'handleHide' },
},
decorators: [
Story => (
<>
<ContextRoot ide={window._ide} settings={{}}>
<Story />
</ContextRoot>
</>
),
],
}
| overleaf/web/frontend/stories/git-bridge-modal.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/git-bridge-modal.stories.js",
"repo_id": "overleaf",
"token_count": 432
} | 525 |
/* eslint-disable jsx-a11y/anchor-is-valid */
import { Grid, Row, Col, Button, Alert, ProgressBar } from 'react-bootstrap'
export const Colors = () => {
return (
<div className="content content-alt">
<Grid>
<Row>
<Col md={8} mdOffset={2}>
<h2>Colours</h2>
<div className="color-row">
<div className="color-box ol-blue-gray-1">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-blue-gray-2">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-blue-gray-3">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-blue-gray-4">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-blue-gray-5">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-blue-gray-6">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
</div>
<div className="color-row">
<div className="color-box ol-green">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-dark-green">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-blue">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-dark-blue">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-red">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
<div className="color-box ol-dark-red">
<div className="color-swatch" />
<div className="color-label">
<pre className="color-less-var" />
<pre className="color-hex-val" />
<pre className="color-rgb-val" />
</div>
</div>
</div>
</Col>
</Row>
</Grid>
</div>
)
}
export const Headings = () => {
return (
<div className="content content-alt">
<Grid>
<Row>
<Col md={8} mdOffset={2}>
<h2>Headings</h2>
<p>Here are our heading styles:</p>
<h1>Heading level 1</h1>
<p>
Lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
ipsum
</p>
<h2>Heading level 2</h2>
<p>
Lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
ipsum lorem ipsum
</p>
<h3>Heading level 3</h3>
<p>
Lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
ipsum lorem ipsum
</p>
<h4>Heading level 4</h4>
<p>
Lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
ipsum lorem ipsum
</p>
</Col>
</Row>
</Grid>
</div>
)
}
export const Buttons = () => {
return (
<div className="content content-alt">
<Grid>
<Row>
<Col md={8} mdOffset={2}>
<h2>Buttons</h2>
<p>Our primary button is red:</p>
<p>
<Button bsStyle="primary">Primary Button</Button>
</p>
<p>Our secondary button is blue:</p>
<p>
<Button bsStyle="info">Secondary Button</Button>
</p>
<p>All button styles</p>
<p />
<div className="btn-toolbar">
<Button bsStyle="primary">Primary</Button>
<Button bsStyle="info">Info (secondary)</Button>
<Button bsStyle="default">Default</Button>
<Button bsStyle="success">Success</Button>
<Button bsStyle="warning">Warning</Button>
<Button bsStyle="danger">Danger</Button>
</div>
<p />
<h2>Hyperlinks</h2>
<p>
Hyperlinks are highlighted <a href="#">as shown</a>.
</p>
</Col>
</Row>
</Grid>
</div>
)
}
export const Alerts = () => {
return (
<div className="content content-alt">
<Grid>
<Row>
<Col md={8} mdOffset={2}>
<h2>Alerts</h2>
<Alert bsStyle="danger">
An <code>.alert-danger</code> alert
</Alert>
<Alert bsStyle="success">
An <code>.alert-success</code> alert
</Alert>
<Alert bsStyle="info">
An <code>.alert-info</code> alert
</Alert>
<Alert bsStyle="warning">
An <code>.alert-warning</code> alert
</Alert>
</Col>
</Row>
</Grid>
</div>
)
}
export const ProgressBars = () => {
return (
<div className="content content-alt">
<Grid>
{' '}
<Row>
<Col md={8} mdOffset={2}>
<h2>Progress bars</h2>
<ProgressBar bsStyle="danger" now={20} />
<ProgressBar bsStyle="success" now={40} />
<ProgressBar bsStyle="info" now={60} />
<ProgressBar bsStyle="warning" now={80} />
</Col>
</Row>
</Grid>
</div>
)
}
export const Cards = () => {
return (
<div className="content content-alt">
<Grid>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<p>
Cards look best on a <code>.content.content-alt</code>{' '}
background
</p>
</div>
</Col>
</Row>
</Grid>
</div>
)
}
export const Forms = () => {
return (
<div className="content content-alt">
<Grid>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<h2>Form elements—basic example</h2>
<form className="ng-pristine ng-valid">
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input
className="form-control"
id="exampleInputEmail1"
type="email"
placeholder="Email"
/>
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input
className="form-control"
id="exampleInputPassword1"
type="password"
placeholder="Password"
/>
</div>
<div className="form-group">
<label htmlFor="exampleInputFile">File input</label>
<input id="exampleInputFile" type="file" />
<p className="help-block">
Example block-level help text here.
</p>
</div>
<div className="checkbox">
<label>
<input type="checkbox" /> Check me out
</label>
<button className="btn btn-default" type="submit">
Submit
</button>
</div>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<h2>Inline form</h2>
<form className="form-inline ng-pristine ng-valid">
<div className="form-group">
<label htmlFor="exampleInputName2">Name</label>
<input
className="form-control"
id="exampleInputName2"
type="text"
placeholder="Jane Doe"
/>
</div>
<div className="form-group">
<label htmlFor="exampleInputEmail2">Email</label>
<input
className="form-control"
id="exampleInputEmail2"
type="email"
placeholder="jane.doe@example.com"
/>
</div>
<button className="btn btn-default" type="submit">
Send invitation
</button>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<form className="form-inline ng-pristine ng-valid">
<div className="form-group">
<label className="sr-only" htmlFor="exampleInputEmail3">
Email address
</label>
<input
className="form-control"
id="exampleInputEmail3"
type="email"
placeholder="Email"
/>
</div>
<div className="form-group">
<label className="sr-only" htmlFor="exampleInputPassword3">
Password
</label>
<input
className="form-control"
id="exampleInputPassword3"
type="password"
placeholder="Password"
/>
</div>
<div className="checkbox">
<label>
<input type="checkbox" /> Remember me
</label>
</div>
<button className="btn btn-default" type="submit">
Sign in
</button>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<form className="form-inline ng-pristine ng-valid">
<div className="form-group">
<label className="sr-only" htmlFor="exampleInputAmount">
Amount (in dollars)
</label>
<div className="input-group">
<div className="input-group-addon">$</div>
<input
className="form-control"
id="exampleInputAmount"
type="text"
placeholder="Amount"
/>
<div className="input-group-addon">.00</div>
</div>
</div>
<button className="btn btn-primary" type="submit">
Transfer cash
</button>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<h2>Horizontal form</h2>
<form className="form-horizontal ng-pristine ng-valid">
<div className="form-group">
<label
className="col-sm-2 control-label"
htmlFor="inputEmail3"
>
Email
</label>
<div className="col-sm-10">
<input
className="form-control"
id="inputEmail3"
type="email"
placeholder="Email"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label"
htmlFor="inputPassword3"
>
Password
</label>
<div className="col-sm-10">
<input
className="form-control"
id="inputPassword3"
type="password"
placeholder="Password"
/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="checkbox">
<label>
<input type="checkbox" /> Remember me
</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button className="btn btn-default" type="submit">
Sign in
</button>
</div>
</div>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<h2>Supported controls</h2>
<form className="ng-pristine ng-valid">
<input
className="form-control"
type="text"
placeholder="Text input"
/>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<textarea
className="form-control"
rows="3"
placeholder="Textarea"
/>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<div className="checkbox">
<label>
<input type="checkbox" value="" />
Option one is this and that—be sure to include why it's
great
</label>
</div>
<div className="checkbox disabled">
<label>
<input type="checkbox" value="" disabled="" />
Option two is disabled
</label>
</div>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<div className="radio">
<label>
<input
id="optionsRadios1"
type="radio"
name="optionsRadios"
value="option1"
checked
/>
Option one is this and that—be sure to include why it's
great
</label>
</div>
<div className="radio">
<label>
<input
id="optionsRadios2"
type="radio"
name="optionsRadios"
value="option2"
/>
Option two can be something else and selecting it will
deselect option one
</label>
</div>
<div className="radio disabled">
<label>
<input
id="optionsRadios3"
type="radio"
name="optionsRadios"
value="option3"
disabled=""
/>
Option three is disabled
</label>
</div>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<label className="checkbox-inline">
<input id="inlineCheckbox1" type="checkbox" value="option1" />
1
</label>
<label className="checkbox-inline">
<input id="inlineCheckbox2" type="checkbox" value="option2" />
2
</label>
<label className="checkbox-inline">
<input id="inlineCheckbox3" type="checkbox" value="option3" />
3
</label>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<label className="radio-inline">
<input
id="inlineRadio1"
type="radio"
name="inlineRadioOptions"
value="option1"
/>
1
</label>
<label className="radio-inline">
<input
id="inlineRadio2"
type="radio"
name="inlineRadioOptions"
value="option2"
/>
2
</label>
<label className="radio-inline">
<input
id="inlineRadio3"
type="radio"
name="inlineRadioOptions"
value="option3"
/>
3
</label>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<select className="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<select className="form-control" multiple="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<h2>Form states</h2>
<form className="form-inline ng-pristine ng-valid">
<div className="form-group">
{/* eslint-disable-next-line */}
<label className="sr-only">Emails</label>
<p className="form-control-static">email@example.com</p>
</div>
<div className="form-group">
<label className="sr-only" htmlFor="inputPassword2">
Password
</label>
<input
className="form-control"
id="inputPassword2"
type="password"
placeholder="Password"
/>
</div>
<button className="btn btn-default" type="submit">
Confirm identity
</button>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<input
className="form-control"
id="focusedInput"
type="text"
value="Demonstrative focus state"
/>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<input
className="form-control"
id="disabledInput"
type="text"
placeholder="Disabled input here…"
disabled=""
/>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<input
className="form-control"
type="text"
placeholder="Readonly input here…"
readOnly=""
/>
</form>
</div>
</Col>
</Row>
<Row>
<Col md={8} mdOffset={2}>
<div className="card">
<form className="ng-pristine ng-valid">
<div className="form-group">
<label htmlFor="inputHelpBlock">Input with help text</label>
<input
className="form-control"
id="inputHelpBlock"
type="text"
aria-describedby="helpBlock"
/>
</div>
<span className="help-block" id="helpBlock">
A block of help text that breaks onto a new line and may
extend beyond one line.
</span>
</form>
</div>
</Col>
</Row>
<Row className="row-spaced">
<Col md={8} mdOffset={2}>
<div className="card">
<h2>Validation states</h2>
<form className="ng-pristine ng-valid">
<div className="form-group has-success">
<label className="control-label" htmlFor="inputSuccess1">
Input with success
</label>
<input
className="form-control"
id="inputSuccess1"
type="text"
aria-describedby="helpBlock2"
/>
<span className="help-block" id="helpBlock2">
A block of help text that breaks onto a new line and may
extend beyond one line.
</span>
</div>
<div className="form-group has-warning">
<label className="control-label" htmlFor="inputWarning1">
Input with warning
</label>
<input
className="form-control"
id="inputWarning1"
type="text"
/>
</div>
<div className="form-group has-error">
<label className="control-label" htmlFor="inputError1">
Input with error
</label>
<input
className="form-control"
id="inputError1"
type="text"
/>
</div>
<div className="has-success">
<div className="checkbox">
<label>
<input
id="checkboxSuccess"
type="checkbox"
value="option1"
/>
Checkbox with success
</label>
</div>
</div>
<div className="has-warning">
<div className="checkbox">
<label>
<input
id="checkboxWarning"
type="checkbox"
value="option1"
/>
Checkbox with warning
</label>
</div>
</div>
<div className="has-error">
<div className="checkbox">
<label>
<input
id="checkboxError"
type="checkbox"
value="option1"
/>
Checkbox with error
</label>
</div>
</div>
</form>
</div>
</Col>
</Row>
</Grid>
</div>
)
}
export default {
title: 'Style Guide',
}
| overleaf/web/frontend/stories/style-guide.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/style-guide.stories.js",
"repo_id": "overleaf",
"token_count": 17077
} | 526 |
@twitter-color: #1da1f2;
@facebook-color: #3b5998;
@email-color: #808b9a;
@link-to-us-color: #406eb3;
.bonus {
margin-top: 15px;
.page-header h1 {
text-align: center;
}
h2 {
text-align: center;
font-size: 20px;
line-height: 28px;
margin-bottom: @line-height-computed;
margin-top: 0;
&.direct-link {
margin-top: @line-height-computed;
}
}
.bonus-banner {
.bonus-top {
border-bottom: 1px solid lighten(@blue, 40%);
}
.title {
a {
display: flex;
align-items: center;
font-size: 18px;
padding: 20px;
background-color: white;
border-bottom: 1px solid lighten(@blue, 40%);
color: @blue;
> i {
margin-right: 10px;
}
&:hover,
&:focus {
background-color: lighten(@blue, 45%);
text-decoration: none;
}
}
}
a.twitter > i {
color: @twitter-color;
}
a.facebook > i {
color: @facebook-color;
}
a.email > i {
color: @email-color;
}
a.link > i {
color: @link-to-us-color;
}
h2.direct-link {
}
}
p.thanks {
font-size: 18px;
line-height: 28px;
margin-top: 10px;
text-align: center;
}
.number {
position: absolute;
margin-left: -13px;
width: 26px;
padding: 3px 0;
text-align: center;
background-color: #ddd;
&.active {
background-color: @blue;
color: white;
}
border-radius: 3px;
}
.progress {
margin-top: @line-height-computed / 2;
margin-left: -15px;
margin-right: -15px;
height: 30px;
}
.perk {
position: absolute;
background-color: #ddd;
border-radius: 5px;
text-align: center;
padding: 5px 5px;
min-width: min-content;
width: 110px;
margin-left: -50px;
font-size: 14px;
&:before {
border-bottom: 8px solid #ddd;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
content: '';
position: absolute;
left: 42px;
top: -8px;
}
&.active {
color: white;
background-color: @blue;
&:before {
border-bottom: 8px solid @blue;
}
}
}
}
.link-modal {
text-align: center;
textarea {
width: 95%;
margin-bottom: 0;
}
}
| overleaf/web/frontend/stylesheets/app/bonus.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/bonus.less",
"repo_id": "overleaf",
"token_count": 1160
} | 527 |
.modal-body-publish {
@label-column-width: 10em;
@control-left-margin: 1em;
.form-control-box {
margin-bottom: 1.5ex;
margin-left: @control-left-margin;
label {
display: inline-block;
width: @label-column-width;
vertical-align: baseline;
}
label.checkbox-label {
width: auto;
}
.form-control {
display: inline-block;
width: 60%;
}
input[type='checkbox'] {
margin-right: 0.5em;
}
textarea {
vertical-align: baseline;
}
select {
padding-top: 1ex;
padding-bottom: 1ex;
padding-left: 1em;
padding-right: 1em;
}
option {
margin-left: -4px;
}
a.help {
margin-left: 0.6em;
}
}
.no-label {
margin-left: @label-column-width + @control-left-margin;
}
#search-input-container {
overflow: hidden;
margin: 5px 0 10px;
}
.table-content-name {
width: 100%;
margin-bottom: 10px;
font-weight: 300;
}
.table-content-category {
font-weight: 300;
text-align: right;
font-style: italic;
width: 30%;
float: right;
text-transform: capitalize;
}
.table-content-category ~ .table-content-name {
width: 70%;
display: inline-block;
}
.wl-icon:before {
font-size: 14px;
}
.btn-wrapping {
min-width: 8em;
max-width: 25em;
white-space: normal;
}
.button-as-link {
color: green;
text-transform: none;
background: none;
padding: 0;
border: none;
border-radius: 0;
font-size: 14px;
@extend a;
&:hover,
&:active,
&:focus {
color: green;
background: none;
}
text-align: left;
}
.affix-content-title {
color: @gray-light;
font-size: 1.2em;
padding-left: 10px;
}
.affix-subcontent {
margin: 5px 0 50px;
}
.overbox {
padding: @line-height-computed / 2;
background-color: white;
margin-top: @line-height-computed / 2;
border: 1px solid @gray-lighter;
border-radius: 9px;
}
.content-as-table {
.table-content,
.table-content > * {
display: table;
}
.table-content-icon {
float: left;
height: 100px;
width: 106px;
display: flex;
align-items: flex-start;
overflow: hidden;
* {
border: 1px solid @gray-lightest;
width: 100%;
}
}
.table-content-text {
float: right;
width: calc(~'100% - 106px');
vertical-align: top;
padding-left: 15px;
}
.table-content-slogan {
height: 100px;
overflow: hidden;
}
.table-content-link {
padding-top: 10px;
}
}
}
| overleaf/web/frontend/stylesheets/app/editor/publish-modal.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/editor/publish-modal.less",
"repo_id": "overleaf",
"token_count": 1243
} | 528 |
@brand-ieee-color: #00629b;
@brand-google-color: #276fea; // Not the "official" color but modified for a11y
@brand-twitter-color: #1da1f2;
@brand-orcid-color: #a6ce39;
@brand-sharelatex-color: #a93529;
.login-register-alternatives {
.form-group:last-child {
margin-bottom: 0;
}
}
.login-register-container {
max-width: 400px;
margin: 0 auto;
}
.login-register-header {
padding-top: @line-height-computed;
padding-bottom: @line-height-computed - 5;
border-bottom: solid 1px @hr-border;
}
.login-register-header-heading {
margin: 0;
color: @text-color;
}
.login-register-card {
padding-top: 0;
padding-bottom: 0;
text-align: center;
}
.login-register-form,
.login-register-sharelatex {
padding: @line-height-computed;
border-bottom: solid 1px @hr-border;
&:last-child {
border-bottom-width: 0;
}
}
.login-register-other-links {
padding: @line-height-computed;
}
.login-register-text,
.login-register-hr-text-container {
margin: 0;
}
.login-register-text {
padding-bottom: 25px;
&:last-child {
padding-bottom: 0;
}
}
.login-register-hr-text-container {
line-height: 1;
position: relative;
padding: @line-height-computed 0;
&::before {
content: '';
position: absolute;
height: 1px;
background-color: @hr-border;
top: 50%;
left: 0;
right: 0;
}
}
.login-register-hr-text {
position: relative;
background-color: #fff;
padding: 0 (@line-height-computed / 2);
}
.login-register-sharelatex-tooltip {
display: inline-block;
font-size: 135%;
position: relative;
top: 2px;
margin-left: 3px;
color: @link-color;
cursor: pointer;
}
.login-register-newsletter {
font-size: 90%;
margin-top: @line-height-computed;
text-align: left;
& > .checkbox {
margin-bottom: 0;
}
}
.login-btn {
.btn;
.btn-default;
position: relative;
padding-left: 20px;
padding-right: 0;
}
.login-btn-sharelatex {
background-color: @brand-sharelatex-color;
&:focus,
&:hover {
background-color: darken(@brand-sharelatex-color, 8%);
}
&:active {
background-color: darken(@brand-sharelatex-color, 16%);
}
}
.login-btn-icon {
position: absolute;
top: 4px;
left: 4px;
background: #fff url(/img/brand/lion.svg) center/20px no-repeat;
border-radius: 99999px;
width: 26px;
height: 26px;
&::before {
content: '\00a0'; // Non-breakable space. A non-breakable character here makes this icon work like font-awesome.
}
}
.login-btn-icon-ieee {
background-image: url(/img/other-brands/logo_ieee.svg);
}
.login-btn-icon-google {
background-image: url(/img/other-brands/logo_google.svg);
}
.login-btn-icon-twitter {
background-image: url(/img/other-brands/logo_twitter.svg);
}
.login-btn-icon-orcid {
background-image: url(/img/other-brands/logo_orcid.svg);
}
.login-btn-icon-sharelatex {
background-size: 22px;
}
.login-register-header-heading {
margin: 0;
color: @text-color;
}
.registration-message-heading {
color: @text-color;
}
.registration-message-details {
font-size: 90%;
}
| overleaf/web/frontend/stylesheets/app/login-register.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/login-register.less",
"repo_id": "overleaf",
"token_count": 1223
} | 529 |
.gallery-title {
margin-bottom: @margin-xl;
}
.field-title {
font-weight: bold;
}
.filters {
float: right;
margin-bottom: @margin-lg;
@media (max-width: @screen-md-min) {
float: none;
}
}
.cta-links {
.cta-link.btn {
margin: 0 @margin-sm @margin-sm 0;
}
}
.popular-tags {
.gallery-thumbnail {
margin: 0 0 1em 0 !important;
}
}
.tag-link {
margin: 0 @margin-xs @margin-sm 0;
max-width: 100%;
white-space: inherit;
}
.gallery-abstract {
word-break: break-word;
hyphens: auto;
a {
hyphens: none;
}
}
.gallery-thumbnail {
display: inline-block;
margin: 0 0 2em;
width: 100%;
.thumbnail {
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin: 0 0 @margin-sm 0;
padding: 0px;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
width: 100%;
h3 {
color: @link-color-alt;
margin: 10px 0px 10px 20px;
}
&.thumbnail-tag {
height: 100px;
}
}
.caption {
// Override ShareLatex template styles
background: none;
border: none;
text-align: center;
}
.caption__description {
font-style: italic;
padding: 0 0 5px 0;
.text-overflow();
}
.caption__title {
display: inline-block;
width: 100%;
text-align: center;
.text-overflow();
}
}
.gallery-large-pdf-preview {
border: solid 1px @gray-lightest;
margin-top: @margin-lg;
img {
max-width: 100%;
}
}
/* Media Queries */
@media (max-width: @screen-xs-max) {
.gallery-container {
column-count: 2;
column-gap: 2em;
}
}
@media (min-width: @screen-sm-min) {
.gallery-container {
&.use-column {
column-count: 3;
column-gap: 3em;
}
&.use-percent {
margin: 0 -1.5em;
.gallery-thumbnail {
width: 33.3333333%;
padding: 0 1.5em;
}
}
}
}
@media (min-width: @screen-md-min) {
.gallery-large-pdf-preview {
margin-top: 0;
}
}
.section-tags {
margin-bottom: @margin-xl;
margin-top: @margin-md;
}
.search__container--addsearch {
.search__input-bar {
display: flex;
}
.search__input {
flex: 1;
margin-right: 10px;
padding: 0 10px;
}
// AddSearch overrides
#addsearch-results {
min-height: 0 !important;
.addsearch-result-item-container {
background-size: auto 80px !important; // Resize image to be smaller
padding: 10px;
margin-left: 10px;
margin-right: 10px;
border-bottom: 2px solid rgb(236, 236, 236);
}
.addsearch-result-item-sub {
min-height: 0 !important;
background: none !important;
border-bottom: none !important;
h2 {
font-family: @font-family-sans-serif;
}
// Unfortunately AddSearch doesn't add very useful classes, so have to use
// some horrible nesting :/
& > div {
min-height: 0 !important;
padding-left: 90px !important;
// Hide some unnecessary metadata
span {
display: none !important;
}
}
a {
color: @link-color-alt !important;
}
&:hover a {
color: @link-hover-color-alt !important;
}
}
}
#addsearch-results-bottom {
height: auto !important;
background: none !important;
padding-top: 0 !important;
#addsearch-rp-paging {
margin-bottom: 10px;
a {
color: @link-color-alt !important;
&.currentResultPage {
color: @ol-blue-gray-5 !important;
}
}
}
}
#addsearch-logo {
display: none !important;
}
}
| overleaf/web/frontend/stylesheets/app/templates-v2.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/app/templates-v2.less",
"repo_id": "overleaf",
"token_count": 1611
} | 530 |
//
// Dropdown menus
// --------------------------------------------------
// Dropdown arrow/caret
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: @caret-width-base solid;
border-right: @caret-width-base solid transparent;
border-left: @caret-width-base solid transparent;
margin-top: -@caret-width-base / 2;
}
// The dropdown wrapper (div)
.dropdown {
position: relative;
}
.open button.dropdown-toggle.dropdown-toggle-no-background,
button.dropdown-toggle.dropdown-toggle-no-background {
background-color: transparent;
box-shadow: none;
border: 0;
&:hover,
&:active,
&:focus {
background-color: transparent;
box-shadow: none;
}
}
// Prevent the focus on the dropdown toggle when closing dropdowns
.dropdown-toggle:focus {
outline: 0;
}
// The dropdown menu (ul)
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: @zindex-dropdown;
display: none; // none by default, but block on "open" of the menu
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0; // override default ul
list-style: none;
font-size: @font-size-base;
background-color: @dropdown-bg;
border: 1px solid @dropdown-fallback-border; // IE8 fallback
border: 1px solid @dropdown-border;
border-radius: @border-radius-base;
.box-shadow(0 6px 12px rgba(0, 0, 0, 0.175));
background-clip: padding-box;
// Aligns the dropdown menu to right
//
// Deprecated as of 3.1.0 in favor of `.dropdown-menu-[dir]`
&.pull-right {
right: 0;
left: auto;
}
// Dividers (basically an hr) within the dropdown
.divider {
.nav-divider(@dropdown-divider-bg);
}
// Links and other items within the dropdown menu
> li > a,
div,
.dropdown-menu-button {
display: block;
padding: @dropdown-item-padding;
clear: both;
font-weight: normal;
line-height: @line-height-base;
color: @dropdown-link-color;
white-space: nowrap; // prevent links from randomly breaking onto new lines
&.subdued {
color: #7a7a7a;
}
.subdued {
color: #7a7a7a;
}
}
// button specific styles
.dropdown-menu-button {
border: none;
outline: none;
width: 100%;
}
}
// Hover/Focus state
.dropdown-menu > li > a,
.dropdown-menu .dropdown-menu-button {
&:hover,
&:focus {
text-decoration: none;
color: @dropdown-link-hover-color;
background-color: @dropdown-link-hover-bg;
.subdued {
color: @dropdown-link-hover-color;
}
}
}
// Active state
.dropdown-menu > .active > a {
&,
&:hover,
&:focus {
color: @dropdown-link-active-color;
text-decoration: none;
outline: 0;
background-color: @dropdown-link-active-bg;
}
}
// Disabled state
//
// Gray out text and ensure the hover/focus state remains gray
.dropdown-menu > .disabled > a {
&,
&:hover,
&:focus {
color: @dropdown-link-disabled-color;
}
}
// Nuke hover/focus effects
.dropdown-menu > .disabled > a {
&:hover,
&:focus {
text-decoration: none;
background-color: transparent;
background-image: none; // Remove CSS gradient
.reset-filter();
cursor: not-allowed;
}
}
// Open state for the dropdown
.open {
// Show the menu
> .dropdown-menu {
display: block;
}
// Remove the outline when :focus is triggered
> a {
outline: 0;
}
}
// Menu positioning
//
// Add extra class to `.dropdown-menu` to flip the alignment of the dropdown
// menu with the parent.
.dropdown-menu-right {
left: auto; // Reset the default from `.dropdown-menu`
right: 0;
}
// With v3, we enabled auto-flipping if you have a dropdown within a right
// aligned nav component. To enable the undoing of that, we provide an override
// to restore the default dropdown menu alignment.
//
// This is only for left-aligning a dropdown menu within a `.navbar-right` or
// `.pull-right` nav component.
.dropdown-menu-left {
left: 0;
right: auto;
}
// Dropdown section headers
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: @font-size-small;
line-height: @line-height-base;
color: @dropdown-header-color;
}
// Backdrop to catch body clicks on mobile, etc.
.dropdown-backdrop {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: (@zindex-dropdown - 10);
}
// Right aligned dropdowns
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
// Allow for dropdowns to go bottom up (aka, dropup-menu)
//
// Just add .dropup after the standard .dropdown class and you're set, bro.
// TODO: abstract this so that the navbar fixed styles are not placed here?
.dropup,
.navbar-fixed-bottom .dropdown {
// Reverse the caret
.caret {
border-top: 0;
border-bottom: @caret-width-base solid;
content: '';
}
// Different positioning for bottom up menu
.dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 1px;
}
}
// Component alignment
//
// Reiterate per navbar.less and the modified component alignment there.
@media (min-width: @grid-float-breakpoint) {
.navbar-right {
.dropdown-menu {
.dropdown-menu-right();
}
// Necessary for overrides of the default right aligned menu.
// Will remove come v4 in all likelihood.
.dropdown-menu-left {
.dropdown-menu-left();
}
}
}
| overleaf/web/frontend/stylesheets/components/dropdowns.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/dropdowns.less",
"repo_id": "overleaf",
"token_count": 1971
} | 531 |
// Media objects
// Source: http://stubbornella.org/content/?p=497
// --------------------------------------------------
// Common styles
// -------------------------
// Clear the floats
.media,
.media-body {
overflow: hidden;
zoom: 1;
}
// Proper spacing between instances of .media
.media,
.media .media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
// For images and videos, set to block
.media-object {
display: block;
}
// Reset margins on headings for tighter default spacing
.media-heading {
margin: 0 0 5px;
}
// Media image alignment
// -------------------------
.media {
> .pull-left {
margin-right: 10px;
}
> .pull-right {
margin-left: 10px;
}
}
// Media list variation
// -------------------------
// Undo default ul/ol styles
.media-list {
padding-left: 0;
list-style: none;
}
| overleaf/web/frontend/stylesheets/components/media.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/media.less",
"repo_id": "overleaf",
"token_count": 277
} | 532 |
.tags-input {
display: block;
}
.tags-input *,
.tags-input *:before,
.tags-input *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.tags-input label.small {
font-weight: normal;
}
.tags-input .host {
position: relative;
height: 100%;
}
.tags-input .host:active {
outline: none;
}
.tags-input .tags {
.form-control;
border-radius: 3px; /* overriding .form-control */
-moz-appearance: textfield;
-webkit-appearance: textfield;
padding: 3px;
overflow: hidden;
word-wrap: break-word;
cursor: text;
background-color: #fff;
height: 100%;
display: flex;
flex-wrap: wrap;
}
.tags-input .tags.focused,
.tags-input .tags:focus-within {
outline: none;
-webkit-box-shadow: 0 0 3px 1px rgba(5, 139, 242, 0.6);
-moz-box-shadow: 0 0 3px 1px rgba(5, 139, 242, 0.6);
box-shadow: 0 0 3px 1px rgba(5, 139, 242, 0.6);
}
.tags-input .tags .tag-list {
margin: 0;
padding: 0;
list-style-type: none;
}
.tags-input .tags .tag-item {
margin: 2px;
padding: 2px 7px;
display: inline-flex;
align-items: center;
line-height: 1;
overflow: hidden;
text-overflow: ellipsis;
border: 1px solid @gray-light;
background-color: @gray-lightest;
border-radius: 3px;
}
.tags-input .tags .tag-item.selected {
background-color: @gray-lighter;
}
.tags-input .tags .tag-item .fa {
flex-shrink: 0;
}
.tags-input .tags .tag-item .remove-button {
color: @gray-light;
text-decoration: none;
cursor: pointer;
flex-shrink: 0;
}
.tags-input .tags .tag-item .remove-button:active {
color: @brand-primary;
}
.tags-input .tags .input {
border: 0;
outline: none;
margin: 2px;
padding: 0;
padding-left: 5px;
flex-grow: 1;
overflow: hidden;
text-overflow: ellipsis;
}
.tags-input .tags .input.invalid-tag {
color: @brand-danger;
}
.tags-input .tags .input::-ms-clear {
display: none;
}
.tags-input.ng-invalid .tags {
-webkit-box-shadow: 0 0 3px 1px rgba(255, 0, 0, 0.6);
-moz-box-shadow: 0 0 3px 1px rgba(255, 0, 0, 0.6);
box-shadow: 0 0 3px 1px rgba(255, 0, 0, 0.6);
}
.tags-input[disabled] .host:focus {
outline: none;
}
.tags-input[disabled] .tags {
background-color: #eee;
cursor: default;
}
.tags-input[disabled] .tags .tag-item {
opacity: 0.65;
background: -webkit-linear-gradient(
top,
#f0f9ff 0%,
rgba(203, 235, 255, 0.75) 47%,
rgba(161, 219, 255, 0.62) 100%
);
background: linear-gradient(
to bottom,
#f0f9ff 0%,
rgba(203, 235, 255, 0.75) 47%,
rgba(161, 219, 255, 0.62) 100%
);
}
.tags-input[disabled] .tags .tag-item .remove-button {
cursor: default;
}
.tags-input[disabled] .tags .tag-item .remove-button:active {
color: @brand-primary;
}
.tags-input[disabled] .tags .input {
background-color: #eee;
cursor: default;
}
.tags-input .autocomplete {
margin-top: 5px;
position: absolute;
padding: 5px 0;
z-index: 999;
width: 100%;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.tags-input .autocomplete .suggestion-list {
margin: 0;
padding: 0;
list-style-type: none;
max-height: 280px;
overflow-y: auto;
position: relative;
}
.tags-input .autocomplete .suggestion-item {
padding: 5px 10px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.tags-input .autocomplete .suggestion-item.selected {
color: white;
background-color: @brand-primary;
.subdued {
color: white;
}
}
.tags-input .autocomplete .suggestion-item em {
font-weight: bold;
font-style: normal;
}
/*# sourceMappingURL=ng-tags-input.css.map */
| overleaf/web/frontend/stylesheets/components/tags-input.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/components/tags-input.less",
"repo_id": "overleaf",
"token_count": 1545
} | 533 |
//
// Typography
// --------------------------------------------------
* {
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
}
// Headings
// -------------------------
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: @headings-font-family;
font-weight: @headings-font-weight;
line-height: @headings-line-height;
color: @headings-color;
small,
.small {
font-weight: normal;
line-height: 1;
color: @headings-small-color;
}
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: @line-height-computed;
margin-bottom: (@line-height-computed / 2);
small,
.small {
font-size: 70%;
}
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: (@line-height-computed / 2);
margin-bottom: (@line-height-computed / 2);
small,
.small {
font-size: 75%;
}
}
h1,
.h1 {
font-size: @font-size-h1;
}
h2,
.h2 {
font-size: @font-size-h2;
}
h3,
.h3 {
font-size: @font-size-h3;
}
h4,
.h4 {
font-size: @font-size-h4;
}
h5,
.h5 {
font-size: @font-size-h5;
}
h6,
.h6 {
font-size: @font-size-h6;
}
// Body text
// -------------------------
p {
margin: 0 0 (@line-height-computed / 2);
}
.lead {
margin-bottom: @line-height-computed;
font-size: floor((@font-size-base * 1.15));
font-weight: 200;
line-height: 1.4;
@media (min-width: @screen-sm-min) {
font-size: (@font-size-base * 1.5);
}
}
// Emphasis & misc
// -------------------------
// Ex: 14px base font * 85% = about 12px
small,
.small {
font-size: 90%;
color: @text-small-color;
}
.login-register-text,
.login-register-hr-text-container,
.text-small {
font-size: 90%;
}
// Undo browser default styling
cite {
font-style: normal;
}
// Alignment
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
// Contextual colors
.text-muted {
color: @text-muted;
}
.text-primary {
.text-emphasis-variant(@brand-primary);
}
.text-success {
.text-emphasis-variant(@state-success-text);
}
.text-info {
.text-emphasis-variant(@state-info-text);
}
.text-warning {
.text-emphasis-variant(@state-warning-text);
}
.text-danger {
.text-emphasis-variant(@state-danger-text);
}
.text-serif {
font-family: @font-family-serif;
}
.text-sans-serif {
font-family: @font-family-sans-serif;
}
.text-centered {
text-align: center;
}
// Transformations
.text-capitalize {
text-transform: capitalize;
}
.text-lowercase {
text-transform: lowercase;
}
// Contextual backgrounds
// For now we'll leave these alongside the text classes until v4 when we can
// safely shift things around (per SemVer rules).
.bg-primary {
// Given the contrast here, this is the only class to have its color inverted
// automatically.
color: #fff;
.bg-variant(@brand-primary);
}
.bg-success {
.bg-variant(@state-success-bg);
}
.bg-info {
.bg-variant(@state-info-bg);
}
.bg-warning {
.bg-variant(@state-warning-bg);
}
.bg-danger {
.bg-variant(@state-danger-bg);
}
// Page header
// -------------------------
.page-header {
padding-bottom: ((@line-height-computed / 2) - 1);
margin: (@line-height-computed) 0 @line-height-computed;
border-bottom: 1px solid @page-header-border-color;
}
// Lists
// --------------------------------------------------
// Unordered and Ordered lists
ul,
ol {
margin-top: 0;
margin-bottom: (@line-height-computed / 2);
ul,
ol {
margin-bottom: 0;
}
}
// List options
.list-no-margin-bottom {
margin-bottom: 0;
}
// Unstyled keeps list items block level, just removes default browser padding and list-style
.list-unstyled {
padding-left: 0;
list-style: none;
}
// Inline turns list items into inline-block
.list-inline {
.list-unstyled();
margin-left: -5px;
> li {
display: inline-block;
padding-left: 5px;
padding-right: 5px;
}
}
// Description Lists
dl {
margin-top: 0; // Remove browser default
margin-bottom: @line-height-computed;
}
dt,
dd {
line-height: @line-height-base;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0; // Undo browser default
}
// Horizontal description lists
//
// Defaults to being stacked without any of the below styles applied, until the
// grid breakpoint is reached (default of ~768px).
@media (min-width: @grid-float-breakpoint) {
.dl-horizontal {
dt {
float: left;
width: (@component-offset-horizontal - 20);
clear: left;
text-align: right;
.text-overflow();
}
dd {
margin-left: @component-offset-horizontal;
&:extend(.clearfix
all); // Clear the floated `dt` if an empty `dd` is present
}
}
}
// MISC
// ----
// Abbreviations and acronyms
abbr[title],
// Add data-* attribute to help out our tooltip plugin, per https://github.com/twbs/bootstrap/issues/5257
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted @abbr-border-color;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
// Blockquotes
blockquote {
padding: (@line-height-computed / 2) @line-height-computed;
margin: 0 0 @line-height-computed;
font-size: @blockquote-font-size;
quotes: '\201C''\201D''\2018''\2019';
border-left: 5px solid @blockquote-border-color;
&:before {
content: open-quote;
font-size: @blockquote-font-size * 3;
color: @blockquote-border-color;
margin-right: 0.25em;
vertical-align: -0.4em;
line-height: 0.1em;
}
&:after {
content: close-quote;
display: inherit;
height: 0;
visibility: hidden;
}
p {
display: inline;
}
p,
ul,
ol {
&:last-child {
margin-bottom: 0;
}
}
// Note: Deprecated small and .small as of v3.1.0
// Context: https://github.com/twbs/bootstrap/issues/11660
footer,
small,
.small {
display: block;
font-size: 80%; // back to default font-size
line-height: @line-height-base;
color: @blockquote-small-color;
padding-top: @line-height-computed / 2;
&:before {
content: '\2014 \00A0'; // em dash, nbsp
}
}
}
// Opposite alignment of blockquote
//
// Heads up: `blockquote.pull-right` has been deprecated as of v3.1.0.
.blockquote-reverse {
padding-right: 15px;
padding-left: 0;
border-right: 5px solid @blockquote-border-color;
border-left: 0;
text-align: right;
// Account for citation
footer,
small,
.small {
&:before {
content: '';
}
&:after {
content: '\00A0 \2014'; // nbsp, em dash
}
}
}
// Quotes
// blockquote:before,
// blockquote:after {
// content: "";
// }
// Addresses
address {
margin-bottom: @line-height-computed;
font-style: normal;
line-height: @line-height-base;
}
.orange-text {
color: @orange-dark;
}
| overleaf/web/frontend/stylesheets/core/type.less/0 | {
"file_path": "overleaf/web/frontend/stylesheets/core/type.less",
"repo_id": "overleaf",
"token_count": 2734
} | 534 |
const webpackConfig = require('./webpack.config.test')
module.exports = function (config) {
config.set({
customLaunchers: {
ChromeCustom: {
base: 'ChromeHeadless',
// We must disable the Chrome sandbox when running Chrome inside Docker
// (Chrome's sandbox needs more permissions than Docker allows by
// default)
flags: ['--no-sandbox'],
},
},
browsers: ['ChromeCustom'],
files: [
// Import all tests (see comment in the file for why this is necessary)
'test/karma/import_tests.js',
],
middleware: ['fake-img'],
preprocessors: {
// Run files through webpack
'test/karma/import_tests.js': ['webpack'],
},
frameworks: ['mocha', 'chai-sinon'],
// Configure webpack in the tests
webpack: webpackConfig,
// Configure the webpack dev server used to serve test files
webpackMiddleware: {
// Disable file-watching -- it is of no use in CI, we use single runs.
// https://webpack.js.org/configuration/watch/
watch: false,
// ^ does not work when placed in webpack.config.test.
// webpack-dev-middleware overrides it :/
// v seems to be supported, according to
// https://www.npmjs.com/package/webpack-dev-middleware#watchoptions
watchOptions: {
ignored: [/node_modules/, /frontend/, /test/],
},
// Disable noisy CLI output
stats: 'errors-only',
},
plugins: [
require('karma-chrome-launcher'),
require('karma-mocha'),
require('karma-chai-sinon'),
require('karma-webpack'),
require('karma-mocha-reporter'),
{ 'middleware:fake-img': ['factory', fakeImgMiddlewareFactory] },
],
reporters: ['mocha'],
})
}
/**
* Handle fake images
*/
function fakeImgMiddlewareFactory() {
return function (req, res, next) {
if (req.originalUrl.startsWith('/fake/')) {
return res.end('fake img response')
}
next()
}
}
| overleaf/web/karma.conf.js/0 | {
"file_path": "overleaf/web/karma.conf.js",
"repo_id": "overleaf",
"token_count": 776
} | 535 |
{
"return_to_login_page": "Вернуться на страницу входа",
"login_failed": "Вход не удался",
"delete_account_warning_message_3": "Вы собираетесь <strong>удалить все данные Вашего аккаунта</strong>, включая все Ваши проекты и настройки. Пожалуйста, введите адрес электронной почты и пароль Вашего аккаунта в форму внизу для продолжения.",
"delete_account_warning_message_2": "Вы собираетесь <strong>удалить все данные Вашего аккаунта</strong>, включая все Ваши проекты и настройки. Пожалуйста, введите адрес электронной почты Вашего аккаунта в форму внизу для продолжения.",
"your_sessions": "Ваши сессии",
"clear_sessions_description": "Это список всех активных сессий Вашего аккаунта, за исключением Вашей текущей сессии. Нажмите кнопку \"Завершить сессии\" для закрытия всех активных сеансов.",
"no_other_sessions": "Нет других активных сессий",
"ip_address": "IP адрес",
"session_created_at": "Сессия создана",
"clear_sessions": "Завершить сессии",
"clear_sessions_success": "Сессии завершены",
"sessions": "Сессии",
"manage_sessions": "Управление Вашими сессиями",
"syntax_validation": "Проверка кода",
"history": "История",
"open_project": "Открыть проект",
"files_cannot_include_invalid_characters": "Файлы не могут содержать символы '*' и '/'",
"invalid_file_name": "Неверное имя файла",
"autocomplete_references": "Автодополнение ссылок (внутри блока <code>\\cite{}</code>)",
"autocomplete": "Автозавершение",
"failed_compile_check": "Похоже, в Вашем проекте имеются критические синтаксические ошибки, которые Вы должны исправить перед компиляцией",
"failed_compile_check_try": "Попытаться скомпилировать всё равно",
"failed_compile_option_or": "или",
"failed_compile_check_ignore": "отключить проверку синтаксиса",
"compile_time_checks": "Проверка синтаксиса",
"stop_on_validation_error": "Проверить синтаксис перед компиляцией",
"ignore_validation_errors": "Не проверять синтаксис",
"run_syntax_check_now": "Выполнить проверку синтаксиса",
"security_code": "Защитный код",
"upgrade_paypal_btn": "Продолжить",
"notification_project_invite": "<b>__userName__</b> приглашает Вас принять участие в проекте __projectName__,<a class=\"ben btn-xs btn-info\" href=\"/project/__projectId__/invite/token/__token__\">Присоединиться</a>",
"file_restored": "Ваш файл (__filename__) был восстановлен.",
"file_restored_back_to_editor": "Вы можете вернуться в редактор и продолжить работу",
"file_restored_back_to_editor_btn": "Назад в редактор",
"view_project": "Просмотр проекта",
"join_project": "Присоединиться к проекту",
"invite_not_accepted": "Приглашение еще не было принято",
"resend": "Отправить еще раз",
"syntax_check": "Проверка синтаксиса",
"revoke_invite": "Отозвать приглашение",
"pending": "В ожидании",
"invite_not_valid": "Приглашение недействительно",
"invite_not_valid_description": "Вышел срок приглашения. Пожалуйста, обратитесь к владельцу проекта",
"accepting_invite_as": "Вы принимаете приглашение как",
"accept_invite": "Принять приглашение",
"log_hint_ask_extra_feedback": "Не могли бы Вы уточнить, почему эта подсказка не была полезной?",
"log_hint_extra_feedback_didnt_understand": "Я не понимаю указаний",
"log_hint_extra_feedback_not_applicable": "Я не могу использовать это решение для своего документа",
"log_hint_extra_feedback_incorrect": "Это не исправляет ошибку",
"log_hint_extra_feedback_other": "Ещё:",
"log_hint_extra_feedback_submit": "Отправить",
"if_you_are_registered": "Если Вы уже зарегистрированы",
"stop_compile": "Остановить компиляцию",
"terminated": "Компиляция отменена",
"compile_terminated_by_user": "Компиляция была прервана. Вы можете просмотреть необработанную выдачу компиляции, чтобы увидеть место остановки компиляции.",
"site_description": "Простой в использовании онлайн редактор LaTeX. Не требует установки, поддерживает совместную работу в реальном времени, контроль версий, сотни шаблонов LaTeX и многое другое.",
"knowledge_base": "база знаний",
"contact_message_label": "Сообщение",
"answer_yes": "Да",
"answer_no": "Нет",
"log_hint_extra_info": "Узнать больше",
"log_hint_feedback_label": "Была ли эта информация полезной?",
"log_hint_feedback_gratitude": "Спасибо за Ваш отзыв!",
"recompile_pdf": "Перекомпилировать PDF",
"login_or_password_wrong_try_again": "Неправильное имя пользователя или пароль. Пожалуйста, попробуйте снова",
"suggest_new_doc": "Предложить новый документ",
"request_sent_thank_you": "Спасибо, Ваш запрос отправлен!",
"suggestion": "Предложения",
"project_url": "URL проекта",
"subject": "Тема",
"confirm": "Подтвердить",
"cancel_personal_subscription_first": "У Вас уже имеется личная подписка. Хотите ли вы её отменить перед переходом на групповую лицензию?",
"delete_projects": "Удалить проекты",
"leave_projects": "Оставить проекты",
"delete_and_leave_projects": "Удалить или оставить проекты",
"too_recently_compiled": "Этот проект был скомпилирован совсем недавно, поэтому компиляция была пропущена.",
"clsi_maintenance": "На сервере компиляции проводятся ремонтные работы, и он будет вскоре доступен снова.",
"references_search_hint": "Нажмите Ctrl + Пробел для поиска",
"search_bib_files": "Поиск по автору, названию, году",
"leave_group": "Покинуть группу",
"leave_now": "Покинуть",
"sure_you_want_to_leave_group": "Вы уверены, что хотите покинуть группу?",
"notification_group_invite": "Вас пригласили вступить в группу __groupName__, <a href=\"/user/subscription/__subscription_id__/group/invited\">присоединиться</a>.",
"search_references": "Поиск .bib файлов в проекте",
"no_search_results": "Ничего не найдено",
"email_already_registered": "Этот адрес уже зарегистрирован.",
"compile_mode": "Режим компиляции",
"normal": "нормальный",
"fast": "быстрый",
"rename_folder": "Переименовать папку",
"delete_folder": "Удалить папку",
"about_to_delete_folder": "Вы собираетесь удалить следующие папки (проекты в них будут сохранены):",
"to_modify_your_subscription_go_to": "Для изменения подписки перейдите по ссылке:",
"manage_subscription": "Управление подпиской",
"activate_account": "Активируйте Ваш аккаунт",
"yes_please": "Да, пожалуйста!",
"nearly_activated": "Вы в одном шаге от активации Вашего аккаунта для __appName__!",
"please_set_a_password": "Пожалуйста, укажите пароль",
"activation_token_expired": "Срок действия Вашего ключа истёк. Вам необходимо запросить новый ключ активации.",
"activate": "Активировать",
"activating": "Активация",
"ill_take_it": "Беру!",
"cancel_your_subscription": "Остановить подписку",
"no_thanks_cancel_now": "Нет, спасибо - я хочу удалить сейчас",
"cancel_my_account": "Отменить подписку",
"sure_you_want_to_cancel": "Вы уверены, что хотите отменить подписку?",
"i_want_to_stay": "Я хочу остаться",
"have_more_days_to_try": "Продлите тестовый период ещё на <strong>__days__ дней</strong>!",
"interested_in_cheaper_plan": "Вас интересует более дешевый студенческий тариф: <strong>__price__</strong>?",
"session_expired_redirecting_to_login": "Срок сессии истёк. Перенаправление на страницу входа через __seconds__ секунд(ы)",
"maximum_files_uploaded_together": "Совместная загрузка до максимум __max__ файлов",
"too_many_files_uploaded_throttled_short_period": "Слишком много файлов загружено за раз - на короткое время загрузка была приостановлена.",
"compile_larger_projects": "Компиляция больших проектов",
"new_group": "Новая группа",
"about_to_delete_groups": "Следующие группы будут удалены:",
"removing": "Удаление",
"adding": "Добавление",
"groups": "Группы",
"rename_group": "Переименовать группу",
"renaming": "Переименование",
"create_group": "Создать группу",
"delete_group": "Удалить группу",
"delete_groups": "Удалить группы",
"your_groups": "Ваши группы",
"group_name": "Имя группы",
"no_groups": "Нет групп",
"Subscription": "Подписка",
"Documentation": "Документация",
"Universities": "Университеты",
"Account Settings": "Параметры учётной записи",
"Projects": "Проекты",
"Account": "Учётная запись",
"global": "глобальная",
"Terms": "Условия",
"Security": "Безопасность",
"About": "О сайте",
"word_count": "Количество слов",
"please_compile_pdf_before_word_count": "Пожалуйста, скомпилируйте проект, прежде чем подсчитывать количество слов!",
"total_words": "Количество слов",
"headers": "Заголовки",
"math_inline": "Встроенные формулы",
"math_display": "Формулы",
"connected_users": "Связанные пользователи",
"projects": "Проекты",
"upload_project": "Загрузить проект",
"all_projects": "Все проекты",
"your_projects": "Созданные мной",
"shared_with_you": "Доступные мне",
"deleted_projects": "Корзина",
"templates": "Шаблоны",
"new_folder": "Новая папка",
"create_your_first_project": "Создайте свой первый проект!",
"complete": "Заполнить",
"on_free_sl": "Вы используете бесплатную версию __appName__",
"upgrade": "Сменить тариф",
"or_unlock_features_bonus": "или получить бонусы,",
"sharing_sl": "рассказать о __appName__",
"add_to_folder": "Переместить в папку",
"create_new_folder": "Создать папку",
"more": "еще",
"rename": "Переименовать",
"make_copy": "Копировать",
"restore": "Восстановить",
"title": "Название",
"last_modified": "Последнее изменение",
"no_projects": "Нет проектов",
"welcome_to_sl": "Добро пожаловать в __appName__!",
"new_to_latex_look_at": "Новичок в LaTeX? Начните с нашего",
"or": "или",
"or_create_project_left": "или создайте свой первый проект слева.",
"thanks_settings_updated": "Спасибо, изменения сохранены",
"update_account_info": "Редактировать профиль",
"must_be_email_address": "Введите правильный адрес электронной почты",
"first_name": "Имя",
"last_name": "Фамилия",
"update": "Сохранить",
"change_password": "Изменение пароля",
"current_password": "Текущий пароль",
"new_password": "Новый пароль",
"confirm_new_password": "Подтверждение нового пароля",
"required": "обязательно",
"doesnt_match": "Не совпадает",
"dropbox_integration": "Синхронизация с Dropbox",
"learn_more": "Узнать больше",
"dropbox_is_premium": "Синхронизация с Dropbox доступна только в премиум аккаунте",
"account_is_linked": "Аккаунт подключен",
"unlink_dropbox": "Отключить Dropbox",
"link_to_dropbox": "Подключить Dropbox",
"newsletter_info_and_unsubscribe": "Мы будем уведомлять вас о новых возможностях каждые 2-3 месяца. Вы можете отписаться от рассылки в любое время:",
"unsubscribed": "Не подписан",
"unsubscribing": "Отмена подписки",
"unsubscribe": "Отменить подписку",
"need_to_leave": "Удалить аккаунт?",
"delete_your_account": "Удалить аккаунт",
"delete_account": "Удалить аккаунт",
"delete_account_warning_message": "Вы собирается безвозвратно <strong>удалить все Ваши данные</strong>, включая Ваши проекты и настройки. Пожалуйста, введите слово \"DELETE\" для того, чтобы продолжить",
"deleting": "Удаление",
"delete": "Удалить",
"sl_benefits_plans": "__appName__ - самый удобный редактор LaTeX в мире: история изменений, совместная работа в реальном времени, доступность из любого уголка мира, где есть Интернет и многое другое.",
"monthly": "Цена за месяц",
"personal": "Личный",
"free": "Бесплатно",
"one_collaborator": "Только один автор на проект",
"collaborator": "Совместная работа",
"collabs_per_proj": "Максимальное число соавторов на проект: __collabcount__",
"full_doc_history": "Полная история изменений",
"sync_to_dropbox": "Синхронизация с Dropbox",
"start_free_trial": "Попробовать бесплатно!",
"professional": "Профессионал",
"unlimited_collabs": "Неограниченно число соавторов",
"name": "Имя",
"student": "Студент",
"university": "Университет",
"position": "Должность",
"choose_plan_works_for_you": "Выберите понравившийся тариф для __len__-дневного бесплатного периода. Вы в любой момент сможете отменить подписку.",
"interested_in_group_licence": "Хотите использовать __appName__ в команде или организации?",
"get_in_touch_for_details": "Свяжитесь с нами!",
"group_plan_enquiry": "Запрос индивидуального тарифа",
"enjoy_these_features": "Используйте все возможности системы",
"create_unlimited_projects": "Создавай столько проектов, сколько хочешь",
"never_loose_work": "Ни одно изменение не потеряется",
"access_projects_anywhere": "Работай над проектами откуда угодно",
"log_in": "Войти",
"login": "Войти",
"logging_in": "Авторизация",
"forgot_your_password": "Забыли пароль?",
"password_reset": "Сбросить пароль",
"password_reset_email_sent": "На ваш электронный адрес было отправлено письмо с инструкцией по восстановлению пароля",
"please_enter_email": "Пожалуйста, введите адрес электронной почты",
"request_password_reset": "Сбросить пароль",
"reset_your_password": "Сбросить пароль",
"password_has_been_reset": "Ваш пароль был сброшен",
"login_here": "Войти",
"set_new_password": "Введите новый пароль",
"user_wants_you_to_see_project": "__username__ приглашает вас к просмотру проекта __projectname__",
"join_sl_to_view_project": "Для доступа к проекту необходимо авторизоваться в __appName__",
"register_to_edit_template": "Пожалуйста, зарегистрируйтесь, чтобы редактировать шаблон __templateName__",
"already_have_sl_account": "Есть аккаунт __appName__?",
"register": "Регистрация",
"password": "Пароль",
"registering": "Создание аккаунта",
"planned_maintenance": "Плановые работы",
"no_planned_maintenance": "В настоящее время плановые работы не осуществляются",
"cant_find_page": "К сожалению, страница не найдена",
"take_me_home": "Вернуться в начало",
"no_preview_available": "К сожалению, предпросмотр не доступен",
"no_messages": "Нет сообщений",
"send_first_message": "Отправьте сообщение",
"account_not_linked_to_dropbox": "Ваш аккаунт не синхронизирован с Dropbox",
"update_dropbox_settings": "Обновить настройки Dropbox",
"refresh_page_after_starting_free_trial": "Пожалуйста, обновите страницу",
"checking_dropbox_status": "проверка состояния Dropbox",
"dismiss": "Отклонить",
"new_file": "Новый файл",
"upload_file": "Загрузить файл",
"create": "Создать",
"creating": "Создание",
"upload_files": "Загрузить файл(ы)",
"sure_you_want_to_delete": "Вы уверены, что хотите перманентно удалить следующие файлы?",
"common": "Общие",
"navigation": "Навигация",
"editing": "Редактор",
"ok": "OK",
"source": "Исходный код",
"actions": "Действия",
"copy_project": "Копировать проект",
"publish_as_template": "Создать шаблон",
"sync": "Синхронизация",
"settings": "Настройки",
"main_document": "Основной документ",
"off": "Откл.",
"auto_complete": "Автодополнение",
"theme": "Тема",
"font_size": "Размер шрифта",
"pdf_viewer": "Просмотрщик PDF",
"built_in": "встроенный",
"native": "браузер",
"show_hotkeys": "Показать горячие клавиши",
"new_name": "Введите название",
"copying": "копирование",
"copy": "Копировать",
"compiling": "Компиляция",
"click_here_to_preview_pdf": "Кликните, чтобы открыть предпросмотр PDF",
"server_error": "Ошибка сервера",
"somthing_went_wrong_compiling": "К сожалению, что-то пошло не так и мы не смогли скомпИлировать Ваш проект. Попробуйте еще раз через пару минут.",
"timedout": "Время ожидания истекло",
"proj_timed_out_reason": "К сожалению, компиляция Вашего документа заняла слишком много времени и была прервана. Возможные причины: документ содержит большое количество изображений в высоком разрешении, или сложные графики",
"no_errors_good_job": "Ошибок нет - отличная работа!",
"compile_error": "Ошибка компиляции",
"generic_failed_compile_message": "К сожалению Ваш LaTeX документ не может быть скомпилирован. Пожалуйста, проверьте сообщения об ошибках внизу, или просмотрите лог-файл",
"other_logs_and_files": "Другие логи и файлы",
"view_raw_logs": "Просмотреть логи",
"hide_raw_logs": "Скрыть логи",
"clear_cache": "Очистить кэш",
"clear_cache_explanation": "Это приведет к удалению всех скрытых файлов LaTeX (.aux, .bbl и др.) с нашего сервера компиляции. Обычно этого делать не требуется, если только у Вас не возникло проблем с перекрёстными ссылками",
"clear_cache_is_safe": "Файлы Вашего проекта не будут удалены или изменены",
"clearing": "Очистка",
"template_description": "Описание шаблона",
"project_last_published_at": "В последний раз проект был опубликован",
"problem_talking_to_publishing_service": "Проблема с сервером публикации. Пожалуйста, попробуйте через некоторое время ещё раз",
"unpublishing": "Отмена публикации",
"republish": "Переопубликовать",
"publishing": "Публикация",
"share_project": "Открыть доступ к проекту",
"this_project_is_private": "Это закрытый проект. К нему имеют доступ только следующие люди:",
"make_public": "Сделать открытым",
"this_project_is_public": "Это открытый проект. Он может быть изменен любым человеком, знающим адрес (URL)",
"make_private": "Сделать закрытым",
"can_edit": "Могут править",
"share_with_your_collabs": "Открыть для соавторов",
"share": "Открыть доступ",
"need_to_upgrade_for_more_collabs": "Для приглашения большего числа соавторов необходимо сменить тариф",
"make_project_public": "Открыть доступ для всех",
"make_project_public_consequences": "Если Вы откроете доступ с своему проекту, то он станет доступным всем пользователям, знающим адрес (URL)",
"allow_public_editing": "Разрешить публичное редактирование",
"allow_public_read_only": "Сделать доступным только для чтения",
"make_project_private": "Сделать проект закрытым",
"make_project_private_consequences": "Если Вы сделаете Ваш проект закрытым, то к небу будут иметь доступ только те люди, которых Вы выбрали.",
"need_to_upgrade_for_history": "Для активации \"Истории изменений\" необходимо сменить тариф",
"ask_proj_owner_to_upgrade_for_history": "Обратитесь к владельцу проекта с просьбой сменить тариф для активации \"Истории изменений\"",
"anonymous": "Аноним",
"generic_something_went_wrong": "Извините, что-то пошло не так... :(",
"restoring": "Восстановление",
"restore_to_before_these_changes": "Отменить последние изменения",
"profile_complete_percentage": "Ваш профиль заполнен на __percentval__%",
"file_has_been_deleted": "Файл __filename__ был удалён",
"sure_you_want_to_restore_before": "Вы уверены, что хотите вернуть файл <0>__filename__</0> к состоянию на __date__?",
"rename_project": "Переименовать проект",
"about_to_delete_projects": "Следующие проекты будут удалены:",
"about_to_leave_projects": "Вы собираетесь оставить следующие проекты:",
"upload_zipped_project": "Загрузить архив проекта (*.zip)",
"upload_a_zipped_project": "Загрузить архив проекта (*.zip)",
"your_profile": "Ваш профиль",
"institution": "Организация",
"role": "Роль",
"folders": "Папки",
"disconnected": "Разъединен",
"please_refresh": "Пожалуйста, обновите страницу для продолжения",
"lost_connection": "Соединение потеряно",
"reconnecting_in_x_secs": "Повторное соединение через __seconds__ секунд",
"try_now": "Попробуйте",
"reconnecting": "Пересоединение",
"saving_notification_with_seconds": "Сохранение __docname__... (__seconds__ секунд с последнего сохранения)",
"help_us_spread_word": "Помогите нам распространить информацию о __appName__",
"share_sl_to_get_rewards": "Поделитесь __appName__ с друзьями и коллегами и разблокируйте награды",
"post_on_facebook": "Опубликовать на Facebook",
"share_us_on_googleplus": "Поделиться на Gooogle+",
"email_us_to_your_friends": "Отправить email друзьям",
"link_to_us": "Ссылка на нас на Вашем веб-сайте",
"direct_link": "Прямая ссылка",
"sl_gives_you_free_stuff_see_progress_below": "Когда кто-либо по вашей рекомендации начнет пользоваться __appName__, вы получите кое-что <strong>бесплатно</strong> в знак благодарности! Узнайте о своем прогрессе ниже.",
"spread_the_word_and_fill_bar": "Распространяйте информацию и заполняйте эту полосу",
"one_free_collab": "Один бесплатный соавтор",
"three_free_collab": "Три бесплатных соавтора",
"free_dropbox_and_history": "Бесплатные Dropbox и История",
"you_not_introed_anyone_to_sl": "Вы пока ещё никого не пригласили в __appName__. Пригласите!",
"you_introed_small_number": " Вы уже пригласили <0>__numberOfPeople__</0> человек в __appName__. Отличная работа, но, возможно, Вы можете пригласить больше?",
"you_introed_high_number": " Вы уже пригласили <0>__numberOfPeople__</0> человек в __appName__. Отличная работа!",
"link_to_sl": "Ссылка на __appName__",
"can_link_to_sl_with_html": "Вы можете вставить ссылку на __appName__ с помощью кода:",
"year": "год",
"month": "месяц",
"subscribe_to_this_plan": "Подписаться на этот тариф",
"your_plan": "Ваш тариф",
"your_subscription": "Ваша подписка",
"on_free_trial_expiring_at": "У вас сейчас бесплатный пробный период, заканчивающийся __expiresAt__.",
"choose_a_plan_below": "Выберите план подписки.",
"currently_subscribed_to_plan": "Вы подписаны на тарифный план <0>__planName__</0>.",
"change_plan": "Сменить тарифный план",
"next_payment_of_x_collectected_on_y": "Следующий платёж в размере <0>__paymentAmmount__</0> будет списан <1>__collectionDate__</1>",
"update_your_billing_details": "Обновить детали счёта",
"subscription_canceled_and_terminate_on_x": " Ваша подписка была отменена и закончится <0>__terminateDate__</0>. Дальнейшие платежи взиматься не будут.",
"your_subscription_has_expired": "Срок Вашей подписки истёк.",
"create_new_subscription": "Создать новую подписку",
"problem_with_subscription_contact_us": "Возникли проблемы с Вашей подпиской. Пожалуйста, свяжитесь с нами, чтобы узнать подробности.",
"manage_group": "Управление группой",
"loading_billing_form": "Загрузка страницы с деталями оплаты",
"you_have_added_x_of_group_size_y": "Вы добавили <0>__addedUsersSize__</0> из <1>__groupSize__</1> доступных участников",
"remove_from_group": "Удалить из группы",
"group_account": "Групповая учетная запись",
"registered": "Зарeгистрирован",
"no_members": "Нет участников",
"add_more_members": "Добавить участников",
"add": "Добавить",
"thanks_for_subscribing": "Благодарим за подписку!",
"your_card_will_be_charged_soon": "В ближайшее время будет проведено списание с карты.",
"if_you_dont_want_to_be_charged": "Если вы не хотите дальнейших списаний ",
"add_your_first_group_member_now": "Добавьте первых участников группы сейчас",
"thanks_for_subscribing_you_help_sl": "Благодарим за подписку по тарифному плану __planName__. Благодаря Вам проект __appName__ может продолжать развиваться и улучшаться.",
"back_to_your_projects": "Назад к списку проектов",
"goes_straight_to_our_inboxes": "Письмо придет на оба наших ящика",
"need_anything_contact_us_at": "Если у Вас есть какие-либо вопросы и пожелания, пожалуйста, пишите нам по адресу",
"regards": "С уважением",
"about": "О проекте",
"comment": "Комментарии",
"restricted_no_permission": "Извините, у Вас недостаточно прав для просмотра данной страницы.",
"online_latex_editor": "Онлайн редактор LaTeX",
"meet_team_behind_latex_editor": "Познакомьтесь с командой, работающей над Вашим любимым онлайн редактором LaTeX.",
"follow_me_on_twitter": "Следовать на Twitter",
"motivation": "Мотивация",
"evolved": "преобразован",
"the_easy_online_collab_latex_editor": "Простой онлайн редактор LaTeX, с возможностью совместной работы",
"get_started_now": "Начать прямо сейчас",
"sl_used_over_x_people_at": "__appName__ используется более чем __numberOfUsers__ студентами и преподавателями в:",
"collaboration": "Совместная разработка",
"work_on_single_version": "Совместная работа над одной версией",
"view_collab_edits": "Смотреть правки других участников ",
"ease_of_use": " Легко использовать",
"no_complicated_latex_install": "Не требуется сложной установки LaTeX",
"all_packages_and_templates": "Все нужные пакеты и <0>__templatesLink__</0>",
"document_history": "История изменений документа",
"see_what_has_been": "Просмотреть, что было ",
"added": "добавлены",
"and": "и",
"removed": "удалено",
"restore_to_any_older_version": "Восстановление любой предыдущей версии",
"work_from_anywhere": "Работа отовсюду",
"acces_work_from_anywhere": "Доступ к Вашей работе по всему миру",
"work_offline_and_sync_with_dropbox": "Работа оффлайн и синхронизация Ваших файлов с Dropbox и GitHub",
"over": "свыше",
"view_templates": "Просмотр шаблонов",
"nothing_to_install_ready_to_go": "Нет никаких трудностей с установкой, поэтому вы можете <0>__start_now__</0>, даже если никогда ранее не пробовали. __appName__ доступен с полным и готовым к работе окружением LaTeX, работающим на наших серверах.",
"start_using_latex_now": "начните использовать LaTeX сейчас",
"get_same_latex_setup": "С __appName__ Вы получаете одинаковые настройки LaTeX в любом месте. Работая с коллегами или учениками в __appName__, Вы никогда не столкнетесь с конфликтом версий или пакетов.",
"support_lots_of_features": "Мы поддерживаем большинство возможностей LaTeX, включая вставку изображений, библиографии, формулы и многое другое! Почитайте обо всем том, что вы можете сделать с помощью __appName__ в нашей <0>__help_guides_link__</0>",
"latex_guides": "Справочники LaTeX",
"reset_password": "Сбросить пароль",
"set_password": "Установить пароль",
"updating_site": "Сайт обновляется",
"bonus_please_recommend_us": "Бонус - пожалуйста, рекомендуйте нас",
"admin": "администратор",
"subscribe": "Подписаться",
"update_billing_details": "Обновить детали счёта",
"group_admin": "Администратор группы",
"all_templates": "Все шаблоны",
"your_settings": "Ваши настройки",
"maintenance": "Ремонтные работы",
"to_many_login_requests_2_mins": "Было предпринято слишком много попыток входа. Пожалуйста, подождите 2 минуты, прежде чем пробовать снова",
"email_or_password_wrong_try_again": "Неверный адрес электронной почты или пароль. Пожалуйста, попробуйте снова",
"rate_limit_hit_wait": "Достигнут лимит попыток входа. Пожалуйста, повторите позднее",
"problem_changing_email_address": "Возникла проблема при обновлении Вашего адреса электронной почты. Пожалуйста, попробуйте через некоторое время снова. Если проблема повторится, пожалуйста свяжитесь с нами.",
"single_version_easy_collab_blurb": "__appName__ гарантирует, что вы всегда работаете над актуальной версией проекта вместе со своими соавторами. Существует только одна основная версия каждого документа, которая доступна для всех. Конфликты изменений невозможны, и Вам нет необходимости ждать своих коллег, пока они пришлют Вам свои последние наработки, чтобы продолжить работу.",
"can_see_collabs_type_blurb": "Несколько человек может без проблем одновременно работать над одним документом. Вы можете видеть, в каком месте печатают Ваши коллеги, прямо в редакторе, и вносимые ими изменения сразу отображаются на Вашем экране.",
"work_directly_with_collabs": "Работа напрямую с Вашими соавторами",
"work_with_word_users": "Работа с пользователями Word",
"work_with_word_users_blurb": "__appName__ настолько прост в использовании, что вы сможете пригласить Ваших коллег, незнакомых с LaTeX, принять участие в работе над Вашими LaTeX документами. Они будут продуктивными с первого дня и смогут немного познакомиться с LaTeX по ходу работы.",
"view_which_changes": "Посмотреть изменения, которые были",
"sl_included_history_of_changes_blurb": "__appName__ сохраняет полную историю всех изменений, так что Вы всегда можете отследить, кем было внесено изменение и когда. Благодаря этому Вы всегда будете в курсе работы, проделанной Вашими соавторами.",
"can_revert_back_blurb": "Ошибки случаются вне зависимости от того, работаете ли Вы один или вместе с соавторами. Вы всегда можете легко вернуться к предыдущей версии, что устраняет риск потери работы или внесения нежелательных изменений.",
"start_using_sl_now": "Начните использовать __appName__ прямо сейчас",
"over_x_templates_easy_getting_started": "В нашей галереи содержится __более__ 400 __шаблонов__, так что Вы можете легко начать работу над Вашей статьёй для журнала, диссертацией, резюме или любым другим документом.",
"done": "Готово",
"change": "Изменить",
"page_not_found": "Страница не найдена",
"please_see_help_for_more_info": "Пожалуйста, воспользуйтесь справкой для более полной информации",
"this_project_will_appear_in_your_dropbox_folder_at": "Этот проект появится в вашей папке Dropbox в ",
"member_of_group_subscription": "Вы являетесь членом группы подписчиков, управляемой __admin_email__. Пожалуйста, свяжитесь с администратором группы для настройки Вашей подписки. \n",
"about_henry_oswald": "программист, живущий в Лондоне. Он создал оригинальный прототип __appName__ и был ответственен за создание стабильной и масштабируемой платформы. Генри - строгий приверженец методики разработки через тестирование (TDD), и следит за тем, чтобы код __appName__ оставался чистым и лёгким в поддержке.",
"about_james_allen": "имеет докторскую степень по теоретической физике и увлечён LaTeX. Он создал один из первых онлайн редакторов LaTeX - ScribTeX, и сыграл огромную роль в разработке технологий, сделавших возможным __appName__.",
"two_strong_principles_behind_sl": "В нашей работы над __appName__ мы строго придерживаемся двух основополагающих принципов:",
"want_to_improve_workflow_of_as_many_people_as_possible": "Мы хотим улучшить рабочий процесс для максимально возможного числа людей.",
"detail_on_improve_peoples_workflow": "LaTeX по своей природе сложен в использовании, и совместная работа всегда требует сложной координации. Мы верим, что смогли разработать отличное решение, которое поможет людям столкнувшимся с этими проблемами, и мы хотим быть уверенными, что __appName__ доступен как можно большему числу людей. Мы старались сохранять наши цены доступными, а также опубликовали значительную часть исходного кода __appName__, так что любой желающий может установить его на собственном хостинге.",
"want_to_create_sustainable_lasting_legacy": "Мы хотим создать стабильное и долгосрочное решение.",
"details_on_legacy": "Разработка и поддержание такого продукта, как __appName__, всегда требует много времени и усилий, поэтому нам очень важно найти такую бизнес-модель, которая будет обеспечивать это сейчас и в будущем. Мы бы не хотели, чтобы __appName__ зависел от внешних инвесторов, или исчез из-за несостоятельной бизнес-модели. Я рад сообщить, что в настоящее время __appName__ стабилен и приносит доход, и надеюсь, что так будет и дальше.",
"get_in_touch": "Связаться с нами",
"want_to_hear_from_you_email_us_at": "Мы рады услышать каждого, кто использует __appName__, или хочет пообщаться о том, что мы делаем. Вы можете связаться с нами по ",
"cant_find_email": "Извините, данный адрес не зарегистрирован.",
"plans_amper_pricing": "Тарифы",
"documentation": "Документация",
"account": "Аккаунт",
"subscription": "Подписка",
"log_out": "Выйти",
"en": "Английский",
"pt": "Португальский",
"es": "Испанский",
"fr": "Французский",
"de": "Немецкий",
"it": "Итальянский",
"da": "Датский",
"sv": "Шведский",
"no": "Норвежский",
"nl": "Голландский",
"pl": "Польский",
"ru": "Русский",
"uk": "Украинский",
"ro": "Румынский",
"click_here_to_view_sl_in_lng": "Кликните здесь, для использования __appName__ на <0>__lngName__</0>",
"language": "Язык",
"upload": "Загрузить",
"menu": "Меню",
"full_screen": "Полный экран",
"logs_and_output_files": "Логи и выводные файлы",
"download_pdf": "Скачать PDF",
"split_screen": "Разделить экран",
"clear_cached_files": "Очистить кэшированные файлы",
"go_to_code_location_in_pdf": "Перейти к местоположению кода в PDF",
"please_compile_pdf_before_download": "Пожалуйста, скомпилируйте проект перед загрузкой PDF",
"remove_collaborator": "Удалить соавтора",
"add_to_folders": "Добавить в папки",
"download_zip_file": "Скачать архив (.zip)",
"price": "Цена",
"close": "Закрыть",
"keybindings": "Горячие клавиши",
"restricted": "Доступ ограничен",
"start_x_day_trial": "Начните свой __len__-дневный пробный период сегодня!",
"buy_now": "Купить!",
"cs": "Чешский",
"view_all": "Показать все",
"terms": "Условия",
"privacy": "Конфиденциальность",
"contact": "Контакт",
"change_to_this_plan": "Перейти на этот тариф",
"processing": "обработка",
"sure_you_want_to_change_plan": "Вы уверены, что хотите сменить тарифный план на <0>__planName__</0>?",
"move_to_annual_billing": "Переход к ежегодной оплате",
"annual_billing_enabled": "Ежегодная оплата подключена",
"move_to_annual_billing_now": "Перейти к ежегодной оплате сейчас",
"change_to_annual_billing_and_save": "Получите <0>__percentage__</0> скидки при ежегодной оплате. Перейдя сейчас, вы сэкономите <1>__yearlySaving__</1> в год.",
"missing_template_question": "Отсутствует нужный шаблон?",
"tell_us_about_the_template": "Если у нас отсутствует какой-либо шаблон, пожалуйста, пришлите нам его копию, либо сообщите нам адрес шаблона (URL) в __appName__, либо укажите, где мы можем его найти. Также, пожалуйста, предоставьте нам краткое описание шаблона.",
"email_us": "Написать нам",
"this_project_is_public_read_only": "Этот проект открыт для всех, у кого есть ссылка (но без возможности редактирования)",
"tr": "Турецкий",
"select_files": "Выбрать файл(-ы)",
"drag_files": "перетащить файл(-ы)",
"upload_failed_sorry": "Загрузка не удалась. Извините! :(",
"inserting_files": "Вставка файла...",
"password_reset_token_expired": "Ваш код восстановления пароля истёк. Пожалуйста, запросите восстановление пароля по почте ещё раз и перейдите по ссылке в письме.",
"merge_project_with_github": "Объединить проект с GitHub",
"pull_github_changes_into_sharelatex": "Скачать изменения с GitHub в __appName__",
"push_sharelatex_changes_to_github": "Загрузить изменения из __appName__ на GitHub",
"features": "Возможности",
"commit": "Фиксировать",
"commiting": "Фиксирование",
"importing_and_merging_changes_in_github": "Импорт и слияние изменений в GitHub",
"upgrade_for_faster_compiles": "Улучшить для более быстрой компиляции и уменьшения задержки",
"free_accounts_have_timeout_upgrade_to_increase": "В бесплатных аккаунтах есть задержка в одну минуту. Перейдите на другой тариф для уменьшения задержки.",
"learn_how_to_make_documents_compile_quickly": "Узнать, как ускорить компиляцию Вашего документа",
"zh-CN": "Китайский",
"cn": "Китайский (упрощённый)",
"sync_to_github": "Синхронизация с GitHub",
"sync_to_dropbox_and_github": "Синхронизировать с Dropbox и GitHub",
"project_too_large": "Проект слишком большой",
"project_too_large_please_reduce": "В этом проекте слишком много текста. Пожалуйста, попробуйте уменьшить количество.",
"please_ask_the_project_owner_to_link_to_github": "Пожалуйста, попросите владельца привязать данный проект к репозиторию на Github",
"go_to_pdf_location_in_code": "Перейти к коду в редакторе",
"ko": "Корейский",
"ja": "Японский",
"about_brian_gough": "программист, бывший физик-теоретик в области физики высоких энергий в Ферми-лаб и в Лос Аламосе. На протяжение долгих лет занимался публикацией бесплатных инструкций по коммерческому использованию TeX и LaTeX, а также осуществлял поддержку проекта GNU Scientific Library.",
"first_few_days_free": "Первые __trialLen__ дней бесплатно",
"every": "каждый",
"credit_card": "банковская карта",
"credit_card_number": "Номер банковской карты",
"invalid": "Недействительный",
"expiry": "Срок действия",
"january": "Январь",
"february": "Февраль",
"march": "Март",
"april": "Апрель",
"may": "Май",
"june": "Июнь",
"july": "Июль",
"august": "Август",
"september": "Сентябрь",
"october": "Октябрь",
"november": "Ноябрь",
"december": "Декабрь",
"zip_post_code": "Индекс",
"city": "Город",
"address": "Адрес",
"coupon_code": "код купона",
"country": "Страна",
"billing_address": "Адрес для счёта",
"upgrade_now": "Сменить тариф",
"state": "Состояние",
"vat_number": "Номер плательщика НДС",
"you_have_joined": "Вы вступили в группу __groupName__",
"claim_premium_account": "Вы запросили премиум аккаунт от __groupName__.",
"you_are_invited_to_group": " Вы приглашены для участия в группе __groupName__",
"you_can_claim_premium_account": "Для получения премиум аккаунта от __groupName__ подтвердите свой адрес электронной почты",
"not_now": "Не сейчас",
"verify_email_join_group": "Подтвердить адрес и вступить в группу",
"check_email_to_complete_group": "Пожалуйста, проверьте Вашу почту для завершения процесса вступления в группу!",
"verify_email_address": "Подтвердить адрес электронной почты",
"group_provides_you_with_premium_account": "__groupName__ предоставляет Вам премиум-доступ. Проверьте свой адрес электронной почты для обновления Вашего аккаунта.",
"check_email_to_complete_the_upgrade": "Пожалуйста, проверьте Вашу почту для завершения",
"email_link_expired": "Срок действия ссылки истёк. Пожалуйста, повторите запрос!",
"services": "Сервисы",
"about_shane_kilkelly": "разработчик ПО из Эдинбурга. Shane - приверженец функционального программирования, разработки через тестирования и гордится созданием качественного ПО.",
"this_is_your_template": "Это шаблон из Вашего проекта",
"links": "Ссылки",
"account_settings": "Настройки профиля",
"search_projects": "Поиск по проектам",
"clone_project": "Копировать проект",
"delete_project": "Удалить проект",
"download_zip": "Скачать архивом (zip)",
"new_project": "Создать проект",
"blank_project": "Новый проект",
"example_project": "Использовать пример",
"from_template": "Использовать шаблон",
"cv_or_resume": "Резюме",
"cover_letter": "Сопроводительное письмо",
"journal_article": "Статья",
"presentation": "Презентация",
"thesis": "Диссертация",
"bibliographies": "Библиография",
"terms_of_service": "Условия использования",
"privacy_policy": "Конфиденциальность",
"plans_and_pricing": "Тарифные планы",
"university_licences": "Академические лицензии",
"security": "Безопасность",
"contact_us": "Связаться с нами",
"thanks": "Спасибо",
"blog": "Блог",
"latex_editor": "Редактор LaTeX",
"get_free_stuff": "Получите бесплатное",
"chat": "Чат",
"your_message": "Введите сообщение",
"loading": "Загрузка",
"connecting": "Подключение",
"recompile": "Компилировать",
"download": "Скачать",
"email": "Email",
"owner": "Владелец",
"read_and_write": "Чтение и запись",
"read_only": "Только чтение",
"publish": "Опубликовать",
"view_in_template_gallery": "Посмотреть в галерее шаблонов",
"unpublish": "Отменить публикацию",
"hotkeys": "Горячие клавиши",
"saving": "Сохранение",
"cancel": "Отмена",
"project_name": "Название проекта",
"root_document": "Корневой документ",
"spell_check": "Проверка правописания",
"compiler": "Компилятор",
"private": "Закрытый",
"public": "Открытый",
"delete_forever": "Удалить навсегда",
"support_and_feedback": "Обратная связь и поддержка",
"help": "Помощь",
"latex_templates": "Шаблоны",
"info": "Информация",
"latex_help_guide": "Помощь по LaTeX",
"choose_your_plan": "Выберите тариф",
"indvidual_plans": "Индивидуальные тарифы",
"free_forever": "Бесплатно навсегда",
"low_priority_compile": "Низкий приоритет компиляции",
"unlimited_projects": "Неограниченное число проектов",
"unlimited_compiles": "Неограниченное число компиляций",
"full_history_of_changes": "Полная история изменений",
"highest_priority_compiling": "Высокий приоритет компиляции",
"dropbox_sync": "Синхронизация с Dropbox",
"beta": "Beta",
"sign_up_now": "Зарегистрироваться",
"annual": "Цена за год",
"half_price_student": "Тарифы для студентов",
"about_us": "О нас",
"loading_recent_github_commits": "Загрузка последний изменений",
"no_new_commits_in_github": "Нет новых коммитов на GitHub с момента последнего слияния.",
"dropbox_sync_description": "Синхронизируйте Ваши __appName__ проекты с Вашим Dropbox. Изменения в __appName__ автоматически сохраняются в Вашем Dropbox, и наоборот.",
"github_sync_description": "Вы можете связать ваши проекты __appName__ с репозиториями на GitHub. Создавайте коммиты в __appName__ и объединяйте их с коммитами, сделанными оффлайн или на GitHub.",
"github_import_description": "Вы можете импортировать Ваши репозитории на GitHub в __appName__. Создавайте коммиты в __appName__ и объединяйте их с коммитами, сделанными оффлайн или на GitHub.",
"link_to_github_description": "Вам необходимо авторизовать __appName__ для доступа к Вашему GitHub аккаунту, чтобы разрешить нам синхронизацию Ваших проектов.",
"unlink": "Отсоединить",
"unlink_github_warning": "Все проекты, которые Вы синхронизировали с GitHub, будут отсоединены и больше не будут синхронизироваться с GitHub. Вы уверены, что хотите отсоединить Ваш GitHub аккаунт?",
"github_account_successfully_linked": "Аккаунт GitHub успешно присоединён!",
"github_successfully_linked_description": "Спасибо, мы успешно связали ваш аккаунт на GitHub с __appName__. Теперь вы можете экспортировать проекты с __appName__ в GitHub или импортировать в обратном направлении.",
"import_from_github": "Импорт с GitHub",
"github_sync_error": "Извините, произошла ошибка в общении с сервисом GitHub. Пожалуйста, попробуйте ещё раз позднее.",
"loading_github_repositories": "Загрузка ваших проектов с GitHub",
"select_github_repository": "Выберите проект на GitHub для импорта в __appName__",
"import_to_sharelatex": "Импортировать в __appName__",
"importing": "Импорт",
"github_sync": "Синхронизация с GitHub",
"checking_project_github_status": "Проверка статуса проекта на GitHub",
"account_not_linked_to_github": "Ваш аккаунт не привязан к GitHub",
"project_not_linked_to_github": "Этот проект не связан ни с одним проектом на GitHub. Вы можете создать для него проект на GitHub:",
"create_project_in_github": "Создать проект на GitHub",
"project_synced_with_git_repo_at": "Проект синхронизирован с GitHub в",
"recent_commits_in_github": "Последние коммиты на GitHub",
"sync_project_to_github": "Синхронизация с GitHub",
"sync_project_to_github_explanation": "Все изменения, сделанные Вами в __appName__ будут интегрированы (commit и merge) со всеми обновлениями на GitHub.",
"github_merge_failed": "Ваши изменения в __appName__ и GitHub не могут быть интегрированы автоматически. Пожалуйста, интегрируйте (merge) ветвь <0>__sharelatex_branch__</0> branch в <1>__master_branch__</1> в git вручную. Нажмите внизу для продолжения, когда будете готовы.",
"continue_github_merge": "Я провел(-а) слияние вручную. Продолжить",
"export_project_to_github": "Экспорт проекта на GitHub",
"github_validation_check": "Пожалуйста, проверьте правильность имени хранилища и права доступа на создание хранилища",
"repository_name": "Наименование репозитория",
"optional": "Необязательный",
"github_public_description": "Этот репозиторий может просмотреть каждый. Вы выбираете, кто может править.",
"github_commit_message_placeholder": "Сообщение о фиксации изменений в __appName__...",
"merge": "Соединить",
"merging": "Соединение",
"github_account_is_linked": "Ваш аккаунт на GitHub успешно привязан.",
"unlink_github": "Отвязать аккаунт на GitHub",
"link_to_github": "Привязать аккаунт на GitHub",
"github_integration": "Интеграция с GitHub",
"github_is_premium": "Синхронизация с GitHub доступна только в премиум аккаунте",
"thank_you": "Спасибо!"
}
| overleaf/web/locales/ru.json/0 | {
"file_path": "overleaf/web/locales/ru.json",
"repo_id": "overleaf",
"token_count": 33607
} | 536 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['saas']
const indexes = [
{
key: {
user_id: 1,
},
name: 'user_id_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.githubSyncUserCredentials, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(
db.githubSyncUserCredentials,
indexes
)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145011_create_githubSyncUserCredentials_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145011_create_githubSyncUserCredentials_indexes.js",
"repo_id": "overleaf",
"token_count": 234
} | 537 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['server-ce', 'server-pro', 'saas']
const indexes = [
{
key: {
token: 1,
},
name: 'token',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.spellingPreferences, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.spellingPreferences, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20190912145027_create_spellingPreferences_indexes.js/0 | {
"file_path": "overleaf/web/migrations/20190912145027_create_spellingPreferences_indexes.js",
"repo_id": "overleaf",
"token_count": 218
} | 538 |
/* eslint-disable no-unused-vars */
const Helpers = require('./lib/helpers')
exports.tags = ['saas']
const indexes = [
{
key: {
requestId: 1,
},
name: 'requestId_1',
},
{
// expire after 24 hours
expireAfterSeconds: 60 * 60 * 24,
key: {
createdAt: 1,
},
name: 'createdAt_1',
},
]
exports.migrate = async client => {
const { db } = client
await Helpers.addIndexesToCollection(db.samlCache, indexes)
}
exports.rollback = async client => {
const { db } = client
try {
await Helpers.dropIndexesFromCollection(db.samlCache, indexes)
} catch (err) {
console.error('Something went wrong rolling back the migrations', err)
}
}
| overleaf/web/migrations/20200608213302_saml-cache-indexes.js/0 | {
"file_path": "overleaf/web/migrations/20200608213302_saml-cache-indexes.js",
"repo_id": "overleaf",
"token_count": 275
} | 539 |
/* 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
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const logger = require('logger-sharelatex')
const LaunchpadController = require('./LaunchpadController')
const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController')
const AuthorizationMiddleware = require('../../../../app/src/Features/Authorization/AuthorizationMiddleware')
module.exports = {
apply(webRouter, apiRouter) {
logger.log({}, 'Init launchpad router')
webRouter.get('/launchpad', LaunchpadController.launchpadPage)
webRouter.post(
'/launchpad/register_admin',
LaunchpadController.registerAdmin
)
webRouter.post(
'/launchpad/register_ldap_admin',
LaunchpadController.registerExternalAuthAdmin('ldap')
)
webRouter.post(
'/launchpad/register_saml_admin',
LaunchpadController.registerExternalAuthAdmin('saml')
)
webRouter.post(
'/launchpad/send_test_email',
AuthorizationMiddleware.ensureUserIsSiteAdmin,
LaunchpadController.sendTestEmail
)
if (AuthenticationController.addEndpointToLoginWhitelist != null) {
AuthenticationController.addEndpointToLoginWhitelist('/launchpad')
AuthenticationController.addEndpointToLoginWhitelist(
'/launchpad/register_admin'
)
AuthenticationController.addEndpointToLoginWhitelist(
'/launchpad/register_ldap_admin'
)
return AuthenticationController.addEndpointToLoginWhitelist(
'/launchpad/register_saml_admin'
)
}
},
}
| overleaf/web/modules/launchpad/app/src/LaunchpadRouter.js/0 | {
"file_path": "overleaf/web/modules/launchpad/app/src/LaunchpadRouter.js",
"repo_id": "overleaf",
"token_count": 627
} | 540 |
const base = require(process.env.BASE_CONFIG)
module.exports = base.mergeWith({
test: {
counterInit: 160000,
},
})
| overleaf/web/modules/server-ce-scripts/test/acceptance/config/settings.test.js/0 | {
"file_path": "overleaf/web/modules/server-ce-scripts/test/acceptance/config/settings.test.js",
"repo_id": "overleaf",
"token_count": 49
} | 541 |
google-site-verification: googleef256f97939bd9b7.html | overleaf/web/public/googleef256f97939bd9b7.html/0 | {
"file_path": "overleaf/web/public/googleef256f97939bd9b7.html",
"repo_id": "overleaf",
"token_count": 20
} | 542 |
const { db, waitForDb } = require('../app/src/infrastructure/mongodb')
async function updateStringDates() {
await waitForDb()
const users = await db.users.aggregate([
{ $unwind: { path: '$emails' } },
{
$match: { 'emails.confirmedAt': { $exists: true, $type: 'string' } },
},
{
$project: {
_id: 1,
'emails.email': 1,
'emails.confirmedAt': 1,
},
},
])
let user
let count = 0
while ((user = await users.next())) {
count += 1
if (count % 10000 === 0) {
console.log(`processed ${count} users`)
}
const confirmedAt = user.emails.confirmedAt
const dateConfirmedAt = new Date(confirmedAt.replace(/ UTC$/, ''))
await db.users.updateOne(
{
_id: user._id,
'emails.email': user.emails.email,
},
{
$set: {
'emails.$.confirmedAt': dateConfirmedAt,
},
}
)
}
console.log(`Updated ${count} confirmedAt strings to dates!`)
}
if (!module.parent) {
updateStringDates()
.then(() => {
process.exit(0)
})
.catch(error => {
console.error(error)
process.exit(1)
})
}
module.exports = updateStringDates
| overleaf/web/scripts/confirmed_at_to_dates.js/0 | {
"file_path": "overleaf/web/scripts/confirmed_at_to_dates.js",
"repo_id": "overleaf",
"token_count": 542
} | 543 |
# Usage
```
node scripts/learn/checkSanitize https://LEARN_WIKI
```
## Bulk export
There is a bulk export for media wiki pages, but it produces different
html escaping compared to the regular parse API we use in web.
The bulk export does not escape all the placeholder HTML-like elements,
like `<project-id` or `<document goes here>`.
## Example output
Here is how a missing tag gets flagged:
```
---
page : MediaWiki markup for the Overleaf support team
title : MediaWiki markup for the Overleaf support team
match : false
toText : false
text : "Overleaf</strong></td>\n </tr>\n <tr><td>Kb/<strong>TITLE_SLUG</strong></td><td><nowiki>https://www.overleaf.com/learn/how-to/</nowiki><strong>TITLE_SLUG</strong></td>\n </"
sanitized : "Overleaf</strong></td>\n </tr>\n <tr><td>Kb/<strong>TITLE_SLUG</strong></td><td><nowiki>https://www.overleaf.com/learn/how-to/</nowiki><strong>TITLE_SLUG</strong></td>\n "
textToText : " \n \n \n \n MediaWiki page\n Maps to on Overleaf\n \n Kb/TITLE_SLUGhttps://www.overleaf.com/learn/how-to/TITLE_SLUG\n "
sanitizedToText: " \n \n \n \n MediaWiki page\n Maps to on Overleaf\n \n Kb/TITLE_SLUG<nowiki>https://www.overleaf.com/learn/how-to/</nowiki>TITLE"
```
Note the hidden/escaped `<nowiki>` element.
In addition to the side-by-side comparison of HTML you will see a plain-text diff.
| overleaf/web/scripts/learn/checkSanitize/README.md/0 | {
"file_path": "overleaf/web/scripts/learn/checkSanitize/README.md",
"repo_id": "overleaf",
"token_count": 758
} | 544 |
# Sync User Entitlements
Entitlement information for insitutional (university) sso users is stored in
both the mongo users collection and the postgres v2_user_universities table.
The mongo users collection is authoratative but these need to be in sync for
everything to work properly.
This script takes exports from both mongo and postgres, finds mismatches, and
then corrects the data in postgres so that it matches mongo.
## Exporting users data from mongo
Follow the directions in `google-ops/README.md` for exporting data from mongo
and copying the files to your local machine.
Run the following user export command.
```
mongoexport --uri $READ_ONLY_MONGO_CONNECTION_STRING --collection users --fields '_id,email,emails,samlIdentifiers' --query '{"samlIdentifiers.providerId": {"$exists": 1}}' --out user-entitlements.json
```
**Note: this file contains PII and caution must be exercised to insure that it
is never transferred or stored insecurely and that it is deleted ASAP**
## Exporting data from postgres
Connect to postgres by running `heroku psql -a electric-leaf-4093`
Run the following v2_user_universities export comand.
```
\copy (select uu.user_id, uu.email, uu.cached_entitlement, ud.university_id from v2_user_universities uu LEFT JOIN university_domains ud ON uu.university_domain_id = ud.id WHERE uu.removed_at IS NULL) to 'cached-entitlements.csv' with csv;
```
**Note: this file contains PII and caution must be exercised to insure that it
is never transferred or stored insecurely and that it is deleted ASAP**
## Run sync
```
node scripts/sync-user-entitlements/sync-user-entitlements --user-entitlements user-entitlements.json --cached-entitlements cached-entitlements.csv --commit
```
| overleaf/web/scripts/sync-user-entitlements/README.md/0 | {
"file_path": "overleaf/web/scripts/sync-user-entitlements/README.md",
"repo_id": "overleaf",
"token_count": 511
} | 545 |
'use strict'
const fs = require('fs-extra')
const xml2js = require('xml2js')
const UKAMFEntity = require('./ukamf-entity')
class UKAMFDB {
constructor(file) {
this.file = file
}
async init() {
const data = await fs.readFile(this.file, 'utf8')
const parser = new xml2js.Parser()
const xml = await parser.parseStringPromise(data)
this.entities = xml.EntitiesDescriptor.EntityDescriptor
}
findByEntityID(matcher) {
const entity = this.entities.find(
matcher instanceof RegExp
? e => e.$.entityID.match(matcher)
: e => e.$.entityID.includes(matcher)
)
return entity ? new UKAMFEntity(entity) : null
}
}
module.exports = UKAMFDB
| overleaf/web/scripts/ukamf/ukamf-db.js/0 | {
"file_path": "overleaf/web/scripts/ukamf/ukamf-db.js",
"repo_id": "overleaf",
"token_count": 274
} | 546 |
const { expect } = require('chai')
const UserHelper = require('../src/helpers/UserHelper')
describe('BetaProgram', function () {
let email, userHelper
beforeEach(async function () {
userHelper = new UserHelper()
email = userHelper.getDefaultEmail()
userHelper = await UserHelper.createUser({ email })
userHelper = await UserHelper.loginUser({
email,
password: userHelper.getDefaultPassword(),
})
})
it('should opt in', async function () {
const response = await userHelper.request.post('/beta/opt-in', {
simple: false,
})
expect(response.statusCode).to.equal(302)
response.statusCode.should.equal(302)
expect(response.headers.location).to.equal('/beta/participate')
const user = (
await UserHelper.getUser({
email,
})
).user
expect(user.betaProgram).to.equal(true)
})
it('should opt out', async function () {
const response = await userHelper.request.post('/beta/opt-out', {
simple: false,
})
expect(response.statusCode).to.equal(302)
response.statusCode.should.equal(302)
expect(response.headers.location).to.equal('/beta/participate')
const user = (
await UserHelper.getUser({
email,
})
).user
expect(user.betaProgram).to.equal(false)
})
})
| overleaf/web/test/acceptance/src/BetaProgramTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/BetaProgramTests.js",
"repo_id": "overleaf",
"token_count": 478
} | 547 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
mocha/no-identical-title,
no-path-concat,
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
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const async = require('async')
const { expect } = require('chai')
const sinon = require('sinon')
const mkdirp = require('mkdirp')
const Path = require('path')
const fs = require('fs')
const Settings = require('@overleaf/settings')
const _ = require('underscore')
const ProjectGetter = require('../../../app/src/Features/Project/ProjectGetter.js')
const request = require('./helpers/request')
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('ProjectDuplicateNames', function () {
beforeEach(function (done) {
this.owner = new User()
this.owner.login(done)
this.project = {}
return (this.callback = sinon.stub())
})
describe('creating a project from the example template', function () {
beforeEach(function (done) {
return this.owner.createProject(
'example-project',
{ template: 'example' },
(error, project_id) => {
if (error != null) {
throw error
}
this.example_project_id = project_id
return this.owner.getProject(project_id, (error, project) => {
this.project = project
this.mainTexDoc = _.find(
project.rootFolder[0].docs,
doc => doc.name === 'main.tex'
)
this.refBibDoc = _.find(
project.rootFolder[0].docs,
doc => doc.name === 'references.bib'
)
this.imageFile = _.find(
project.rootFolder[0].fileRefs,
file => file.name === 'universe.jpg'
)
this.rootFolderId = project.rootFolder[0]._id.toString()
// create a folder called 'testfolder'
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'testfolder',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.testFolderId = body._id
return done()
}
)
})
}
)
})
it('should create a project', function () {
expect(this.project.rootFolder[0].docs.length).to.equal(2)
return expect(this.project.rootFolder[0].fileRefs.length).to.equal(1)
})
it('should create two docs in the docstore', function () {
const docs = MockDocstoreApi.docs[this.example_project_id]
return expect(Object.keys(docs).length).to.equal(2)
})
it('should create one file in the filestore', function () {
const files = MockFilestoreApi.files[this.example_project_id]
return expect(Object.keys(files).length).to.equal(1)
})
describe('for an existing doc', function () {
describe('trying to add a doc with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
json: {
name: 'main.tex',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to add a folder with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'main.tex',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to add a folder with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'main.tex',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
describe('for an existing file', function () {
describe('trying to add a doc with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
json: {
name: 'universe.jpg',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to add a folder with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'universe.jpg',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to upload a file with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/upload`,
json: true,
qs: {
folder_id: this.rootFolderId,
qqfilename: 'universe.jpg',
},
formData: {
qqfile: {
value: fs.createReadStream(
Path.resolve(__dirname + '/../files/1pixel.png')
),
options: {
filename: 'universe.jpg',
contentType: 'image/jpeg',
},
},
},
},
(err, res, body) => {
this.body = body
// update the image id because we have replaced the file
this.imageFile._id = this.body.entity_id
return done()
}
)
})
it('should succeed (overwriting the file)', function () {
return expect(this.body.success).to.equal(true)
})
})
})
// at this point the @imageFile._id has changed
describe('for an existing folder', function () {
describe('trying to add a doc with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
json: {
name: 'testfolder',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to add a folder with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'testfolder',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to upload a file with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/upload`,
json: true,
qs: {
folder_id: this.rootFolderId,
qqfilename: 'universe.jpg',
},
formData: {
qqfile: {
value: fs.createReadStream(
Path.resolve(__dirname + '/../files/1pixel.png')
),
options: {
filename: 'testfolder',
contentType: 'image/jpeg',
},
},
},
},
(err, res, body) => {
this.body = body
return done()
}
)
})
it('should respond with failure status', function () {
return expect(this.body.success).to.equal(false)
})
})
})
describe('for an existing doc', function () {
describe('trying to rename a doc to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.refBibDoc._id}/rename`,
json: {
name: 'main.tex',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to rename a folder to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/rename`,
json: {
name: 'main.tex',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to rename a file to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/rename`,
json: {
name: 'main.tex',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with failure status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
describe('for an existing file', function () {
describe('trying to rename a doc to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.refBibDoc._id}/rename`,
json: {
name: 'universe.jpg',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to rename a folder to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/rename`,
json: {
name: 'universe.jpg',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to rename a file to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/rename`,
json: {
name: 'universe.jpg',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with failure status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
describe('for an existing folder', function () {
describe('trying to rename a doc to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.refBibDoc._id}/rename`,
json: {
name: 'testfolder',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to rename a folder to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/rename`,
json: {
name: 'testfolder',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to rename a file to the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/rename`,
json: {
name: 'testfolder',
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with failure status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
describe('for an existing folder with a file with the same name', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
json: {
name: 'main.tex',
parent_folder_id: this.testFolderId,
},
},
(err, res, body) => {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc`,
json: {
name: 'universe.jpg',
parent_folder_id: this.testFolderId,
},
},
(err, res, body) => {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'otherFolder',
parent_folder_id: this.testFolderId,
},
},
(err, res, body) => {
this.subFolderId = body._id
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder`,
json: {
name: 'otherFolder',
parent_folder_id: this.rootFolderId,
},
},
(err, res, body) => {
this.otherFolderId = body._id
return done()
}
)
}
)
}
)
}
)
})
describe('trying to move a doc into the folder', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/doc/${this.mainTexDoc._id}/move`,
json: {
folder_id: this.testFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to move a file into the folder', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/file/${this.imageFile._id}/move`,
json: {
folder_id: this.testFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to move a folder into the folder', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.otherFolderId}/move`,
json: {
folder_id: this.testFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
describe('trying to move a folder into a subfolder of itself', function () {
beforeEach(function (done) {
return this.owner.request.post(
{
uri: `/project/${this.example_project_id}/folder/${this.testFolderId}/move`,
json: {
folder_id: this.subFolderId,
},
},
(err, res, body) => {
this.res = res
return done()
}
)
})
it('should respond with 400 error status', function () {
return expect(this.res.statusCode).to.equal(400)
})
})
})
})
})
| overleaf/web/test/acceptance/src/ProjectDuplicateNameTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/ProjectDuplicateNameTests.js",
"repo_id": "overleaf",
"token_count": 10902
} | 548 |
/* eslint-disable
camelcase,
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { expect } = require('chai')
const ProjectGetter = require('../../../app/src/Features/Project/ProjectGetter.js')
const request = require('./helpers/request')
const User = require('./helpers/User')
describe('TpdsUpdateTests', function () {
beforeEach(function (done) {
this.owner = new User()
return this.owner.login(error => {
if (error != null) {
throw error
}
return this.owner.createProject(
'test-project',
{ template: 'example' },
(error, project_id) => {
if (error != null) {
throw error
}
this.project_id = project_id
return done()
}
)
})
})
describe('adding a file', function () {
beforeEach(function (done) {
return request(
{
method: 'POST',
url: `/project/${this.project_id}/contents/test.tex`,
auth: {
username: 'sharelatex',
password: 'password',
sendImmediately: true,
},
body: 'test one two',
},
(error, response, body) => {
if (error != null) {
throw error
}
expect(response.statusCode).to.equal(200)
return done()
}
)
})
it('should have added the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
}
const projectFolder = project.rootFolder[0]
const file = projectFolder.docs.find(e => e.name === 'test.tex')
expect(file).to.exist
return done()
})
})
})
describe('deleting a file', function () {
beforeEach(function (done) {
return request(
{
method: 'DELETE',
url: `/project/${this.project_id}/contents/main.tex`,
auth: {
username: 'sharelatex',
password: 'password',
sendImmediately: true,
},
},
(error, response, body) => {
if (error != null) {
throw error
}
expect(response.statusCode).to.equal(200)
return done()
}
)
})
it('should have deleted the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
}
const projectFolder = project.rootFolder[0]
for (const doc of Array.from(projectFolder.docs)) {
if (doc.name === 'main.tex') {
throw new Error('expected main.tex to have been deleted')
}
}
return done()
})
})
})
describe('update a new file', function () {
beforeEach(function (done) {
return request(
{
method: 'POST',
url: `/user/${this.owner._id}/update/test-project/other.tex`,
auth: {
username: 'sharelatex',
password: 'password',
sendImmediately: true,
},
body: 'test one two',
},
(error, response, body) => {
if (error != null) {
throw error
}
expect(response.statusCode).to.equal(200)
return done()
}
)
})
it('should have added the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
}
const projectFolder = project.rootFolder[0]
const file = projectFolder.docs.find(e => e.name === 'other.tex')
expect(file).to.exist
return done()
})
})
})
describe('update when the project is archived', function () {
beforeEach(function (done) {
this.owner.request(
{
url: `/Project/${this.project_id}/archive`,
method: 'post',
},
(err, response, body) => {
expect(err).to.not.exist
return request(
{
method: 'POST',
url: `/user/${this.owner._id}/update/test-project/test.tex`,
auth: {
username: 'sharelatex',
password: 'password',
sendImmediately: true,
},
body: 'test one two',
},
(error, response, body) => {
if (error != null) {
throw error
}
expect(response.statusCode).to.equal(200)
return done()
}
)
}
)
})
it('should not have created a new project', function (done) {
ProjectGetter.findAllUsersProjects(
this.owner._id,
'name',
(err, projects) => {
expect(err).to.not.exist
expect(projects.owned.length).to.equal(1)
done()
}
)
})
it('should not have added the file', function (done) {
return ProjectGetter.getProject(this.project_id, (error, project) => {
if (error != null) {
throw error
}
const projectFolder = project.rootFolder[0]
const file = projectFolder.docs.find(e => e.name === 'test.tex')
expect(file).to.not.exist
return done()
})
})
})
})
| overleaf/web/test/acceptance/src/TpdsUpdateTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/TpdsUpdateTests.js",
"repo_id": "overleaf",
"token_count": 2731
} | 549 |
const { callbackify } = require('util')
const request = require('./request')
async function getMetric(matcher) {
const { body } = await request.promises.request('/metrics')
const found = body.split('\n').find(matcher)
if (!found) return 0
return parseInt(found.split(' ')[1], 0)
}
module.exports = {
getMetric: callbackify(getMetric),
promises: {
getMetric,
},
}
| overleaf/web/test/acceptance/src/helpers/metrics.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/helpers/metrics.js",
"repo_id": "overleaf",
"token_count": 135
} | 550 |
const AbstractMockApi = require('./AbstractMockApi')
const { EventEmitter } = require('events')
class MockV1HistoryApi extends AbstractMockApi {
reset() {
this.fakeZipCall = 0
this.requestedZipPacks = 0
this.sentChunks = 0
this.events = new EventEmitter()
}
applyRoutes() {
this.app.get(
'/api/projects/:project_id/version/:version/zip',
(req, res, next) => {
res.header('content-disposition', 'attachment; name=project.zip')
res.header('content-type', 'application/octet-stream')
res.send(
`Mock zip for ${req.params.project_id} at version ${req.params.version}`
)
}
)
this.app.get(
'/fake-zip-download/:project_id/version/:version',
(req, res, next) => {
if (!(this.fakeZipCall++ > 0)) {
return res.sendStatus(404)
}
res.header('content-disposition', 'attachment; name=project.zip')
res.header('content-type', 'application/octet-stream')
if (req.params.version === '42') {
return res.send(
`Mock zip for ${req.params.project_id} at version ${req.params.version}`
)
}
const writeChunk = () => {
res.write('chunk' + this.sentChunks++)
}
const writeEvery = interval => {
if (req.aborted) return
// setInterval delays the first run
writeChunk()
const periodicWrite = setInterval(writeChunk, interval)
req.on('aborted', () => clearInterval(periodicWrite))
const deadLine = setTimeout(() => {
clearInterval(periodicWrite)
res.end()
}, 10 * 1000)
res.on('end', () => clearTimeout(deadLine))
}
if (req.params.version === '100') {
return writeEvery(100)
}
res.sendStatus(400)
}
)
this.app.post(
'/api/projects/:project_id/version/:version/zip',
(req, res, next) => {
this.requestedZipPacks++
this.events.emit('v1-history-pack-zip')
res.json({
zipUrl: `http://localhost:3100/fake-zip-download/${req.params.project_id}/version/${req.params.version}`,
})
}
)
this.app.delete('/api/projects/:project_id', (req, res, next) => {
res.sendStatus(204)
})
}
}
module.exports = MockV1HistoryApi
// type hint for the inherited `instance` method
/**
* @function instance
* @memberOf MockV1HistoryApi
* @static
* @returns {MockV1HistoryApi}
*/
| overleaf/web/test/acceptance/src/mocks/MockV1HistoryApi.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/mocks/MockV1HistoryApi.js",
"repo_id": "overleaf",
"token_count": 1138
} | 551 |
import { expect } from 'chai'
import * as sinon from 'sinon'
import { useEffect } from 'react'
import {
screen,
render,
fireEvent,
cleanup,
waitFor,
} from '@testing-library/react'
import fetchMock from 'fetch-mock'
import PropTypes from 'prop-types'
import { contextProps } from './context-props'
import FileTreeModalCreateFile from '../../../../../../frontend/js/features/file-tree/components/modals/file-tree-modal-create-file'
import FileTreeContext from '../../../../../../frontend/js/features/file-tree/components/file-tree-context'
import { useFileTreeActionable } from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-actionable'
import { useFileTreeMutable } from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-mutable'
describe('<FileTreeModalCreateFile/>', function () {
beforeEach(function () {
window.csrfToken = 'token'
})
afterEach(function () {
delete window.csrfToken
fetchMock.restore()
cleanup()
})
it('handles invalid file names', async function () {
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="doc" />
</FileTreeContext>
)
const submitButton = screen.getByRole('button', { name: 'Create' })
const input = screen.getByLabelText('File Name')
expect(input.value).to.equal('name.tex')
expect(submitButton.disabled).to.be.false
expect(screen.queryAllByRole('alert')).to.be.empty
fireEvent.change(input, { target: { value: '' } })
expect(submitButton.disabled).to.be.true
screen.getByRole(
(role, element) =>
role === 'alert' && element.textContent.match(/File name is empty/)
)
await fireEvent.change(input, { target: { value: 'test.tex' } })
expect(submitButton.disabled).to.be.false
expect(screen.queryAllByRole('alert')).to.be.empty
await fireEvent.change(input, { target: { value: 'oops/i/did/it/again' } })
expect(submitButton.disabled).to.be.true
screen.getByRole(
(role, element) =>
role === 'alert' &&
element.textContent.match(/contains invalid characters/)
)
})
it('displays an error when the file limit is reached', async function () {
const rootFolder = [
{
docs: Array.from({ length: 10 }, (_, index) => ({
_id: `entity-${index}`,
})),
fileRefs: [],
folders: [],
},
]
render(
<FileTreeContext
{...contextProps}
rootFolder={rootFolder}
initialSelectedEntityId="entity-1"
>
<OpenWithMode mode="doc" />
</FileTreeContext>
)
screen.getByRole(
(role, element) =>
role === 'alert' &&
element.textContent.match(/This project has reached the \d+ file limit/)
)
})
it('displays a warning when the file limit is nearly reached', async function () {
const rootFolder = [
{
docs: Array.from({ length: 9 }, (_, index) => ({
_id: `entity-${index}`,
})),
fileRefs: [],
folders: [],
},
]
render(
<FileTreeContext
{...contextProps}
rootFolder={rootFolder}
initialSelectedEntityId="entity-1"
>
<OpenWithMode mode="doc" />
</FileTreeContext>
)
screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
})
it('counts files in nested folders', async function () {
const rootFolder = [
{
docs: [{ _id: 'entity-1' }],
fileRefs: [],
folders: [
{
docs: [{ _id: 'entity-1-2' }],
fileRefs: [],
folders: [
{
docs: [
{ _id: 'entity-3' },
{ _id: 'entity-4' },
{ _id: 'entity-5' },
{ _id: 'entity-6' },
{ _id: 'entity-7' },
{ _id: 'entity-8' },
{ _id: 'entity-9' },
],
fileRefs: [],
folders: [],
},
],
},
],
},
]
render(
<FileTreeContext
{...contextProps}
rootFolder={rootFolder}
initialSelectedEntityId="entity-1"
>
<OpenWithMode mode="doc" />
</FileTreeContext>
)
screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
})
it('creates a new file when the form is submitted', async function () {
fetchMock.post('express:/project/:projectId/doc', () => 204)
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="doc" />
</FileTreeContext>
)
const input = screen.getByLabelText('File Name')
await fireEvent.change(input, { target: { value: 'test.tex' } })
const submitButton = screen.getByRole('button', { name: 'Create' })
await fireEvent.click(submitButton)
expect(
fetchMock.called('express:/project/:projectId/doc', {
body: { name: 'test.tex' },
})
).to.be.true
})
it('imports a new file from a project', async function () {
fetchMock
.get('path:/user/projects', {
projects: [
{
_id: 'test-project',
name: 'This Project',
},
{
_id: 'project-1',
name: 'Project One',
},
{
_id: 'project-2',
name: 'Project Two',
},
],
})
.get('express:/project/:projectId/entities', {
entities: [
{
path: '/foo.tex',
},
{
path: '/bar.tex',
},
],
})
.post('express:/project/:projectId/compile', {
status: 'success',
outputFiles: [
{
build: 'test',
path: 'baz.jpg',
},
{
build: 'test',
path: 'ball.jpg',
},
],
})
.post('express:/project/:projectId/linked_file', () => 204)
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="project" />
</FileTreeContext>
)
// initial state, no project selected
const projectInput = screen.getByLabelText('Select a Project')
expect(projectInput.disabled).to.be.true
await waitFor(() => {
expect(projectInput.disabled).to.be.false
})
// the submit button should be disabled
const submitButton = screen.getByRole('button', { name: 'Create' })
expect(submitButton.disabled).to.be.true
// the source file selector should be disabled
const fileInput = screen.getByLabelText('Select a File')
expect(fileInput.disabled).to.be.true
// TODO: check for options length, excluding current project
// select a project
await fireEvent.change(projectInput, { target: { value: 'project-2' } }) // TODO: getByRole('option')?
// wait for the source file selector to be enabled
await waitFor(() => {
expect(fileInput.disabled).to.be.false
})
expect(screen.queryByLabelText('Select a File')).not.to.be.null
expect(screen.queryByLabelText('Select an Output File')).to.be.null
expect(submitButton.disabled).to.be.true
// TODO: check for fileInput options length, excluding current project
// click on the button to toggle between source and output files
const sourceTypeButton = screen.getByRole('button', {
// NOTE: When changing the label, update the other tests with this label as well.
name: 'select from output files',
})
await fireEvent.click(sourceTypeButton)
// wait for the output file selector to be enabled
const entityInput = screen.getByLabelText('Select an Output File')
await waitFor(() => {
expect(entityInput.disabled).to.be.false
})
expect(screen.queryByLabelText('Select a File')).to.be.null
expect(screen.queryByLabelText('Select an Output File')).not.to.be.null
expect(submitButton.disabled).to.be.true
// TODO: check for entityInput options length, excluding current project
await fireEvent.change(entityInput, { target: { value: 'ball.jpg' } }) // TODO: getByRole('option')?
await waitFor(() => {
expect(submitButton.disabled).to.be.false
})
await fireEvent.click(submitButton)
expect(
fetchMock.called('express:/project/:projectId/linked_file', {
body: {
name: 'ball.jpg',
provider: 'project_output_file',
data: {
source_project_id: 'project-2',
source_output_file_path: 'ball.jpg',
build_id: 'test',
},
},
})
).to.be.true
})
describe('when the output files feature is not available', function () {
const flagBefore = window.ExposedSettings.hasLinkedProjectOutputFileFeature
before(function () {
window.ExposedSettings.hasLinkedProjectOutputFileFeature = false
})
after(function () {
window.ExposedSettings.hasLinkedProjectOutputFileFeature = flagBefore
})
it('should not show the import from output file mode', async function () {
fetchMock.get('path:/user/projects', {
projects: [
{
_id: 'test-project',
name: 'This Project',
},
{
_id: 'project-1',
name: 'Project One',
},
{
_id: 'project-2',
name: 'Project Two',
},
],
})
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="project" />
</FileTreeContext>
)
// should not show the toggle
expect(
screen.queryByRole('button', {
name: 'select from output files',
})
).to.be.null
})
})
it('import from a URL when the form is submitted', async function () {
fetchMock.post('express:/project/:projectId/linked_file', () => 204)
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="url" />
</FileTreeContext>
)
const urlInput = screen.getByLabelText('URL to fetch the file from')
const nameInput = screen.getByLabelText('File Name In This Project')
await fireEvent.change(urlInput, {
target: { value: 'https://example.com/example.tex' },
})
// check that the name has updated automatically
expect(nameInput.value).to.equal('example.tex')
await fireEvent.change(nameInput, {
target: { value: 'test.tex' },
})
// check that the name can still be edited manually
expect(nameInput.value).to.equal('test.tex')
const submitButton = screen.getByRole('button', { name: 'Create' })
await fireEvent.click(submitButton)
expect(
fetchMock.called('express:/project/:projectId/linked_file', {
body: {
name: 'test.tex',
provider: 'url',
data: { url: 'https://example.com/example.tex' },
},
})
).to.be.true
})
it('uploads a dropped file', async function () {
const xhr = sinon.useFakeXMLHttpRequest()
const requests = []
xhr.onCreate = request => {
requests.push(request)
}
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="upload" />
</FileTreeContext>
)
// the submit button should not be present
expect(screen.queryByRole('button', { name: 'Create' })).to.be.null
const dropzone = screen.getByLabelText('File Uploader')
expect(dropzone).not.to.be.null
fireEvent.drop(dropzone, {
dataTransfer: {
files: [new File(['test'], 'test.tex', { type: 'text/plain' })],
},
})
await waitFor(() => expect(requests).to.have.length(1))
const [request] = requests
expect(request.url).to.equal('/project/test-project/upload')
expect(request.method).to.equal('POST')
xhr.restore()
})
it('uploads a pasted file', async function () {
const xhr = sinon.useFakeXMLHttpRequest()
const requests = []
xhr.onCreate = request => {
requests.push(request)
}
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="upload" />
</FileTreeContext>
)
// the submit button should not be present
expect(screen.queryByRole('button', { name: 'Create' })).to.be.null
const dropzone = screen.getByLabelText('File Uploader')
expect(dropzone).not.to.be.null
fireEvent.paste(dropzone, {
clipboardData: {
files: [new File(['test'], 'test.tex', { type: 'text/plain' })],
},
})
await waitFor(() => expect(requests).to.have.length(1))
const [request] = requests
expect(request.url).to.equal('/project/test-project/upload')
expect(request.method).to.equal('POST')
xhr.restore()
})
it('displays upload errors', async function () {
const xhr = sinon.useFakeXMLHttpRequest()
const requests = []
xhr.onCreate = request => {
requests.push(request)
}
render(
<FileTreeContext {...contextProps}>
<OpenWithMode mode="upload" />
</FileTreeContext>
)
// the submit button should not be present
expect(screen.queryByRole('button', { name: 'Create' })).to.be.null
const dropzone = screen.getByLabelText('File Uploader')
expect(dropzone).not.to.be.null
fireEvent.paste(dropzone, {
clipboardData: {
files: [new File(['test'], 'tes!t.tex', { type: 'text/plain' })],
},
})
await waitFor(() => expect(requests).to.have.length(1))
const [request] = requests
expect(request.url).to.equal('/project/test-project/upload')
expect(request.method).to.equal('POST')
request.respond(
422,
{ 'Content-Type': 'application/json' },
'{ "success": false, "error": "invalid_filename" }'
)
await screen.findByText(
`Upload failed: check that the file name doesn't contain special characters, trailing/leading whitespace or more than 150 characters`
)
xhr.restore()
})
})
function OpenWithMode({ mode }) {
const { newFileCreateMode, startCreatingFile } = useFileTreeActionable()
const { fileCount } = useFileTreeMutable()
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => startCreatingFile(mode), [])
if (!fileCount || !newFileCreateMode) {
return null
}
return <FileTreeModalCreateFile />
}
OpenWithMode.propTypes = {
mode: PropTypes.string.isRequired,
}
| overleaf/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-modal-create-file.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/file-tree/components/file-tree-create/file-tree-modal-create-file.test.js",
"repo_id": "overleaf",
"token_count": 6003
} | 552 |
import { screen } from '@testing-library/react'
import { renderWithEditorContext } from '../../../helpers/render-with-context'
import FileViewImage from '../../../../../frontend/js/features/file-view/components/file-view-image.js'
describe('<FileViewImage />', function () {
const file = {
id: '60097ca20454610027c442a8',
name: 'file.jpg',
linkedFileData: {
source_entity_path: '/source-entity-path',
provider: 'project_file',
},
}
it('renders an image', function () {
renderWithEditorContext(
<FileViewImage
fileName={file.name}
fileId={file.id}
onError={() => {}}
onLoad={() => {}}
/>
)
screen.getByRole('img')
})
})
| overleaf/web/test/frontend/features/file-view/components/file-view-image.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/file-view/components/file-view-image.test.js",
"repo_id": "overleaf",
"token_count": 291
} | 553 |
import sinon from 'sinon'
import { expect } from 'chai'
import { screen, render, fireEvent } from '@testing-library/react'
import PreviewToolbar from '../../../../../frontend/js/features/preview/components/preview-toolbar'
describe('<PreviewToolbar />', function () {
const onRecompile = sinon.stub()
const onRecompileFromScratch = sinon.stub()
const onRunSyntaxCheckNow = sinon.stub()
const onSetAutoCompile = sinon.stub()
const onSetDraftMode = sinon.stub()
const onSetSyntaxCheck = sinon.stub()
const onToggleLogs = sinon.stub()
const onSetSplitLayout = sinon.stub()
const onSetFullLayout = sinon.stub()
const onStopCompilation = sinon.stub()
function renderPreviewToolbar(
compilerState = {},
logState = {},
showLogs = false,
splitLayout = true
) {
render(
<PreviewToolbar
compilerState={{
autoCompileHasChanges: true,
isAutoCompileOn: true,
isClearingCache: false,
isCompiling: false,
isDraftModeOn: false,
isSyntaxCheckOn: false,
logEntries: {},
...compilerState,
}}
logsState={{ nErrors: 0, nWarnings: 0, ...logState }}
onRecompile={onRecompile}
onRecompileFromScratch={onRecompileFromScratch}
onRunSyntaxCheckNow={onRunSyntaxCheckNow}
onSetAutoCompile={onSetAutoCompile}
onSetDraftMode={onSetDraftMode}
onSetSyntaxCheck={onSetSyntaxCheck}
onToggleLogs={onToggleLogs}
outputFiles={[]}
pdfDownloadUrl="/download-pdf-url"
showLogs={showLogs}
splitLayout={splitLayout}
onSetSplitLayout={onSetSplitLayout}
onSetFullLayout={onSetFullLayout}
onStopCompilation={onStopCompilation}
/>
)
}
it('renders the toolbar', function () {
renderPreviewToolbar()
screen.getByText('Recompile')
screen.getByText('Download PDF')
screen.getByText('View logs')
})
it('all toolbar items have "toolbar-item" class and text has "toolbar-text"', function () {
renderPreviewToolbar()
const toolbar = screen.getByTestId('toolbar-preview')
for (const toolbarSection of toolbar.children) {
for (const toolbarItem of toolbarSection.children) {
expect(toolbarItem.className).to.contain('toolbar-item')
for (const parts of toolbarItem.children) {
for (const part of parts.children) {
if (part.nodeName !== 'LI' && part.textContent) {
expect(part.className).to.contain('toolbar-text')
}
}
}
}
}
})
it('renders a full-screen button with a tooltip when when in split-screen mode', function () {
renderPreviewToolbar()
const btn = screen.getByLabelText('Full screen')
fireEvent.click(btn)
expect(onSetFullLayout).to.have.been.calledOnce
fireEvent.mouseOver(btn)
screen.getByRole('tooltip', { name: 'Full screen' })
})
it('renders a split-screen button with a tooltip when when in full-screen mode', function () {
renderPreviewToolbar({}, {}, false, false)
const btn = screen.getByLabelText('Split screen')
fireEvent.click(btn)
expect(onSetSplitLayout).to.have.been.calledOnce
fireEvent.mouseOver(btn)
screen.getByRole('tooltip', { name: 'Split screen' })
})
})
| overleaf/web/test/frontend/features/preview/components/preview-toolbar.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/preview/components/preview-toolbar.test.js",
"repo_id": "overleaf",
"token_count": 1326
} | 554 |
/* eslint-disable
max-len,
*/
/* global inject, sinon */
// 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 SpellCheckManager from '../../../../../../frontend/js/ide/editor/directives/aceEditor/spell-check/SpellCheckManager'
export default describe('SpellCheckManager', function () {
beforeEach(function (done) {
this.timelord = sinon.useFakeTimers()
window.user = { id: 1 }
window.csrfToken = 'token'
this.scope = {
$watch: sinon.stub(),
spellCheck: true,
spellCheckLanguage: 'en',
}
this.highlightedWordManager = {
reset: sinon.stub(),
clearRow: sinon.stub(),
addHighlight: sinon.stub(),
}
this.adapter = {
getLineCount: sinon.stub(),
getFirstVisibleRowNum: sinon.stub(),
getLastVisibleRowNum: sinon.stub(),
getLinesByRows: sinon.stub(),
highlightedWordManager: this.highlightedWordManager,
}
return inject(($q, $http, $httpBackend, $cacheFactory) => {
this.$http = $http
this.$q = $q
this.$httpBackend = $httpBackend
this.spellCheckManager = new SpellCheckManager(
this.scope,
$cacheFactory,
$http,
$q,
this.adapter
)
return done()
})
})
afterEach(function () {
return this.timelord.restore()
})
it('adds an highlight when a misspelling is found', function () {
this.$httpBackend.when('POST', '/spelling/check').respond({
misspellings: [
{
index: 0,
suggestions: ['opposition'],
},
],
})
this.adapter.getLinesByRows.returns(['oppozition'])
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
expect(this.highlightedWordManager.addHighlight).to.have.been.called
})
describe('runSpellCheck', function () {
beforeEach(function () {
this.adapter.getLineCount.returns(10)
this.adapter.getFirstVisibleRowNum.returns(3)
this.adapter.getLastVisibleRowNum.returns(5)
this.adapter.getLinesByRows.returns([
'Lorem ipsum dolor sit amet',
'consectetur adipisicing elit',
'sed do eiusmod',
])
this.$httpBackend.when('POST', '/spelling/check').respond({
misspellings: [
{
index: 0,
suggestions: ['opposition'],
},
],
})
})
describe('when doing the first check', function () {
beforeEach(function () {
this.spellCheckManager.init()
})
it('initially flags all lines as dirty ', function () {
expect(this.spellCheckManager.changedLines)
.to.have.lengthOf(10)
.and.to.not.include(false)
})
it('checks beyond the currently visible viewport', function () {
this.timelord.tick(500)
this.$httpBackend.flush()
expect(this.adapter.getLinesByRows).to.have.been.calledWith([
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
])
})
})
describe('after the initial check', function () {
beforeEach(function () {
this.spellCheckManager.init()
this.spellCheckManager.firstCheck = false
})
it('only checks visible lines', function () {
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
expect(this.adapter.getLinesByRows).to.have.been.calledWith([3, 4, 5])
})
it('flags checked lines as non-dirty', function () {
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
expect(this.spellCheckManager.changedLines[2]).to.equal(true)
expect(this.spellCheckManager.changedLines[3]).to.equal(false)
expect(this.spellCheckManager.changedLines[4]).to.equal(false)
expect(this.spellCheckManager.changedLines[5]).to.equal(false)
expect(this.spellCheckManager.changedLines[6]).to.equal(true)
})
it('ignores updated lines', function () {
this.spellCheckManager.changedLines[4] = false
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
expect(this.adapter.getLinesByRows).to.have.been.calledWith([3, 5])
})
it('clears highlights for changed lines', function () {
this.spellCheckManager.runSpellCheck()
this.spellCheckManager.timeoutId = null
this.$httpBackend.flush()
expect(
this.highlightedWordManager.clearRow.getCall(0).args[0]
).to.equal(3)
expect(
this.highlightedWordManager.clearRow.getCall(1).args[0]
).to.equal(4)
expect(
this.highlightedWordManager.clearRow.getCall(2).args[0]
).to.equal(5)
})
})
})
describe('cache', function () {
beforeEach(function () {
this.adapter.getLineCount.returns(1)
this.adapter.getFirstVisibleRowNum.returns(1)
this.adapter.getLastVisibleRowNum.returns(1)
this.adapter.getLinesByRows.returns(['Lorem ipsum dolor'])
this.$httpBackend.when('POST', '/spelling/check').respond({
misspellings: [
{
index: 0,
suggestions: ['foobarbaz'],
},
],
})
})
it('adds already checked words to the spellchecker cache', function () {
expect(this.spellCheckManager.cache.info().size).to.equal(0)
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
expect(this.spellCheckManager.cache.info().size).to.equal(3)
})
it('adds misspeled word suggestions to the cache', function () {
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
expect(
this.spellCheckManager.cache.get(
`${this.scope.spellCheckLanguage}:Lorem`
)
).to.eql(['foobarbaz'])
})
it('adds non-misspeled words to the cache as a boolean', function () {
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
expect(
this.spellCheckManager.cache.get(
`${this.scope.spellCheckLanguage}:ipsum`
)
).to.equal(true)
})
})
describe('backend', function () {
beforeEach(function () {
this.adapter.getLineCount.returns(1)
this.adapter.getFirstVisibleRowNum.returns(1)
this.adapter.getLastVisibleRowNum.returns(1)
this.adapter.getLinesByRows.returns(['Lorem ipsum dolor'])
})
it('hits the backend with all words at startup', function () {
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
words: ['Lorem', 'ipsum', 'dolor'],
token: window.user.id,
_csrf: window.csrfToken,
})
.respond({
misspellings: [
{
index: 0,
suggestions: ['foobarbaz'],
},
],
})
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
})
it('does not hit the backend when all words are already in the cache', function () {
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
words: ['Lorem', 'ipsum', 'dolor'],
token: window.user.id,
_csrf: window.csrfToken,
})
.respond({
misspellings: [
{
index: 0,
suggestions: ['foobarbaz'],
},
],
})
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
this.spellCheckManager.init()
this.timelord.tick(500)
})
it('hits the backend only with non-cached words', function () {
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
words: ['Lorem', 'ipsum', 'dolor'],
token: window.user.id,
_csrf: window.csrfToken,
})
.respond({
misspellings: [
{
index: 0,
suggestions: ['foobarbaz'],
},
],
})
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
this.adapter.getLinesByRows.returns(['Lorem ipsum dolor sit amet'])
this.$httpBackend
.expect('POST', '/spelling/check', {
language: this.scope.spellCheckLanguage,
words: ['sit', 'amet'],
token: window.user.id,
_csrf: window.csrfToken,
})
.respond({
misspellings: [
{
index: 0,
suggestions: ['bazbarfoo'],
},
],
})
this.spellCheckManager.init()
this.timelord.tick(500)
this.$httpBackend.flush()
})
afterEach(function () {
this.$httpBackend.verifyNoOutstandingRequest()
this.$httpBackend.verifyNoOutstandingExpectation()
})
})
})
| overleaf/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js/0 | {
"file_path": "overleaf/web/test/karma/ide/editor/aceEditor/spell-check/SpellCheckManagerTests.js",
"repo_id": "overleaf",
"token_count": 4340
} | 555 |
const SandboxedModule = require('sandboxed-module')
const path = require('path')
const modulePath = path.join(
__dirname,
'../../../../app/src/Features/Analytics/AnalyticsController'
)
const sinon = require('sinon')
describe('AnalyticsController', function () {
beforeEach(function () {
this.SessionManager = { getLoggedInUserId: sinon.stub() }
this.AnalyticsManager = {
updateEditingSession: sinon.stub(),
recordEvent: sinon.stub(),
}
this.Features = {
hasFeature: sinon.stub().returns(true),
}
this.controller = SandboxedModule.require(modulePath, {
requires: {
'./AnalyticsManager': this.AnalyticsManager,
'../Authentication/SessionManager': this.SessionManager,
'../../infrastructure/Features': this.Features,
'../../infrastructure/GeoIpLookup': (this.GeoIpLookup = {
getDetails: sinon.stub(),
}),
},
})
this.res = {
send() {},
sendStatus() {},
}
})
describe('updateEditingSession', function () {
beforeEach(function () {
this.req = {
params: {
projectId: 'a project id',
},
}
this.GeoIpLookup.getDetails = sinon
.stub()
.callsArgWith(1, null, { country_code: 'XY' })
})
it('delegates to the AnalyticsManager', function (done) {
this.SessionManager.getLoggedInUserId.returns('1234')
this.controller.updateEditingSession(this.req, this.res)
this.AnalyticsManager.updateEditingSession
.calledWith('1234', 'a project id', 'XY')
.should.equal(true)
done()
})
})
describe('recordEvent', function () {
beforeEach(function () {
this.req = {
params: {
event: 'i_did_something',
},
body: 'stuff',
sessionID: 'sessionIDHere',
session: {},
}
})
it('should use the user_id', function (done) {
this.SessionManager.getLoggedInUserId.returns('1234')
this.controller.recordEvent(this.req, this.res)
this.AnalyticsManager.recordEvent
.calledWith('1234', this.req.params.event, this.req.body)
.should.equal(true)
done()
})
it('should use the session id', function (done) {
this.controller.recordEvent(this.req, this.res)
this.AnalyticsManager.recordEvent
.calledWith(this.req.sessionID, this.req.params.event, this.req.body)
.should.equal(true)
done()
})
})
})
| overleaf/web/test/unit/src/Analytics/AnalyticsControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Analytics/AnalyticsControllerTests.js",
"repo_id": "overleaf",
"token_count": 1048
} | 556 |
/* eslint-disable
chai-friendly/no-unused-expressions,
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
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath =
'../../../../app/src/Features/Collaborators/CollaboratorsInviteHandler.js'
const SandboxedModule = require('sandboxed-module')
const events = require('events')
const { ObjectId } = require('mongodb')
const Crypto = require('crypto')
describe('CollaboratorsInviteHandler', function () {
beforeEach(function () {
let ProjectInvite
this.ProjectInvite = ProjectInvite = (function () {
ProjectInvite = class ProjectInvite {
static initClass() {
this.prototype.save = sinon.stub()
this.findOne = sinon.stub()
this.find = sinon.stub()
this.deleteOne = sinon.stub()
this.countDocuments = sinon.stub()
}
constructor(options) {
if (options == null) {
options = {}
}
this._id = ObjectId()
for (const k in options) {
const v = options[k]
this[k] = v
}
this
}
}
ProjectInvite.initClass()
return ProjectInvite
})()
this.Crypto = Crypto
this.CollaboratorsInviteHandler = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': (this.settings = {}),
'../../models/ProjectInvite': { ProjectInvite: this.ProjectInvite },
'./CollaboratorsEmailHandler': (this.CollaboratorsEmailHandler = {}),
'./CollaboratorsHandler': (this.CollaboratorsHandler = {
addUserIdToProject: sinon.stub(),
}),
'../User/UserGetter': (this.UserGetter = { getUser: sinon.stub() }),
'../Project/ProjectGetter': (this.ProjectGetter = {}),
'../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {}),
crypto: this.Crypto,
},
})
this.projectId = ObjectId()
this.sendingUserId = ObjectId()
this.sendingUser = {
_id: this.sendingUserId,
name: 'Bob',
}
this.email = 'user@example.com'
this.userId = ObjectId()
this.user = {
_id: this.userId,
email: 'someone@example.com',
}
this.inviteId = ObjectId()
this.token = 'hnhteaosuhtaeosuahs'
this.privileges = 'readAndWrite'
return (this.fakeInvite = {
_id: this.inviteId,
email: this.email,
token: this.token,
sendingUserId: this.sendingUserId,
projectId: this.projectId,
privileges: this.privileges,
createdAt: new Date(),
})
})
describe('getInviteCount', function () {
beforeEach(function () {
this.ProjectInvite.countDocuments.callsArgWith(1, null, 2)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.getInviteCount(
this.projectId,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call((err, invites) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should produce the count of documents', function (done) {
return this.call((err, count) => {
expect(count).to.equal(2)
return done()
})
})
describe('when model.countDocuments produces an error', function () {
beforeEach(function () {
return this.ProjectInvite.countDocuments.callsArgWith(
1,
new Error('woops')
)
})
it('should produce an error', function (done) {
return this.call((err, count) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('getAllInvites', function () {
beforeEach(function () {
this.fakeInvites = [
{ _id: ObjectId(), one: 1 },
{ _id: ObjectId(), two: 2 },
]
this.ProjectInvite.find.callsArgWith(1, null, this.fakeInvites)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.getAllInvites(
this.projectId,
callback
)
})
})
describe('when all goes well', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call((err, invites) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should produce a list of invite objects', function (done) {
return this.call((err, invites) => {
expect(invites).to.not.be.oneOf([null, undefined])
expect(invites).to.deep.equal(this.fakeInvites)
return done()
})
})
it('should have called ProjectInvite.find', function (done) {
return this.call((err, invites) => {
this.ProjectInvite.find.callCount.should.equal(1)
this.ProjectInvite.find
.calledWith({ projectId: this.projectId })
.should.equal(true)
return done()
})
})
})
describe('when ProjectInvite.find produces an error', function () {
beforeEach(function () {
return this.ProjectInvite.find.callsArgWith(1, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call((err, invites) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('inviteToProject', function () {
beforeEach(function () {
this.ProjectInvite.prototype.save = sinon.spy(function (cb) {
return cb(null, this)
})
this.randomBytesSpy = sinon.spy(this.Crypto, 'randomBytes')
this.CollaboratorsInviteHandler._sendMessages = sinon
.stub()
.callsArgWith(3, null)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.inviteToProject(
this.projectId,
this.sendingUser,
this.email,
this.privileges,
callback
)
})
})
afterEach(function () {
return this.randomBytesSpy.restore()
})
describe('when all goes well', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should produce the invite object', function (done) {
return this.call((err, invite) => {
expect(invite).to.not.equal(null)
expect(invite).to.not.equal(undefined)
expect(invite).to.be.instanceof(Object)
expect(invite).to.have.all.keys([
'_id',
'email',
'token',
'sendingUserId',
'projectId',
'privileges',
])
return done()
})
})
it('should have generated a random token', function (done) {
return this.call((err, invite) => {
this.randomBytesSpy.callCount.should.equal(1)
return done()
})
})
it('should have called ProjectInvite.save', function (done) {
return this.call((err, invite) => {
this.ProjectInvite.prototype.save.callCount.should.equal(1)
return done()
})
})
it('should have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
1
)
this.CollaboratorsInviteHandler._sendMessages
.calledWith(this.projectId, this.sendingUser)
.should.equal(true)
return done()
})
})
})
describe('when saving model produces an error', function () {
beforeEach(function () {
return (this.ProjectInvite.prototype.save = sinon.spy(function (cb) {
return cb(new Error('woops'), this)
}))
})
it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('_sendMessages', function () {
beforeEach(function () {
this.CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon
.stub()
.callsArgWith(4, null)
this.CollaboratorsInviteHandler._trySendInviteNotification = sinon
.stub()
.callsArgWith(3, null)
return (this.call = callback => {
return this.CollaboratorsInviteHandler._sendMessages(
this.projectId,
this.sendingUser,
this.fakeInvite,
callback
)
})
})
describe('when all goes well', function () {
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should call CollaboratorsEmailHandler.notifyUserOfProjectInvite', function (done) {
return this.call(err => {
this.CollaboratorsEmailHandler.notifyUserOfProjectInvite.callCount.should.equal(
1
)
this.CollaboratorsEmailHandler.notifyUserOfProjectInvite
.calledWith(this.projectId, this.fakeInvite.email, this.fakeInvite)
.should.equal(true)
return done()
})
})
it('should call _trySendInviteNotification', function (done) {
return this.call(err => {
this.CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal(
1
)
this.CollaboratorsInviteHandler._trySendInviteNotification
.calledWith(this.projectId, this.sendingUser, this.fakeInvite)
.should.equal(true)
return done()
})
})
})
describe('when CollaboratorsEmailHandler.notifyUserOfProjectInvite produces an error', function () {
beforeEach(function () {
return (this.CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon
.stub()
.callsArgWith(4, new Error('woops')))
})
it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should not call _trySendInviteNotification', function (done) {
return this.call(err => {
this.CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal(
0
)
return done()
})
})
})
describe('when _trySendInviteNotification produces an error', function () {
beforeEach(function () {
return (this.CollaboratorsInviteHandler._trySendInviteNotification = sinon
.stub()
.callsArgWith(3, new Error('woops')))
})
it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('revokeInvite', function () {
beforeEach(function () {
this.ProjectInvite.deleteOne.callsArgWith(1, null)
this.CollaboratorsInviteHandler._tryCancelInviteNotification = sinon
.stub()
.callsArgWith(1, null)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.revokeInvite(
this.projectId,
this.inviteId,
callback
)
})
})
describe('when all goes well', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should call ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(1)
this.ProjectInvite.deleteOne
.calledWith({ projectId: this.projectId, _id: this.inviteId })
.should.equal(true)
return done()
})
})
it('should call _tryCancelInviteNotification', function (done) {
return this.call(err => {
this.CollaboratorsInviteHandler._tryCancelInviteNotification.callCount.should.equal(
1
)
this.CollaboratorsInviteHandler._tryCancelInviteNotification
.calledWith(this.inviteId)
.should.equal(true)
return done()
})
})
})
describe('when remove produces an error', function () {
beforeEach(function () {
return this.ProjectInvite.deleteOne.callsArgWith(1, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('resendInvite', function () {
beforeEach(function () {
this.ProjectInvite.findOne.callsArgWith(1, null, this.fakeInvite)
this.CollaboratorsInviteHandler._sendMessages = sinon
.stub()
.callsArgWith(3, null)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.resendInvite(
this.projectId,
this.sendingUser,
this.inviteId,
callback
)
})
})
describe('when all goes well', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should call ProjectInvite.findOne', function (done) {
return this.call((err, invite) => {
this.ProjectInvite.findOne.callCount.should.equal(1)
this.ProjectInvite.findOne
.calledWith({ _id: this.inviteId, projectId: this.projectId })
.should.equal(true)
return done()
})
})
it('should have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
1
)
this.CollaboratorsInviteHandler._sendMessages
.calledWith(this.projectId, this.sendingUser, this.fakeInvite)
.should.equal(true)
return done()
})
})
})
describe('when findOne produces an error', function () {
beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should not have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
0
)
return done()
})
})
})
describe('when findOne does not find an invite', function () {
beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, null, null)
})
it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should not have called _sendMessages', function (done) {
return this.call((err, invite) => {
this.CollaboratorsInviteHandler._sendMessages.callCount.should.equal(
0
)
return done()
})
})
})
})
describe('getInviteByToken', function () {
beforeEach(function () {
this.ProjectInvite.findOne.callsArgWith(1, null, this.fakeInvite)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.getInviteByToken(
this.projectId,
this.token,
callback
)
})
})
describe('when all goes well', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should produce the invite object', function (done) {
return this.call((err, invite) => {
expect(invite).to.deep.equal(this.fakeInvite)
return done()
})
})
it('should call ProjectInvite.findOne', function (done) {
return this.call((err, invite) => {
this.ProjectInvite.findOne.callCount.should.equal(1)
this.ProjectInvite.findOne
.calledWith({ projectId: this.projectId, token: this.token })
.should.equal(true)
return done()
})
})
})
describe('when findOne produces an error', function () {
beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
describe('when findOne does not find an invite', function () {
beforeEach(function () {
return this.ProjectInvite.findOne.callsArgWith(1, null, null)
})
it('should not produce an error', function (done) {
return this.call((err, invite) => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should not produce an invite object', function (done) {
return this.call((err, invite) => {
expect(invite).to.not.be.instanceof(Error)
expect(invite).to.be.oneOf([null, undefined])
return done()
})
})
})
})
describe('acceptInvite', function () {
beforeEach(function () {
this.fakeProject = {
_id: this.projectId,
collaberator_refs: [],
readOnly_refs: [],
}
this.CollaboratorsHandler.addUserIdToProject.callsArgWith(4, null)
this._getInviteByToken = sinon.stub(
this.CollaboratorsInviteHandler,
'getInviteByToken'
)
this._getInviteByToken.callsArgWith(2, null, this.fakeInvite)
this.CollaboratorsInviteHandler._tryCancelInviteNotification = sinon
.stub()
.callsArgWith(1, null)
this.ProjectInvite.deleteOne.callsArgWith(1, null)
return (this.call = callback => {
return this.CollaboratorsInviteHandler.acceptInvite(
this.projectId,
this.token,
this.user,
callback
)
})
})
afterEach(function () {
return this._getInviteByToken.restore()
})
describe('when all goes well', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
.calledWith(this.projectId, this.token)
.should.equal(true)
return done()
})
})
it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
.calledWith(
this.projectId,
this.sendingUserId,
this.userId,
this.fakeInvite.privileges
)
.should.equal(true)
return done()
})
})
it('should have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(1)
this.ProjectInvite.deleteOne
.calledWith({ _id: this.inviteId })
.should.equal(true)
return done()
})
})
})
describe('when the invite is for readOnly access', function () {
beforeEach(function () {
this.fakeInvite.privileges = 'readOnly'
return this._getInviteByToken.callsArgWith(2, null, this.fakeInvite)
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.not.be.instanceof(Error)
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
.calledWith(
this.projectId,
this.sendingUserId,
this.userId,
this.fakeInvite.privileges
)
.should.equal(true)
return done()
})
})
})
describe('when getInviteByToken does not find an invite', function () {
beforeEach(function () {
return this._getInviteByToken.callsArgWith(2, null, null)
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
expect(err.name).to.equal('NotFoundError')
return done()
})
})
it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
.calledWith(this.projectId, this.token)
.should.equal(true)
return done()
})
})
it('should not have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(0)
return done()
})
})
it('should not have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(0)
return done()
})
})
})
describe('when getInviteByToken produces an error', function () {
beforeEach(function () {
return this._getInviteByToken.callsArgWith(2, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
.calledWith(this.projectId, this.token)
.should.equal(true)
return done()
})
})
it('should not have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(0)
return done()
})
})
it('should not have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(0)
return done()
})
})
})
describe('when addUserIdToProject produces an error', function () {
beforeEach(function () {
return this.CollaboratorsHandler.addUserIdToProject.callsArgWith(
4,
new Error('woops')
)
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
.calledWith(this.projectId, this.token)
.should.equal(true)
return done()
})
})
it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
.calledWith(
this.projectId,
this.sendingUserId,
this.userId,
this.fakeInvite.privileges
)
.should.equal(true)
return done()
})
})
it('should not have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(0)
return done()
})
})
})
describe('when ProjectInvite.deleteOne produces an error', function () {
beforeEach(function () {
return this.ProjectInvite.deleteOne.callsArgWith(1, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should have called getInviteByToken', function (done) {
return this.call(err => {
this._getInviteByToken.callCount.should.equal(1)
this._getInviteByToken
.calledWith(this.projectId, this.token)
.should.equal(true)
return done()
})
})
it('should have called CollaboratorsHandler.addUserIdToProject', function (done) {
return this.call(err => {
this.CollaboratorsHandler.addUserIdToProject.callCount.should.equal(1)
this.CollaboratorsHandler.addUserIdToProject
.calledWith(
this.projectId,
this.sendingUserId,
this.userId,
this.fakeInvite.privileges
)
.should.equal(true)
return done()
})
})
it('should have called ProjectInvite.deleteOne', function (done) {
return this.call(err => {
this.ProjectInvite.deleteOne.callCount.should.equal(1)
return done()
})
})
})
})
describe('_tryCancelInviteNotification', function () {
beforeEach(function () {
this.inviteId = ObjectId()
this.currentUser = { _id: ObjectId() }
this.notification = { read: sinon.stub().callsArgWith(0, null) }
this.NotificationsBuilder.projectInvite = sinon
.stub()
.returns(this.notification)
return (this.call = callback => {
return this.CollaboratorsInviteHandler._tryCancelInviteNotification(
this.inviteId,
callback
)
})
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should call notification.read', function (done) {
return this.call(err => {
this.notification.read.callCount.should.equal(1)
return done()
})
})
describe('when notification.read produces an error', function () {
beforeEach(function () {
this.notification = {
read: sinon.stub().callsArgWith(0, new Error('woops')),
}
return (this.NotificationsBuilder.projectInvite = sinon
.stub()
.returns(this.notification))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('_trySendInviteNotification', function () {
beforeEach(function () {
this.invite = {
_id: ObjectId(),
token: 'some_token',
sendingUserId: ObjectId(),
projectId: this.project_id,
targetEmail: 'user@example.com',
createdAt: new Date(),
}
this.sendingUser = {
_id: ObjectId(),
first_name: 'jim',
}
this.existingUser = { _id: ObjectId() }
this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, null, this.existingUser)
this.fakeProject = {
_id: this.project_id,
name: 'some project',
}
this.ProjectGetter.getProject = sinon
.stub()
.callsArgWith(2, null, this.fakeProject)
this.notification = { create: sinon.stub().callsArgWith(0, null) }
this.NotificationsBuilder.projectInvite = sinon
.stub()
.returns(this.notification)
return (this.call = callback => {
return this.CollaboratorsInviteHandler._trySendInviteNotification(
this.project_id,
this.sendingUser,
this.invite,
callback
)
})
})
describe('when the user exists', function () {
beforeEach(function () {})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should call getUser', function (done) {
return this.call(err => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
.calledWith(this.invite.email)
.should.equal(true)
return done()
})
})
it('should call getProject', function (done) {
return this.call(err => {
this.ProjectGetter.getProject.callCount.should.equal(1)
this.ProjectGetter.getProject
.calledWith(this.project_id)
.should.equal(true)
return done()
})
})
it('should call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(1)
this.notification.create.callCount.should.equal(1)
return done()
})
})
describe('when getProject produces an error', function () {
beforeEach(function () {
return this.ProjectGetter.getProject.callsArgWith(
2,
new Error('woops')
)
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should not call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(0)
this.notification.create.callCount.should.equal(0)
return done()
})
})
})
describe('when projectInvite.create produces an error', function () {
beforeEach(function () {
return this.notification.create.callsArgWith(0, new Error('woops'))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
})
})
describe('when the user does not exist', function () {
beforeEach(function () {
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, null, null))
})
it('should not produce an error', function (done) {
return this.call(err => {
expect(err).to.be.oneOf([null, undefined])
return done()
})
})
it('should call getUser', function (done) {
return this.call(err => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
.calledWith(this.invite.email)
.should.equal(true)
return done()
})
})
it('should not call getProject', function (done) {
return this.call(err => {
this.ProjectGetter.getProject.callCount.should.equal(0)
return done()
})
})
it('should not call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(0)
this.notification.create.callCount.should.equal(0)
return done()
})
})
})
describe('when the getUser produces an error', function () {
beforeEach(function () {
return (this.UserGetter.getUserByAnyEmail = sinon
.stub()
.callsArgWith(2, new Error('woops')))
})
it('should produce an error', function (done) {
return this.call(err => {
expect(err).to.be.instanceof(Error)
return done()
})
})
it('should call getUser', function (done) {
return this.call(err => {
this.UserGetter.getUserByAnyEmail.callCount.should.equal(1)
this.UserGetter.getUserByAnyEmail
.calledWith(this.invite.email)
.should.equal(true)
return done()
})
})
it('should not call getProject', function (done) {
return this.call(err => {
this.ProjectGetter.getProject.callCount.should.equal(0)
return done()
})
})
it('should not call NotificationsBuilder.projectInvite.create', function (done) {
return this.call(err => {
this.NotificationsBuilder.projectInvite.callCount.should.equal(0)
this.notification.create.callCount.should.equal(0)
return done()
})
})
})
})
})
| overleaf/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Collaborators/CollaboratorsInviteHandlerTests.js",
"repo_id": "overleaf",
"token_count": 15852
} | 557 |
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath =
'../../../../app/src/Features/Downloads/ProjectDownloadsController.js'
const SandboxedModule = require('sandboxed-module')
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
describe('ProjectDownloadsController', function () {
beforeEach(function () {
this.project_id = 'project-id-123'
this.req = new MockRequest()
this.res = new MockResponse()
this.next = sinon.stub()
this.DocumentUpdaterHandler = sinon.stub()
return (this.ProjectDownloadsController = SandboxedModule.require(
modulePath,
{
requires: {
'./ProjectZipStreamManager': (this.ProjectZipStreamManager = {}),
'../Project/ProjectGetter': (this.ProjectGetter = {}),
'@overleaf/metrics': (this.metrics = {}),
'../DocumentUpdater/DocumentUpdaterHandler': this
.DocumentUpdaterHandler,
},
}
))
})
describe('downloadProject', function () {
beforeEach(function () {
this.stream = { pipe: sinon.stub() }
this.ProjectZipStreamManager.createZipStreamForProject = sinon
.stub()
.callsArgWith(1, null, this.stream)
this.req.params = { Project_id: this.project_id }
this.res.contentType = sinon.stub()
this.res.header = sinon.stub()
this.project_name = 'project name with accênts'
this.ProjectGetter.getProject = sinon
.stub()
.callsArgWith(2, null, { name: this.project_name })
this.DocumentUpdaterHandler.flushProjectToMongo = sinon
.stub()
.callsArgWith(1)
this.metrics.inc = sinon.stub()
return this.ProjectDownloadsController.downloadProject(
this.req,
this.res,
this.next
)
})
it('should create a zip from the project', function () {
return this.ProjectZipStreamManager.createZipStreamForProject
.calledWith(this.project_id)
.should.equal(true)
})
it('should stream the zip to the request', function () {
return this.stream.pipe.calledWith(this.res).should.equal(true)
})
it('should set the correct content type on the request', function () {
return this.res.contentType
.calledWith('application/zip')
.should.equal(true)
})
it('should flush the project to mongo', function () {
return this.DocumentUpdaterHandler.flushProjectToMongo
.calledWith(this.project_id)
.should.equal(true)
})
it("should look up the project's name", function () {
return this.ProjectGetter.getProject
.calledWith(this.project_id, { name: true })
.should.equal(true)
})
it('should name the downloaded file after the project', function () {
return this.res.setContentDisposition
.calledWith('attachment', { filename: `${this.project_name}.zip` })
.should.equal(true)
})
it('should record the action via Metrics', function () {
return this.metrics.inc.calledWith('zip-downloads').should.equal(true)
})
})
describe('downloadMultipleProjects', function () {
beforeEach(function () {
this.stream = { pipe: sinon.stub() }
this.ProjectZipStreamManager.createZipStreamForMultipleProjects = sinon
.stub()
.callsArgWith(1, null, this.stream)
this.project_ids = ['project-1', 'project-2']
this.req.query = { project_ids: this.project_ids.join(',') }
this.res.contentType = sinon.stub()
this.res.header = sinon.stub()
this.DocumentUpdaterHandler.flushMultipleProjectsToMongo = sinon
.stub()
.callsArgWith(1)
this.metrics.inc = sinon.stub()
return this.ProjectDownloadsController.downloadMultipleProjects(
this.req,
this.res,
this.next
)
})
it('should create a zip from the project', function () {
return this.ProjectZipStreamManager.createZipStreamForMultipleProjects
.calledWith(this.project_ids)
.should.equal(true)
})
it('should stream the zip to the request', function () {
return this.stream.pipe.calledWith(this.res).should.equal(true)
})
it('should set the correct content type on the request', function () {
return this.res.contentType
.calledWith('application/zip')
.should.equal(true)
})
it('should flush the projects to mongo', function () {
return this.DocumentUpdaterHandler.flushMultipleProjectsToMongo
.calledWith(this.project_ids)
.should.equal(true)
})
it('should name the downloaded file after the project', function () {
return this.res.setContentDisposition
.calledWith('attachment', {
filename: 'Overleaf Projects (2 items).zip',
})
.should.equal(true)
})
it('should record the action via Metrics', function () {
return this.metrics.inc
.calledWith('zip-downloads-multiple')
.should.equal(true)
})
})
})
| overleaf/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Downloads/ProjectDownloadsControllerTests.js",
"repo_id": "overleaf",
"token_count": 2111
} | 558 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.