text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
--- title: AttachObjectToObject description: Objeyi objeye bağlar. tags: [] --- ## Açıklama Bu fonksiyon, objeleri diğer objelere bağlar. | Parametre | Açıklama | | ------------- | ------------------------------------------------------------------------------- | | objectid | Bağlanacak obje ID'si. | | attachtoid | Bağlanılacak (ana obje) obje ID'si. | | Float:OffsetX | X yönündeki ana obje ile obje arasındaki mesafe. | | Float:OffsetY | Y yönündeki ana obje ile obje arasındaki mesafe. | | Float:OffsetZ | Z yönündeki ana obje ile obje arasındaki yüksekliği. | | Float:RotX | Obje ve ana obje arasındaki X rotasyonu. | | Float:RotY | Obje ve ana obje arasındaki Y rotasyonu. | | Float:RotZ | Obje ve ana obje arasındaki Z rotasyonu. | | SyncRotation | Eğer sıfırsa, objenin rotasyonu ana objenin rotasyonuyla birlikte değişmez. | ## Çalışınca Vereceği Sonuçlar 1: Fonksiyon başarıyla çalıştı. 0: Fonksiyon çalışmadı. Bu, ilk (bağlanacak - objectid) objenin mevcut olmadığı anlamına gelir. Bağlanılacak ana objenin (bağlanılacak - attachtoid) oluşturulup oluşturulmadığının herhangi bir kontrolü yoktur. ## Örnekler ```c new gObjectId = CreateObject(...); new gAttachToId = CreateObject(...); AttachObjectToObject(gObjectId, gAttachToId, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1); ``` ## Notlar :::tip Fonksiyon kullanılmadan önce iki objede oluşturulmalıdır. Bu fonksiyon oyuncu için özel oluşturulmuş objelerde çalışmaz. ::: ## Bağlantılı Fonksiyonlar - [AttachObjectToPlayer](AttachObjectToPlayer): Oyuncuya obje bağlama. - [AttachObjectToVehicle](AttachObjectToVehicle): Araca obje bağlama. - [AttachPlayerObjectToPlayer](AttachPlayerObjectToPlayer): Oyuncuya oyuncu objesi bağlama. - [CreateObject](CreateObject): Obje oluşturma. - [DestroyObject](DestroyObject): Obje silme. - [IsValidObject](IsValidObject): Objenin olup olmadığını kontrol etme. - [MoveObject](MoveObject): Objeyi taşıma. - [StopObject](StopObject): Objenin haraket etmesini durdurma. - [SetObjectPos](SetObjectPos): Objenin pozisyonunu düzenleme. - [SetObjectRot](SetObjectRot): Objenin rotasyonunu düzenleme. - [GetObjectPos](GetObjectPos): Objenin pozisyonunu kontrol etme. - [GetObjectRot](GetObjectRot): Objenin rotasyonunu kontrol etme. - [CreatePlayerObject](CreatePlayerObject): Oyuncuya özel obje oluşturma. - [DestroyPlayerObject](DestroyPlayerObject): Oyuncuya özel objeyi silme. - [IsValidPlayerObject](IsValidPlayerObject): Oyuncuya özel objenin olup olmadığını kontrol etme. - [MovePlayerObject](MovePlayerObject): Oyuncuya özel objeyi taşıma. - [StopPlayerObject](StopPlayerObject): Oyuncuya özel objenin haraket etmesini durdurma. - [SetPlayerObjectPos](SetPlayerObjectPos): Oyuncuya özel objenin pozisyonunu düzenleme. - [SetPlayerObjectRot](SetPlayerObjectRot): Oyuncuya özel objenin rotasyonunu pozisyonunu düzenleme. - [GetPlayerObjectPos](GetPlayerObjectPos): Oyuncuya özel objenin pozisyonunu kontrol etme. - [GetPlayerObjectRot](GetPlayerObjectRot): Oyuncuya özel objenin rotasyonunu pozisyonunu kontrol etme.
openmultiplayer/web/docs/translations/tr/scripting/functions/AttachObjectToObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AttachObjectToObject.md", "repo_id": "openmultiplayer", "token_count": 1640 }
450
--- title: CreateExplosion description: Patlama oluşturma. tags: [] --- ## Açıklama Girilen koordinatlarda patlama oluşturma. | Parametre | Açıklama | | ------------ | --------------------------------------- | | Float:X | Patlamanın oluşturulacağı X koordinatı. | | Float:Y | Patlamanın oluşturulacağı Y koordinatı. | | Float:Z | Patlamanın oluşturulacağı Z koordinatı. | | type | Oluşturulacak patlamanın türü. | | Float:radius | Patlamanın yarıçapı. | ## Çalışınca Vereceği Sonuçlar Fonksiyon patlamanın türü veya yarıçapı geçersiz olsa bile her zaman 1 döndürür. ## Örnekler ```c public OnPlayerEnterCheckpoint(playerid) { // Oyuncunun koordinat değerlerini çekiyoruz. new Float:x, Float:y, Float:z; GetPlayerPos(playerid, x, y, z); // Oyuncunun bulunduğu koordinatlarda patlama oluşturuyoruz. CreateExplosion(x, y, z, 12, 10.0); return 1; } ``` ## Notlar :::tip Bir oyuncu maksimum aynı anda 10 tane patlama görüntüleyebilir. ::: ## Bağlantılı Fonksiyonlar - [CreateExplosionForPlayer](CreateExplosionForPlayer): Tek bir oyuncunun görebildiği patlama oluşturma.
openmultiplayer/web/docs/translations/tr/scripting/functions/CreateExplosion.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/CreateExplosion.md", "repo_id": "openmultiplayer", "token_count": 590 }
451
--- title: "Kontrol Yapıları" description: Pawn dilinde kontrol yapılarının genel bir bakışı --- ## Koşullu İfadeler ### if Bir "if" ifadesi, bir şeyin doğru olup olmadığını kontrol eder ve doğruysa belirli bir işlem yapar. ```c new a = 5; if (a == 5) { print("a 5'tir"); } ``` "if" ifadesinden sonraki parantez içindeki kod koşul olarak adlandırılır ve test edilebilecek birçok farklı şey vardır (operatörlere bakınız). Yukarıdaki örnekte, hem "a" hem de 5 sembolleridir, fonksiyonlar da sembol olabilir: ```c if (SomeFunction() == 5) { print("SomeFunction() 5'tir"); } ``` Bu, SomeFunction'ın dönüş değerini (aşağıya bakınız) 5 ile karşılaştırır. Birden fazla şeyi kontrol etmek için kontrolleri birleştirebilirsiniz: ```c new a = 5, b = 3; if (a == 5 && b != 3) { print("Yazdırılmayacak"); } ``` Bu örnek, a'nın 5'e eşit olduğunu VE b'nin 3'e eşit olmadığını kontrol eder, ancak b 3 olduğundan kontrol başarısız olur. ```c new a = 5, b = 3; if (a == 5 || b != 3) { print("Yazdırılacak"); } ``` Bu örnek, a'nın 5'e eşit olup olmadığını VEYA b'nin 3'e eşit olmadığını kontrol eder, b 3 olduğundan o kısım başarısız olur\* ancak a 5 olduğu için bu kısım doğrudur, || (veya) kullanıyoruz, bu nedenle sadece bir kısım doğru olmalıdır (her ikisi de doğruysa ifadesi hala doğrudur, bu, "veya"nın dilbilgisel anlamından biraz farklıdır, yani sadece bir tanesi doğru olmalıdır). Ayrıca, karşılaştırmaları iki farklı karşılaştırmanın açıkça yapılmasına gerek olmadan birbirine zincirleme yapmak mümkündür. ```c new idx = 3; if (0 < idx < 5) { print("idx 0'dan büyük ve 5'ten küçüktür!"); } ``` ### Operatörler Aşağıdakiler, karşılaştırmalarda kullanabileceğiniz semboller ve açıklamalarıdır. Bazıları zaten örneklerde kullanılmıştır. | Operatör | Anlam | Kullanım | | ------------- | ----------------------------------------------------------------- | ------------------------------------------------------------ | | == | Sol, Sağ'a eşittir | if (Sol == Sağ) | | != | Sol, Sağ'a eşit değildir | if (Sol != Sağ) | | > | Sol, Sağ'dan büyüktür | if (Sol > Sağ) | | >= | Sol, Sağ'dan büyük veya eşittir | if (Sol >= Sağ) | | < | Sol, Sağ'dan küçüktür | if (Sol < Sağ) | | <= | Sol, Sağ'dan küçük veya eşittir | if (Sol <= Sağ) | | && | ve | if (Sol && Sağ) | | &#124;&#124; | veya | if (Sol &#124;&#124; Sağ) | | ! | değil | if (!Değişken) | | | değil veya | if (!(Sol &#124;&#124; Sağ)) | | | değil ve | if (!(Sol && Sağ)) | | | özel veya (xor, eor) - sadece biri doğru, ikisi değil | if (!(Sol && Sağ) && (Sol &#124;&#124; Sağ)) | | | özel değil veya (nxor, neor) - ikisi de doğru veya ikisi de değil | if ((Sol && Sağ) &#124;&#124; !(Sol &#124;&#124; Sağ)) | ### Parantezler If ifadelerinin diğer ana bileşeni parantezlerdir, bunlar işlerin hangi sırayla yapıldığını kontrol eder: ```c new a = 3, b = 3, c = 1; if (a == 5 && b == 3 || c == 1) { print("Bunu çağıracak mı?"); } ``` Yukarıdaki ifadeye iki farklı şekilde bakabiliriz: ```c if ((a == 5 && b == 3) || c == 1) ``` Ve: ```c if (a == 5 && (b == 3 || c == 1)) ``` İlk sürüm, a'nın 5 ve b'nin 3 olduğunu kontrol eder, bu yanlışsa (yani bunlardan biri veya ikisi de kendi değerlerine sahip değilse), c'nin 1 olup olmadığını kontrol eder. (a == 5 && b == 3) yanlıştır, yani bunu FALSE ile değiştiririz: ```c if (FALSE || c == 1) ``` FALSE'nin doğru olamayacağını biliyoruz (tanım gereği doğru değildir), ancak c 1 olduğundan bu kısım doğrudur ve, || (veya) kullanıyoruz çünkü bu kısım doğru olmalıdır. İkinci sürüm, a'nın 5 olduğunu kontrol eder, 5 ise b'nin 3 veya c'nin 1 olup olmadığını kontrol eder. Oyun a == 5 kısmını önce yapacak olsa da netlik açısından tersini yapacağız. (b == 3 || c == 1) doğrudur, her iki taraf da doğrudur, ancak sadece birinin doğru olması yeterlidir, bu nedenle if ifadesine girerken: ```c if (a == 5 && TRUE) ``` (a == 5) yanlıştır, çünkü a 3'tür, bu yüzden şuna sahibiz: ```c if (FALSE && TRUE) ``` Açıkçası FALSE yanlıştır, bu nedenle kontrol başarısız olur. Bu küçük örnek, parantezlerin bir kontrolün sonucunu nasıl değiştirebileceğini gösterir; parantez olmaksızın derleyici her iki sürümden ilkinde olacaksa da bunun her zaman garantisi olmadığından her zaman parantez kullanmalısınız, sadece başkalarına neyin olduğunu açıklamak için bile olsa. - (b != 3) örneğindeki OR örneği aslında başarısız olmaz, kodu kısa devreleme adlı bir şeyi kullanarak sıralar, çünkü ilk kısım zaten doğru olduğundan ikinci kısmı kontrol etmenin bir anlamı yoktur. ### else else, temel olarak bir if kontrolünün başarısız olduğunda bir şey yapar: ```c new a = 5; if (a == 3) // Yanlış { print("Çağrılmayacak"); } else { print("Kontrol başarısız olduğu için çağrılacak"); } ``` ### else if else if, ilk if kontrolünün başarısız olduğunda başka bir şeyi kontrol etmek için kullanılır: ```c new a = 5; if (a == 1) { print("a 1 ise çağrılacak"); } else if (a == 5) { print("a 5 ise çağrılacak"); } else { print("Diğer tüm sayılar"); } ``` Bunlardan istediğiniz kadarını kullanabilirsiniz (bir grup kontrolde yalnızca bir if ve bir else olabilir): ```c new a = 4; if (a == 1) { // Yanlış } else if (a == 2) { // Yanlış } else if (a == 3) { // Yanlış } else if (a == 4) { // Doğru } else { // Yanlış } ``` else if'ler, if'lerin başladığı sırada değeri kontrol eder, bu nedenle şunu yapamazsınız: ```c new a = 5; if (a == 5) { // Çağrılacak a = 4; } else if (a == 4) { // İlk kontrol başarısız olmadığı için çağrılmayacak, hatta a şimdi 4 olsa bile } ``` Bunu çözmek için else if'i basitçe bir if yapardınız. ### ?: '?' ve ':' birlikte bir üçlü operatör olarak adlandırılır, temel olarak başka bir if ifadesinin içinde bir if ifadesi gibi davranırlar: ```c new a, b = 3; if (b == 3) { a = 5; } else { a = 7; } ``` Bu, bir değişkeni başka bir değişkene dayanarak atamak için basit bir örnektir, ancak çok daha kısa hale getirilebilir: ```c new a, b = 3; a = (b == 3) ? (5) : (7); ``` '?' öncesindeki kısım koşuldur, bu normal bir koşuldur. '?' ve ':' arasındaki kısım, koşulun doğru olması durumunda döndürülecek değerdir, diğer kısım ise koşul yanlışsa döndürülecek değerdir. Bunları else if'ler gibi yığıp kullanabilirsiniz: ```c new a, b = 3; if (b == 1) { a = 2; } else if (b == 2) { a = 3; } else if (b == 3) { a = 4; } else { a = 5; } ``` Aşağıdaki gibi yazılabilir: ```c new a, b = 3; a = (b == 1) ? (2) : ((b == 2) ? (3) : ((b == 3) ? (4) : (5))); ``` Bu aslında şunu yapmakla daha benzerdir: ```c new a, b = 3; if (b == 1) { a = 2; } else { if (b == 2) { a = 3; } else { if (b == 3) { a = 4; } else { a = 5; } } } ``` Ancak bunlar eşdeğerdir (en azından bu örnekte). ## Döngüler ### While "while" döngüleri, belirtilen koşul doğru olduğu sürece bir şeyleri gerçekleştirir. Koşul, tam olarak bir if ifadesindeki koşul formatı gibidir, sadece sürekli kontrol edilir ve her kontrolde doğruysa her kontrolde yapılan kodu gerçekleştirir: ```c new a = 9; while (a < 10) { // Döngü içindeki kod a++; } // Döngüden sonraki kod ``` Bu kod, 'a' 10'dan küçükse kontrol eder. Eğer öyleyse, süslü parantez içindeki kod (a++;) yürütülür, böylece 'a' arttırılır. Kapanan süslü paranteze ulaşıldığında, kod yürütme kontrolün tekrar kontrol etmeye atlar ve bu kez kontrol 10 olduğu için başarısız olur ve döngüden sonraki kodun üzerine atlar. 'a' 8 olarak başladıysa, kod iki kez çalıştırılacaktır, vb. ### for() Bir "for" döngüsü, temelde sıkıştırılmış bir "while" döngüsüdür. "for" ifadesi üç bölümden oluşur: başlatma, koşul ve bitirme. Bir "for" döngüsü olarak, yukarıdaki "while" örneği şu şekilde yazılabilir: ```c for (new a = 9; a < 10; a++) { // Döngü içindeki kod } // Döngüden sonraki kod ``` İşte tüm oyuncuları döngülemek için basit bir kod: ```c for(new i, a = GetMaxPlayers(); i < a; i++) { if (IsPlayerConnected(i)) { // bir şey yap } } ``` Herhangi bir koşul, basitçe içine kod yazılmadan atlanabilir: ```c new a = 9; for ( ; a < 10; ) { // Döngü içindeki kod a++; } // Döngüden sonraki kod ``` Bu örnek, bir "for" döngüsünün bir "while" döngüsüyle nasıl eşleştiğini göstermeyi biraz daha kolaylaştırır. İki "for" döngüsü arasında iki çok küçük fark vardır. İlk fark, ikinci örnekte 'a'yı "for" döngüsünün dışında tanımlar, bu da 'a'yı "for" döngüsünün dışında kullanılabilir hale getirir, ilk örnekte 'a'nın kapsamı (bir değişkenin var olduğu kod bölümü) sadece döngü içindedir. İkinci fark, ikinci örnekteki a++, aslında birinci örnekteki a++'dan biraz önce yapılır, çoğu zaman bu hiçbir fark yaratmaz, tek fark ettiği zaman 'continue' kullanıyorsanız (aşağıya bakınız), 'continue', birinci örnekteki a++'ı çağıracak, ancak ikinci örnektekini atlayacaktır. ### do-while do-while döngüsü, koşulun döngü içindeki kodun öncesinde değil, sonrasında gelmesi durumunda bir while döngüsüdür. Bu, içerideki kodun kontrol yapılmadan önce her zaman en az bir kez yürütüleceği anlamına gelir: ```c new a = 10; do { // Döngü içindeki kod a++; } while (a < 10); // Noktalı virgülü unutma // Döngüden sonraki kod ``` Eğer bu standart bir while döngüsü olsaydı, a, (a < 10) kontrolü yanlış olduğu için arttırılmazdı, ancak burada kontrol yapılmadan önce artırılır. Eğer a 9 olarak başladıysa, döngü yine de bir kez çalıştırılır, 8 - iki kez vb. ### if-goto Bu, yukarıdaki döngülerin özünde derlenen şeydir, genellikle goto kullanımı kaçınılması gereken bir yöntemdir, ancak bir döngünün tam olarak ne yaptığını görmek ilginçtir: ```c new a = 9; loop_start: if (a < 10) { // Döngü içindeki kod a++; goto loop_start; } // Döngüden sonraki kod ``` ### OBOE OBOE, Off By One Error'ın kısaltmasıdır. Bu, bir döngünün bir fazla veya iki eksik kez çalıştığı çok yaygın bir hatadır. Örneğin: ```c new a = 0, b[10]; while (a <= sizeof (b)) { b[a] = 0; } ``` Bu çok basit bir örnek, ancak insanlar bu döngünün b'nin tüm içeriğini döngüleyeceğini ve bunları 0'a ayarlayacağını düşünebilir, ancak bu döngü aslında 11 kez çalışacak ve b[10]'a erişmeye çalışacak, ki bu var olmayan bir elemandır (0'dan başlayarak b'nin 11. yuvası olacaktı), bu nedenle çeşitli sorunlara neden olabilir. Bu, bir Sınırlar Dışı Hata (OOB) olarak bilinir. Do-while döngüleri kullanırken OBOE'lere karşı özellikle dikkatli olmalısınız, çünkü HER ZAMAN en az bir kez çalışırlar. ## Switch ### switch Switch ifadesi temelde bir yapılandırılmış if/else if/else sistemidir (for'un while gibi yapılandırılmış olması gibi). Onu bir örnek ile açıklamak en kolay yoldur: ```c new a = 5; switch (a) { case 1: { // Çağrılmayacak } case 2: { // Çağrılmayacak } case 5: { // Çağrılacak } default: { // Çağrılmayacak } } ``` Bu, işlevsel olarak şuna eşittir: ```c new a = 5; if (a == 1) { // Çağrılmayacak } else if (a == 2) { // Çağrılmayacak } else if (a == 5) { // Çağrılacak } else { // Çağrılmayacak } ``` Ancak, neyin olduğunu görmek biraz daha açıktır. Burada dikkate alınması gereken önemli bir şey, if'lerin ve switch'in farklı şekillerde işlenmesidir: ```c switch (SomeFunction()) { case 1: {} case 2: {} case 3: {} } ``` Bu, SomeFunction()'ı BİR KEZ çağırır ve sonucunu 3 kez karşılaştırır. ```c if (SomeFunction() == 1) {} else if (SomeFunction() == 2) {} else if (SomeFunction() == 3) {} ``` Bu, SomeFunction()'ı üç kez çağırır, bu da çok verimsizdir. Bir switch, daha çok şu gibi bir şey yapmaya benzer: ```c new result = SomeFunction(); if (result == 1) {} else if (result == 2) {} else if (result == 3) {} ``` C dili bilenler için, PAWN switch'i biraz farklıdır, bireysel koşullar FALLEN-THROUGH DEĞİLDİR ve süslü parantezle sınırlanır, bu nedenle break ifadelerine gerek yoktur. ### case case ifadeleri (switch ifadesinin "case X:" bölümleri), bir tek sayıdan başka seçeneklere sahip olabilir. Bir değeri bir sayı listesiyle karşılaştırabilirsiniz (C'deki fall-through'ın yerine geçer) veya hatta bir değer aralığıyla karşılaştırabilirsiniz: ```c case 1, 2, 3, 4: ``` Bu durum, test edilen sembolün 1, 2, 3 veya 4 olduğunda tetiklenecektir, aşağıdaki gibi yapmakla aynıdır: ```c if (bla == 1 || bla == 2 || bla == 3 || bla == 4) ``` ancak çok daha özeldir. Sayılar listesinde ardışık olmak zorunda değildir, aslında öyleyse: ```c case 1 .. 4: ``` Bu durum, yukarıdakiyle tam olarak aynı şeyi yapar, ancak bir liste yerine bir aralığı kontrol ederek yapar, yukarıdakiyle aynıdır: ```c if (bla >= 1 && bla <= 4) ``` ```c new a = 4; switch (a) { case 1 .. 3: { } case 5, 8, 11: { } case 4: { } default: { } } ``` ### default Bu, if ifadelerinde else'e eşdeğerdir, diğer tüm case ifadeleri başarısız olursa bir şey yapar. ## Tek satırlık ifadeler ### goto goto temelde bir sıçramadır, şartsız olarak bir etikete gider (yani doğru olması gereken bir koşul yoktur). Bir örneği yukarıda if-goto döngüsünde görebilirsiniz. ```c goto my_label; // Bu bölüm atlanacaktır my_label: // Etiketler iki nokta üst üste ile biter ve kendi satırında olur // Bu bölüm normal olarak işlenir ``` Gotonun kullanımı, program akışı üzerindeki etkileri nedeniyle geniş çapta tavsiye edilmez. ### break break, bir döngüden çıkar, onu önceden sonlandırır: ```c for (new a = 0; a < 10; a++) { if (a == 5) break; } ``` Bu döngü 6 kez devam eder, ancak break'ten sonraki kod yalnızca 5 kez çalıştırılır. ### continue continue basitçe bir döngü yineleme atlar ```c for (new a = 0; a < 3; a++) { if (a == 1) continue; printf("a = %d", a); } ``` Bu, şu çıktıyı verecektir: ```c a = 0 a = 2 ``` Continue, temelde döngünün kapanan süslü parantezine atlar, yukarıda belirtildiği gibi bazı döngülerle continue kullanırken dikkatli olmanız gerekir: ```c new a = 0; while (a < 3) { if (a == 1) continue; printf("a = %d", a); a++; } ``` Bu, diğer örneğe çok benziyor, ancak bu sefer continue a++; satırını atlar, bu nedenle döngü a her zaman 1 olduğu için sonsuz bir döngüye sıkışır. ### return return, bir işlevi durdurur ve kodun, o işlevi başlatan noktaya geri dönmesini sağlar: ```c main() { print("1"); MyFunction(1); print("3"); } MyFunction(num) { if (num == 1) { return; } print("2"); } ``` Bu kod, şu çıktıyı verecektir: 1 3 Çünkü print("2"); satırı asla ulaşılmayacaktır. return'u bir değer döndürmek için de kullanabilirsiniz: ```c main() { print("1"); if (MyFunction(1) == 27) { print("3"); } } MyFunction(num) { if (num == 1) { return 27; } print("2"); return 0; } ``` Bu kod, yukarıdakiyle aynı çıktıyı verecektir, ancak işlevin sonuna başka bir return eklenmiştir. Bir işlevin sonunda bir return önerilir, ancak bu returnun değeri yoktur, aynı işlevden bir değer döndüremezsiniz, bu nedenle bir değeri açıkça döndürmemiz gerekir. Döndürdüğünüz sembol bir sayı, bir değişken veya hatta başka bir işlev olabilir (bu durumda diğer işlev çağrılır, bir değer döndürür (onu bir dönüş değeri olarak kullanırsanız BİR değer döndürmeli) ve bu değer ilk işlevden döndürülür. Dönüş değerlerini daha sonra kullanmak için de saklayabilirsiniz: ```c main() { print("1"); new ret = MyFunction(1); if (ret == 27) { print("3"); } } MyFunction(num) { if (num == 1) { return 27; } print("2"); return 0; } ```
openmultiplayer/web/docs/translations/tr/scripting/language/ControlStructures.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/language/ControlStructures.md", "repo_id": "openmultiplayer", "token_count": 9805 }
452
--- title: "Sunucuyu Kontrol Etme" description: Sunucuyu kontrol etmek için kullanışlı komutlar. --- ## Oyun Modu Değiştirme ### Özel/İndirilmiş Oyun Modu Çalıştırma - Sunucu kurduğunuz dizini açın (örneğin: /Rockstar Games/GTA San Andreas/server). - İndirilen/derlenmiş .amx dosyasını alın ve sunucuyu kurduğunuz dizindeki gamemodes klasörünün içine atın. - RCON'u kullanarak açıklandığı gibi moda geçiş yapın (2.1). - Alternatif olarak, yeni modu yukarıda açıklandığı gibi bir yapılandırmaya ekleyebilirsiniz (2.3). ### Filterscripts Kullanma Özel bir oyun modu çalıştırmakla aynıdır, fakat farklı olarak: - .amx uzantılı Filterscriptler, sunucu ana dizininde bulunan `filterscripts` adlı klasörde barındırılır. - server.cfg yapılandırma dosyasına şöyle eklenir: `filterscripts <scriptadı>` ## Sunucunuza Şifre Koyma - Sadece arkadaşlarınızın katılmasını istiyorsanız, [server.cfg](server.cfg) - sunucu yapılandırma dosyasına şunu ekleyin: ``` password herneyse ``` - Bu, sunucunuzu 'herneyse' olarak ayarlanmış bir şifre ile korumalı hale getirecektir - istediğiniz şeyi yazarak değiştirebilirsiniz. - Şifreyi oyun içinden `/rcon password halilcanoz` komutunu kullanarak değiştirebilirsiniz. - Şifreyi kaldırmak için `/rcon password 0` komutunu kullanmayı veya sunucuyu yeniden başlatmayı tercih edebilirsiniz. ## RCON Kullanma ### Giriş Yapma Girişi oyun içi `/rcon login sifre` yazarak veya [server.cfg](server.cfg) dosyasında ayarladığınız şifreyi kullanarak oyun dışından RCON modunu kullanarak yapabilirsiniz. ### Oyuncu Yasaklama ##### samp.ban samp.ban, yasaklamalar hakkında bilgileri içeren bir dosyadır, yasaklamalar hakkında aşağıdaki bilgileri içerir: - IP - Tarih - Saat - Ad (Kişinin adı veya bir neden, [BanEx](../../functions/BanEx) sayfasına bakın) - Yasaklama türü Oyuncu yasaklamak için, basitçe şu şekilde bir satır ekleyin: ``` IP_BURAYA [28/05/09 | 13:37:00] OYUNCU - YASAKLAMA NEDENİ ``` `IP_BURAYA` kısmına, yasaklamak istediğiniz IP'yi ekleyin. ##### Ban() Fonksiyonu [Ban](../scripting/functions/Ban) fonksiyonu bir oyuncuyu script üzerinden yasaklamak için kullanılabilir. [BanEx](../scripting/functions/BanEx) fonksiyonu, aşağıdaki gibi isteğe bağlı bir neden ekler: ``` 13.37.13.37 [28/05/09 | 13:37:00] Sack - OYUNICI YASAKLAMA ``` ##### RCON Yasaklama Komutu RCON yasaklama komutu, oyun içi `/rcon ban OYUNCUID` yazarak veya konsol'a "ban" yazarak kullanılır ve sunucuda belirli bir oyuncuyu yasaklamak için kullanılır. Basitçe şu şekilde kullanabilirsiniz: ``` # Oyun içi: /rcon ban OYUNCUID # Konsol: ban OYUNCUID ``` ##### banip RCON banip komutu, oyun içi `/rcon banip IP` yazarak veya konsola "banip IP" yazarak kullanılır ve belirli bir IP'yi yasaklamak için kullanılır. Aralıklı yasaklamalar için joker karakterlerini kabul eder. Basitçe şunu yazın: ``` # Oyun içi: /rcon banip IP # Konsol: banip IP ``` ### Yasaklamaları Kaldırma Birisi oyuncunun yasağını kaldırmanın iki yolu vardır. - samp.ban dosyasından kaldırmak - Konsoldan veya oyun içinden RCON `unbanip` komutunu kullanmak #### samp.ban samp.ban, sa-mp sunucu dizininde bulunabilir ve içinde şu bilgileri içeren IP'ler hakkında bilgi içerir: - IP - Tarih - Saat - Ad (Kişinin adı veya neden (bkz: [BanEx](../scripting/functions/BanEx))) - Yasak Türü (OYUNİÇİ, IP BAN vb.) Örnekler: ``` 127.8.57.32 [13/06/09 | 69:69:69] YOK - IP BAN 13.37.13.37 [28/05/09 | 13:37:00] Martin - OYUN İÇİ YASAK ``` Yasaklanan oyunucunun yasağını kaldırmak için, sadece satırı kaldırın ve ardından sunucunun samp.ban'ı tekrar okumasını sağlamak için RCON `reloadbans` komutunu kullanın. #### unbanip RCON unbanip komutu oyun içi `/rcon unbanip IP_BURAYA` yazarak veya konsol'a "unbanip IP_BURAYA" yazarak kullanılabilir. Bir IP'nin yasağını kaldırmak için, sadece `/rcon unbanip IP_BURAYA` komutunu oyun içinden veya konsoldan `unbanip IP_BURAYA` şeklinde yazın. Örnek: ``` 13.37.13.37 [28/05/09 | 13:37:00] Martin - OYUN İÇİ BAN ``` ``` # Oyun içi: /rcon unbanip 13.37.13.37 # Konsol: unbanip 13.37.13.37 ``` Yasağı kaldırmak için, sadece `unbanip` komutunu kullanın ve ardından sunucunun `samp.ban`'ı tekrar okumasını sağlamak için RCON `reloadbans` komutunu kullanın. #### reloadbans `samp.ban`, sunucudan yasaklanan IP adresleri hakkındaki bilgileri içeren bir dosyadır. Bu dosya, sunucu çalıştırıldığında okunur, bu nedenle bir IP'yi veya oyuncuyu yasaklarsanız, sunucunun `samp.ban`'ı tekrar okumasını sağlamak için RCON `reloadbans` komutunu yazmalısınız, böylece tekrar sunucuya giremezler. ### RCON Komutları Oyun içinde (`/rcon cmdlist` yazarak) RCON kullanarak kullanabileceğiniz komutlardır. Aşağıdaki komutları sadece RCON girişi yapmış yöneticiler kullanabilir: | Komut | Açıklama | | --------------------------------- | -------------------------------------------------------------------------------------------------- | | `/rcon cmdlist` | Komutları gösterir. | | `/rcon varlist` | Mevcut değişkenleri gösterir. | | `/rcon exit` | Sunucuyu kapatır. | | `/rcon echo [metin]` | Metni sunucu konsolunda gösterir (Oyun içi oyuncu konsolu değil). | | `/rcon hostname [isim]` | hostname metnini değiştirir (_örnek: /rcon hostname benim sunucum_). | | `/rcon gamemodetext [isim]` | oyun modu metnini değiştirir (_örnek: /rcon gamemodetext benim oyun modum_). | | `/rcon mapname [isim]` | harita metnini değiştirir (_örnek: /rcon mapname San Andreas_). | | `/rcon exec [dosyaadı]` | Sunucu yapılandırmalarını içeren dosyayı yürütür (_örnek: /rcon exec blah.cfg_). | | `/rcon kick [ID]` | Belirtilen ID'ye sahip oyuncuyu sunucudan atar (_örnek: /rcon kick 2_). | | `/rcon ban [ID]` | Belirtilen ID'ye sahip oyuncuyu yasaklar (_örnek: /rcon ban 2_). | | `/rcon changemode [mod]` | Bu komut, mevcut oyun modunu belirtilen oyun modu ile değiştirecek (_örnek: sftdm oynamak istiyorsanız: /rcon changemode sftdm_). | | `/rcon gmx` | [server.cfg](server.cfg) dosyasındaki bir sonraki oyun modunu yükler. | | `/rcon reloadbans` | Yasaklı IP adreslerini içeren `samp.ban` dosyasını tekrar yükler. Bu, bir IP'yi yasakladıktan sonra kullanılmalıdır. | | `/rcon reloadlog` | `server_log.txt` dosyasını tekrar yükler. Otomatik log döndürme için kullanışlıdır. Sadece Linux sunucuda `SIGUSR1` sinyali gönderilerek tetiklenebilir. | | `/rcon say` | Oyuncu konsoluna mesaj gösterir (örnek: `/rcon say merhaba` "Admin: merhaba" olarak görüntülenir). | | `/rcon players` | Sunucuda bulunan oyuncuları (adları, IP'leri ve ping'leri ile birlikte) gösterir. | | `/rcon banip [IP]` | Belirtilen IP'yi yasaklar (_örnek: /rcon banip 127.0.0.1_). | | `/rcon unbanip [IP]` | Belirtilen IP'nin yasaklamasını kaldırır (_örnek: /rcon unbanip 127.0.0.1_). | | `/rcon gravity` | Yer çekimini değiştirir (_örnek: /rcon gravity 0.008_). | | `/rcon weather [ID]` | Hava durumunu değiştirir (_örnek: /rcon weather 1_). | | `/rcon loadfs` | Belirtilem filterscript'i yükler (_örnek: /rcon loadfs adminfs_). | | `/rcon weburl [sunucu url]` | Masterlist/SA-MP istemcisinde görünen sunucu URL'sini değiştirir. | | `/rcon unloadfs` | Belirtilen filterscript'i devre dışı bırakır (_örnek: /rcon unloadfs adminfs_). | | `/rcon reloadfs` | Belirtilem filterscript'i tekrar yükler (_örnek: /rcon reloadfs adminfs_). | | `/rcon rcon_password [ŞİFRE]` | Rcon'un şifresini değiştirir. | | `/rcon password [şifre]` | Sunucu şifresini ayarlar/sıfırlar. | | `/rcon messageslimit [sayı]` | İstemcinin sunucuya saniyede gönderdiği mesaj sayısını değiştirir. (varsayılan 500) | | `/rcon ackslimit [sayı]` | Ack'ların sınırını değiştirir (varsayılan 3000) | | `/rcon messageholelimit [sayı]` | Mesaj deliklerinin sınırını değiştirir (varsayılan 3000). | | `/rcon playertimeout [limit ms]` | Bir oyuncunun hiç paket göndermediği süreyi milisaniye cinsinden değiştirir (varsayılan 1000). | | `/rcon language [dil]` | Sunucu dilini değiştirir (_örnek: /rcon language Turkish_). Sunucu tarayıcısında gösterilir. | Yukarıdaki dört sınırlama/sayı, herhangi bir SA-MP sunucusuna saldıran birkaç çakkalı önlemek için yapılmıştır, bu nedenle sadece sunucunuza göre bunları ayarlayın. Varsayılan değerler, eğer yanlış bir şeyler görürseniz, masum oyuncuların bunun nedeniyle atılmaması için değerleri mümkün olan en kısa sürede arttırın. [Daha fazla bilgi için buraya bakın](http://web-old.archive.org/web/20190426141744/https://forum.sa-mp.com/showpost.php?p=2990193&postcount=47). ### İlgili Callbackler ve Fonksiyonlar Aşağıdaki callbackler ve fonksiyonlar, bu makaleyle bir şekilde ilişkili olabilir ve bu nedenle ilginizi çekebilir. #### Callbackler - [OnRconLoginAttempt](../scripting/callbacks/OnRconLoginAttempt): RCON'a giriş denemesi yapıldığında çağrılır. #### Fonksiyonlar - [IsPlayerAdmin](../scripting/functions/IsPlayerAdmin): Bir oyuncunun RCON'a giriş yapılıp yapılmadığını kontrol eder. - [SendRconCommand](../scripting/functions/SendRconCommand): Bir komutu script üzerinden RCON aracılığıyla gönderir.
openmultiplayer/web/docs/translations/tr/server/ControllingServer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/server/ControllingServer.md", "repo_id": "openmultiplayer", "token_count": 5847 }
453
--- title: OnDialogResponse description: 当玩家通过单击按钮、按Enter/Esc键或双击列表项(如果使用列表样式对话框)来响应使用ShowPlayerDialog显示的对话框时,将调用此回调。 tags: [] --- ## 说明 当玩家通过单击按钮、按 Enter/Esc 键或双击列表项(如果使用列表样式对话框)来响应使用 ShowPlayerDialog 显示的对话框时,将调用此回调。 | 参数名 | 说明 | | ----------- | ------------------------------------------------------------------------ | | playerid | 响应对话框的玩家 ID。 | | dialogid | 玩家响应的对话框的 ID,在 ShowPlayerDialog 中分配。 | | response | 左按钮为 1,右按钮为 0(如果只显示一个按钮,则始终为 1) | | listitem | 玩家选择的列表项的 ID(从 0 开始)(仅当使用列表样式对话框时,否则将为-1)。 | | inputtext[] | 玩家在输入框中输入的文本或选定的列表项文本。 | ## 返回值 它在过滤脚本中总是先被调用,因此在那里返回 1 会阻止其他过滤脚本看到它。 ## 案例 ```c // 定义对话ID,以便我们可以处理响应 #define DIALOG_RULES 1 // 在某些命令中 ShowPlayerDialog(playerid, DIALOG_RULES, DIALOG_STYLE_MSGBOX, "服务器规则", "- 不能作弊\n- 禁止发送垃圾邮件\n- 尊敬的管理员\n\n你同意这些规则吗?", "是", "否"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_RULES) { if (response) //如果他们点击‘是’或按Enter键 { SendClientMessage(playerid, COLOR_GREEN, "感谢你同意服务器规则!"); } else //按Esc或点击Cancel { Kick(playerid); } return 1; // 我们处理了一个对话框,因此返回 1。就像OnPlayerCommandText一样。 } return 0; // 此处必须返回0!就像OnPlayerCommandText一样。 } #define DIALOG_LOGIN 2 // 在某些命令中 ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "登录", "请输入你的密码:", "登录", "取消"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_LOGIN) { if (!response) //如果他们点击‘Cancel’或按Esc { Kick(playerid); } else //按Enter或点击‘Login’按钮 { if (CheckPassword(playerid, inputtext)) { SendClientMessage(playerid, COLOR_RED, "你现在已登录!"); } else { SendClientMessage(playerid, COLOR_RED, "登录失败。"); // 重新显示登录对话框 ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "登录", "请输入你的密码:", "登录", "取消"); } } return 1; // 我们处理了一个对话框,因此返回 1。就像OnPlayerCommandText一样。 } return 0; // 此处必须返回0!就像OnPlayerCommandText一样。 } #define DIALOG_WEAPONS 3 // 在某些命令中 ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "武器", "沙漠之鹰\nAK-47\n战斗猎枪", "选择", "关闭"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_WEAPONS) { if (response) // 如果他们点击了‘选择’或双击了一个武器 { // 把武器给他们 switch(listitem) { case 0: GivePlayerWeapon(playerid, WEAPON_DEAGLE, 14); // 给他们一把沙漠之鹰 case 1: GivePlayerWeapon(playerid, WEAPON_AK47, 120); // 给他们一把AK-47 case 2: GivePlayerWeapon(playerid, WEAPON_SHOTGSPA, 28); // 给他们一把战斗猎枪 } } return 1; // 我们处理了一个对话框,因此返回 1。就像OnPlayerCommandText一样。 } return 0; // 此处必须返回0!就像OnPlayerCommandText一样。 } #define DIALOG_WEAPONS 3 // 在某些命令中 ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "武器列表", "名称\t子弹\t价格\n\ M4\t120\t500\n\ MP5\t90\t350\n\ AK-47\t120\t400", "选择", "关闭"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_WEAPONS) { if (response) //如果他们点击了‘选择’或双击了一个武器 { // 把武器给他们 switch(listitem) { case 0: GivePlayerWeapon(playerid, WEAPON_M4, 120); // 给他们一把M4 case 1: GivePlayerWeapon(playerid, WEAPON_MP5, 90); // 给他们一把MP5 case 2: GivePlayerWeapon(playerid, WEAPON_AK47, 120); // 给他们一把AK-47 } } return 1; // 我们处理了一个对话框,因此返回 1。就像OnPlayerCommandText一样。 } return 0; // 你必须在此处返回0!就像OnPlayerCommandText一样。 } ``` ## 要点 :::tip 根据对话框的样式,参数可以包含不同的值 ([点击查看更多示例](../resources/dialogstyles)). ::: :::tip 如果你有多个对话框,则最好使用不同的对话框 ID。 ::: :::warning 当游戏模式重启时,玩家的对话框不会隐藏。 如果玩家在重启后响应此对话框,则会导致服务器打印“警告:玩家对话框响应 玩家 ID:0 对话框 ID 与上次发送的对话框 ID 不匹配”。 ::: ## 相关函数 - [ShowPlayerDialog](../functions/ShowPlayerDialog): 向玩家展示一个对话框。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnDialogResponse.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnDialogResponse.md", "repo_id": "openmultiplayer", "token_count": 3544 }
454
--- title: OnPlayerClickPlayer description: 当一个玩家在记分板上双击另一个玩家时调用。 tags: ["player"] --- ## 描述 当一个玩家在记分板上双击另一个玩家时调用。 | 参数名 | 描述 | | --------------- | ------------------------------- | | playerid | 在记分板上点击玩家的玩家的 ID。 | | clickedplayerid | 被点击的玩家的 ID。 | | source | 玩家点击的来源。 | ## 返回值 1 - 将阻止其他过滤脚本接收到这个回调。 0 - 表示这个回调函数将被传递给下一个过滤脚本。 它在游戏模式中总是先被调用。 ## 案例 ```c public OnPlayerClickPlayer(playerid, clickedplayerid, CLICK_SOURCE:source) { new message[32]; format(message, sizeof(message), "你点击了玩家 %d", clickedplayerid); SendClientMessage(playerid, 0xFFFFFFFF, message); return 1; } ``` ## 要点 :::tip 目前只有一个“来源”(0 - CLICK_SOURCE_SCOREBOARD(点击\_源\_计分板))。这一论点的存在表明,未来可能会有更多的来源得到支持。 ::: ## 相关回调 - [OnPlayerClickTextDraw](OnPlayerClickTextDraw): 当玩家点击文本绘制时调用。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerClickPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerClickPlayer.md", "repo_id": "openmultiplayer", "token_count": 732 }
455
--- title: OnPlayerGiveDamageActor description: 当一个玩家对一个演员造成伤害时,这个回调会被调用。 tags: ["player"] --- <VersionWarnCN name='回调' version='SA-MP 0.3.7' /> ## 描述 当一个玩家对一个演员造成伤害时,这个回调会被调用。 | 参数名 | 描述 | | --------------- | ------------------------------------------ | | playerid | 造成伤害的玩家 ID | | damaged_actorid | 受到伤害的演员 ID | | Float:amount | 演员 ID 所损失的生命值/装甲伤害 | | WEAPON:weaponid | 造成伤害的原因 | | bodypart | 被击中的[身体部位](../resources/bodyparts) | ## 返回值 1 - 回调不会在其他过滤脚本中被调用。 0 -允许在其他过滤脚本中调用此回调。 它在过滤脚本中总是先被调用,所以在那里返回 1 会阻止其他过滤脚本看到它。 ## 案例 ```c public OnPlayerGiveDamageActor(playerid, damaged_actorid, Float:amount, WEAPON:weaponid, bodypart) { new string[128], attacker[MAX_PLAYER_NAME]; new weaponname[24]; GetPlayerName(playerid, attacker, sizeof (attacker)); GetWeaponName(weaponid, weaponname, sizeof (weaponname)); format(string, sizeof(string), "%s 已经造成 %.0f 点伤害给演员 id %d, 武器: %s", attacker, amount, damaged_actorid, weaponname); SendClientMessageToAll(0xFFFFFFFF, string); return 1; } ``` ## 要点 :::tip 如果演员被设置为不可攻击(这是默认情况),这个函数不会被调用。见 SetActorInvulnerable。 ::: ## 相关函数 - [CreateActor](../functions/CreateActor): 创建一个演员(静态 NPC)。 - [SetActorInvulnerable](../functions/SetActorInvulnerable): 让演员无敌。 - [SetActorHealth](../functions/SetActorHealth): 设置演员的健康值。 - [GetActorHealth](../functions/GetActorHealth): 获取演员的健康值。 - [IsActorInvulnerable](../functions/IsActorInvulnerable): 检查演员是否无懈可击。 - [IsValidActor](../functions/IsValidActor): 检查演员 ID 是否有效。 ## Related Callbacks - [OnActorStreamOut](OnActorStreamOut): 当一个演员被一个玩家流出时调用。 - [OnPlayerStreamIn](OnPlayerStreamIn): 当一个玩家被另一个玩家流入时调用。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerGiveDamageActor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerGiveDamageActor.md", "repo_id": "openmultiplayer", "token_count": 1292 }
456
--- title: OnPlayerTakeDamage description: 当玩家受到伤害时,会调用该回调。 tags: ["player"] --- ## 描述 当玩家受到伤害时,会调用该回调。 | 参数名 | 描述 | | -------- | --------------------------------------------------------------------------------------------------- | | playerid | 受伤的玩家的 ID。 | | issuerid | 造成伤害的玩家的 ID。 如果是自己造成的则为 INVALID_PLAYER_ID。 | | Float:amount | 玩家受到的伤害(生命值和护甲的总和)。 | | WEAPON:weaponid | 造成伤害的武器/原因的 ID | | bodypart | 被击中的[身体部位](../resources/bodyparts)。| ## 返回值 1 - 回调不会在其他过滤脚本中被调用。 0 -允许在其他过滤脚本中调用此回调。 它在过滤脚本中总是先被调用,所以在那里返回 1 会阻止其他过滤脚本看到它。 ## 案例 ```c public OnPlayerTakeDamage(playerid, issuerid, Float:amount, WEAPON:weaponid, bodypart) { if (issuerid != INVALID_PLAYER_ID) // 如果不是自己造成的 { new infoString[128], weaponName[24], victimName[MAX_PLAYER_NAME], attackerName[MAX_PLAYER_NAME]; GetPlayerName(playerid, victimName, sizeof (victimName)); GetPlayerName(issuerid, attackerName, sizeof (attackerName)); GetWeaponName(weaponid, weaponName, sizeof (weaponName)); format(infoString, sizeof(infoString), "%s 已造成 %.0f 点伤害给 %s, 武器: %s, 身体部位: %d", attackerName, amount, victimName, weaponName, bodypart); SendClientMessageToAll(-1, infoString); } return 1; } public OnPlayerTakeDamage(playerid, issuerid, Float:amount, WEAPON:weaponid, bodypart) { if (issuerid != INVALID_PLAYER_ID && weaponid == 34 && bodypart == 9) { // 用狙击步枪一枪爆头 SetPlayerHealth(playerid, 0.0); } return 1; } ``` ## 要点 :::tip 武器 ID 会从任何火源(如燃烧弹,18) 返回 37(火焰喷射器);会从任何制造爆炸的武器(如 RPG,手榴弹) 返回 51 。 只有玩家 ID 能调用该回调。 数量总是武器所能造成的最大伤害,即使当剩余生命值低于最大伤害时也是如此。 所以当玩家拥有 100.0 的生命值并被伤害值为 46.2 的沙漠之鹰击中时,他需要 3 次射击才能杀死该玩家。 所有 3 次射击都将显示 46.2,即使当最后一次射击命中时,玩家只剩下 7.6 生命值。 ::: :::warning GetPlayerHealth 和 GetPlayerArmour 将在此回调之前返回玩家的旧数值。 在将 issuerid 用作数组索引之前,一定要检查它是否有效。 :::
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerTakeDamage.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerTakeDamage.md", "repo_id": "openmultiplayer", "token_count": 1816 }
457
--- title: OnVehicleStreamIn description: 当车辆流入玩家的客户端时调用。 tags: ["vehicle"] --- ## 描述 当车辆流入玩家的客户端时调用。 | 参数名 | 描述 | | ----------- | ------------------------------ | | vehicleid | 为玩家流入的车辆 ID。 | | forplayerid | 这辆车是为哪个玩家 ID 流入的。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnVehicleStreamIn(vehicleid, forplayerid) { new string[32]; format(string, sizeof(string), "你现在可以看到车辆 %d.", vehicleid); SendClientMessage(forplayerid, 0xFFFFFFFF, string); return 1; } ``` ## 要点 <TipNPCCallbacksCN />
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleStreamIn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleStreamIn.md", "repo_id": "openmultiplayer", "token_count": 400 }
458
--- title: ApplyAnimation description: 将动画应用于玩家。 tags: [] --- ## 描述 将动画应用于玩家。 | 参数名 | 说明 | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | playerid | 要应用动画的玩家的 ID。 | | | animlib[] | 要应用动画的动画库的名称。 | | animname[] | 在指定的库中,要应用的动画的名称。 | | fDelta | 播放动画的速度(默认使用 4.1)。 | | loop | 如果设置为 1,动画将循环播放。如果设置为 0,动画将播放一次。 | | lockx | 如果设置为 0,一旦动画完成,玩家就会返回到他们原来的 X 坐标(对于会移动玩家位置的动画,如行走)。1 将不会返回到他们的旧位置。 | | locky | 与上述相同,但对 Y 轴而言。应保持与前面的参数相同。 | | freeze | 设置为 1 会在动画结束时定住玩家。0 则不会。 | | time | 计时器,单位是毫秒。对于永远要循环的动画,应传入 0。 | | forcesync | 设置为 1 可以使服务器与流半径内的所有其他玩家同步动画(可选)。2 的作用与 1 相同,但只对流入的玩家应用动画,而不是对实际被动画的应用的玩家应用(当玩家被流入时,对 npc 动画和持久性动画很有用)。 | ## 返回值 这个函数总是返回 1,即使指定的玩家不存在,或者任何参数无效(例如无效的库)。 ## 案例 ```c ApplyAnimation(playerid, "PED", "WALK_DRUNK", 4.1, 1, 1, 1, 1, 1, 1); ``` ## 要点 :::tip 'forcesync' 为可选参数,默认为 0,在大多数情况下不需要传入,因为其他玩家会自动同步动画。'forcesync' 参数可以强制所有可以看到'playerid'的玩家播放动画,而不管该玩家是否正在执行该动画。这在其他玩家不能自动同步动画的情况下很有用。例如,他们可能暂停了游戏而导致没接收到该动画。 ::: :::warning 无效的动画库将使玩家的游戏崩溃。 ::: ## 相关函数 - [ClearAnimations](ClearAnimations): 清除玩家正在执行的任何动画。 - [SetPlayerSpecialAction](SetPlayerSpecialAction): 设置玩家的特殊动作。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/ApplyAnimation.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/ApplyAnimation.md", "repo_id": "openmultiplayer", "token_count": 2883 }
459
--- title: GetPlayerCameraMode description: 返回所请求玩家的当前GTA视角模式。 tags: ["player", "camera"] --- ## 描述 返回所请求玩家的当前 GTA [视角模式](../resources/cameramodes)。视角模式在判断玩家是否在瞄准、作为乘客在车内射击等方面非常有用。 | 参数名 | 说明 | | -------- | ----------------------- | | playerid | 要检索视角模式的玩家 ID | ## 返回值 整数形式的视角模式(如果玩家没有连接则为-1) ## 案例 ```c /* 当玩家在聊天框中输入“cameramode”时,他们会看到下面的消息。 */ public OnPlayerText(playerid, text[]) { if (strcmp(text, "cameramode", true) == 0) { new szMessage[22]; format(szMessage, sizeof(szMessage), "你的视角模式是: %d", GetPlayerCameraMode(playerid)); SendClientMessage(playerid, 0xA9C4E4FF, szMessage); } return 0; } ``` ## 相关函数 - [GetPlayerCameraPos](GetPlayerCameraPos): 找出玩家的视角在哪里。 - [GetPlayerCameraFrontVector](GetPlayerCameraFrontVector): 获取玩家视角的前向量。 - [SetPlayerCameraPos](SetPlayerCameraPos): 设置玩家的视角位置。 - [SetPlayerCameraLookAt](SetPlayerCameraLookAt): 设置玩家的视角所看的方向。 - [SetCameraBehindPlayer](SetCameraBehindPlayer): 重置视角到玩家后面。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerCameraMode.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerCameraMode.md", "repo_id": "openmultiplayer", "token_count": 752 }
460
--- title: atan description: 以度为单位求正切值的倒数。 tags: ["math"] --- <LowercaseNoteCN /> ## 描述 以度为单位求正切值的倒数。在三角函数中,反正切是正切的逆运算。请注意,由于符号模糊,该函数无法仅通过正切值确定角度落在哪个象限。请参见[atan2](atan2)以了解采用分数参数的替代方案。 | 参数名 | 说明 | | ----------- | -------------------- | | Float:value | 用于计算反正切的值。 | ## 返回值 以度为单位的角度,在区间[-90.0,+90.0]内。 ## 案例 ```c // 1.000000的反正切值是45.000000度。 public OnGameModeInit() { new Float:param, Float:result; param = 1.0; result = atan(param); printf("%f 的反正切是 %f 度。", param, result); return 1; } ``` ## 相关函数 - [floatsin](floatsin): 从特定角度求正弦值。 - [floatcos](floatcos): 从特定角度求余弦值。 - [floattan](floattan): 从特定角度求正切值。 - [asin](asin): 以度为单位求正弦值的倒数。 - [acos](acos): 以度为单位求余弦函数的倒数。 - [atan2](atan2): 以度为单位求正切的多值倒数。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/atan.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/atan.md", "repo_id": "openmultiplayer", "token_count": 719 }
461
--- title: 提交貢獻 description: 如何給SA-MP Wiki和open.mp的說明文件提交貢獻。 --- 這份說明文件是開放給任何人參與修改的!你只需要有一個 [GitHub](https://github.com) 帳號和一些空閒時間。你甚至不需要學習使用 Git,你可以全部在網頁界面上進行! 如果你想要幫助維護某個特定語言,請對 [`CODEOWNERS`](https://github.com/openmultiplayer/web/blob/master/CODEOWNERS) 說明文件發起一個 PR,並加入一行你的語言目錄和你的使用者名稱。 ## 編輯內容 在每個頁面上,都有一個按鈕可以讓你前往 GitHub 的編輯頁面: ![在每個 wiki 頁面上都有「編輯此頁面」連結](images/contributing/edit-this-page.png) 例如,在 [SetVehicleAngularVelocity](../scripting/functions/SetVehicleAngularVelocity) 頁面上點擊這個按鈕,會帶你前往 [這個頁面](https://github.com/openmultiplayer/web/blob/master/docs/scripting/functions/SetVehicleAngularVelocity.md),讓你透過文字編輯器修改檔案(假設你已經登入 GitHub)。 修改你要的內容後,提交一個「拉取請求」(Pull Request),這樣 Wiki 維護人員和其他社群成員就可以檢查你的更改,討論是否需要進一步的修改,然後合併它。 ## 新增內容 新增內容需要多花點功夫。你可以有兩個方法: ### 透過 GitHub 網頁界面新增 當你在 GitHub 上瀏覽某個目錄時,檔案列表右上角會有一個「Add file」按鈕: ![「新增檔案」按鈕](images/contributing/add-new-file.png) 你可以直接上傳你已經寫好的 Markdown 檔案,或是在 GitHub 的文字編輯器中直接撰寫。 這個檔案必須要有 `.md` 的檔案副檔名,並且內容是 Markdown 語法。如果你想更深入了解 Markdown,可以參考[這份指南](https://guides.github.com/features/mastering-markdown/)。 完成後,按下「Propose new file」就會開啟一個拉取請求,等待審查。 ### Git 如果你想使用 Git,你只需要使用以下命令克隆 Wiki 存儲庫: ```sh git clone https://github.com/openmultiplayer/wiki.git ``` 使用你喜歡的編輯器打開它。我建議使用 Visual Studio Code,因為它具有編輯和格式化 Markdown 文件的出色工具。正如你所看到的,我正在使用 Visual Studio Code 創建這篇文章! ![Visual Studio Code markdown preview](images/contributing/vscode.png) 我建議你使用兩個擴展程序,讓你的體驗更好: - [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint),由 David Anson 開發--這是一個擴展程序,可以確保你的 Markdown 正確格式化。它可以避免一些語法和語意上的錯誤。並不是所有的警告都很重要,但有些可以提高可讀性。請適當地使用最佳判斷力,如有疑問,請向審查者詢問! - [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode),由 Prettier.js 團隊開發--這是一個格式化程序,可以自動格式化你的 Markdown 文件,以便它們都使用一致的風格。Wiki 存儲庫的 `package.json` 中有一些設置,擴展程序應該自動使用這些設置。請確保在你的編輯器設置中啟用"保存時格式化",這樣每次保存時你的 Markdown 文件都會自動格式化! ## 注意事項、提示和約定 ### 內部鏈接 不要使用絕對 URL 進行站內鏈接。使用相對路徑。 - ❌ ```md 和 [OnPlayerClickPlayer](https://www.open.mp/docs/scripting/callbacks/OnPlayerClickPlayer) 搭配使用 ``` - ✔ ```md 和 [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer) 搭配使用 ``` `../` 表示"返回上一級目錄",因此如果你正在編輯的文件位於"functions"目錄中,並且你要鏈接到"callbacks",則使用 `../` 返回到"scripting/",然後進入 callbacks 目錄,最後輸入你想要鏈接的回調函數的文件名(不包括 `.md`)。 ### 圖片 圖片需要放在 `/static/images` 目錄下的子目錄中。當你在 `![]()` 中連結圖片時,只需使用 `/images/` 作為基本路徑(不需要使用 `static`,因為那只是用於存儲庫)。 如果不確定,請閱讀另一個使用圖片的頁面,並複製其中的操作。 ### 元資料 在 _任何_ 文件中,都應該首先是元資料: ```mdx --- title: 我的文件 description: 這是一個關於CJ、BigSmoke和火車的頁面,耶! --- ``` 每個頁面都應包含標題和描述。 有關可以放在 `---` 之間的完整列表,請參閱[Docusaurus說明文件](https://v2.docusaurus.io/docs/markdown-features#markdown-headers)。 ### 標題 不要使用 `#` 創建一級標題(`<h1>`),因為這是自動生成的。你的第一個標題應始終是 `##`。 - ❌ ```md # 我的標題 這是關於...的文件 # 子章節 ``` - ✔ ```md 這是關於...的文件 ## 子章節 ``` ### 使用 `Code` 碼片段進行技術參考 當撰寫包含函數名稱、數字、表達式或任何不是標準書面語言的內容時,將它們用 \`反引號\` 括起來。這有助於區分用於描述事物的語言和用於描述技術要素(例如函數名稱和代碼片段)的語言。 - ❌ > fopen 函数將返回一個類型為 File: 的標記值,在這一行上沒有問題,因為返回值也被存儲到具有 File: 標記的變量中(注意大小寫也相同)。然而,在下一行中,值 4 被添加到文件處理程序上。4 沒有標記 [...] - ✔ > `fopen` 函数將返回一個類型為 `File:` 的標記值,在這一行上沒有問題,因為返回值也被存儲到具有 `File:` 標記的變量中(注意大小寫也相同)。然而,在下一行中,值 `4` 被添加到文件處理程序上。`4` 沒有標記 在上述示例中,`fopen` 是一個函數名稱,而不是英文單詞,因此將其與 `code` 碼片段標記括起來有助於區分它與其他內容。 此外,如果該段落參考一個示例代碼塊,這有助於讀者將詞語與示例關聯起來。 ### 表格 如果表格有標題,它們應該放在頂部: - ❌ ```md | | | | ------- | ------------------------------------ | | 耐久度 | 引擎狀態 | | 650 | 未受損 | | 650-550 | 白煙 | | 550-390 | 灰煙 | | 390-250 | 黑煙 | | < 250 | 著火(幾秒後將爆炸) | ``` - ✔ ```md | 耐久度 | 引擎狀態 | | ------- | ------------------------------------ | | 650 | 未受損 | | 650-550 | 白煙 | | 550-390 | 灰煙 | | 390-250 | 黑煙 | | < 250 | 著火(幾秒後將爆炸) | ``` ## 從SA-MP Wiki遷移 大部分內容已經移植,但如果你發現缺少一個頁面,這是一個將內容轉換為Markdown的簡短指南。 ### 獲取HTML 1. 點擊此按鈕 (Firefox) ![image](images/contributing/04f024579f8d.png) (Chrome) ![image](images/contributing/f62bb8112543.png) 2. 懸停在主Wiki頁面的左邊邊緣或角落,直到看到 `#content` ![image](images/contributing/65761ffbc429.png) 或搜尋 `<div id=content>` ![image](images/contributing/77befe2749fd.png) 3. 複製該元素的內部HTML ![image](images/contributing/8c7c75cfabad.png) 現在你只有實際內容的 HTML 代碼,我們關心的部分,可以轉換為Markdown。 ### 將HTML轉換為Markdown 要將基本HTML(沒有表格)轉換為Markdown,請使用: https://domchristie.github.io/turndown/ ![image](images/contributing/77f4ea555bbb.png) ^^ 注意,現在它完全弄壞了表格... ### HTML表格轉換為Markdown表格 因為上述工具不支持表格,所以使用此工具: https://jmalarcon.github.io/markdowntables/ 只需將 `<table>` 元素複製到其中: ![image](images/contributing/57f171ae0da7.png) ### 清理 轉換可能不會完美。因此,你需要進行一些手動清理工作。上面列出的格式擴展應有助於這方面,但你可能仍然需要花時間進行手動編輯。 如果沒有時間,別擔心!提交一份未完成的草稿,其他人可以接手! ## 授權協議 所有 open.mp 項目都有一份 [貢獻者授權協議](https://cla-assistant.io/openmultiplayer/homepage)。這基本上意味著你同意讓我們使用你的工作,並將其置於開源許可證下。第一次提交拉取請求時,CLA-Assistant 機器人會發布一個鏈接,你可以在那裡簽署協議。
openmultiplayer/web/docs/translations/zh-tw/meta/Contributing.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-tw/meta/Contributing.md", "repo_id": "openmultiplayer", "token_count": 5777 }
462
# Frontend This directory contains the [Next.js](https://nextjs.org/) frontend codebase. It's written in TypeScript with some fairly relaxed but standard tsconfig rules (no strict mode). To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. ## Getting Started To install the required dependencies: ``` yarn ``` To run the local development server: ``` yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. Any edits to files in `src/` will trigger hot-reloads. Edits to any Markdown content in either `content/` or `../docs/` will not unfortunately. ## Development Most of the time, you can just fire up the site and work on it. It will always use the live API at `api.open.mp` for things like server listings, user dashboard, etc. Some things may result in a CORS error so you may need to change API calls to use `http://localhost` instead.
openmultiplayer/web/frontend/README.md/0
{ "file_path": "openmultiplayer/web/frontend/README.md", "repo_id": "openmultiplayer", "token_count": 301 }
463
# FAQ <hr /> ## Šta je open.mp? open.mp (Open Multiplayer, OMP) je zamjena za multiplayer mod za San Andreas, nastao kao odgovor na nesretan porast problema sa ažuriranjima i upravljanjem SA:MP-a. Početno izdanje bit će drop-in zamjena samo za poslužitelj (server). Postojeći SA:MP klijenti moći će se povezati s ovim serverom. U budućnosti će biti dostupan i novi open.mp klijent, koji će omogućavati izdavanje novih ažuriranja i ispravki. <hr /> ## Da li je ovo samo kopija? Ne. Ovo je u potpunosti ponovno napisan kod, iskorištavanjem prednosti decenija znanja i iskustva. Bilo je više pokušaja za forkom/kopijom (rekreacijom na osnovu već napisanog koda) SA:MP-a ranije, ali vjerujemo da su imali dva glavna problema: 1. Bili su bazirani na osnovu procurenog SA:MP source koda. Autori tih modova nemaju legalna prava na taj kod, i tako su uvijek bili na zadnjem stopalu, i moralno i pravno. Izravno odbijamo koristiti ovaj kod. To malo otežava razvojnu brzinu, ali to je pravi potez za ovaj dugi put. 2. Pokušali su iznova izmisliti previše. Ili zamjenom cijelog mehanizma za skriptiranje, ili uklanjanjem funkcija dok dodajete nove, ili jednostavno podešavanjem stvari na nekompatibilne načine. Ovo spriječava postojeće servere sa ogromnim bazama koda i bazama reproduktora da se prebace, jer bi morali prepisati neke, ako ne i sve svoje kodove - potencijalno masovni poduhvat. S vremenom u potpunosti namjeravamo dodavati funkcije i dotjerivati ​​stvari, ali usredotočeni smo i na podršku postojećih servera, omogućavajući im da koriste naš kôd bez promjene vlastitog. <hr /> ## Zašto radite ovo? Uprkos brojnim pokušajima da se službeno pogura razvoj SA:MP, u obliku prijedloga, kretanja i ponuda beta tima; zajedno sa zajednicom koja vapi za bilo čim novim; nije se uočio nikakav napredak. Široko se vjerovalo da se to jednostavno svodi na nedostatak interesa rukovodstva modne službe, što samo po sebi nije problem, ali nije postojala linija sukcesije. Umjesto da razvoj preda vlada onima koji su zainteresirani za nastavak rada na modu, osnivač je jednostavno želio sve srušiti sa sobom, dok je očito nizao stvari što je duže moguće uz minimalan napor. Neki tvrde da je to zbog pasivnih prihoda, ali za to nema dokaza. Uprkos ogromnom interesu i snažnoj i porodičnoj zajednici, vjerovao je da su u modu ostale samo 1-2 godine i da zajednica koja je toliko naporno napravila SA:MP ono što je danas ne zaslužuje nastavak. We disagree. <hr /> ## Koja su vaša mišljenja na Kalcora/SA:MP/bilo šta? Mi volimo SA:MP, zato smo ovdje prije svega - i to dugujemo Kalcoru. Tijekom godina učinio je ogroman iznos za mod i taj doprinos ne treba zaboraviti ili zanemariti. Radnje koje su vodile do open.mp-a su poduzete jer se nismo složili s nekoliko nedavnih odluka, i uprkos ponovljenim pokušajima usmjeravanja mod-a u drugom smjeru, nije se vidjelo rješenje. Stoga smo bili prisiljeni donijeti nesrećnu odluku da pokušamo nastaviti SA:MP u duhu bez Kalcora. Ovo nije radnja poduzeta protiv njega lično i ne bi se trebala smatrati napadom na njega lično. Nećemo tolerirati bilo kakve lične uvrede prema bilo kome - bez obzira na to gdje stoje po pitanju open.mp; trebali bismo biti u mogućnosti voditi razumnu raspravu bez pribjegavanja napadima ad-hominema. <hr /> ## Nije li ovo samo cijepanje zajednice? To nije naša namjera. U idealnom slučaju uopće ne bi bilo potrebno razdvajanje, ali razdvajanje nekih i spremanje tog dijela je bolje nego gledanje kako cijela stvar vene. U stvari, otkako je ovaj mod najavljen, veliki broj neengleskih zajednica ponovo se povezao sa engleskom zajednicom. Te su zajednice ranije polako potiskivane i stavljane po strani, tako da njihovo ponovno uključivanje zapravo ponovo dovodi do podjele zajednice. Velikom broju ljudi je zabranjen pristup službenim forumima SA:MP (au nekim slučajevima i čitava njihova istorija postova), ali sam Kalcor je istakao da zvanični forumi nisu SA:MP, već samo dio SA:MP. Mnogi igrači i vlasnici servera nikada nisu postavljali ili čak se nisu pridružili tim forumima; tako da ponovni razgovor s tim ljudima ujedinjuje još više dijelova zajednice. <hr /> ## S obzirom da je ovo "Open" Multiplayer, da li će biti open-source? Na kraju svega to je i plan, da. Za sada pokušavamo učiniti razvoj otvorenim u smislu komunikacije i transparentnosti (što je samo po sebi poboljšanje) i kretat ćemo se prema otvorenom izvoru kada i kad budemo mogli, kada se sve posloži i posloži. <hr /> ## Kada će biti objavljen? Ovo je prastaro pitanje, na žalost, ima prastari odgovor: kada je gotovo. Jednostavno ne možemo znati koliko će dugo trajati ovakav projekt. Već neko vrijeme tiho radi i već je vidio nekoliko oscilacija u nivou aktivnosti, ovisno o tome koliko su ljudi zauzeti. Ali budite sigurni da je na dobrom putu i brzo napreduje zahvaljujući nekim temeljnim dizajnerskim odlukama (o arhitekturi ćemo reći kasnije). <hr /> ## Kako mogu pomoći? Držite se na forumima. Imamo temu upravo za to i ažurirat ćemo je kako bude postajalo dostupno više radova. Iako je projekt otkriven malo ranije nego što je planirano, već smo na putu ka početnom izdanju, ali to ne znači da se veća pomoć ne cijeni uvijek masovno. Unaprijed zahvaljujem na interesovanju i vjerovanju u projekat: ["Kako pomoći" tema](https://forum.open.mp/showthread.php?tid=99) <hr /> ## Šta je burgershot.gg? burgershot.gg je gaming forum, ništa više. Mnogi su ljudi uključeni u oboje, a tamo su postavljeni i neki OMP razvoj i ažuriranja, ali to su dva neovisna projekta. Oni nisu forumi OMP-a, niti je OMP burgerhot svojstvo. Jednom kada puna OMP stranica bude pokrenuta, dvije se mogu izvući jedna iz druge (približno kao što je SA:MP jednom bio domaćin GTAForums prije nego što je pokrenula vlastitu stranicu). <hr /> ## Šta o OpenMP? Open Multi-Processing projekat je "OpenMP", mi smo "open.mp". Potpuno različito.
openmultiplayer/web/frontend/content/bs/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/bs/faq.mdx", "repo_id": "openmultiplayer", "token_count": 2645 }
464
# Često postavljana pitanja <hr /> ## Što je open.mp? open.mp (Open Multiplayer, OMP) je zamjenski multiplayer mod za GTA: San Andreas, pokrenut kao odgovor na sve brojnije probleme u vezi novih ažuriranja i u vođenju SA:MP-a. Prvo izdanje će biti instant zamjena samo za server. Postojeći SA:MP klijenti moći će se spojiti na ovaj server. Nešto kasnije će se razviti i novi open.mp klijent, koji će omogućiti još zanimljivija ažuriranja. <hr /> ## Je li ovo samo još jedna kopija? Ne. Ovo je u potpunosti novi kôd, uzimajući u obzir desetljeća znanja i iskustva. Bilo je pokušaja kopiranja SA:MP-a i ranije, ali vjerujemo da su imali dva glavna problema: 1. Bazirani su na procurenom SA:MP izvornom kodu. Autori tih modova nisu imali zakonsko pravo korištenja tog kôda i uvijek su zbog toga bili jedan korak unazad, moralno i zakonski. Mi odbijamo koristiti taj kôd. Ovo malo škodi brzini razvoja ali je ispravan potez u konačnici. 2. Pokušali su promijeniti previše toga odjednom. Bilo to zamijenom cijelog skripterskog jezika ili uklanjanjem mogućnosti dok su dodavane nove, ili jednostavno nekompatibilnim podešavanjem. To je zauzvrat spriječilo prebacivanje servera sa velikim baznim kôdom i velikim brojem igrača, jer bi trebali ponovno napisati dio, ako ne i čitav svoj kôd, što je velik poduhvat. Mi ćemo u potpunosti nastojati dodati mogućnosti i izgladiti stvari tijekom vremena ali se isto tako fokusiramo podržati postojeće servere i omogućiti im korištenje našeg kôda bez potrebe da mijenjaju svoj. <hr /> ## Zbog čega radite ovo? Unatoč brojnim pokušajima da "poguramo" razvoj SA:MP-a službenim kanalima, u obliku prijedloga, druženja i ponuda pomoći iz tima beta testera; uz cijelu zajednicu koja je vapila za nečim novim; nije bilo napretka. Vjerovalo se da je to jednostavno zbog nedostatka interesa od strane vodstva moda, što nije problem samo po sebi, ali nije bilo linije nasljedstva. Umjesto da preda "ključeve carstva" onima koji su zainteresirani raditi na modu, osnivač je želio sve povući dolje sa sobom, dok je istovremeno razvlačio stvari što je dulje moguće, uz minimalan napor. Neki tvrde da je to iz razloga pasivnih prihoda, ali za to nema dokaza. Unatoč velikom zanimanju te jakoj i obiteljskoj zajednici, vjerovao je da je preostalo još godinu-dvije životu moda i da zajednica, koja je radila toliko naporno da učini SA:MP onim što je danas, nije zaslužila nastavak. Mi se ne slažemo. <hr /> ## Koja su vaša mišljenja o Kalcoru/SA:MP-u/ostalom? Mi volimo SA:MP i zbog toga smo ovdje na prvom mjestu, i zahvalni smo Kalcoru što ga je stvorio. Učinio je puno toga za mod tijekom godina i njegov doprinos ne smije biti zaboravljen ili zapostavljen. Postupci koji su rezultirali open.mp-om poduzeti su jer se nismo slagali sa nekoliko nedavnih odluka, i unatoč opetovanim pokušajima da vodimo mod u drugom smjeru, rješenja nije bilo na pomolu. Stoga smo bili prisiljeni učiniti nesretnu odluku i nastaviti razvitak u duhu SA:MP-a bez Kalcora. Ovo nije radnja poduzeta protiv njega osobno, i ne treba se gledati kao napad na njega osobno. Nećemo tolerirati bilo kakve osobne uvrede protiv bilo koga, bez obzira gdje stoje po pitanju open.mp-a; trebali bi moći voditi razumnu raspravu bez da posežemo za ad-hominem rasuđivanjem. <hr /> ## Ne dijeli li ovo zajednicu još više? To nam nije namjera. Idealno, nikakva podjela ne bi bila potrebna, ali odijeliti se od jednog dijela kako bi spasili ostatak je bolje nego gledati kako sve polako nestaje. Ustvari, nakon objavljivanja ovog moda velik broj zajednica koje ne pričaju engleskim jezikom ponovno su stupile u kontakt sa našom zajednicom. Te zajednice su polako bile gurane na stranu ranije, stoga njihovo ponovno uključivanje zapravo zbližava zajednicu. Velik broj ljudi je isključen(banan) sa službenog SA:MP foruma (i, u nekim slučajevima, svi njihovi postovi su obrisani), ali sam Kalcor je istaknuo da službeni forum nije SA:MP, već samo dio SA:MP-a. Mnogi igrači i vlasnici servera nisu nikada postali, niti su se čak priključili tom forumu; tako da razgovor s tim ljudima ujedinjuje sve više dijelova zajednice. <hr /> ## Iz naziva "Open" Multiplayer, hoće li ovo biti otvorenog kôda? U konačnici to je plan, da. Za sada nastojimo učiniti razvoj otvoren u smislu komunikacije i transparentnosti (što je samo po sebi napredak), i pokušat ćemo objaviti kôd kada možemo, nakon što se sve sredi. <hr /> ## Kada će biti dostupno za preuzimanje? Ovo je vječito pitanje, na žalost na to možemo odgovoriti samo sa jednakim odgovorom: kada bude gotovo. Jednostavno ne možemo znati koliko će vremena projekt kao što je ovaj iziskivati. Tiho se radi na njemu već duže vrijeme, i već je bilo par fluktuacija u razini aktivnosti, ovisno o tome koliko su ljudi bili zauzeti. Ali budite sigurni da je na dobrom putu, i razvija se brzo zahvaljujući dobrim odlukama programerske prakse (reći ćemo nešto više o softverskoj arhitekturi kasnije). <hr /> ## Kako Ja mogu pomoći? Napravili smo temu upravo za to, i ažurirat ćemo je kada još posla bude dostupno. Iako je projekt otkriven nešto ranije no što je planirano, već smo na dobrom putu prema prvom izdanju, ali to ne znači da još pomoći nije veoma cijenjeno. Hvala Vam unaprijed za Vaš interes, i što vjerujete u ovaj projekt: ["Kako pomoći" tema](https://forum.open.mp/showthread.php?tid=99) <hr /> ## Što je burgershot.gg? burgershot.gg je gaming forum, ništa više. Puno ljudi je uključeno u oboje i dio objava vezanih uz razvitak OMP-a se tamo objavljuje, no to su dva nezavisna projekta. To nije OMP forum, niti je OMP vlasništvo burgershot-a. Jednom kada potpuna OMP stranica bude pokrenuta, to dvoje može biti odvojeno jedno od drugog (jednako kako je i SA:MP bio hostan od strane GTAForums stranice prije nego su stvorili vlastitu). <hr /> ## A što je sa OpenMP? Open Multi-Processing projekt je "OpenMP", mi smo "open.mp". Potpuno nevezano.
openmultiplayer/web/frontend/content/hr/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/hr/faq.mdx", "repo_id": "openmultiplayer", "token_count": 2762 }
465
# Open Multiplayer Naujai kuriama Multiplayer modifikacija <em>Grand Theft Auto: San Andreas</em> žaidimui, kuri bus pilnai suderinama su jau egzistuojančiu <em>San Andreas Multiplayer</em> modu. <br /> Tai reiškia **kad SA:MP programa ir visi sukurti SA:MP skriptai veiks su open.mp**, kartu bus sutaisyta daug klaidų serverio programinėje įrangoje apsieinant be įvairiausių apėjimų bei taip vadinamų hackų. Jeigu jums smalsu, kada planuojama išleisti modifikaciją arba kaip galėtumėte prisidėti prie projekto, prašome apsilankyti <a href="https://forum.open.mp/showthread.php?tid=99">šioje forumo temoje</a>. # [DUK](/faq)
openmultiplayer/web/frontend/content/lt/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/lt/index.mdx", "repo_id": "openmultiplayer", "token_count": 279 }
466
--- title: Модул територија (претходно зоне банди) date: "2019-10-19T04:20:00" author: J0sh --- Ћао! Управо сам завршио имплементацију нашег модула територија у сервер и мислио сам да поставим преглед овог модула и да покажем да нисмо одустали! ```pawn // Креира територију. playerid може бити унет да би била играчева територија. native Turf:Turf_Create(Float:minx, Float:miny, Float:maxx, Float:maxy, Player:owner = INVALID_PLAYER_ID); // Уништава територију. native Turf_Destroy(Turf:turf); // Приказује територију играчу или играчима. // Послаће свим играчима ако је playerid = INVALID_PLAYER_ID. native Turf_Show(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID); // Склања територију играчу или играчима. // Послаће свим играчима ако је playerid = INVALID_PLAYER_ID. native Turf_Hide(Turf:turf, Player:playerid = INVALID_PLAYER_ID); // Територија сева за играча или играче. // Послаће свим играчима ако је playerid = INVALID_PLAYER_ID. native Turf_Flash(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID); // Прекида севање територије за играча или играче. // Послаће свим играчима ако је playerid = INVALID_PLAYER_ID. native Turf_StopFlashing(Turf:turf, Player:playerid = INVALID_PLAYER_ID); ``` Ово је веома другачије од старог API, али немојте бринути, биће функција за компактибилност за ову врсту ствари да бисмо направили да старе скрипте сигурно могу да се поново компајлују без проблема и мењања. Следећа занимљива чињеница коју би требало да знате је да је свака територија у истом скупу и да је максимум 4,294,967,295 направљених у једној скрипти. Свакако, клијент може да ради са 1024 територије истовремено.
openmultiplayer/web/frontend/content/sr/blog/turfs-formerly-gangzones-module.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/sr/blog/turfs-formerly-gangzones-module.mdx", "repo_id": "openmultiplayer", "token_count": 1356 }
467
--- title: 计时器模块 date: "2019-05-22T03:15:00" author: Y_Less --- 这是我们所做的一个改进模块,open.mp 中的计时器: ```pawn native SetTimer(const func[], msInterval, bool:repeat) = SetTimerEx; native SetTimerEx(const func[], msInterval, bool:repeat, const params[], GLOBAL_TAG_TYPES:...); native KillTimer(timer) = Timer_Kill; // 创建计时器 native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...); // 销毁计时器 native bool:Timer_Kill(Timer:timer); // 返回直到下一次调用的剩余时间 native Timer_GetTimeRemaining(Timer:timer); // 获取剩余的调用次数(0表示无限)。 native Timer_GetCallsRemaining(Timer:timer); // 获取 `repeatCount` 重复次数参数. native Timer_GetTotalCalls(Timer:timer); // 获取 `usInterval` 间隔执行参数. native Timer_GetInterval(Timer:timer); // 将下一次调用前的剩余时间重置为`usInterval`间隔执行参数。 native bool:Timer_Restart(Timer:timer); ``` 前两个只是为了向后兼容,其余的是改进的 API: ```pawn native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...); ``` - `func` - 显而易见;指调用哪个函数。 - `usDelay` - 同样显而易见,指第一次调用前的延迟(以微秒为单位)。 - `usInterval` - 在第一次调用后,将`usDelay`重置为什么。因此,如果你想要一个每小时整的定时器,但现在是早上 8 点 47 分,那么调用的结果是`Timer_Create("OnTheHour", 780 SECONDS, 3600 SECONDS, 0);`。 - `repeatCount` - 不像以前的函数只是 "一次 "或 "永远",这里指需要调用函数的次数。"一次"将是`1`,500 将在调用 500 次后停止,而 0 意味着 "永远"(和旧的 API 相反)。 - `GLOBAL_TAG_TYPES` - 就像`{Float, ...}`,但支持更多的标签。
openmultiplayer/web/frontend/content/zh-cn/blog/timers.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/zh-cn/blog/timers.mdx", "repo_id": "openmultiplayer", "token_count": 1040 }
468
import { Heading, Spinner } from "@chakra-ui/react"; import React, { FC } from "react"; const LoadingBanner: FC = () => { return ( <section> <Spinner thickness="4px" speed="0.65s" emptyColor="gray.200" color="purple.500" size="xl" /> <Heading fontStyle="italic" size="lg"> Following the damn train... </Heading> <style jsx>{` section { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%; gap: 1em; } `}</style> </section> ); }; export default LoadingBanner;
openmultiplayer/web/frontend/src/components/LoadingBanner.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/LoadingBanner.tsx", "repo_id": "openmultiplayer", "token_count": 336 }
469
import { useToast } from "@chakra-ui/react"; import { useCallback } from "react"; import { API_ADDRESS } from "src/config"; import { useMutationAPI } from "src/fetcher/hooks"; import { All } from "src/types/_generated_Server"; // TODO: Remove this when server listing is refactored. const mutateKey = `${API_ADDRESS}/servers/`; type DeleteServerPayload = { time: string }; type DeleteServerFn = (ip: string) => void; export const useDeleteServer = (): DeleteServerFn => { const api = useMutationAPI<DeleteServerPayload, All>(true); const toast = useToast(); return useCallback( async (id: string) => { const r = await api("PATCH", `/servers/${id}/deleted`, { mutate: mutateKey, })({ time: new Date().toISOString(), }); if (r) { toast({ title: "Server deleted!", description: `${r.ip} deleted.`, status: "success", }); } }, [api, toast] ); };
openmultiplayer/web/frontend/src/components/listing/hooks.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/components/listing/hooks.ts", "repo_id": "openmultiplayer", "token_count": 383 }
470
import Admonition from "../Admonition"; export default function NoteLowercase({ name = "function" }) { return ( <Admonition type="warning"> <p>This {name} starts with a lowercase letter.</p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/lowercase-note.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/lowercase-note.tsx", "repo_id": "openmultiplayer", "token_count": 80 }
471
import Admonition from "../../../Admonition"; export default function WarningVersion({ version, name = "function", }: { version: string; name: string; }) { return ( <Admonition type="warning"> <p> Bu {name} öğesi {version} sürümünde eklendi ve daha önceki sürümlerde çalışmayacaktır! </p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/translations/tr/version-warning.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/translations/tr/version-warning.tsx", "repo_id": "openmultiplayer", "token_count": 153 }
472
// This page is a catch-all ([...slug]) for all pages (including sub-routes) // it will take the slug and use it to locate content in the "content" directory // in the frontend directory. The user's locale from Next.js is used to pick a // directory. // // For example, if the user visits /blog/somepost and their Locale is French, // the server render code will serve the content from content/fr/blog/somepost. // If there is none available, a fallback from content/en/blog/somepost will be // displayed with a warning that the content is unavailable in their language. import Error from "next/error"; import { NextSeo } from "next-seo"; // - // Client side // - import { hydrate } from "src/mdx-helpers/csr"; import Admonition from "src/components/Admonition"; import components from "src/components/templates"; import { useColorModeValue } from "@chakra-ui/react"; type Props = { source?: any; error?: string; data?: { [key: string]: any }; fallback?: boolean; }; const Page = ({ source, error, data, fallback }: Props) => { if (error) { return ( <section> <Error statusCode={404} title={error} /> </section> ); } const content = source && hydrate(source, { components: components as Components }); const codeColor = useColorModeValue( "var(--chakra-colors-gray-200)", "var(--chakra-colors-gray-700)" ); return ( <div className="flex flex-column flex-row-ns flex-auto justify-center-ns"> <NextSeo title={data?.title} description={data?.description} /> <section className="mw7 pa3 flex-auto"> {fallback && ( <Admonition type="warning" title="Not Translated"> This page has not been translated into the language that your browser requested. </Admonition> )} <h1>{data?.title}</h1> {content} <style global jsx>{` pre, code { background: ${codeColor}; } `}</style> </section> </div> ); }; // - // Server side // - import { GetStaticPathsResult, GetStaticPropsContext, GetStaticPropsResult, } from "next"; import matter from "gray-matter"; import { getAllContentLocales, getContentPaths, getContentPathsForLocale, readLocaleContent, } from "src/utils/content"; import { renderToString } from "src/mdx-helpers/ssr"; import { RawContent } from "src/types/content"; import { Components } from "@mdx-js/react"; import { concat, flatten, flow, map } from "lodash/fp"; import rehypeStarryNight from "@microflash/rehype-starry-night"; export async function getStaticProps( context: GetStaticPropsContext<{ slug: string[] }> ): Promise<GetStaticPropsResult<Props>> { const { locale } = context; const route = context?.params?.slug || ["index"]; let result: RawContent; try { result = await readLocaleContent(route.join("/"), locale || "en"); } catch (e) { return { props: { error: "Not found: " + e.message } }; } const { content, data } = matter(result.source); const mdxSource = await renderToString(content, { components: components as Components, mdxOptions: { components: components as Components, rehypePlugins: [ [rehypeStarryNight, { showHeader: false, showLines: false }], ], }, }); return { props: { source: mdxSource, data, fallback: result.fallback } }; } export function getStaticPaths(): GetStaticPathsResult { return { paths: getContentPaths(), fallback: true, }; } export default Page;
openmultiplayer/web/frontend/src/pages/[...slug].tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/[...slug].tsx", "repo_id": "openmultiplayer", "token_count": 1276 }
473
import React from "react"; import { useState } from "react"; import { Button, HStack, Input, Select, useDisclosure } from "@chakra-ui/react"; import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, useToast, } from "@chakra-ui/react"; import useSWR from "swr"; import { api, apiSWR } from "src/fetcher/fetcher"; import { User } from "src/types/_generated_User"; import nProgress from "nprogress"; import LoadingBanner from "src/components/LoadingBanner"; import { APIError } from "src/types/_generated_Error"; import ErrorBanner from "src/components/ErrorBanner"; const UserView = ({ user, users, setUsers }: any) => { return ( <div style={{ display: "grid", padding: "0.4em 0.8em", backgroundColor: user.deletedAt ? "#FC5900" : "#FAFAFA", margin: "0.4em 0", border: "1px solid #E2E8F0", borderRadius: "8px", gridTemplateColumns: "1fr 1fr 1fr 0.2fr", alignItems: "center", }} > <p>{user.name}</p> <p> <strong>{user.posts || 0}</strong> posts </p> <p>Joined on {user.createdAt.slice(0, 10)}</p> <BanModal user={user} users={users} setUsers={setUsers} /> </div> ); }; const BanModal = ({ users, user, setUsers }: any) => { const toast = useToast(); const { isOpen, onOpen, onClose } = useDisclosure(); const handleBan = async (id: string) => { nProgress.start(); setUsers(users.filter((user: any) => user.id !== id)); await api(`/users/${user.id}`, { method: "DELETE" }); toast({ title: "Operation successful", description: `${user.name} has been banned.`, status: "success", duration: 3000, isClosable: true, position: "top-right", }); nProgress.done(); }; return ( <> <Button onClick={onOpen} border="1px solid lightgrey"> ❌ </Button> <Modal isCentered onClose={onClose} isOpen={isOpen} motionPreset="slideInBottom" > <ModalOverlay /> <ModalContent> <ModalHeader>Ban member?</ModalHeader> <ModalBody>Are you sure you want to ban {user.name}?</ModalBody> <ModalFooter> <Button colorScheme="red" mr={3} onClick={() => handleBan(user.id)}> Ban </Button> <Button variant="ghost" onClick={onClose}> Cancel </Button> </ModalFooter> </ModalContent> </Modal> </> ); }; export default function Members() { const [memberSearch, setMemberSearch] = useState(""); const [sort, setSort] = useState("asc"); const [pageExtremes, setPageExtremes] = useState({ start: 0, end: 10, }); const { data, error, mutate } = useSWR<User[], APIError>("/users", apiSWR()); if (error) { return <ErrorBanner {...error} />; } if (!data) { return <LoadingBanner />; } const users = Object.values(data); const handleMemberSearch = (event: any) => { setMemberSearch(event.target.value); if (event.target.value != "") { const extremeObj = { ...pageExtremes }; extremeObj.start = 0; extremeObj.end = users.length; setPageExtremes(extremeObj); } else { const extremeObj = { ...pageExtremes }; extremeObj.start = 0; extremeObj.end = 10; setPageExtremes(extremeObj); } }; const handleSort = (event: any) => { setSort(event.target.value); }; const nextPage = () => { const extremeObj = { ...pageExtremes }; if (extremeObj.end + 10 > users.length) { extremeObj.start += 10; extremeObj.end = users.length; } else { extremeObj.start += 10; extremeObj.end += 10; } setPageExtremes(extremeObj); }; const lastPage = () => { const extremeObj = { ...pageExtremes }; if (extremeObj.end + 10 > users.length && extremeObj.end % 10 != 0) { extremeObj.start -= 10; extremeObj.end = extremeObj.end - (extremeObj.end % 10); } else { extremeObj.start -= 10; extremeObj.end -= 10; } setPageExtremes(extremeObj); }; return ( <> <section className="center measure-wide"> <h1>Members</h1> <div style={{ display: "flex", flexDirection: "column" }}> <HStack spacing="10px"> <Input placeholder="search members" style={{ margin: "0.8em 0em", minWidth: "70%" }} value={memberSearch} onChange={handleMemberSearch} ></Input> <Select value={sort} onChange={handleSort}> <option value="asc">ascending</option> <option value="desc">descending</option> </Select> </HStack> {`Showing ${pageExtremes.start + 1} - ${pageExtremes.end} of ${ users.length } registered members.`} <div style={{ minHeight: "620px" }}> {users .filter( (person) => person.name .toLowerCase() .trim() .includes(memberSearch.toLowerCase().trim()) || memberSearch === "" ) .slice(pageExtremes.start, pageExtremes.end) .map((el) => ( <UserView key={el.id} user={el} setUsers={mutate} users={users} /> ))} </div> <HStack justifyContent="center" margin="1em"> <Button isDisabled={pageExtremes.start === 0 ? true : false} onClick={lastPage} > previous </Button> <Button isDisabled={pageExtremes.end >= users.length ? true : false} onClick={nextPage} > next </Button> </HStack> </div> </section> </> ); }
openmultiplayer/web/frontend/src/pages/members/index.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/members/index.tsx", "repo_id": "openmultiplayer", "token_count": 2868 }
474
import * as z from "zod" export const APIErrorSchema = z.object({ message: z.string().optional(), suggested: z.string().optional(), error: z.string().optional(), }) export type APIError = z.infer<typeof APIErrorSchema>
openmultiplayer/web/frontend/src/types/_generated_Error.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/types/_generated_Error.ts", "repo_id": "openmultiplayer", "token_count": 73 }
475
package web import ( "net/http" "go.uber.org/zap" ) // WithLogger is simple Zap logger HTTP middleware func WithLogger(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { zap.L().Info( "request", zap.String("method", r.Method), zap.String("path", r.URL.Path), zap.Any("query", r.URL.Query()), zap.Int64("body", r.ContentLength), ) next.ServeHTTP(w, r) }) }
openmultiplayer/web/internal/web/logger.go/0
{ "file_path": "openmultiplayer/web/internal/web/logger.go", "repo_id": "openmultiplayer", "token_count": 186 }
476
-- AlterTable ALTER TABLE "Server" ADD COLUMN "partner" BOOL NOT NULL DEFAULT false;
openmultiplayer/web/prisma/migrations/20230928210340_add_partner_column/migration.sql/0
{ "file_path": "openmultiplayer/web/prisma/migrations/20230928210340_add_partner_column/migration.sql", "repo_id": "openmultiplayer", "token_count": 31 }
477
import './preview.css' // Storybook does not (currently) support async loading of "stories". Therefore // the strategy in frontend/js/i18n.js does not work (because we cannot wait on // the promise to resolve). // Therefore we have to use the synchronous method for configuring // react-i18next. Because this, we can only hard-code a single language. import i18n from 'i18next' import { initReactI18next } from 'react-i18next' import en from '../locales/en.json' i18n.use(initReactI18next).init({ lng: 'en', resources: { en: { translation: en }, }, react: { useSuspense: false, }, interpolation: { prefix: '__', suffix: '__', unescapeSuffix: 'HTML', skipOnVariables: true, defaultVariables: { appName: 'Overleaf', }, }, }) export const parameters = { // Automatically mark prop-types like onClick, onToggle, etc as Storybook // "actions", so that they are logged in the Actions pane at the bottom of the // viewer actions: { argTypesRegex: '^on.*' }, docs: { // render stories in iframes, to isolate modals inlineStories: false, }, } export const globalTypes = { theme: { name: 'Theme', description: 'Editor theme', defaultValue: 'default-', toolbar: { icon: 'circlehollow', items: [ { value: 'default-', title: 'Default' }, { value: 'light-', title: 'Light' }, { value: 'ieee-', title: 'IEEE' }, ], }, }, } export const loaders = [ async ({ globals }) => { const { theme } = globals return { // NOTE: this uses `${theme}style.less` rather than `${theme}.less` // so that webpack only bundles files ending with "style.less" activeStyle: await import( `../frontend/stylesheets/${theme === 'default-' ? '' : theme}style.less` ), } }, ] const withTheme = (Story, context) => { const { activeStyle } = context.loaded return ( <> {activeStyle && <style>{activeStyle.default}</style>} <Story {...context} /> </> ) } export const decorators = [withTheme] window.ExposedSettings = { maxEntitiesPerProject: 10, maxUploadSize: 5 * 1024 * 1024, enableSubscriptions: true, textExtensions: [ 'tex', 'latex', 'sty', 'cls', 'bst', 'bib', 'bibtex', 'txt', 'tikz', 'mtx', 'rtex', 'md', 'asy', 'latexmkrc', 'lbx', 'bbx', 'cbx', 'm', 'lco', 'dtx', 'ins', 'ist', 'def', 'clo', 'ldf', 'rmd', 'lua', 'gv', 'mf', ], } window.user = { id: 'storybook', }
overleaf/web/.storybook/preview.js/0
{ "file_path": "overleaf/web/.storybook/preview.js", "repo_id": "overleaf", "token_count": 1065 }
478
const AuthenticationManager = require('./AuthenticationManager') const SessionManager = require('./SessionManager') const OError = require('@overleaf/o-error') const LoginRateLimiter = require('../Security/LoginRateLimiter') const UserUpdater = require('../User/UserUpdater') const Metrics = require('@overleaf/metrics') const logger = require('logger-sharelatex') const querystring = require('querystring') const Settings = require('@overleaf/settings') const basicAuth = require('basic-auth-connect') const crypto = require('crypto') const UserHandler = require('../User/UserHandler') const UserSessionsManager = require('../User/UserSessionsManager') const SessionStoreManager = require('../../infrastructure/SessionStoreManager') const Analytics = require('../Analytics/AnalyticsManager') const passport = require('passport') const NotificationsBuilder = require('../Notifications/NotificationsBuilder') const UrlHelper = require('../Helpers/UrlHelper') const AsyncFormHelper = require('../Helpers/AsyncFormHelper') const _ = require('lodash') const UserAuditLogHandler = require('../User/UserAuditLogHandler') const AnalyticsRegistrationSourceHelper = require('../Analytics/AnalyticsRegistrationSourceHelper') const { acceptsJson, } = require('../../infrastructure/RequestContentTypeDetection') function send401WithChallenge(res) { res.setHeader('WWW-Authenticate', 'OverleafLogin') res.sendStatus(401) } const AuthenticationController = { serializeUser(user, callback) { if (!user._id || !user.email) { const err = new Error('serializeUser called with non-user object') logger.warn({ user }, err.message) return callback(err) } const lightUser = { _id: user._id, first_name: user.first_name, last_name: user.last_name, isAdmin: user.isAdmin, staffAccess: user.staffAccess, email: user.email, referal_id: user.referal_id, session_created: new Date().toISOString(), ip_address: user._login_req_ip, must_reconfirm: user.must_reconfirm, v1_id: user.overleaf != null ? user.overleaf.id : undefined, } callback(null, lightUser) }, deserializeUser(user, cb) { cb(null, user) }, passportLogin(req, res, next) { // This function is middleware which wraps the passport.authenticate middleware, // so we can send back our custom `{message: {text: "", type: ""}}` responses on failure, // and send a `{redir: ""}` response on success passport.authenticate('local', function (err, user, info) { if (err) { return next(err) } if (user) { // `user` is either a user object or false return AuthenticationController.finishLogin(user, req, res, next) } else { if (info.redir != null) { return res.json({ redir: info.redir }) } else { return res.json({ message: info }) } } })(req, res, next) }, finishLogin(user, req, res, next) { if (user === false) { return res.redirect('/login') } // OAuth2 'state' mismatch const Modules = require('../../infrastructure/Modules') Modules.hooks.fire( 'preFinishLogin', req, res, user, function (error, results) { if (error) { return next(error) } if (results.some(result => result && result.doNotFinish)) { return } if (user.must_reconfirm) { return AuthenticationController._redirectToReconfirmPage( req, res, user ) } const redir = AuthenticationController._getRedirectFromSession(req) || '/project' _loginAsyncHandlers(req, user) const userId = user._id UserAuditLogHandler.addEntry(userId, 'login', userId, req.ip, err => { if (err) { return next(err) } _afterLoginSessionSetup(req, user, function (err) { if (err) { return next(err) } AuthenticationController._clearRedirectFromSession(req) AnalyticsRegistrationSourceHelper.clearSource(req.session) AnalyticsRegistrationSourceHelper.clearInbound(req.session) AsyncFormHelper.redirect(req, res, redir) }) }) } ) }, doPassportLogin(req, username, password, done) { const email = username.toLowerCase() const Modules = require('../../infrastructure/Modules') Modules.hooks.fire( 'preDoPassportLogin', req, email, function (err, infoList) { if (err) { return done(err) } const info = infoList.find(i => i != null) if (info != null) { return done(null, false, info) } LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) { if (err) { return done(err) } if (!isAllowed) { logger.log({ email }, 'too many login requests') return done(null, null, { text: req.i18n.translate('to_many_login_requests_2_mins'), type: 'error', }) } AuthenticationManager.authenticate( { email }, password, function (error, user) { if (error != null) { return done(error) } if (user != null) { // async actions done(null, user) } else { AuthenticationController._recordFailedLogin() logger.log({ email }, 'failed log in') done(null, false, { text: req.i18n.translate('email_or_password_wrong_try_again'), type: 'error', }) } } ) }) } ) }, ipMatchCheck(req, user) { if (req.ip !== user.lastLoginIp) { NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip) } return UserUpdater.updateUser(user._id.toString(), { $set: { lastLoginIp: req.ip }, }) }, requireLogin() { const doRequest = function (req, res, next) { if (next == null) { next = function () {} } if (!SessionManager.isUserLoggedIn(req.session)) { if (acceptsJson(req)) return send401WithChallenge(res) return AuthenticationController._redirectToLoginOrRegisterPage(req, res) } else { req.user = SessionManager.getSessionUser(req.session) return next() } } return doRequest }, requireOauth() { // require this here because module may not be included in some versions const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server') return function (req, res, next) { if (next == null) { next = function () {} } const request = new Oauth2Server.Request(req) const response = new Oauth2Server.Response(res) return Oauth2Server.server.authenticate( request, response, {}, function (err, token) { if (err) { // use a 401 status code for malformed header for git-bridge if ( err.code === 400 && err.message === 'Invalid request: malformed authorization header' ) { err.code = 401 } // send all other errors return res .status(err.code) .json({ error: err.name, error_description: err.message }) } req.oauth = { access_token: token.accessToken } req.oauth_token = token req.oauth_user = token.user return next() } ) } }, validateUserSession: function () { // Middleware to check that the user's session is still good on key actions, // such as opening a a project. Could be used to check that session has not // exceeded a maximum lifetime (req.session.session_created), or for session // hijacking checks (e.g. change of ip address, req.session.ip_address). For // now, just check that the session has been loaded from the session store // correctly. return function (req, res, next) { // check that the session store is returning valid results if (req.session && !SessionStoreManager.hasValidationToken(req)) { // force user to update session req.session.regenerate(() => { // need to destroy the existing session and generate a new one // otherwise they will already be logged in when they are redirected // to the login page if (acceptsJson(req)) return send401WithChallenge(res) AuthenticationController._redirectToLoginOrRegisterPage(req, res) }) } else { next() } } }, _globalLoginWhitelist: [], addEndpointToLoginWhitelist(endpoint) { return AuthenticationController._globalLoginWhitelist.push(endpoint) }, requireGlobalLogin(req, res, next) { if ( AuthenticationController._globalLoginWhitelist.includes( req._parsedUrl.pathname ) ) { return next() } if (req.headers.authorization != null) { AuthenticationController.requirePrivateApiAuth()(req, res, next) } else if (SessionManager.isUserLoggedIn(req.session)) { next() } else { logger.log( { url: req.url }, 'user trying to access endpoint not in global whitelist' ) if (acceptsJson(req)) return send401WithChallenge(res) AuthenticationController.setRedirectInSession(req) res.redirect('/login') } }, validateAdmin(req, res, next) { const adminDomains = Settings.adminDomains if ( !adminDomains || !(Array.isArray(adminDomains) && adminDomains.length) ) { return next() } const user = SessionManager.getSessionUser(req.session) if (!(user && user.isAdmin)) { return next() } const email = user.email if (email == null) { return next( new OError('[ValidateAdmin] Admin user without email address', { userId: user._id, }) ) } if (!adminDomains.find(domain => email.endsWith(`@${domain}`))) { return next( new OError('[ValidateAdmin] Admin user with invalid email domain', { email: email, userId: user._id, }) ) } return next() }, requireBasicAuth: function (userDetails) { return basicAuth(function (user, pass) { const expectedPassword = userDetails[user] const isValid = expectedPassword && expectedPassword.length === pass.length && crypto.timingSafeEqual(Buffer.from(expectedPassword), Buffer.from(pass)) if (!isValid) { logger.err({ user }, 'invalid login details') } return isValid }) }, requirePrivateApiAuth() { return AuthenticationController.requireBasicAuth(Settings.httpAuthUsers) }, setRedirectInSession(req, value) { if (value == null) { value = Object.keys(req.query).length > 0 ? `${req.path}?${querystring.stringify(req.query)}` : `${req.path}` } if ( req.session != null && !/^\/(socket.io|js|stylesheets|img)\/.*$/.test(value) && !/^.*\.(png|jpeg|svg)$/.test(value) ) { const safePath = UrlHelper.getSafeRedirectPath(value) return (req.session.postLoginRedirect = safePath) } }, _redirectToLoginOrRegisterPage(req, res) { if ( req.query.zipUrl != null || req.query.project_name != null || req.path === '/user/subscription/new' ) { AuthenticationController._redirectToRegisterPage(req, res) } else { AuthenticationController._redirectToLoginPage(req, res) } }, _redirectToLoginPage(req, res) { logger.log( { url: req.url }, 'user not logged in so redirecting to login page' ) AuthenticationController.setRedirectInSession(req) const url = `/login?${querystring.stringify(req.query)}` res.redirect(url) Metrics.inc('security.login-redirect') }, _redirectToReconfirmPage(req, res, user) { logger.log( { url: req.url }, 'user needs to reconfirm so redirecting to reconfirm page' ) req.session.reconfirm_email = user != null ? user.email : undefined const redir = '/user/reconfirm' AsyncFormHelper.redirect(req, res, redir) }, _redirectToRegisterPage(req, res) { logger.log( { url: req.url }, 'user not logged in so redirecting to register page' ) AuthenticationController.setRedirectInSession(req) const url = `/register?${querystring.stringify(req.query)}` res.redirect(url) Metrics.inc('security.login-redirect') }, _recordSuccessfulLogin(userId, callback) { if (callback == null) { callback = function () {} } UserUpdater.updateUser( userId.toString(), { $set: { lastLoggedIn: new Date() }, $inc: { loginCount: 1 }, }, function (error) { if (error != null) { callback(error) } Metrics.inc('user.login.success') callback() } ) }, _recordFailedLogin(callback) { Metrics.inc('user.login.failed') if (callback) callback() }, _getRedirectFromSession(req) { let safePath const value = _.get(req, ['session', 'postLoginRedirect']) if (value) { safePath = UrlHelper.getSafeRedirectPath(value) } return safePath || null }, _clearRedirectFromSession(req) { if (req.session != null) { delete req.session.postLoginRedirect } }, } function _afterLoginSessionSetup(req, user, callback) { if (callback == null) { callback = function () {} } req.login(user, function (err) { if (err) { OError.tag(err, 'error from req.login', { user_id: user._id, }) return callback(err) } // Regenerate the session to get a new sessionID (cookie value) to // protect against session fixation attacks const oldSession = req.session req.session.destroy(function (err) { if (err) { OError.tag(err, 'error when trying to destroy old session', { user_id: user._id, }) return callback(err) } req.sessionStore.generate(req) // Note: the validation token is not writable, so it does not get // transferred to the new session below. for (const key in oldSession) { const value = oldSession[key] if (key !== '__tmp' && key !== 'csrfSecret') { req.session[key] = value } } req.session.save(function (err) { if (err) { OError.tag(err, 'error saving regenerated session after login', { user_id: user._id, }) return callback(err) } UserSessionsManager.trackSession(user, req.sessionID, function () {}) callback(null) }) }) }) } function _loginAsyncHandlers(req, user) { UserHandler.setupLoginData(user, err => { if (err != null) { logger.warn({ err }, 'error setting up login data') } }) LoginRateLimiter.recordSuccessfulLogin(user.email) AuthenticationController._recordSuccessfulLogin(user._id) AuthenticationController.ipMatchCheck(req, user) Analytics.recordEvent(user._id, 'user-logged-in') Analytics.identifyUser(user._id, req.sessionID) logger.log( { email: user.email, user_id: user._id.toString() }, 'successful log in' ) req.session.justLoggedIn = true // capture the request ip for use when creating the session return (user._login_req_ip = req.ip) } module.exports = AuthenticationController
overleaf/web/app/src/Features/Authentication/AuthenticationController.js/0
{ "file_path": "overleaf/web/app/src/Features/Authentication/AuthenticationController.js", "repo_id": "overleaf", "token_count": 6521 }
479
/* eslint-disable camelcase, node/handle-callback-err, max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let CollaboratorsEmailHandler const { Project } = require('../../models/Project') const EmailHandler = require('../Email/EmailHandler') const Settings = require('@overleaf/settings') module.exports = CollaboratorsEmailHandler = { _buildInviteUrl(project, invite) { return ( `${Settings.siteUrl}/project/${project._id}/invite/token/${invite.token}?` + [ `project_name=${encodeURIComponent(project.name)}`, `user_first_name=${encodeURIComponent(project.owner_ref.first_name)}`, ].join('&') ) }, notifyUserOfProjectInvite(project_id, email, invite, sendingUser, callback) { return Project.findOne({ _id: project_id }) .select('name owner_ref') .populate('owner_ref') .exec(function (err, project) { const emailOptions = { to: email, replyTo: project.owner_ref.email, project: { name: project.name, }, inviteUrl: CollaboratorsEmailHandler._buildInviteUrl(project, invite), owner: project.owner_ref, sendingUser_id: sendingUser._id, } return EmailHandler.sendEmail('projectInvite', emailOptions, callback) }) }, }
overleaf/web/app/src/Features/Collaborators/CollaboratorsEmailHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Collaborators/CollaboratorsEmailHandler.js", "repo_id": "overleaf", "token_count": 602 }
480
/* eslint-disable node/handle-callback-err, max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let CooldownManager const RedisWrapper = require('../../infrastructure/RedisWrapper') const rclient = RedisWrapper.client('cooldown') const logger = require('logger-sharelatex') const COOLDOWN_IN_SECONDS = 60 * 10 module.exports = CooldownManager = { _buildKey(projectId) { return `Cooldown:{${projectId}}` }, putProjectOnCooldown(projectId, callback) { if (callback == null) { callback = function (err) {} } logger.log( { projectId }, `[Cooldown] putting project on cooldown for ${COOLDOWN_IN_SECONDS} seconds` ) return rclient.set( CooldownManager._buildKey(projectId), '1', 'EX', COOLDOWN_IN_SECONDS, callback ) }, isProjectOnCooldown(projectId, callback) { if (callback == null) { callback = function (err, isOnCooldown) {} } return rclient.get( CooldownManager._buildKey(projectId), function (err, result) { if (err != null) { return callback(err) } return callback(null, result === '1') } ) }, }
overleaf/web/app/src/Features/Cooldown/CooldownManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Cooldown/CooldownManager.js", "repo_id": "overleaf", "token_count": 552 }
481
const sanitizeHtml = require('sanitize-html') const sanitizeOptions = { html: { allowedTags: ['span', 'b', 'br', 'i'], allowedAttributes: { span: ['style', 'class'], }, }, plainText: { allowedTags: [], allowedAttributes: {}, }, } function cleanHTML(text, isPlainText) { if (!isPlainText) return sanitizeHtml(text, sanitizeOptions.html) return sanitizeHtml(text, sanitizeOptions.plainText) } function displayLink(text, url, isPlainText) { return isPlainText ? `${text} (${url})` : `<a href="${url}">${text}</a>` } module.exports = { cleanHTML, displayLink, }
overleaf/web/app/src/Features/Email/EmailMessageHelper.js/0
{ "file_path": "overleaf/web/app/src/Features/Email/EmailMessageHelper.js", "repo_id": "overleaf", "token_count": 241 }
482
// eslint-disable-next-line no-useless-escape const EMAIL_REGEXP = /^([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ function getDomain(email) { email = parseEmail(email) return email ? email.split('@').pop() : null } function parseEmail(email) { if (email == null) { return null } if (email.length > 254) { return null } email = email.trim().toLowerCase() const matched = email.match(EMAIL_REGEXP) if (matched == null || matched[0] == null) { return null } return matched[0] } module.exports = { getDomain, parseEmail, }
overleaf/web/app/src/Features/Helpers/EmailHelper.js/0
{ "file_path": "overleaf/web/app/src/Features/Helpers/EmailHelper.js", "repo_id": "overleaf", "token_count": 304 }
483
function emailHasLicence(emailData) { if (!emailData.confirmedAt) { return false } if (!emailData.affiliation) { return false } const affiliation = emailData.affiliation const institution = affiliation.institution if (!institution) { return false } if (!institution.confirmed) { return false } if (!affiliation.licence) { return false } if (affiliation.pastReconfirmDate) { return false } return affiliation.licence !== 'free' } module.exports = { emailHasLicence, }
overleaf/web/app/src/Features/Institutions/InstitutionsHelper.js/0
{ "file_path": "overleaf/web/app/src/Features/Institutions/InstitutionsHelper.js", "repo_id": "overleaf", "token_count": 181 }
484
const PasswordResetHandler = require('./PasswordResetHandler') const AuthenticationController = require('../Authentication/AuthenticationController') const SessionManager = require('../Authentication/SessionManager') const UserGetter = require('../User/UserGetter') const UserUpdater = require('../User/UserUpdater') const UserSessionsManager = require('../User/UserSessionsManager') const OError = require('@overleaf/o-error') const EmailsHelper = require('../Helpers/EmailHelper') const { expressify } = require('../../util/promises') async function setNewUserPassword(req, res, next) { let user let { passwordResetToken, password } = req.body if (!passwordResetToken || !password) { return res.sendStatus(400) } passwordResetToken = passwordResetToken.trim() delete req.session.resetToken const initiatorId = SessionManager.getLoggedInUserId(req.session) // password reset via tokens can be done while logged in, or not const auditLog = { initiatorId, ip: req.ip, } try { const result = await PasswordResetHandler.promises.setNewUserPassword( passwordResetToken, password, auditLog ) const { found, reset, userId } = result if (!found) return res.sendStatus(404) if (!reset) return res.sendStatus(500) await UserSessionsManager.promises.revokeAllUserSessions( { _id: userId }, [] ) await UserUpdater.promises.removeReconfirmFlag(userId) if (!req.session.doLoginAfterPasswordReset) { return res.sendStatus(200) } user = await UserGetter.promises.getUser(userId) } catch (error) { if (error.name === 'NotFoundError') { return res.sendStatus(404) } else if (error.name === 'InvalidPasswordError') { return res.sendStatus(400) } else { return res.sendStatus(500) } } AuthenticationController.finishLogin(user, req, res, next) } module.exports = { renderRequestResetForm(req, res) { res.render('user/passwordReset', { title: 'reset_password' }) }, requestReset(req, res, next) { const email = EmailsHelper.parseEmail(req.body.email) if (!email) { return res.status(400).send({ message: req.i18n.translate('must_be_email_address'), }) } PasswordResetHandler.generateAndEmailResetToken(email, (err, status) => { if (err != null) { OError.tag(err, 'failed to generate and email password reset token', { email, }) next(err) } else if (status === 'primary') { res.status(200).send({ message: { text: req.i18n.translate('password_reset_email_sent') }, }) } else if (status === 'secondary') { res.status(404).send({ message: req.i18n.translate('secondary_email_password_reset'), }) } else { res.status(404).send({ message: req.i18n.translate('cant_find_email'), }) } }) }, renderSetPasswordForm(req, res) { if (req.query.passwordResetToken != null) { req.session.resetToken = req.query.passwordResetToken let emailQuery = '' if (typeof req.query.email === 'string') { const email = EmailsHelper.parseEmail(req.query.email) if (email) { emailQuery = `?email=${encodeURIComponent(email)}` } } return res.redirect('/user/password/set' + emailQuery) } if (req.session.resetToken == null) { return res.redirect('/user/password/reset') } res.render('user/setPassword', { title: 'set_password', passwordResetToken: req.session.resetToken, }) }, setNewUserPassword: expressify(setNewUserPassword), }
overleaf/web/app/src/Features/PasswordReset/PasswordResetController.js/0
{ "file_path": "overleaf/web/app/src/Features/PasswordReset/PasswordResetController.js", "repo_id": "overleaf", "token_count": 1400 }
485
const _ = require('lodash') const OError = require('@overleaf/o-error') const async = require('async') const logger = require('logger-sharelatex') const Settings = require('@overleaf/settings') const Path = require('path') const fs = require('fs') const { Doc } = require('../../models/Doc') const DocstoreManager = require('../Docstore/DocstoreManager') const DocumentUpdaterHandler = require('../../Features/DocumentUpdater/DocumentUpdaterHandler') const Errors = require('../Errors/Errors') const FileStoreHandler = require('../FileStore/FileStoreHandler') const LockManager = require('../../infrastructure/LockManager') const { Project } = require('../../models/Project') const ProjectEntityHandler = require('./ProjectEntityHandler') const ProjectGetter = require('./ProjectGetter') const ProjectLocator = require('./ProjectLocator') const ProjectUpdateHandler = require('./ProjectUpdateHandler') const ProjectEntityMongoUpdateHandler = require('./ProjectEntityMongoUpdateHandler') const SafePath = require('./SafePath') const TpdsUpdateSender = require('../ThirdPartyDataStore/TpdsUpdateSender') const FileWriter = require('../../infrastructure/FileWriter') const EditorRealTimeController = require('../Editor/EditorRealTimeController') const { promisifyAll } = require('../../util/promises') const LOCK_NAMESPACE = 'sequentialProjectStructureUpdateLock' const VALID_ROOT_DOC_EXTENSIONS = Settings.validRootDocExtensions const VALID_ROOT_DOC_REGEXP = new RegExp( `^\\.(${VALID_ROOT_DOC_EXTENSIONS.join('|')})$`, 'i' ) function wrapWithLock(methodWithoutLock) { // This lock is used to make sure that the project structure updates are made // sequentially. In particular the updates must be made in mongo and sent to // the doc-updater in the same order. if (typeof methodWithoutLock === 'function') { const methodWithLock = (projectId, ...rest) => { const adjustedLength = Math.max(rest.length, 1) const args = rest.slice(0, adjustedLength - 1) const callback = rest[adjustedLength - 1] LockManager.runWithLock( LOCK_NAMESPACE, projectId, cb => methodWithoutLock(projectId, ...args, cb), callback ) } methodWithLock.withoutLock = methodWithoutLock return methodWithLock } else { // handle case with separate setup and locked stages const wrapWithSetup = methodWithoutLock.beforeLock // a function to set things up before the lock const mainTask = methodWithoutLock.withLock // function to execute inside the lock const methodWithLock = wrapWithSetup((projectId, ...rest) => { const adjustedLength = Math.max(rest.length, 1) const args = rest.slice(0, adjustedLength - 1) const callback = rest[adjustedLength - 1] LockManager.runWithLock( LOCK_NAMESPACE, projectId, cb => mainTask(projectId, ...args, cb), callback ) }) methodWithLock.withoutLock = wrapWithSetup(mainTask) methodWithLock.beforeLock = methodWithoutLock.beforeLock methodWithLock.mainTask = methodWithoutLock.withLock return methodWithLock } } function getDocContext(projectId, docId, callback) { ProjectGetter.getProject( projectId, { name: true, rootFolder: true }, (err, project) => { if (err) { return callback( OError.tag(err, 'error fetching project', { projectId, }) ) } if (!project) { return callback(new Errors.NotFoundError('project not found')) } ProjectLocator.findElement( { project, element_id: docId, type: 'docs' }, (err, doc, path) => { if (err && err instanceof Errors.NotFoundError) { // (Soft-)Deleted docs are removed from the file-tree (rootFolder). // docstore can tell whether it exists and is (soft)-deleted. DocstoreManager.isDocDeleted( projectId, docId, (err, isDeletedDoc) => { if (err && err instanceof Errors.NotFoundError) { logger.warn( { projectId, docId }, 'doc not found while updating doc lines' ) callback(err) } else if (err) { callback( OError.tag( err, 'error checking deletion status with docstore', { projectId, docId } ) ) } else { if (!isDeletedDoc) { // NOTE: This can happen while we delete a doc: // 1. web will update the projects entry // 2. web triggers flushes to tpds/doc-updater // 3. web triggers (soft)-delete in docstore // Specifically when an update comes in after 1 // and before 3 completes. logger.info( { projectId, docId }, 'updating doc that is in process of getting soft-deleted' ) } callback(null, { projectName: project.name, isDeletedDoc: true, path: null, }) } } ) } else if (err) { callback( OError.tag(err, 'error finding doc in rootFolder', { docId, projectId, }) ) } else { callback(null, { projectName: project.name, isDeletedDoc: false, path: path.fileSystem, }) } } ) } ) } const ProjectEntityUpdateHandler = { updateDocLines( projectId, docId, lines, version, ranges, lastUpdatedAt, lastUpdatedBy, callback ) { getDocContext(projectId, docId, (err, ctx) => { if (err && err instanceof Errors.NotFoundError) { // Do not allow an update to a doc which has never exist on this project logger.warn( { docId, projectId }, 'project or doc not found while updating doc lines' ) return callback(err) } if (err) { return callback(err) } const { projectName, isDeletedDoc, path } = ctx logger.log({ projectId, docId }, 'telling docstore manager to update doc') DocstoreManager.updateDoc( projectId, docId, lines, version, ranges, (err, modified, rev) => { if (err != null) { OError.tag(err, 'error sending doc to docstore', { docId, projectId, }) return callback(err) } logger.log( { projectId, docId, modified }, 'finished updating doc lines' ) // path will only be present if the doc is not deleted if (!modified || isDeletedDoc) { return callback() } // Don't need to block for marking as updated ProjectUpdateHandler.markAsUpdated( projectId, lastUpdatedAt, lastUpdatedBy ) TpdsUpdateSender.addDoc( { project_id: projectId, path, doc_id: docId, project_name: projectName, rev, }, callback ) } ) }) }, setRootDoc(projectId, newRootDocID, callback) { logger.log({ projectId, rootDocId: newRootDocID }, 'setting root doc') if (projectId == null || newRootDocID == null) { return callback( new Errors.InvalidError('missing arguments (project or doc)') ) } ProjectEntityHandler.getDocPathByProjectIdAndDocId( projectId, newRootDocID, (err, docPath) => { if (err != null) { return callback(err) } if (ProjectEntityUpdateHandler.isPathValidForRootDoc(docPath)) { Project.updateOne( { _id: projectId }, { rootDoc_id: newRootDocID }, {}, callback ) } else { callback( new Errors.UnsupportedFileTypeError( 'invalid file extension for root doc' ) ) } } ) }, unsetRootDoc(projectId, callback) { logger.log({ projectId }, 'removing root doc') Project.updateOne( { _id: projectId }, { $unset: { rootDoc_id: true } }, {}, callback ) }, _addDocAndSendToTpds(projectId, folderId, doc, callback) { ProjectEntityMongoUpdateHandler.addDoc( projectId, folderId, doc, (err, result, project) => { if (err != null) { OError.tag(err, 'error adding file with project', { projectId, folderId, doc_name: doc != null ? doc.name : undefined, doc_id: doc != null ? doc._id : undefined, }) return callback(err) } TpdsUpdateSender.addDoc( { project_id: projectId, doc_id: doc != null ? doc._id : undefined, path: result && result.path && result.path.fileSystem, project_name: project.name, rev: 0, }, err => { if (err != null) { return callback(err) } callback(null, result, project) } ) } ) }, addDoc(projectId, folderId, docName, docLines, userId, callback) { ProjectEntityUpdateHandler.addDocWithRanges( projectId, folderId, docName, docLines, {}, userId, callback ) }, addDocWithRanges: wrapWithLock({ beforeLock(next) { return function ( projectId, folderId, docName, docLines, ranges, userId, callback ) { if (!SafePath.isCleanFilename(docName)) { return callback(new Errors.InvalidNameError('invalid element name')) } // Put doc in docstore first, so that if it errors, we don't have a doc_id in the project // which hasn't been created in docstore. const doc = new Doc({ name: docName }) DocstoreManager.updateDoc( projectId.toString(), doc._id.toString(), docLines, 0, ranges, (err, modified, rev) => { if (err != null) { return callback(err) } next( projectId, folderId, doc, docName, docLines, ranges, userId, callback ) } ) } }, withLock( projectId, folderId, doc, docName, docLines, ranges, userId, callback ) { ProjectEntityUpdateHandler._addDocAndSendToTpds( projectId, folderId, doc, (err, result, project) => { if (err != null) { return callback(err) } const docPath = result && result.path && result.path.fileSystem const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id const newDocs = [ { doc, path: docPath, docLines: docLines.join('\n'), }, ] DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, { newDocs, newProject: project }, error => { if (error != null) { return callback(error) } callback(null, doc, folderId) } ) } ) }, }), _uploadFile(projectId, folderId, fileName, fsPath, linkedFileData, callback) { if (!SafePath.isCleanFilename(fileName)) { return callback(new Errors.InvalidNameError('invalid element name')) } const fileArgs = { name: fileName, linkedFileData, } FileStoreHandler.uploadFileFromDisk( projectId, fileArgs, fsPath, (err, fileStoreUrl, fileRef) => { if (err != null) { OError.tag(err, 'error uploading image to s3', { projectId, folderId, file_name: fileName, fileRef, }) return callback(err) } callback(null, fileStoreUrl, fileRef) } ) }, _addFileAndSendToTpds(projectId, folderId, fileRef, callback) { ProjectEntityMongoUpdateHandler.addFile( projectId, folderId, fileRef, (err, result, project) => { if (err != null) { OError.tag(err, 'error adding file with project', { projectId, folderId, file_name: fileRef.name, fileRef, }) return callback(err) } TpdsUpdateSender.addFile( { project_id: projectId, file_id: fileRef._id, path: result && result.path && result.path.fileSystem, project_name: project.name, rev: fileRef.rev, }, err => { if (err != null) { return callback(err) } callback(null, result, project) } ) } ) }, addFile: wrapWithLock({ beforeLock(next) { return function ( projectId, folderId, fileName, fsPath, linkedFileData, userId, callback ) { if (!SafePath.isCleanFilename(fileName)) { return callback(new Errors.InvalidNameError('invalid element name')) } ProjectEntityUpdateHandler._uploadFile( projectId, folderId, fileName, fsPath, linkedFileData, (error, fileStoreUrl, fileRef) => { if (error != null) { return callback(error) } next( projectId, folderId, fileName, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, callback ) } ) } }, withLock( projectId, folderId, fileName, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, callback ) { ProjectEntityUpdateHandler._addFileAndSendToTpds( projectId, folderId, fileRef, (err, result, project) => { if (err != null) { return callback(err) } const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id const newFiles = [ { file: fileRef, path: result && result.path && result.path.fileSystem, url: fileStoreUrl, }, ] DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, { newFiles, newProject: project }, error => { if (error != null) { return callback(error) } ProjectUpdateHandler.markAsUpdated(projectId, new Date(), userId) callback(null, fileRef, folderId) } ) } ) }, }), replaceFile: wrapWithLock({ beforeLock(next) { return function ( projectId, fileId, fsPath, linkedFileData, userId, callback ) { // create a new file const fileArgs = { name: 'dummy-upload-filename', linkedFileData, } FileStoreHandler.uploadFileFromDisk( projectId, fileArgs, fsPath, (err, fileStoreUrl, fileRef) => { if (err != null) { return callback(err) } next( projectId, fileId, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, callback ) } ) } }, withLock( projectId, fileId, fsPath, linkedFileData, userId, newFileRef, fileStoreUrl, callback ) { ProjectEntityMongoUpdateHandler.replaceFileWithNew( projectId, fileId, newFileRef, (err, oldFileRef, project, path, newProject) => { if (err != null) { return callback(err) } const oldFiles = [ { file: oldFileRef, path: path.fileSystem, }, ] const newFiles = [ { file: newFileRef, path: path.fileSystem, url: fileStoreUrl, }, ] const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id // Increment the rev for an in-place update (with the same path) so the third-party-datastore // knows this is a new file. // Ideally we would get this from ProjectEntityMongoUpdateHandler.replaceFileWithNew // but it returns the original oldFileRef (after incrementing the rev value in mongo), // so we add 1 to the rev from that. This isn't atomic and relies on the lock // but it is acceptable for now. TpdsUpdateSender.addFile( { project_id: project._id, file_id: newFileRef._id, path: path.fileSystem, rev: oldFileRef.rev + 1, project_name: project.name, }, err => { if (err != null) { return callback(err) } ProjectUpdateHandler.markAsUpdated(projectId, new Date(), userId) DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, { oldFiles, newFiles, newProject }, callback ) } ) } ) }, }), upsertDoc: wrapWithLock(function ( projectId, folderId, docName, docLines, source, userId, callback ) { if (!SafePath.isCleanFilename(docName)) { return callback(new Errors.InvalidNameError('invalid element name')) } ProjectLocator.findElement( { project_id: projectId, element_id: folderId, type: 'folder' }, (error, folder, folderPath) => { if (error != null) { return callback(error) } if (folder == null) { return callback(new Error("Couldn't find folder")) } const existingDoc = folder.docs.find(({ name }) => name === docName) const existingFile = folder.fileRefs.find( ({ name }) => name === docName ) if (existingFile) { const doc = new Doc({ name: docName }) const filePath = `${folderPath.fileSystem}/${existingFile.name}` DocstoreManager.updateDoc( projectId.toString(), doc._id.toString(), docLines, 0, {}, (err, modified, rev) => { if (err != null) { return callback(err) } ProjectEntityMongoUpdateHandler.replaceFileWithDoc( projectId, existingFile._id, doc, (err, project) => { if (err) { return callback(err) } TpdsUpdateSender.addDoc( { project_id: projectId, doc_id: doc._id, path: filePath, project_name: project.name, rev: existingFile.rev + 1, }, err => { if (err) { return callback(err) } const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id const newDocs = [ { doc, path: filePath, docLines: docLines.join('\n'), }, ] const oldFiles = [ { file: existingFile, path: filePath, }, ] DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, { oldFiles, newDocs, newProject: project }, error => { if (error != null) { return callback(error) } EditorRealTimeController.emitToRoom( projectId, 'removeEntity', existingFile._id, 'convertFileToDoc' ) callback(null, doc, true) } ) } ) } ) } ) } else if (existingDoc) { DocumentUpdaterHandler.setDocument( projectId, existingDoc._id, userId, docLines, source, err => { if (err != null) { return callback(err) } logger.log( { projectId, docId: existingDoc._id }, 'notifying users that the document has been updated' ) DocumentUpdaterHandler.flushDocToMongo( projectId, existingDoc._id, err => { if (err != null) { return callback(err) } callback(null, existingDoc, existingDoc == null) } ) } ) } else { ProjectEntityUpdateHandler.addDocWithRanges.withoutLock( projectId, folderId, docName, docLines, {}, userId, (err, doc) => { if (err != null) { return callback(err) } callback(null, doc, existingDoc == null) } ) } } ) }), upsertFile: wrapWithLock({ beforeLock(next) { return function ( projectId, folderId, fileName, fsPath, linkedFileData, userId, callback ) { if (!SafePath.isCleanFilename(fileName)) { return callback(new Errors.InvalidNameError('invalid element name')) } // create a new file const fileArgs = { name: fileName, linkedFileData, } FileStoreHandler.uploadFileFromDisk( projectId, fileArgs, fsPath, (err, fileStoreUrl, fileRef) => { if (err != null) { return callback(err) } next( projectId, folderId, fileName, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, callback ) } ) } }, withLock( projectId, folderId, fileName, fsPath, linkedFileData, userId, newFileRef, fileStoreUrl, callback ) { ProjectLocator.findElement( { project_id: projectId, element_id: folderId, type: 'folder' }, (error, folder) => { if (error != null) { return callback(error) } if (folder == null) { return callback(new Error("Couldn't find folder")) } const existingFile = folder.fileRefs.find( ({ name }) => name === fileName ) const existingDoc = folder.docs.find(({ name }) => name === fileName) if (existingDoc) { ProjectLocator.findElement( { project_id: projectId, element_id: existingDoc._id, type: 'doc', }, (err, doc, path) => { if (err) { return callback(new Error('coudnt find existing file')) } ProjectEntityMongoUpdateHandler.replaceDocWithFile( projectId, existingDoc._id, newFileRef, (err, project) => { if (err) { return callback(err) } const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id TpdsUpdateSender.addFile( { project_id: project._id, file_id: newFileRef._id, path: path.fileSystem, rev: newFileRef.rev, project_name: project.name, }, err => { if (err) { return callback(err) } DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, { oldDocs: [ { doc: existingDoc, path: path.fileSystem }, ], newFiles: [ { file: newFileRef, path: path.fileSystem, url: fileStoreUrl, }, ], newProject: project, }, err => { if (err) { return callback(err) } EditorRealTimeController.emitToRoom( projectId, 'removeEntity', existingDoc._id, 'convertDocToFile' ) callback(null, newFileRef, true, existingFile) } ) } ) } ) } ) } else if (existingFile) { // this calls directly into the replaceFile main task (without the beforeLock part) return ProjectEntityUpdateHandler.replaceFile.mainTask( projectId, existingFile._id, fsPath, linkedFileData, userId, newFileRef, fileStoreUrl, err => { if (err != null) { return callback(err) } callback(null, newFileRef, existingFile == null, existingFile) } ) } else { // this calls directly into the addFile main task (without the beforeLock part) ProjectEntityUpdateHandler.addFile.mainTask( projectId, folderId, fileName, fsPath, linkedFileData, userId, newFileRef, fileStoreUrl, err => { if (err != null) { return callback(err) } callback(null, newFileRef, existingFile == null, existingFile) } ) } } ) }, }), upsertDocWithPath: wrapWithLock(function ( projectId, elementPath, docLines, source, userId, callback ) { if (!SafePath.isCleanPath(elementPath)) { return callback(new Errors.InvalidNameError('invalid element name')) } const docName = Path.basename(elementPath) const folderPath = Path.dirname(elementPath) ProjectEntityUpdateHandler.mkdirp.withoutLock( projectId, folderPath, (err, newFolders, folder) => { if (err != null) { return callback(err) } ProjectEntityUpdateHandler.upsertDoc.withoutLock( projectId, folder._id, docName, docLines, source, userId, (err, doc, isNewDoc) => { if (err != null) { return callback(err) } callback(null, doc, isNewDoc, newFolders, folder) } ) } ) }), upsertFileWithPath: wrapWithLock({ beforeLock(next) { return function ( projectId, elementPath, fsPath, linkedFileData, userId, callback ) { if (!SafePath.isCleanPath(elementPath)) { return callback(new Errors.InvalidNameError('invalid element name')) } const fileName = Path.basename(elementPath) const folderPath = Path.dirname(elementPath) // create a new file const fileArgs = { name: fileName, linkedFileData, } FileStoreHandler.uploadFileFromDisk( projectId, fileArgs, fsPath, (err, fileStoreUrl, fileRef) => { if (err != null) { return callback(err) } next( projectId, folderPath, fileName, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, callback ) } ) } }, withLock( projectId, folderPath, fileName, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, callback ) { ProjectEntityUpdateHandler.mkdirp.withoutLock( projectId, folderPath, (err, newFolders, folder) => { if (err != null) { return callback(err) } // this calls directly into the upsertFile main task (without the beforeLock part) ProjectEntityUpdateHandler.upsertFile.mainTask( projectId, folder._id, fileName, fsPath, linkedFileData, userId, fileRef, fileStoreUrl, (err, newFile, isNewFile, existingFile) => { if (err != null) { return callback(err) } callback( null, newFile, isNewFile, existingFile, newFolders, folder ) } ) } ) }, }), deleteEntity: wrapWithLock(function ( projectId, entityId, entityType, userId, callback ) { logger.log({ entityId, entityType, projectId }, 'deleting project entity') if (entityType == null) { logger.warn({ err: 'No entityType set', projectId, entityId }) return callback(new Error('No entityType set')) } entityType = entityType.toLowerCase() ProjectEntityMongoUpdateHandler.deleteEntity( projectId, entityId, entityType, (error, entity, path, projectBeforeDeletion, newProject) => { if (error != null) { return callback(error) } ProjectEntityUpdateHandler._cleanUpEntity( projectBeforeDeletion, newProject, entity, entityType, path.fileSystem, userId, error => { if (error != null) { return callback(error) } TpdsUpdateSender.deleteEntity( { project_id: projectId, path: path.fileSystem, project_name: projectBeforeDeletion.name, }, error => { if (error != null) { return callback(error) } callback(null, entityId) } ) } ) } ) }), deleteEntityWithPath: wrapWithLock((projectId, path, userId, callback) => ProjectLocator.findElementByPath( { project_id: projectId, path }, (err, element, type) => { if (err != null) { return callback(err) } if (element == null) { return callback(new Errors.NotFoundError('project not found')) } ProjectEntityUpdateHandler.deleteEntity.withoutLock( projectId, element._id, type, userId, callback ) } ) ), mkdirp: wrapWithLock(function (projectId, path, callback) { for (const folder of path.split('/')) { if (folder.length > 0 && !SafePath.isCleanFilename(folder)) { return callback(new Errors.InvalidNameError('invalid element name')) } } ProjectEntityMongoUpdateHandler.mkdirp( projectId, path, { exactCaseMatch: false }, callback ) }), mkdirpWithExactCase: wrapWithLock(function (projectId, path, callback) { for (const folder of path.split('/')) { if (folder.length > 0 && !SafePath.isCleanFilename(folder)) { return callback(new Errors.InvalidNameError('invalid element name')) } } ProjectEntityMongoUpdateHandler.mkdirp( projectId, path, { exactCaseMatch: true }, callback ) }), addFolder: wrapWithLock(function ( projectId, parentFolderId, folderName, callback ) { if (!SafePath.isCleanFilename(folderName)) { return callback(new Errors.InvalidNameError('invalid element name')) } ProjectEntityMongoUpdateHandler.addFolder( projectId, parentFolderId, folderName, callback ) }), moveEntity: wrapWithLock(function ( projectId, entityId, destFolderId, entityType, userId, callback ) { logger.log( { entityType, entityId, projectId, destFolderId }, 'moving entity' ) if (entityType == null) { logger.warn({ err: 'No entityType set', projectId, entityId }) return callback(new Error('No entityType set')) } entityType = entityType.toLowerCase() ProjectEntityMongoUpdateHandler.moveEntity( projectId, entityId, destFolderId, entityType, (err, project, startPath, endPath, rev, changes) => { if (err != null) { return callback(err) } const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id // do not wait TpdsUpdateSender.promises .moveEntity({ project_id: projectId, project_name: project.name, startPath, endPath, rev, }) .catch(err => { logger.error({ err }, 'error sending tpds update') }) DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, changes, callback ) } ) }), renameEntity: wrapWithLock(function ( projectId, entityId, entityType, newName, userId, callback ) { if (!SafePath.isCleanFilename(newName)) { return callback(new Errors.InvalidNameError('invalid element name')) } logger.log({ entityId, projectId }, `renaming ${entityType}`) if (entityType == null) { logger.warn({ err: 'No entityType set', projectId, entityId }) return callback(new Error('No entityType set')) } entityType = entityType.toLowerCase() ProjectEntityMongoUpdateHandler.renameEntity( projectId, entityId, entityType, newName, (err, project, startPath, endPath, rev, changes) => { if (err != null) { return callback(err) } const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id // do not wait TpdsUpdateSender.promises .moveEntity({ project_id: projectId, project_name: project.name, startPath, endPath, rev, }) .catch(err => { logger.error({ err }, 'error sending tpds update') }) DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, changes, callback ) } ) }), // This doesn't directly update project structure but we need to take the lock // to prevent anything else being queued before the resync update resyncProjectHistory: wrapWithLock((projectId, callback) => ProjectGetter.getProject( projectId, { rootFolder: true, overleaf: true }, (error, project) => { if (error != null) { return callback(error) } const projectHistoryId = project && project.overleaf && project.overleaf.history && project.overleaf.history.id if (projectHistoryId == null) { error = new Errors.ProjectHistoryDisabledError( `project history not enabled for ${projectId}` ) return callback(error) } ProjectEntityHandler.getAllEntitiesFromProject( project, (error, docs, files) => { if (error != null) { return callback(error) } docs = _.map(docs, doc => ({ doc: doc.doc._id, path: doc.path, })) files = _.map(files, file => ({ file: file.file._id, path: file.path, url: FileStoreHandler._buildUrl(projectId, file.file._id), })) DocumentUpdaterHandler.resyncProjectHistory( projectId, projectHistoryId, docs, files, callback ) } ) } ) ), isPathValidForRootDoc(docPath) { const docExtension = Path.extname(docPath) return VALID_ROOT_DOC_REGEXP.test(docExtension) }, _cleanUpEntity( project, newProject, entity, entityType, path, userId, callback ) { ProjectEntityUpdateHandler._updateProjectStructureWithDeletedEntity( project, newProject, entity, entityType, path, userId, error => { if (error != null) { return callback(error) } if (entityType.indexOf('file') !== -1) { ProjectEntityUpdateHandler._cleanUpFile( project, entity, path, userId, callback ) } else if (entityType.indexOf('doc') !== -1) { ProjectEntityUpdateHandler._cleanUpDoc( project, entity, path, userId, callback ) } else if (entityType.indexOf('folder') !== -1) { ProjectEntityUpdateHandler._cleanUpFolder( project, entity, path, userId, callback ) } else { callback() } } ) }, // Note: the _cleanUpEntity code and _updateProjectStructureWithDeletedEntity // methods both need to recursively iterate over the entities in folder. // These are currently using separate implementations of the recursion. In // future, these could be simplified using a common project entity iterator. _updateProjectStructureWithDeletedEntity( project, newProject, entity, entityType, entityPath, userId, callback ) { // compute the changes to the project structure let changes if (entityType.indexOf('file') !== -1) { changes = { oldFiles: [{ file: entity, path: entityPath }] } } else if (entityType.indexOf('doc') !== -1) { changes = { oldDocs: [{ doc: entity, path: entityPath }] } } else if (entityType.indexOf('folder') !== -1) { changes = { oldDocs: [], oldFiles: [] } const _recurseFolder = (folder, folderPath) => { for (const doc of folder.docs) { changes.oldDocs.push({ doc, path: Path.join(folderPath, doc.name) }) } for (const file of folder.fileRefs) { changes.oldFiles.push({ file, path: Path.join(folderPath, file.name), }) } for (const childFolder of folder.folders) { _recurseFolder(childFolder, Path.join(folderPath, childFolder.name)) } } _recurseFolder(entity, entityPath) } // now send the project structure changes to the docupdater changes.newProject = newProject const projectId = project._id.toString() const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, changes, callback ) }, _cleanUpDoc(project, doc, path, userId, callback) { const projectId = project._id.toString() const docId = doc._id.toString() const unsetRootDocIfRequired = callback => { if ( project.rootDoc_id != null && project.rootDoc_id.toString() === docId ) { ProjectEntityUpdateHandler.unsetRootDoc(projectId, callback) } else { callback() } } unsetRootDocIfRequired(error => { if (error != null) { return callback(error) } const { name } = doc const deletedAt = new Date() DocstoreManager.deleteDoc(projectId, docId, name, deletedAt, error => { if (error) { return callback(error) } DocumentUpdaterHandler.deleteDoc(projectId, docId, callback) }) }) }, _cleanUpFile(project, file, path, userId, callback) { ProjectEntityMongoUpdateHandler._insertDeletedFileReference( project._id, file, callback ) }, _cleanUpFolder(project, folder, folderPath, userId, callback) { const jobs = [] folder.docs.forEach(doc => { const docPath = Path.join(folderPath, doc.name) jobs.push(callback => ProjectEntityUpdateHandler._cleanUpDoc( project, doc, docPath, userId, callback ) ) }) folder.fileRefs.forEach(file => { const filePath = Path.join(folderPath, file.name) jobs.push(callback => ProjectEntityUpdateHandler._cleanUpFile( project, file, filePath, userId, callback ) ) }) folder.folders.forEach(childFolder => { folderPath = Path.join(folderPath, childFolder.name) jobs.push(callback => ProjectEntityUpdateHandler._cleanUpFolder( project, childFolder, folderPath, userId, callback ) ) }) async.series(jobs, callback) }, convertDocToFile: wrapWithLock({ beforeLock(next) { return function (projectId, docId, userId, callback) { DocumentUpdaterHandler.flushDocToMongo(projectId, docId, err => { if (err) { return callback(err) } ProjectLocator.findElement( { project_id: projectId, element_id: docId, type: 'doc' }, (err, doc, path) => { const docPath = path.fileSystem if (err) { return callback(err) } DocstoreManager.getDoc( projectId, docId, (err, docLines, rev, version, ranges) => { if (err) { return callback(err) } if (!_.isEmpty(ranges)) { return callback(new Errors.DocHasRangesError({})) } DocumentUpdaterHandler.deleteDoc(projectId, docId, err => { if (err) { return callback(err) } FileWriter.writeLinesToDisk( projectId, docLines, (err, fsPath) => { if (err) { return callback(err) } FileStoreHandler.uploadFileFromDisk( projectId, { name: doc.name, rev: rev + 1 }, fsPath, (err, fileStoreUrl, fileRef) => { if (err) { return callback(err) } fs.unlink(fsPath, err => { if (err) { logger.warn( { err, path: fsPath }, 'failed to clean up temporary file' ) } next( projectId, doc, docPath, fileRef, fileStoreUrl, userId, callback ) }) } ) } ) }) } ) } ) }) } }, withLock(projectId, doc, path, fileRef, fileStoreUrl, userId, callback) { ProjectEntityMongoUpdateHandler.replaceDocWithFile( projectId, doc._id, fileRef, (err, project) => { if (err) { return callback(err) } const projectHistoryId = project.overleaf && project.overleaf.history && project.overleaf.history.id DocumentUpdaterHandler.updateProjectStructure( projectId, projectHistoryId, userId, { oldDocs: [{ doc, path }], newFiles: [{ file: fileRef, path, url: fileStoreUrl }], newProject: project, }, err => { if (err) { return callback(err) } ProjectLocator.findElement( { project_id: projectId, element_id: fileRef._id, type: 'file', }, (err, element, path, folder) => { if (err) { return callback(err) } EditorRealTimeController.emitToRoom( projectId, 'removeEntity', doc._id, 'convertDocToFile' ) EditorRealTimeController.emitToRoom( projectId, 'reciveNewFile', folder._id, fileRef, 'convertDocToFile', null, userId ) callback(null, fileRef) } ) } ) } ) }, }), } module.exports = ProjectEntityUpdateHandler module.exports.promises = promisifyAll(ProjectEntityUpdateHandler, { without: ['isPathValidForRootDoc'], multiResult: { _addDocAndSendToTpds: ['result', 'project'], addDoc: ['doc', 'folderId'], addDocWithRanges: ['doc', 'folderId'], _uploadFile: ['fileStoreUrl', 'fileRef'], _addFileAndSendToTpds: ['result', 'project'], addFile: ['fileRef', 'folderId'], upsertDoc: ['doc', 'isNew'], upsertFile: ['fileRef', 'isNew', 'oldFileRef'], upsertDocWithPath: ['doc', 'isNew', 'newFolders', 'folder'], upsertFileWithPath: ['fileRef', 'isNew', 'oldFile', 'newFolders', 'folder'], mkdirp: ['newFolders', 'folder'], mkdirpWithExactCase: ['newFolders', 'folder'], addFolder: ['folder', 'parentFolderId'], }, })
overleaf/web/app/src/Features/Project/ProjectEntityUpdateHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/ProjectEntityUpdateHandler.js", "repo_id": "overleaf", "token_count": 26746 }
486
/* eslint-disable node/handle-callback-err, max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * 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 ReferencesHandler const OError = require('@overleaf/o-error') const logger = require('logger-sharelatex') const request = require('request') const settings = require('@overleaf/settings') const Features = require('../../infrastructure/Features') const ProjectGetter = require('../Project/ProjectGetter') const UserGetter = require('../User/UserGetter') const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler') const _ = require('underscore') const Async = require('async') const oneMinInMs = 60 * 1000 const fiveMinsInMs = oneMinInMs * 5 if (!Features.hasFeature('references')) { logger.log('references search not enabled') } module.exports = ReferencesHandler = { _buildDocUrl(projectId, docId) { return `${settings.apis.docstore.url}/project/${projectId}/doc/${docId}/raw` }, _buildFileUrl(projectId, fileId) { return `${settings.apis.filestore.url}/project/${projectId}/file/${fileId}` }, _findBibFileIds(project) { const ids = [] var _process = function (folder) { _.each(folder.fileRefs || [], function (file) { if ( __guard__(file != null ? file.name : undefined, x1 => x1.match(/^.*\.bib$/) ) ) { return ids.push(file._id) } }) return _.each(folder.folders || [], folder => _process(folder)) } _.each(project.rootFolder || [], rootFolder => _process(rootFolder)) return ids }, _findBibDocIds(project) { const ids = [] var _process = function (folder) { _.each(folder.docs || [], function (doc) { if ( __guard__(doc != null ? doc.name : undefined, x1 => x1.match(/^.*\.bib$/) ) ) { return ids.push(doc._id) } }) return _.each(folder.folders || [], folder => _process(folder)) } _.each(project.rootFolder || [], rootFolder => _process(rootFolder)) return ids }, _isFullIndex(project, callback) { if (callback == null) { callback = function (err, result) {} } return UserGetter.getUser( project.owner_ref, { features: true }, function (err, owner) { if (err != null) { return callback(err) } const features = owner != null ? owner.features : undefined return callback( null, (features != null ? features.references : undefined) === true || (features != null ? features.referencesSearch : undefined) === true ) } ) }, indexAll(projectId, callback) { if (callback == null) { callback = function (err, data) {} } return ProjectGetter.getProject( projectId, { rootFolder: true, owner_ref: 1 }, function (err, project) { if (err) { OError.tag(err, 'error finding project', { projectId, }) return callback(err) } logger.log({ projectId }, 'indexing all bib files in project') const docIds = ReferencesHandler._findBibDocIds(project) const fileIds = ReferencesHandler._findBibFileIds(project) return ReferencesHandler._doIndexOperation( projectId, project, docIds, fileIds, callback ) } ) }, index(projectId, docIds, callback) { if (callback == null) { callback = function (err, data) {} } return ProjectGetter.getProject( projectId, { rootFolder: true, owner_ref: 1 }, function (err, project) { if (err) { OError.tag(err, 'error finding project', { projectId, }) return callback(err) } return ReferencesHandler._doIndexOperation( projectId, project, docIds, [], callback ) } ) }, _doIndexOperation(projectId, project, docIds, fileIds, callback) { if (!Features.hasFeature('references')) { return callback() } return ReferencesHandler._isFullIndex(project, function (err, isFullIndex) { if (err) { OError.tag(err, 'error checking whether to do full index', { projectId, }) return callback(err) } logger.log( { projectId, docIds }, 'flushing docs to mongo before calling references service' ) return Async.series( docIds.map(docId => cb => DocumentUpdaterHandler.flushDocToMongo(projectId, docId, cb) ), function (err) { // continue if (err) { OError.tag(err, 'error flushing docs to mongo', { projectId, docIds, }) return callback(err) } const bibDocUrls = docIds.map(docId => ReferencesHandler._buildDocUrl(projectId, docId) ) const bibFileUrls = fileIds.map(fileId => ReferencesHandler._buildFileUrl(projectId, fileId) ) const allUrls = bibDocUrls.concat(bibFileUrls) return request.post( { url: `${settings.apis.references.url}/project/${projectId}/index`, json: { docUrls: allUrls, fullIndex: isFullIndex, }, }, function (err, res, data) { if (err) { OError.tag(err, 'error communicating with references api', { projectId, }) return callback(err) } if (res.statusCode >= 200 && res.statusCode < 300) { logger.log({ projectId }, 'got keys from references api') return callback(null, data) } else { err = new Error( `references api responded with non-success code: ${res.statusCode}` ) return callback(err) } } ) } ) }) }, } function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/app/src/Features/References/ReferencesHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/References/ReferencesHandler.js", "repo_id": "overleaf", "token_count": 3012 }
487
const Errors = require('../Errors/Errors') class RecurlyTransactionError extends Errors.BackwardCompatibleError { constructor(options) { super({ message: 'Unknown transaction error', ...options, }) } } module.exports = { RecurlyTransactionError, }
overleaf/web/app/src/Features/Subscription/Errors.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/Errors.js", "repo_id": "overleaf", "token_count": 93 }
488
const { db, ObjectId } = require('../../infrastructure/mongodb') const OError = require('@overleaf/o-error') const async = require('async') const { promisify, callbackify } = require('../../util/promises') const { Subscription } = require('../../models/Subscription') const SubscriptionLocator = require('./SubscriptionLocator') const UserGetter = require('../User/UserGetter') const PlansLocator = require('./PlansLocator') const FeaturesUpdater = require('./FeaturesUpdater') const AnalyticsManager = require('../Analytics/AnalyticsManager') const { DeletedSubscription } = require('../../models/DeletedSubscription') const logger = require('logger-sharelatex') /** * Change the admin of the given subscription. * * If the subscription is a group, add the new admin as manager while keeping * the old admin. Otherwise, replace the manager. * * Validation checks are assumed to have been made: * * subscription exists * * user exists * * user does not have another subscription * * subscription is not a Recurly subscription * * If the subscription is Recurly, we silently do nothing. */ function updateAdmin(subscription, adminId, callback) { const query = { _id: ObjectId(subscription._id), customAccount: true, } const update = { $set: { admin_id: ObjectId(adminId) }, } if (subscription.groupPlan) { update.$addToSet = { manager_ids: ObjectId(adminId) } } else { update.$set.manager_ids = [ObjectId(adminId)] } Subscription.updateOne(query, update, callback) } function syncSubscription( recurlySubscription, adminUserId, requesterData, callback ) { if (!callback) { callback = requesterData requesterData = {} } SubscriptionLocator.getUsersSubscription( adminUserId, function (err, subscription) { if (err != null) { return callback(err) } if (subscription != null) { updateSubscriptionFromRecurly( recurlySubscription, subscription, requesterData, callback ) } else { _createNewSubscription(adminUserId, function (err, subscription) { if (err != null) { return callback(err) } updateSubscriptionFromRecurly( recurlySubscription, subscription, requesterData, callback ) }) } } ) } function addUserToGroup(subscriptionId, userId, callback) { Subscription.updateOne( { _id: subscriptionId }, { $addToSet: { member_ids: userId } }, function (err) { if (err != null) { return callback(err) } FeaturesUpdater.refreshFeatures(userId, 'add-to-group', function () { callbackify(_sendUserGroupPlanCodeUserProperty)(userId, callback) }) } ) } function removeUserFromGroup(subscriptionId, userId, callback) { Subscription.updateOne( { _id: subscriptionId }, { $pull: { member_ids: userId } }, function (error) { if (error) { OError.tag(error, 'error removing user from group', { subscriptionId, userId, }) return callback(error) } UserGetter.getUser(userId, function (error, user) { if (error) { return callback(error) } FeaturesUpdater.refreshFeatures( userId, 'remove-user-from-group', function () { callbackify(_sendUserGroupPlanCodeUserProperty)(userId, callback) } ) }) } ) } function removeUserFromAllGroups(userId, callback) { SubscriptionLocator.getMemberSubscriptions( userId, function (error, subscriptions) { if (error) { return callback(error) } if (!subscriptions) { return callback() } const subscriptionIds = subscriptions.map(sub => sub._id) const removeOperation = { $pull: { member_ids: userId } } Subscription.updateMany( { _id: subscriptionIds }, removeOperation, function (error) { if (error) { OError.tag(error, 'error removing user from groups', { userId, subscriptionIds, }) return callback(error) } UserGetter.getUser(userId, function (error, user) { if (error) { return callback(error) } FeaturesUpdater.refreshFeatures( userId, 'remove-user-from-groups', function () { callbackify(_sendUserGroupPlanCodeUserProperty)( userId, callback ) } ) }) } ) } ) } function deleteWithV1Id(v1TeamId, callback) { Subscription.deleteOne({ 'overleaf.id': v1TeamId }, callback) } function deleteSubscription(subscription, deleterData, callback) { if (callback == null) { callback = function () {} } async.series( [ cb => // 1. create deletedSubscription createDeletedSubscription(subscription, deleterData, cb), cb => // 2. remove subscription Subscription.deleteOne({ _id: subscription._id }, cb), cb => // 3. refresh users features refreshUsersFeatures(subscription, cb), ], callback ) } function restoreSubscription(subscriptionId, callback) { SubscriptionLocator.getDeletedSubscription( subscriptionId, function (err, deletedSubscription) { if (err) { return callback(err) } const subscription = deletedSubscription.subscription async.series( [ cb => // 1. upsert subscription db.subscriptions.updateOne( { _id: subscription._id }, subscription, { upsert: true }, cb ), cb => // 2. refresh users features. Do this before removing the // subscription so the restore can be retried if this fails refreshUsersFeatures(subscription, cb), cb => // 3. remove deleted subscription DeletedSubscription.deleteOne( { 'subscription._id': subscription._id }, callback ), ], callback ) } ) } function refreshUsersFeatures(subscription, callback) { const userIds = [subscription.admin_id].concat(subscription.member_ids || []) async.mapSeries( userIds, function (userId, cb) { FeaturesUpdater.refreshFeatures(userId, 'subscription-updater', cb) }, callback ) } function createDeletedSubscription(subscription, deleterData, callback) { subscription.teamInvites = [] subscription.invited_emails = [] const filter = { 'subscription._id': subscription._id } const data = { deleterData: { deleterId: deleterData.id, deleterIpAddress: deleterData.ip, }, subscription: subscription, } const options = { upsert: true, new: true, setDefaultsOnInsert: true } DeletedSubscription.findOneAndUpdate(filter, data, options, callback) } function _createNewSubscription(adminUserId, callback) { const subscription = new Subscription({ admin_id: adminUserId, manager_ids: [adminUserId], }) subscription.save(err => callback(err, subscription)) } function _deleteAndReplaceSubscriptionFromRecurly( recurlySubscription, subscription, requesterData, callback ) { const adminUserId = subscription.admin_id deleteSubscription(subscription, requesterData, err => { if (err) { return callback(err) } _createNewSubscription(adminUserId, (err, newSubscription) => { if (err) { return callback(err) } updateSubscriptionFromRecurly( recurlySubscription, newSubscription, requesterData, callback ) }) }) } function updateSubscriptionFromRecurly( recurlySubscription, subscription, requesterData, callback ) { if (recurlySubscription.state === 'expired') { return deleteSubscription(subscription, requesterData, callback) } const updatedPlanCode = recurlySubscription.plan.plan_code const plan = PlansLocator.findLocalPlanInSettings(updatedPlanCode) if (plan == null) { return callback(new Error(`plan code not found: ${updatedPlanCode}`)) } if (!plan.groupPlan && subscription.groupPlan) { // If downgrading from group to individual plan, delete group sub and create a new one return _deleteAndReplaceSubscriptionFromRecurly( recurlySubscription, subscription, requesterData, callback ) } subscription.recurlySubscription_id = recurlySubscription.uuid subscription.planCode = updatedPlanCode if (plan.groupPlan) { if (!subscription.groupPlan) { subscription.member_ids = subscription.member_ids || [] subscription.member_ids.push(subscription.admin_id) } subscription.groupPlan = true subscription.membersLimit = plan.membersLimit // Some plans allow adding more seats than the base plan provides. // This is recorded as a subscription add on. if ( plan.membersLimitAddOn && Array.isArray(recurlySubscription.subscription_add_ons) ) { recurlySubscription.subscription_add_ons.forEach(addOn => { if (addOn.add_on_code === plan.membersLimitAddOn) { subscription.membersLimit += addOn.quantity } }) } } subscription.save(function (error) { if (error) { return callback(error) } refreshUsersFeatures(subscription, callback) }) } async function _sendUserGroupPlanCodeUserProperty(userId) { try { const subscriptions = (await SubscriptionLocator.promises.getMemberSubscriptions(userId)) || [] let bestPlanCode = null let bestFeatures = {} for (const subscription of subscriptions) { const plan = PlansLocator.findLocalPlanInSettings(subscription.planCode) if ( plan && FeaturesUpdater.isFeatureSetBetter(plan.features, bestFeatures) ) { bestPlanCode = plan.planCode bestFeatures = plan.features } } AnalyticsManager.setUserProperty( userId, 'group-subscription-plan-code', bestPlanCode ) } catch (error) { logger.error( { err: error }, `Failed to update group-subscription-plan-code property for user ${userId}` ) } } module.exports = { updateAdmin, syncSubscription, deleteSubscription, createDeletedSubscription, addUserToGroup, refreshUsersFeatures, removeUserFromGroup, removeUserFromAllGroups, deleteWithV1Id, restoreSubscription, updateSubscriptionFromRecurly, promises: { updateAdmin: promisify(updateAdmin), syncSubscription: promisify(syncSubscription), addUserToGroup: promisify(addUserToGroup), refreshUsersFeatures: promisify(refreshUsersFeatures), removeUserFromGroup: promisify(removeUserFromGroup), removeUserFromAllGroups: promisify(removeUserFromAllGroups), deleteSubscription: promisify(deleteSubscription), createDeletedSubscription: promisify(createDeletedSubscription), deleteWithV1Id: promisify(deleteWithV1Id), restoreSubscription: promisify(restoreSubscription), updateSubscriptionFromRecurly: promisify(updateSubscriptionFromRecurly), }, }
overleaf/web/app/src/Features/Subscription/SubscriptionUpdater.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionUpdater.js", "repo_id": "overleaf", "token_count": 4499 }
489
const { callbackify } = require('util') const logger = require('logger-sharelatex') const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler') const ProjectGetter = require('../Project/ProjectGetter') const ProjectEntityHandler = require('../Project/ProjectEntityHandler') const { Project } = require('../../models/Project') const TpdsUpdateSender = require('./TpdsUpdateSender') module.exports = { flushProjectToTpds: callbackify(flushProjectToTpds), deferProjectFlushToTpds: callbackify(deferProjectFlushToTpds), flushProjectToTpdsIfNeeded: callbackify(flushProjectToTpdsIfNeeded), promises: { flushProjectToTpds, deferProjectFlushToTpds, flushProjectToTpdsIfNeeded, }, } /** * Flush a complete project to the TPDS. */ async function flushProjectToTpds(projectId) { const project = await ProjectGetter.promises.getProject(projectId, { name: true, deferredTpdsFlushCounter: true, }) await _flushProjectToTpds(project) } /** * Flush a project to TPDS if a flush is pending */ async function flushProjectToTpdsIfNeeded(projectId) { const project = await ProjectGetter.promises.getProject(projectId, { name: true, deferredTpdsFlushCounter: true, }) if (project.deferredTpdsFlushCounter > 0) { await _flushProjectToTpds(project) } } async function _flushProjectToTpds(project) { logger.debug({ projectId: project._id }, 'flushing project to TPDS') logger.debug({ projectId: project._id }, 'finished flushing project to TPDS') await DocumentUpdaterHandler.promises.flushProjectToMongo(project._id) const [docs, files] = await Promise.all([ ProjectEntityHandler.promises.getAllDocs(project._id), ProjectEntityHandler.promises.getAllFiles(project._id), ]) for (const [docPath, doc] of Object.entries(docs)) { await TpdsUpdateSender.promises.addDoc({ project_id: project._id, doc_id: doc._id, path: docPath, project_name: project.name, rev: doc.rev || 0, }) } for (const [filePath, file] of Object.entries(files)) { await TpdsUpdateSender.promises.addFile({ project_id: project._id, file_id: file._id, path: filePath, project_name: project.name, rev: file.rev, }) } await _resetDeferredTpdsFlushCounter(project) } /** * Reset the TPDS pending flush counter. * * To avoid concurrency problems, the flush counter is not reset if it has been * incremented since we fetched it from the database. */ async function _resetDeferredTpdsFlushCounter(project) { if (project.deferredTpdsFlushCounter > 0) { await Project.updateOne( { _id: project._id, deferredTpdsFlushCounter: { $lte: project.deferredTpdsFlushCounter }, }, { $set: { deferredTpdsFlushCounter: 0 } } ).exec() } } /** * Mark a project as pending a flush to TPDS. */ async function deferProjectFlushToTpds(projectId) { await Project.updateOne( { _id: projectId }, { $inc: { deferredTpdsFlushCounter: 1 } } ).exec() }
overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsProjectFlusher.js/0
{ "file_path": "overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsProjectFlusher.js", "repo_id": "overleaf", "token_count": 1095 }
490
const APP_ROOT = '../../../../app/src' const UserAuditLogHandler = require(`${APP_ROOT}/Features/User/UserAuditLogHandler`) const EmailHandler = require(`${APP_ROOT}/Features/Email/EmailHandler`) const EmailOptionsHelper = require(`${APP_ROOT}/Features/Email/EmailOptionsHelper`) const Errors = require('../Errors/Errors') const _ = require('lodash') const logger = require('logger-sharelatex') const OError = require('@overleaf/o-error') const settings = require('@overleaf/settings') const { User } = require(`${APP_ROOT}/models/User`) const { promisifyAll } = require(`${APP_ROOT}/util/promises`) const oauthProviders = settings.oauthProviders || {} function getUser(providerId, externalUserId, callback) { if (providerId == null || externalUserId == null) { return callback( new OError('invalid SSO arguments', { externalUserId, providerId, }) ) } const query = _getUserQuery(providerId, externalUserId) User.findOne(query, function (err, user) { if (err != null) { return callback(err) } if (!user) { return callback(new Errors.ThirdPartyUserNotFoundError()) } callback(null, user) }) } function login(providerId, externalUserId, externalData, callback) { ThirdPartyIdentityManager.getUser( providerId, externalUserId, function (err, user) { if (err != null) { return callback(err) } if (!externalData) { return callback(null, user) } const query = _getUserQuery(providerId, externalUserId) const update = _thirdPartyIdentifierUpdate( user, providerId, externalUserId, externalData ) User.findOneAndUpdate(query, update, { new: true }, callback) } ) } function link( userId, providerId, externalUserId, externalData, auditLog, callback, retry ) { const accountLinked = true if (!oauthProviders[providerId]) { return callback(new Error('Not a valid provider')) } UserAuditLogHandler.addEntry( userId, 'link-sso', auditLog.initiatorId, auditLog.ipAddress, { providerId, }, error => { if (error) { return callback(error) } const query = { _id: userId, 'thirdPartyIdentifiers.providerId': { $ne: providerId, }, } const update = { $push: { thirdPartyIdentifiers: { externalUserId, externalData, providerId, }, }, } // add new tpi only if an entry for the provider does not exist // projection includes thirdPartyIdentifiers for tests User.findOneAndUpdate(query, update, { new: 1 }, (err, res) => { if (err && err.code === 11000) { callback(new Errors.ThirdPartyIdentityExistsError()) } else if (err != null) { callback(err) } else if (res) { _sendSecurityAlert(accountLinked, providerId, res, userId) callback(null, res) } else if (retry) { // if already retried then throw error callback(new Error('update failed')) } else { // attempt to clear existing entry then retry ThirdPartyIdentityManager.unlink( userId, providerId, auditLog, function (err) { if (err != null) { return callback(err) } ThirdPartyIdentityManager.link( userId, providerId, externalUserId, externalData, auditLog, callback, true ) } ) } }) } ) } function unlink(userId, providerId, auditLog, callback) { const accountLinked = false if (!oauthProviders[providerId]) { return callback(new Error('Not a valid provider')) } UserAuditLogHandler.addEntry( userId, 'unlink-sso', auditLog.initiatorId, auditLog.ipAddress, { providerId, }, error => { if (error) { return callback(error) } const query = { _id: userId, } const update = { $pull: { thirdPartyIdentifiers: { providerId, }, }, } // projection includes thirdPartyIdentifiers for tests User.findOneAndUpdate(query, update, { new: 1 }, (err, res) => { if (err != null) { callback(err) } else if (!res) { callback(new Error('update failed')) } else { // no need to wait, errors are logged and not passed back _sendSecurityAlert(accountLinked, providerId, res, userId) callback(null, res) } }) } ) } function _getUserQuery(providerId, externalUserId) { externalUserId = externalUserId.toString() providerId = providerId.toString() const query = { 'thirdPartyIdentifiers.externalUserId': externalUserId, 'thirdPartyIdentifiers.providerId': providerId, } return query } function _sendSecurityAlert(accountLinked, providerId, user, userId) { const providerName = oauthProviders[providerId].name const emailOptions = EmailOptionsHelper.linkOrUnlink( accountLinked, providerName, user.email ) EmailHandler.sendEmail('securityAlert', emailOptions, error => { if (error) { logger.error( { err: error, userId }, `could not send security alert email when ${emailOptions.action}` ) } }) } function _thirdPartyIdentifierUpdate( user, providerId, externalUserId, externalData ) { providerId = providerId.toString() // get third party identifier object from array const thirdPartyIdentifier = user.thirdPartyIdentifiers.find( tpi => tpi.externalUserId === externalUserId && tpi.providerId === providerId ) // do recursive merge of new data over existing data _.merge(thirdPartyIdentifier.externalData, externalData) const update = { 'thirdPartyIdentifiers.$': thirdPartyIdentifier } return update } const ThirdPartyIdentityManager = { getUser, login, link, unlink, } ThirdPartyIdentityManager.promises = promisifyAll(ThirdPartyIdentityManager) module.exports = ThirdPartyIdentityManager
overleaf/web/app/src/Features/User/ThirdPartyIdentityManager.js/0
{ "file_path": "overleaf/web/app/src/Features/User/ThirdPartyIdentityManager.js", "repo_id": "overleaf", "token_count": 2652 }
491
const RedisWrapper = require('../../infrastructure/RedisWrapper') const rclient = RedisWrapper.client('websessions') const UserSessionsRedis = { client() { return rclient }, sessionSetKey(user) { return `UserSessions:{${user._id}}` }, } module.exports = UserSessionsRedis
overleaf/web/app/src/Features/User/UserSessionsRedis.js/0
{ "file_path": "overleaf/web/app/src/Features/User/UserSessionsRedis.js", "repo_id": "overleaf", "token_count": 101 }
492
const _ = require('lodash') const Settings = require('@overleaf/settings') const publicRegistrationModuleAvailable = Settings.moduleImportSequence.includes( 'public-registration' ) const supportModuleAvailable = Settings.moduleImportSequence.includes('support') const historyV1ModuleAvailable = Settings.moduleImportSequence.includes( 'history-v1' ) const trackChangesModuleAvailable = Settings.moduleImportSequence.includes( 'track-changes' ) /** * @typedef {Object} Settings * @property {Object | undefined} apis * @property {Object | undefined} apis.linkedUrlProxy * @property {string | undefined} apis.linkedUrlProxy.url * @property {Object | undefined} apis.references * @property {string | undefined} apis.references.url * @property {boolean | undefined} enableGithubSync * @property {boolean | undefined} enableGitBridge * @property {boolean | undefined} enableHomepage * @property {boolean | undefined} enableSaml * @property {boolean | undefined} ldap * @property {boolean | undefined} oauth * @property {Object | undefined} overleaf * @property {Object | undefined} overleaf.oauth * @property {boolean | undefined} saml */ const Features = { /** * @returns {boolean} */ externalAuthenticationSystemUsed() { return ( (Boolean(Settings.ldap) && Boolean(Settings.ldap.enable)) || (Boolean(Settings.saml) && Boolean(Settings.saml.enable)) || Boolean(_.get(Settings, ['overleaf', 'oauth'])) ) }, /** * Whether a feature is enabled in the appliation's configuration * * @param {string} feature * @returns {boolean} */ hasFeature(feature) { switch (feature) { case 'saas': return Boolean(Settings.overleaf) case 'homepage': return Boolean(Settings.enableHomepage) case 'registration-page': return ( !Features.externalAuthenticationSystemUsed() || Boolean(Settings.overleaf) ) case 'registration': return publicRegistrationModuleAvailable || Boolean(Settings.overleaf) case 'github-sync': return Boolean(Settings.enableGithubSync) case 'git-bridge': return Boolean(Settings.enableGitBridge) case 'custom-togglers': return Boolean(Settings.overleaf) case 'oauth': return Boolean(Settings.oauth) case 'templates-server-pro': return !Settings.overleaf case 'history-v1': return historyV1ModuleAvailable case 'affiliations': case 'analytics': return Boolean(_.get(Settings, ['apis', 'v1', 'url'])) case 'overleaf-integration': return Boolean(Settings.overleaf) case 'references': return Boolean(_.get(Settings, ['apis', 'references', 'url'])) case 'saml': return Boolean(Settings.enableSaml) case 'linked-project-file': return Boolean(Settings.enabledLinkedFileTypes.includes('project_file')) case 'linked-project-output-file': return Boolean( Settings.enabledLinkedFileTypes.includes('project_output_file') ) case 'link-url': return Boolean( _.get(Settings, ['apis', 'linkedUrlProxy', 'url']) && Settings.enabledLinkedFileTypes.includes('url') ) case 'public-registration': return publicRegistrationModuleAvailable case 'support': return supportModuleAvailable case 'track-changes': return trackChangesModuleAvailable default: throw new Error(`unknown feature: ${feature}`) } }, } module.exports = Features
overleaf/web/app/src/infrastructure/Features.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/Features.js", "repo_id": "overleaf", "token_count": 1300 }
493
const Settings = require('@overleaf/settings') const redis = require('@overleaf/redis-wrapper') if ( typeof global.beforeEach === 'function' && process.argv.join(' ').match(/unit/) ) { throw new Error( 'It looks like unit tests are running, but you are connecting to Redis. Missing a stub?' ) } // A per-feature interface to Redis, // looks up the feature in `settings.redis` // and returns an appropriate client. // Necessary because we don't want to migrate web over // to redis-cluster all at once. module.exports = { // feature = 'websessions' | 'ratelimiter' | ... client(feature) { const redisFeatureSettings = Settings.redis[feature] || Settings.redis.web return redis.createClient(redisFeatureSettings) }, }
overleaf/web/app/src/infrastructure/RedisWrapper.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/RedisWrapper.js", "repo_id": "overleaf", "token_count": 236 }
494
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const FileSchema = new Schema({ name: { type: String, default: '', }, created: { type: Date, default() { return new Date() }, }, rev: { type: Number, default: 0 }, linkedFileData: { type: Schema.Types.Mixed }, hash: { type: String, }, }) exports.File = mongoose.model('File', FileSchema) exports.FileSchema = FileSchema
overleaf/web/app/src/models/File.js/0
{ "file_path": "overleaf/web/app/src/models/File.js", "repo_id": "overleaf", "token_count": 178 }
495
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const TeamInviteSchema = new Schema({ email: { type: String, required: true }, token: { type: String }, inviterName: { type: String }, sentAt: { type: Date }, }) exports.TeamInvite = mongoose.model('TeamInvite', TeamInviteSchema) exports.TeamInviteSchema = TeamInviteSchema
overleaf/web/app/src/models/TeamInvite.js/0
{ "file_path": "overleaf/web/app/src/models/TeamInvite.js", "repo_id": "overleaf", "token_count": 125 }
496
mixin reconfirmAffiliationNotification(location) .reconfirm-notification(ng-controller="UserAffiliationsReconfirmController") div(ng-if="!reconfirm[userEmail.email].reconfirmationSent" style="width:100%;") i.fa.fa-warning button.btn-reconfirm.btn.btn-sm.btn-info( data-location=location ng-if="!ui.sentReconfirmation" ng-click="requestReconfirmation($event, userEmail)" ng-disabled="ui.isMakingRequest" ) #{translate("confirm_affiliation")} | !{translate("are_you_still_at", {institutionName: '{{userEmail.affiliation.institution.name}}'}, ['strong'])}&nbsp; if location == '/user/settings' | !{translate('please_reconfirm_institutional_email', {}, [{ name: 'span' }])} span(ng-if="userEmail.default") &nbsp;#{translate('need_to_add_new_primary_before_remove')} else | !{translate("please_reconfirm_institutional_email", {}, [{name: 'a', attrs: {href: '/user/settings?remove={{userEmail.email}}' }}])} | &nbsp; a(href="/learn/how-to/Institutional_Email_Reconfirmation") #{translate("learn_more")} div(ng-if="reconfirm[userEmail.email].reconfirmationSent") | !{translate("please_check_your_inbox_to_confirm", {institutionName: '{{userEmail.affiliation.institution.name}}'}, ['strong'])} | &nbsp; button( class="btn-inline-link" ng-click="requestReconfirmation($event, userEmail)" ng-disabled="ui.isMakingRequest" ) #{translate('resend_confirmation_email')} mixin reconfirmedAffiliationNotification() .alert.alert-info .reconfirm-notification div(style="width:100%;") //- extra div for flex styling | !{translate("your_affiliation_is_confirmed", {institutionName: '{{userEmail.affiliation.institution.name}}'}, ['strong'])}&nbsp;#{translate('thank_you_exclamation')}
overleaf/web/app/views/_mixins/reconfirm_affiliation.pug/0
{ "file_path": "overleaf/web/app/views/_mixins/reconfirm_affiliation.pug", "repo_id": "overleaf", "token_count": 687 }
497
extends ../layout block vars - var suppressNavbar = true - var suppressFooter = true - var suppressSkipToContent = true - metadata.robotsNoindexNofollow = true block _headLinks link(rel='stylesheet', href=buildStylesheetPath("ide.css")) block content .editor(ng-controller="IdeController").full-size //- required by react2angular-shared-context, must be rendered as a top level component shared-context-react() .loading-screen(ng-if="state.loading") .loading-screen-brand-container .loading-screen-brand( style="height: 20%;" ng-style="{ 'height': state.load_progress + '%' }" ) h3.loading-screen-label(ng-if="!state.error") #{translate("loading")} span.loading-screen-ellip . span.loading-screen-ellip . span.loading-screen-ellip . p.loading-screen-error(ng-if="state.error").ng-cloak span(ng-bind-html="state.error") .global-alerts(ng-cloak ng-hide="editor.error_state") .alert.alert-danger.small(ng-if="connection.forced_disconnect") strong #{translate("disconnected")} .alert.alert-warning.small(ng-if="connection.reconnection_countdown") strong #{translate("lost_connection")}. | #{translate("reconnecting_in_x_secs", {seconds:"{{ connection.reconnection_countdown }}"})}. a#try-reconnect-now-button.alert-link-as-btn.pull-right(href, ng-click="tryReconnectNow()") #{translate("try_now")} .alert.alert-warning.small(ng-if="connection.reconnecting && connection.stillReconnecting") strong #{translate("reconnecting")}… .alert.alert-warning.small(ng-if="sync_tex_error") strong #{translate("synctex_failed")}. a#synctex-more-info-button.alert-link-as-btn.pull-right( href="/learn/how-to/SyncTeX_Errors" target="_blank" ) #{translate("more_info")} .alert.alert-warning.small(ng-if="connection.inactive_disconnect") strong #{translate("editor_disconected_click_to_reconnect")} .alert.alert-warning.small(ng-if="connection.debug") {{ connection.state }} .div(ng-controller="SavingNotificationController") .alert.alert-warning.small(ng-repeat="(doc_id, state) in docSavingStatus" ng-if="state.unsavedSeconds > 8") #{translate("saving_notification_with_seconds", {docname:"{{ state.doc.name }}", seconds:"{{ state.unsavedSeconds }}"})} .div(ng-controller="SystemMessagesController") .alert.alert-warning.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") &times; span.sr-only #{translate("close")} .system-message-content(ng-bind-html="htmlContent") include ./editor/left-menu #chat-wrapper.full-size( layout="chat", spacing-open="{{ui.chatResizerSizeOpen}}", spacing-closed="{{ui.chatResizerSizeClosed}}", initial-size-east="250", init-closed-east="true", open-east="ui.chatOpen", ng-hide="state.loading", ng-cloak ) .ui-layout-center if showNewNavigationUI include ./editor/header-react else include ./editor/header != moduleIncludes("publish:body", locals) include ./editor/history/toolbarV2.pug main#ide-body( ng-cloak, role="main", ng-class="{ 'ide-history-open' : (ui.view == 'history' && history.isV2) }", layout="main", ng-hide="state.loading", resize-on="layout:chat:resize,history:toggle", minimum-restore-size-west="130" custom-toggler-pane=hasFeature('custom-togglers') ? "west" : false custom-toggler-msg-when-open=hasFeature('custom-togglers') ? translate("tooltip_hide_filetree") : false custom-toggler-msg-when-closed=hasFeature('custom-togglers') ? translate("tooltip_show_filetree") : false ) .ui-layout-west include ./editor/file-tree-react include ./editor/file-tree-history include ./editor/history/fileTreeV2 .ui-layout-center include ./editor/editor if showNewFileViewUI include ./editor/file-view else include ./editor/binary-file include ./editor/history if !isRestrictedTokenMember .ui-layout-east aside.chat( ng-controller="ReactChatController" ) chat() script(type="text/ng-template", id="genericMessageModalTemplate") .modal-header button.close( type="button" data-dismiss="modal" ng-click="done()" aria-label="Close" ) span(aria-hidden="true") &times; h3 {{ title }} .modal-body(ng-bind-html="message") .modal-footer button.btn.btn-info(ng-click="done()") #{translate("ok")} script(type="text/ng-template", id="outOfSyncModalTemplate") .modal-header button.close( type="button" data-dismiss="modal" ng-click="done()" aria-label="Close" ) span(aria-hidden="true") &times; h3 {{ title }} .modal-body(ng-bind-html="message") .modal-body button.btn.btn-info( ng-init="showFileContents = false" ng-click="showFileContents = !showFileContents" ) | {{showFileContents ? "Hide" : "Show"}} Local File Contents .text-preview(ng-show="showFileContents") textarea.scroll-container(readonly="readonly" rows="{{editorContentRows}}") | {{editorContent}} .modal-footer button.btn.btn-info(ng-click="done()") #{translate("reload_editor")} script(type="text/ng-template", id="lockEditorModalTemplate") .modal-header h3 {{ title }} .modal-body(ng-bind-html="message") block append meta meta(name="ol-useV2History" data-type="boolean" content=useV2History) meta(name="ol-project_id" content=project_id) meta(name="ol-userSettings" data-type="json" content=userSettings) meta(name="ol-user" data-type="json" content=user) meta(name="ol-anonymous" data-type="boolean" content=anonymous) meta(name="ol-brandVariation" data-type="json" content=brandVariation) meta(name="ol-anonymousAccessToken" content=anonymousAccessToken) meta(name="ol-isTokenMember" data-type="boolean" content=isTokenMember) meta(name="ol-isRestrictedTokenMember" data-type="boolean" content=isRestrictedTokenMember) meta(name="ol-maxDocLength" data-type="json" content=maxDocLength) meta(name="ol-wikiEnabled" data-type="boolean" content=!!(settings.apis.wiki && settings.apis.wiki.url)) meta(name="ol-gitBridgePublicBaseUrl" content=gitBridgePublicBaseUrl) //- Set base path for Ace scripts loaded on demand/workers and don't use cdn meta(name="ol-aceBasePath" content="/js/" + lib('ace')) //- Set path for PDFjs CMaps meta(name="ol-pdfCMapsPath" content="/js/cmaps/") //- enable doc hash checking for all projects //- used in public/js/libs/sharejs.js meta(name="ol-useShareJsHash" data-type="boolean" content=true) meta(name="ol-wsRetryHandshake" data-type="json" content=settings.wsRetryHandshake) meta(name="ol-showNewLogsUI" data-type="boolean" content=showNewLogsUI) meta(name="ol-logsUISubvariant" content=logsUISubvariant) meta(name="ol-showSymbolPalette" data-type="boolean" content=showSymbolPalette) meta(name="ol-enablePdfCaching" data-type="boolean" content=enablePdfCaching) meta(name="ol-trackPdfDownload" data-type="boolean" content=trackPdfDownload) meta(name="ol-resetServiceWorker" data-type="boolean" content=resetServiceWorker) - var fileActionI18n = ['edited', 'renamed', 'created', 'deleted'].reduce((acc, i) => {acc[i] = translate('file_action_' + i); return acc}, {}) meta(name="ol-fileActionI18n" data-type="json" content=fileActionI18n) if (settings.overleaf != null) meta(name="ol-overallThemes" data-type="json" content=overallThemes) block foot-scripts script(type="text/javascript", nonce=scriptNonce, src=(wsUrl || '/socket.io') + '/socket.io.js') script(type="text/javascript", nonce=scriptNonce, src=mathJaxPath) script(type="text/javascript", nonce=scriptNonce, src=buildJsPath('libraries.js')) script(type="text/javascript", nonce=scriptNonce, src=buildJsPath('ide.js'))
overleaf/web/app/views/project/editor.pug/0
{ "file_path": "overleaf/web/app/views/project/editor.pug", "repo_id": "overleaf", "token_count": 3087 }
498
.diff-panel.full-size( ng-if="history.isV2 && history.viewMode === HistoryViewModes.COMPARE && history.updates.length !== 0" ) .diff( ng-show="!!history.selection.diff && !isHistoryLoading() && !history.selection.diff.error", ng-class="{ 'diff-binary': history.selection.diff.binary }" ) .diff-editor-v2.hide-ace-cursor( ng-if="!history.selection.diff.binary" ace-editor="history", theme="settings.editorTheme", font-size="settings.fontSize", text="history.selection.diff.text", highlights="history.selection.diff.highlights", read-only="true", resize-on="layout:main:resize,history:toggle", navigate-highlights="true" ) .alert.alert-info(ng-if="history.selection.diff.binary") | We're still working on showing image and binary changes, sorry. Stay tuned! .loading-panel(ng-show="isHistoryLoading()") i.fa.fa-spin.fa-refresh | &nbsp;&nbsp;#{translate("loading")}… .error-panel(ng-show="history.selection.diff.error && !isHistoryLoading()") .alert.alert-danger #{translate("generic_something_went_wrong")} .point-in-time-panel.full-size( ng-if="history.isV2 && history.viewMode === HistoryViewModes.POINT_IN_TIME && history.updates.length !== 0" ) .point-in-time-editor-container( ng-if="!!history.selection.file && !history.selection.file.loading && !history.selection.file.error" ) .hide-ace-cursor( ng-if="!history.selection.file.binary" ace-editor="history-pointintime", theme="settings.editorTheme", font-size="settings.fontSize", text="history.selection.file.text", read-only="true", resize-on="layout:main:resize,history:toggle", ) .alert.alert-info(ng-if="history.selection.file.binary") | We're still working on showing image and binary changes, sorry. Stay tuned! .loading-panel(ng-show="isHistoryLoading()") i.fa.fa-spin.fa-refresh | &nbsp;&nbsp;#{translate("loading")}… .error-panel(ng-show="history.error") .alert.alert-danger p | #{translate("generic_history_error")} a( ng-href="mailto:#{settings.adminEmail}?Subject=Error%20loading%20history%20for%project%20{{ project_id }}", ng-non-bindable ) #{settings.adminEmail} p.clearfix a.alert-link-as-btn.pull-right( href ng-click="toggleHistory()" ) #{translate("back_to_editor")} .error-panel(ng-show="history.selection.file.error") .alert.alert-danger #{translate("generic_something_went_wrong")}
overleaf/web/app/views/project/editor/history/previewPanelV2.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/history/previewPanelV2.pug", "repo_id": "overleaf", "token_count": 938 }
499
include ../../_mixins/reconfirm_affiliation .user-notifications(ng-controller="NotificationsController") ul.list-unstyled( ng-if="notifications.length > 0 && projects.length > 0", ng-cloak ) li.notification-entry( ng-repeat="notification in notifications" ) div(ng-switch="notification.templateKey" ng-hide="notification.hide") .alert.alert-info( ng-switch-when="notification_project_invite", ng-controller="ProjectInviteNotificationController" ) .notification-body span(ng-show="!notification.accepted") !{translate("notification_project_invite_message", { userName: "{{ userName }}", projectName: "{{ projectName }}" })} span(ng-show="notification.accepted") !{translate("notification_project_invite_accepted_message", { projectName: "{{ projectName }}" })} .notification-action a.pull-right.btn.btn-sm.btn-info( ng-show="notification.accepted", href="/project/{{ notification.messageOpts.projectId }}" ) #{translate("open_project")} a.pull-right.btn.btn-sm.btn-info( href, ng-click="accept()", ng-disabled="notification.inflight", ng-show="!notification.accepted" ) span(ng-show="!notification.inflight") #{translate("join_project")} span(ng-show="notification.inflight") i.fa.fa-fw.fa-spinner.fa-spin(aria-hidden="true") | &nbsp; | #{translate("joining")}… .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-info( ng-switch-when="wfh_2020_upgrade_offer" ) .notification-body span Important notice: Your free WFH2020 upgrade came to an end on June 30th 2020. We're still providing a number of special initiatives to help you continue collaborating throughout 2020. .notification-action a.pull-right.btn.btn-sm.btn-info(href="https://www.overleaf.com/events/wfh2020") View .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-info( ng-switch-when="notification_ip_matched_affiliation" ng-if="notification.messageOpts.ssoEnabled" ) .notification-body | !{translate("looks_like_youre_at", {institutionName: '{{notification.messageOpts.university_name}}'}, ['strong'])} br | !{translate("you_can_now_log_in_sso", {}, ['strong'])} br | #{translate("link_institutional_email_get_started", {}, ['strong'])}&nbsp; a( ng-href="{{notification.messageOpts.portalPath || 'https://www.overleaf.com/learn/how-to/Institutional_Login'}}" ) #{translate("find_out_more_nt")} .notification-action a.pull-right.btn.btn-sm.btn-info( ng-href=`{{samlInitPath}}?university_id={{notification.messageOpts.institutionId}}&auto=/project` ) | #{translate("link_account")} .notification-close button.btn-sm(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-info( ng-switch-when="notification_ip_matched_affiliation" ng-if="!notification.messageOpts.ssoEnabled" ) .notification-body | !{translate("looks_like_youre_at", {institutionName: '{{notification.messageOpts.university_name}}'}, ['strong'])} br | !{translate("did_you_know_institution_providing_professional", {institutionName: '{{notification.messageOpts.university_name}}'}, ['strong'])} br | #{translate("add_email_to_claim_features")} .notification-action a.pull-right.btn.btn-sm.btn-info( href="/user/settings" ) #{translate("add_affiliation")} .notification-close button.btn-sm(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-danger( ng-switch-when="notification_tpds_file_limit" ) .notification-body | Error: Your project strong {{ notification.messageOpts.projectName }} | has gone over the 2000 file limit using an integration (e.g. Dropbox or Github) <br/> | Please decrease the size of your project to prevent further errors. .notification-action a.pull-right.btn.btn-sm.btn-info(href="/user/settings") | Account Settings .notification-close button.btn-sm(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-warning( ng-switch-when="notification_dropbox_duplicate_project_names" ) .notification-body p() | !{translate("dropbox_duplicate_project_names", { projectName: '{{notification.messageOpts.projectName}}'}, ['strong'])} p() | !{translate("dropbox_duplicate_project_names_suggestion", {}, ['strong'])} | &nbsp; a(href="/learn/how-to/Dropbox_Synchronization#Troubleshooting") #{translate("learn_more")} |. .notification-close button.btn-sm(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-info( ng-switch-when="notification_dropbox_unlinked_due_to_lapsed_reconfirmation" ) .notification-body if user.features.dropbox | !{translate("dropbox_unlinked_premium_feature", {}, ['strong'])} | !{translate("can_now_relink_dropbox", {}, [{name: 'a', attrs: {href: '/user/settings#dropboxSettings' }}])} else | !{translate("dropbox_unlinked_premium_feature", {}, ['strong'])} | !{translate("confirm_affiliation_to_relink_dropbox")} | &nbsp; a(href="/learn/how-to/Institutional_Email_Reconfirmation") #{translate("learn_more")} .notification-close button.btn-sm(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-info( ng-switch-default ) span(ng-bind-html="notification.html").notification-body .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} ul.list-unstyled( ng-if="notificationsInstitution.length > 0", ng-cloak ) li.notification-entry( ng-repeat="notification in notificationsInstitution" ) div(ng-switch="notification.templateKey" ng-hide="notification.hide") .alert.alert-info( ng-switch-when="notification_institution_sso_available" ) .notification-body p !{translate("can_link_institution_email_acct_to_institution_acct", {appName: settings.appName, email: "{{notification.email}}", institutionName: "{{notification.institutionName}}"})} div !{translate("doing_this_allow_log_in_through_institution", {appName: settings.appName})} .notification-action a.btn.btn-sm.btn-info(ng-href="{{samlInitPath}}?university_id={{notification.institutionId}}&auto=/project&email={{notification.email}}") | #{translate('link_account')} .alert.alert-info( ng-switch-when="notification_institution_sso_linked" ) .notification-body div !{translate("account_has_been_link_to_institution_account", {appName: settings.appName, email: "{{notification.email}}", institutionName: "{{notification.institutionName}}"})} .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-warning( ng-switch-when="notification_institution_sso_non_canonical" ) .notification-body div i.fa.fa-fw.fa-exclamation-triangle(aria-hidden="true") | !{translate("tried_to_log_in_with_email", {email: "{{notification.requestedEmail}}"})} !{translate("in_order_to_match_institutional_metadata_associated", {email: "{{notification.institutionEmail}}"})} .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-info( ng-switch-when="notification_institution_sso_already_registered" ) .notification-body | !{translate("tried_to_register_with_email", {appName: settings.appName, email: "{{notification.email}}"})} | #{translate("we_logged_you_in")} .notification-action a.btn.btn-sm.btn-info(href="/learn/how-to/Institutional_Login") | #{translate("find_out_more")} .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} .alert.alert-danger(ng-switch-when="notification_institution_sso_error") .notification-body div i.fa.fa-fw.fa-exclamation-triangle(aria-hidden="true") | &nbsp;#{translate("generic_something_went_wrong")}. div(ng-if="notification.error.translatedMessage" ng-bind-html="notification.error.translatedMessage") div(ng-else="notification.error.message") {{ notification.error.message}} div(ng-if="notification.error.tryAgain") #{translate("try_again")}. .notification-close button(ng-click="dismiss(notification)").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")} ul.list-unstyled( ng-controller="EmailNotificationController", ng-cloak ) li.notification-entry( ng-repeat="userEmail in userEmails", ng-if="showConfirmEmail(userEmail) && projects.length > 0" ) .alert.alert-warning .notification-body div(ng-if="!userEmail.confirmationInflight") | #{translate("please_confirm_email", {emailAddress: "{{ userEmail.email }}"})} | a( href ng-click="resendConfirmationEmail(userEmail)" ) (#{translate('resend_confirmation_email')}) div(ng-if="userEmail.confirmationInflight") i.fa.fa-spinner.fa-spin(aria-hidden="true") | | #{translate('resending_confirmation_email')}&hellip; div(ng-if="!userEmail.confirmationInflight && userEmail.error" aria-live="polite") span(ng-if="userEmail.errorMessage") {{ userEmail.errorMessage }} span(ng-if="!userEmail.errorMessage") #{translate('generic_something_went_wrong')} ui.list-unstyled(ng-controller="UserAffiliationsReconfirmController") li.notification-entry( ng-repeat="userEmail in allInReconfirmNotificationPeriods" ) .alert.alert-info() +reconfirmAffiliationNotification('/project') li.notification-entry( ng-repeat="userEmail in userEmails" ng-if="userEmail.samlIdentifier && userEmail.samlIdentifier.providerId === reconfirmedViaSAML" ) +reconfirmedAffiliationNotification() - var hasPaidAffiliation = userAffiliations.some(affiliation => affiliation.licence && affiliation.licence !== 'free') if settings.enableSubscriptions && !hasSubscription && !hasPaidAffiliation ul.list-unstyled( ng-controller="DismissableNotificationsController", ng-cloak ) li.notification-entry( ng-if="shouldShowNotification && projects.length > 0" ) .alert.alert-info .notification-body span To help you work from home throughout 2021, we're providing discounted plans and special initiatives. .notification-action a.pull-right.btn.btn-sm.btn-info(href="https://www.overleaf.com/events/wfh2021" event-tracking="Event-Pages" event-tracking-trigger="click" event-tracking-ga="WFH-Offer-Click" event-tracking-label="Dash-Banner") Upgrade .notification-close button(ng-click="dismiss()").close.pull-right span(aria-hidden="true") &times; span.sr-only #{translate("close")}
overleaf/web/app/views/project/list/notifications.pug/0
{ "file_path": "overleaf/web/app/views/project/list/notifications.pug", "repo_id": "overleaf", "token_count": 5006 }
500
each managedGroupSubscription in managedGroupSubscriptions p | You are a manager of | +teamName(managedGroupSubscription) p a.btn.btn-primary(href="/manage/groups/" + managedGroupSubscription._id + "/members") i.fa.fa-fw.fa-users | &nbsp; | Manage members | &nbsp; p a(href="/manage/groups/" + managedGroupSubscription._id + "/managers") i.fa.fa-fw.fa-users | &nbsp; | Manage group managers | &nbsp; p a(href="/metrics/groups/" + managedGroupSubscription._id) i.fa.fa-fw.fa-line-chart | &nbsp; | View metrics hr
overleaf/web/app/views/subscriptions/dashboard/_managed_groups.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/dashboard/_managed_groups.pug", "repo_id": "overleaf", "token_count": 239 }
501
extends ../layout block content | !{content}
overleaf/web/app/views/university/university_holder.pug/0
{ "file_path": "overleaf/web/app/views/university/university_holder.pug", "repo_id": "overleaf", "token_count": 16 }
502
script(type="text/ng-template", id="BonusLinkToUsModal") .modal-header button.close( type="button" data-dismiss="modal" ng-click="cancel()" aria-label="Close" ) span(aria-hidden="true") &times; h3 Dropbox link .modal-body.modal-body-share div(ng-show="dbState.gotLinkStatus") div(ng-hide="dbState.userIsLinkedToDropbox || !dbState.hasDropboxFeature") span(ng-hide="dbState.startedLinkProcess") Your account is not linked to dropbox | &nbsp; &nbsp; a(ng-click="linkToDropbox()").btn.btn-info Update Dropbox Settings p.small.text-center(ng-show="dbState.startedLinkProcess") | Please refresh this page after starting your free trial. div(ng-show="dbState.hasDropboxFeature && dbState.userIsLinkedToDropbox") progressbar.progress-striped.active(value='dbState.percentageLeftTillNextPoll', type="info") span strong {{dbState.minsTillNextPoll}} minutes span until dropbox is next checked for changes. div.text-center(ng-hide="dbState.hasDropboxFeature") p You need to upgrade your account to link to dropbox. p a.btn(ng-click="startFreeTrial('dropbox')", ng-class="buttonClass") Start Free Trial p.small(ng-show="startedFreeTrial") | Please refresh this page after starting your free trial. div(ng-hide="dbState.gotLinkStatus") span.small &nbsp; checking dropbox status &nbsp; i.fa.fa-refresh.fa-spin(aria-hidden="true") .modal-footer() button.btn.btn-default( ng-click="cancel()", ) span Dismiss
overleaf/web/app/views/view_templates/bonus_templates.pug/0
{ "file_path": "overleaf/web/app/views/view_templates/bonus_templates.pug", "repo_id": "overleaf", "token_count": 591 }
503
@font-face { font-family: 'Lato'; font-style: normal; font-weight: 300; src: local('Lato Light'), local('Lato-Light'), url('lato-v16-latin-ext-300.woff2') format('woff2'), url('lato-v16-latin-ext-300.woff') format('woff'); } @font-face { font-family: 'Lato'; font-style: normal; font-weight: 400; src: local('Lato Regular'), local('Lato-Regular'), url('lato-v16-latin-ext-regular.woff2') format('woff2'), url('lato-v16-latin-ext-regular.woff') format('woff'); } @font-face { font-family: 'Lato'; font-style: normal; font-weight: 700; src: local('Lato Bold'), local('Lato-Bold'), url('lato-v16-latin-ext-700.woff2') format('woff2'), url('lato-v16-latin-ext-700.woff') format('woff'); }
overleaf/web/frontend/fonts/lato.css/0
{ "file_path": "overleaf/web/frontend/fonts/lato.css", "repo_id": "overleaf", "token_count": 322 }
504
/* eslint-disable 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' App.directive('focusWhen', $timeout => ({ restrict: 'A', link(scope, element, attr) { return scope.$watch(attr.focusWhen, function (value) { if (value) { return $timeout(() => element.focus()) } }) }, })) App.directive('focusOn', $timeout => ({ restrict: 'A', link(scope, element, attrs) { return scope.$on(attrs.focusOn, () => element.focus()) }, })) App.directive('selectWhen', $timeout => ({ restrict: 'A', link(scope, element, attr) { return scope.$watch(attr.selectWhen, function (value) { if (value) { return $timeout(() => element.select()) } }) }, })) App.directive('selectOn', $timeout => ({ restrict: 'A', link(scope, element, attrs) { return scope.$on(attrs.selectOn, () => element.select()) }, })) App.directive('selectNameWhen', $timeout => ({ restrict: 'A', link(scope, element, attrs) { return scope.$watch(attrs.selectNameWhen, function (value) { if (value) { return $timeout(() => selectName(element)) } }) }, })) App.directive('selectNameOn', () => ({ restrict: 'A', link(scope, element, attrs) { return scope.$on(attrs.selectNameOn, () => selectName(element)) }, })) App.directive('focus', $timeout => ({ scope: { trigger: '@focus', }, link(scope, element) { return scope.$watch('trigger', function (value) { if (value === 'true') { return $timeout(() => element[0].focus()) } }) }, })) function selectName(element) { // Select up to last '.'. I.e. everything except the file extension element.focus() const name = element.val() if (element[0].setSelectionRange != null) { let selectionEnd = name.lastIndexOf('.') if (selectionEnd === -1) { selectionEnd = name.length } return element[0].setSelectionRange(0, selectionEnd) } }
overleaf/web/frontend/js/directives/focus.js/0
{ "file_path": "overleaf/web/frontend/js/directives/focus.js", "repo_id": "overleaf", "token_count": 841 }
505
import { createContext, useCallback, useContext, useEffect, useReducer, useMemo, } from 'react' import PropTypes from 'prop-types' import { v4 as uuid } from 'uuid' import { useUserContext } from '../../../shared/context/user-context' import { useProjectContext } from '../../../shared/context/project-context' import { getJSON, postJSON } from '../../../infrastructure/fetch-json' import { appendMessage, prependMessages } from '../utils/message-list-appender' import useBrowserWindow from '../../../shared/hooks/use-browser-window' import { useLayoutContext } from '../../../shared/context/layout-context' const PAGE_SIZE = 50 export function chatReducer(state, action) { switch (action.type) { case 'INITIAL_FETCH_MESSAGES': return { ...state, status: 'pending', initialMessagesLoaded: true, } case 'FETCH_MESSAGES': return { ...state, status: 'pending', } case 'FETCH_MESSAGES_SUCCESS': return { ...state, status: 'idle', messages: prependMessages(state.messages, action.messages), lastTimestamp: action.messages[0] ? action.messages[0].timestamp : null, atEnd: action.messages.length < PAGE_SIZE, } case 'SEND_MESSAGE': return { ...state, messages: appendMessage(state.messages, { // Messages are sent optimistically, so don't have an id (used for // React keys). The uuid is valid for this session, and ensures all // messages have an id. It will be overwritten by the actual ids on // refresh id: uuid(), user: action.user, content: action.content, timestamp: Date.now(), }), messageWasJustSent: true, } case 'RECEIVE_MESSAGE': return { ...state, messages: appendMessage(state.messages, action.message), messageWasJustSent: false, unreadMessageCount: state.unreadMessageCount + 1, } case 'MARK_MESSAGES_AS_READ': return { ...state, unreadMessageCount: 0, } case 'CLEAR': return { ...initialState } case 'ERROR': return { ...state, status: 'error', error: action.error, } default: throw new Error('Unknown action') } } const initialState = { status: 'idle', messages: [], initialMessagesLoaded: false, lastTimestamp: null, atEnd: false, messageWasJustSent: false, unreadMessageCount: 0, error: null, } export const ChatContext = createContext() ChatContext.Provider.propTypes = { value: PropTypes.shape({ status: PropTypes.string.isRequired, messages: PropTypes.array.isRequired, initialMessagesLoaded: PropTypes.bool.isRequired, atEnd: PropTypes.bool.isRequired, unreadMessageCount: PropTypes.number.isRequired, loadInitialMessages: PropTypes.func.isRequired, loadMoreMessages: PropTypes.func.isRequired, sendMessage: PropTypes.func.isRequired, markMessagesAsRead: PropTypes.func.isRequired, reset: PropTypes.func.isRequired, error: PropTypes.object, }).isRequired, } export function ChatProvider({ children }) { const user = useUserContext({ id: PropTypes.string.isRequired, }) const { _id: projectId } = useProjectContext({ _id: PropTypes.string.isRequired, }) const { chatIsOpen } = useLayoutContext({ chatIsOpen: PropTypes.bool }) const { hasFocus: windowHasFocus, flashTitle, stopFlashingTitle, } = useBrowserWindow() const [state, dispatch] = useReducer(chatReducer, initialState) const { loadInitialMessages, loadMoreMessages, reset } = useMemo(() => { function fetchMessages() { if (state.atEnd) return const query = { limit: PAGE_SIZE } if (state.lastTimestamp) { query.before = state.lastTimestamp } const queryString = new URLSearchParams(query) const url = `/project/${projectId}/messages?${queryString.toString()}` getJSON(url) .then((messages = []) => { dispatch({ type: 'FETCH_MESSAGES_SUCCESS', messages: messages.reverse(), }) }) .catch(error => { dispatch({ type: 'ERROR', error: error, }) }) } function loadInitialMessages() { if (state.initialMessagesLoaded) return dispatch({ type: 'INITIAL_FETCH_MESSAGES' }) fetchMessages() } function loadMoreMessages() { dispatch({ type: 'FETCH_MESSAGES' }) fetchMessages() } function reset() { dispatch({ type: 'CLEAR' }) fetchMessages() } return { loadInitialMessages, loadMoreMessages, reset, } }, [projectId, state.atEnd, state.initialMessagesLoaded, state.lastTimestamp]) const sendMessage = useCallback( content => { if (!content) return dispatch({ type: 'SEND_MESSAGE', user, content, }) const url = `/project/${projectId}/messages` postJSON(url, { body: { content }, }).catch(error => { dispatch({ type: 'ERROR', error: error, }) }) }, [projectId, user] ) const markMessagesAsRead = useCallback(() => { dispatch({ type: 'MARK_MESSAGES_AS_READ' }) }, []) // Handling receiving messages over the socket const socket = window._ide?.socket useEffect(() => { if (!socket) return function receivedMessage(message) { // If the message is from the current user and they just sent a message, // then we are receiving the sent message back from the socket. Ignore it // to prevent double message const messageIsFromSelf = message?.user?.id === user?.id if (messageIsFromSelf && state.messageWasJustSent) return dispatch({ type: 'RECEIVE_MESSAGE', message }) // Temporary workaround to pass state to unread message balloon in Angular window.dispatchEvent( new CustomEvent('Chat.MessageReceived', { detail: { message } }) ) } socket.on('new-chat-message', receivedMessage) return () => { if (!socket) return socket.removeListener('new-chat-message', receivedMessage) } // We're adding and removing the socket listener every time we send a // message (and messageWasJustSent changes). Not great, but no good way // around it }, [socket, state.messageWasJustSent, state.unreadMessageCount, user]) // Handle unread messages useEffect(() => { if (windowHasFocus) { stopFlashingTitle() if (chatIsOpen) { markMessagesAsRead() } } if (!windowHasFocus && state.unreadMessageCount > 0) { flashTitle('New Message') } }, [ windowHasFocus, chatIsOpen, state.unreadMessageCount, flashTitle, stopFlashingTitle, markMessagesAsRead, ]) const value = useMemo( () => ({ status: state.status, messages: state.messages, initialMessagesLoaded: state.initialMessagesLoaded, atEnd: state.atEnd, unreadMessageCount: state.unreadMessageCount, loadInitialMessages, loadMoreMessages, reset, sendMessage, markMessagesAsRead, error: state.error, }), [ loadInitialMessages, loadMoreMessages, markMessagesAsRead, reset, sendMessage, state.atEnd, state.error, state.initialMessagesLoaded, state.messages, state.status, state.unreadMessageCount, ] ) return <ChatContext.Provider value={value}>{children}</ChatContext.Provider> } ChatProvider.propTypes = { children: PropTypes.any, } export function useChatContext(propTypes) { const data = useContext(ChatContext) PropTypes.checkPropTypes(propTypes, data, 'data', 'ChatContext.Provider') return data }
overleaf/web/frontend/js/features/chat/context/chat-context.js/0
{ "file_path": "overleaf/web/frontend/js/features/chat/context/chat-context.js", "repo_id": "overleaf", "token_count": 3172 }
506
import PropTypes from 'prop-types' import { useTranslation } from 'react-i18next' import Icon from '../../../shared/components/icon' function ShareProjectButton({ onClick }) { const { t } = useTranslation() return ( // eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/interactive-supports-focus <a role="button" className="btn btn-full-height" onClick={onClick}> <Icon type="fw" modifier="group" /> <p className="toolbar-label">{t('share')}</p> </a> ) } ShareProjectButton.propTypes = { onClick: PropTypes.func.isRequired, } export default ShareProjectButton
overleaf/web/frontend/js/features/editor-navigation-toolbar/components/share-project-button.js/0
{ "file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/share-project-button.js", "repo_id": "overleaf", "token_count": 237 }
507
import { useState, useEffect } from 'react' import { Trans } from 'react-i18next' import { useFileTreeMainContext } from '../../contexts/file-tree-main' // handle "not-logged-in" errors by redirecting to the login page export default function RedirectToLogin() { const { projectId } = useFileTreeMainContext() const [secondsToRedirect, setSecondsToRedirect] = useState(10) useEffect(() => { setSecondsToRedirect(10) const timer = window.setInterval(() => { setSecondsToRedirect(value => { if (value === 0) { window.clearInterval(timer) window.location.assign(`/login?redir=/project/${projectId}`) return 0 } return value - 1 }) }, 1000) return () => { window.clearInterval(timer) } }, [projectId]) return ( <Trans i18nKey="session_expired_redirecting_to_login" values={{ seconds: secondsToRedirect }} /> ) }
overleaf/web/frontend/js/features/file-tree/components/file-tree-create/redirect-to-login.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/redirect-to-login.js", "repo_id": "overleaf", "token_count": 373 }
508
import { createContext, useCallback, useMemo, useReducer, useContext, useEffect, } from 'react' import PropTypes from 'prop-types' import { mapSeries } from '../../../infrastructure/promise' import { syncRename, syncDelete, syncMove, syncCreateEntity, } from '../util/sync-mutation' import { findInTree, findInTreeOrThrow } from '../util/find-in-tree' import { isNameUniqueInFolder } from '../util/is-name-unique-in-folder' import { isBlockedFilename, isCleanFilename } from '../util/safe-path' import { useFileTreeMainContext } from './file-tree-main' import { useFileTreeMutable } from './file-tree-mutable' import { useFileTreeSelectable } from './file-tree-selectable' import { InvalidFilenameError, BlockedFilenameError, DuplicateFilenameError, DuplicateFilenameMoveError, } from '../errors' const FileTreeActionableContext = createContext() const ACTION_TYPES = { START_RENAME: 'START_RENAME', START_DELETE: 'START_DELETE', DELETING: 'DELETING', START_CREATE_FILE: 'START_CREATE_FILE', START_CREATE_FOLDER: 'START_CREATE_FOLDER', CREATING_FILE: 'CREATING_FILE', CREATING_FOLDER: 'CREATING_FOLDER', MOVING: 'MOVING', CANCEL: 'CANCEL', CLEAR: 'CLEAR', ERROR: 'ERROR', } const defaultState = { isDeleting: false, isRenaming: false, isCreatingFile: false, isCreatingFolder: false, isMoving: false, inFlight: false, actionedEntities: null, newFileCreateMode: null, error: null, } function fileTreeActionableReadOnlyReducer(state) { return state } function fileTreeActionableReducer(state, action) { switch (action.type) { case ACTION_TYPES.START_RENAME: return { ...defaultState, isRenaming: true } case ACTION_TYPES.START_DELETE: return { ...defaultState, isDeleting: true, actionedEntities: action.actionedEntities, } case ACTION_TYPES.START_CREATE_FILE: return { ...defaultState, isCreatingFile: true, newFileCreateMode: action.newFileCreateMode, } case ACTION_TYPES.START_CREATE_FOLDER: return { ...defaultState, isCreatingFolder: true } case ACTION_TYPES.CREATING_FILE: return { ...defaultState, isCreatingFile: true, newFileCreateMode: state.newFileCreateMode, inFlight: true, } case ACTION_TYPES.CREATING_FOLDER: return { ...defaultState, isCreatingFolder: true, inFlight: true } case ACTION_TYPES.DELETING: // keep `actionedEntities` so the entities list remains displayed in the // delete modal return { ...defaultState, isDeleting: true, inFlight: true, actionedEntities: state.actionedEntities, } case ACTION_TYPES.MOVING: return { ...defaultState, isMoving: true, inFlight: true, } case ACTION_TYPES.CLEAR: return { ...defaultState } case ACTION_TYPES.CANCEL: if (state.inFlight) return state return { ...defaultState } case ACTION_TYPES.ERROR: return { ...state, inFlight: false, error: action.error } default: throw new Error(`Unknown user action type: ${action.type}`) } } export function FileTreeActionableProvider({ hasWritePermissions, children }) { const [state, dispatch] = useReducer( hasWritePermissions ? fileTreeActionableReducer : fileTreeActionableReadOnlyReducer, defaultState ) const { projectId } = useFileTreeMainContext() const { fileTreeData, dispatchRename, dispatchMove } = useFileTreeMutable() const { selectedEntityIds } = useFileTreeSelectable() const startRenaming = useCallback(() => { dispatch({ type: ACTION_TYPES.START_RENAME }) }, []) // update the entity with the new name immediately in the tree, but revert to // the old name if the sync fails const finishRenaming = useCallback( newName => { const selectedEntityId = Array.from(selectedEntityIds)[0] const found = findInTreeOrThrow(fileTreeData, selectedEntityId) const oldName = found.entity.name if (newName === oldName) { return dispatch({ type: ACTION_TYPES.CLEAR }) } const error = validateRename(fileTreeData, found, newName) if (error) return dispatch({ type: ACTION_TYPES.ERROR, error }) dispatch({ type: ACTION_TYPES.CLEAR }) dispatchRename(selectedEntityId, newName) return syncRename(projectId, found.type, found.entity._id, newName).catch( error => { dispatchRename(selectedEntityId, oldName) // The state from this error action isn't used anywhere right now // but we need to handle the error for linting dispatch({ type: ACTION_TYPES.ERROR, error }) } ) }, [dispatchRename, fileTreeData, projectId, selectedEntityIds] ) const isDuplicate = useCallback( (parentFolderId, name) => { return !isNameUniqueInFolder(fileTreeData, parentFolderId, name) }, [fileTreeData] ) // init deletion flow (this will open the delete modal). // A copy of the selected entities is set as `actionedEntities` so it is kept // unchanged as the entities are deleted and the selection is updated const startDeleting = useCallback(() => { const actionedEntities = Array.from(selectedEntityIds).map( entityId => findInTreeOrThrow(fileTreeData, entityId).entity ) dispatch({ type: ACTION_TYPES.START_DELETE, actionedEntities }) }, [fileTreeData, selectedEntityIds]) // deletes entities in series. Tree will be updated via the socket event const finishDeleting = useCallback(() => { dispatch({ type: ACTION_TYPES.DELETING }) return mapSeries(Array.from(selectedEntityIds), id => { const found = findInTreeOrThrow(fileTreeData, id) return syncDelete(projectId, found.type, found.entity._id).catch( error => { // throw unless 404 if (error.info.statusCode !== 404) { throw error } } ) }) .then(() => { dispatch({ type: ACTION_TYPES.CLEAR }) }) .catch(error => { // set an error and allow user to retry dispatch({ type: ACTION_TYPES.ERROR, error }) }) }, [fileTreeData, projectId, selectedEntityIds]) // moves entities. Tree is updated immediately and data are sync'd after. const finishMoving = useCallback( (toFolderId, draggedEntityIds) => { dispatch({ type: ACTION_TYPES.MOVING }) // find entities and filter out no-ops const founds = Array.from(draggedEntityIds) .map(draggedEntityId => findInTreeOrThrow(fileTreeData, draggedEntityId) ) .filter(found => found.parentFolderId !== toFolderId) // make sure all entities can be moved, return early otherwise const isMoveToRoot = toFolderId === fileTreeData._id const validationError = founds .map(found => validateMove(fileTreeData, toFolderId, found, isMoveToRoot) ) .find(error => error) if (validationError) { return dispatch({ type: ACTION_TYPES.ERROR, error: validationError }) } // dispatch moves immediately founds.forEach(found => dispatchMove(found.entity._id, toFolderId)) // sync dispatched moves after return mapSeries(founds, found => syncMove(projectId, found.type, found.entity._id, toFolderId) ) .then(() => { dispatch({ type: ACTION_TYPES.CLEAR }) }) .catch(error => { dispatch({ type: ACTION_TYPES.ERROR, error }) }) }, [dispatchMove, fileTreeData, projectId] ) const startCreatingFolder = useCallback(() => { dispatch({ type: ACTION_TYPES.START_CREATE_FOLDER }) }, []) const parentFolderId = useMemo( () => getSelectedParentFolderId(fileTreeData, selectedEntityIds), [fileTreeData, selectedEntityIds] ) const finishCreatingEntity = useCallback( entity => { const error = validateCreate(fileTreeData, parentFolderId, entity) if (error) { return Promise.reject(error) } return syncCreateEntity(projectId, parentFolderId, entity) }, [fileTreeData, parentFolderId, projectId] ) const finishCreatingFolder = useCallback( name => { dispatch({ type: ACTION_TYPES.CREATING_FOLDER }) return finishCreatingEntity({ endpoint: 'folder', name }) .then(() => { dispatch({ type: ACTION_TYPES.CLEAR }) }) .catch(error => { dispatch({ type: ACTION_TYPES.ERROR, error }) }) }, [finishCreatingEntity] ) const startCreatingFile = useCallback(newFileCreateMode => { dispatch({ type: ACTION_TYPES.START_CREATE_FILE, newFileCreateMode }) }, []) const startCreatingDocOrFile = useCallback(() => { startCreatingFile('doc') }, [startCreatingFile]) const startUploadingDocOrFile = useCallback(() => { startCreatingFile('upload') }, [startCreatingFile]) const finishCreatingDocOrFile = useCallback( entity => { dispatch({ type: ACTION_TYPES.CREATING_FILE }) return finishCreatingEntity(entity) .then(() => { dispatch({ type: ACTION_TYPES.CLEAR }) }) .catch(error => { dispatch({ type: ACTION_TYPES.ERROR, error }) }) }, [finishCreatingEntity] ) const finishCreatingDoc = useCallback( entity => { entity.endpoint = 'doc' return finishCreatingDocOrFile(entity) }, [finishCreatingDocOrFile] ) const finishCreatingLinkedFile = useCallback( entity => { entity.endpoint = 'linked_file' return finishCreatingDocOrFile(entity) }, [finishCreatingDocOrFile] ) const cancel = useCallback(() => { dispatch({ type: ACTION_TYPES.CANCEL }) }, []) // listen for `file-tree.start-creating` events useEffect(() => { function handleEvent(event) { dispatch({ type: ACTION_TYPES.START_CREATE_FILE, newFileCreateMode: event.detail.mode, }) } window.addEventListener('file-tree.start-creating', handleEvent) return () => { window.removeEventListener('file-tree.start-creating', handleEvent) } }, []) const value = { canDelete: selectedEntityIds.size > 0, canRename: selectedEntityIds.size === 1, canCreate: selectedEntityIds.size < 2, ...state, parentFolderId, isDuplicate, startRenaming, finishRenaming, startDeleting, finishDeleting, finishMoving, startCreatingFile, startCreatingFolder, finishCreatingFolder, startCreatingDocOrFile, startUploadingDocOrFile, finishCreatingDoc, finishCreatingLinkedFile, cancel, } return ( <FileTreeActionableContext.Provider value={value}> {children} </FileTreeActionableContext.Provider> ) } FileTreeActionableProvider.propTypes = { hasWritePermissions: PropTypes.bool.isRequired, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, } export function useFileTreeActionable() { const context = useContext(FileTreeActionableContext) if (!context) { throw new Error( 'useFileTreeActionable is only available inside FileTreeActionableProvider' ) } return context } function getSelectedParentFolderId(fileTreeData, selectedEntityIds) { // we expect only one entity to be selected in that case, so we pick the first const selectedEntityId = Array.from(selectedEntityIds)[0] if (!selectedEntityId) { // in some cases no entities are selected. Return the root folder id then. return fileTreeData._id } const found = findInTree(fileTreeData, selectedEntityId) if (!found) { // if the entity isn't in the tree, return the root folder id. return fileTreeData._id } return found.type === 'folder' ? found.entity._id : found.parentFolderId } function validateCreate(fileTreeData, parentFolderId, entity) { if (!isCleanFilename(entity.name)) { return new InvalidFilenameError() } if (!isNameUniqueInFolder(fileTreeData, parentFolderId, entity.name)) { return new DuplicateFilenameError() } // check that the name of a file is allowed, if creating in the root folder const isMoveToRoot = parentFolderId === fileTreeData._id const isFolder = entity.endpoint === 'folder' if (isMoveToRoot && !isFolder && isBlockedFilename(entity.name)) { return new BlockedFilenameError() } } function validateRename(fileTreeData, found, newName) { if (!isCleanFilename(newName)) { return new InvalidFilenameError() } if (!isNameUniqueInFolder(fileTreeData, found.parentFolderId, newName)) { return new DuplicateFilenameError() } const isTopLevel = found.path.length === 1 const isFolder = found.type === 'folder' if (isTopLevel && !isFolder && isBlockedFilename(newName)) { return new BlockedFilenameError() } } function validateMove(fileTreeData, toFolderId, found, isMoveToRoot) { if (!isNameUniqueInFolder(fileTreeData, toFolderId, found.entity.name)) { const error = new DuplicateFilenameMoveError() error.entityName = found.entity.name return error } const isFolder = found.type === 'folder' if (isMoveToRoot && !isFolder && isBlockedFilename(found.entity.name)) { return new BlockedFilenameError() } }
overleaf/web/frontend/js/features/file-tree/contexts/file-tree-actionable.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/contexts/file-tree-actionable.js", "repo_id": "overleaf", "token_count": 4938 }
509
export default function iconTypeFromName(name) { let ext = name.split('.').pop() ext = ext ? ext.toLowerCase() : ext if (['png', 'pdf', 'jpg', 'jpeg', 'gif'].includes(ext)) { return 'image' } else if (['csv', 'xls', 'xlsx'].includes(ext)) { return 'table' } else if (['py', 'r'].includes(ext)) { return 'file-text' } else if (['bib'].includes(ext)) { return 'book' } else { return 'file' } }
overleaf/web/frontend/js/features/file-tree/util/icon-type-from-name.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/util/icon-type-from-name.js", "repo_id": "overleaf", "token_count": 175 }
510
import App from '../../../base' import OutlinePane from '../components/outline-pane' import { react2angular } from 'react2angular' import { rootContext } from '../../../shared/context/root-context' App.controller('OutlineController', function ($scope, ide, eventTracking) { $scope.isTexFile = false $scope.outline = [] $scope.eventTracking = eventTracking $scope.$on('outline-manager:outline-changed', onOutlineChange) function onOutlineChange(e, outlineInfo) { $scope.$applyAsync(() => { $scope.isTexFile = outlineInfo.isTexFile $scope.outline = outlineInfo.outline $scope.highlightedLine = outlineInfo.highlightedLine }) } $scope.jumpToLine = (lineNo, syncToPdf) => { ide.outlineManager.jumpToLine(lineNo, syncToPdf) eventTracking.sendMB('outline-jump-to-line') } $scope.onToggle = isOpen => { $scope.$applyAsync(() => { $scope.$emit('outline-toggled', isOpen) }) } }) // Wrap React component as Angular component. Only needed for "top-level" component App.component( 'outlinePane', react2angular(rootContext.use(OutlinePane), [ 'outline', 'jumpToLine', 'highlightedLine', 'eventTracking', 'onToggle', 'isTexFile', ]) )
overleaf/web/frontend/js/features/outline/controllers/outline-controller.js/0
{ "file_path": "overleaf/web/frontend/js/features/outline/controllers/outline-controller.js", "repo_id": "overleaf", "token_count": 457 }
511
import { useState, useEffect } from 'react' import PropTypes from 'prop-types' import { Trans, useTranslation } from 'react-i18next' import { useShareProjectContext } from './share-project-modal' import Icon from '../../../shared/components/icon' import TransferOwnershipModal from './transfer-ownership-modal' import { Button, Col, Form, FormControl, FormGroup, OverlayTrigger, Tooltip, } from 'react-bootstrap' import { removeMemberFromProject, updateMember } from '../utils/api' import { useProjectContext } from '../../../shared/context/project-context' export default function EditMember({ member }) { const [privileges, setPrivileges] = useState(member.privileges) const [ confirmingOwnershipTransfer, setConfirmingOwnershipTransfer, ] = useState(false) // update the local state if the member's privileges change externally useEffect(() => { setPrivileges(member.privileges) }, [member.privileges]) const { updateProject, monitorRequest } = useShareProjectContext() const project = useProjectContext() function handleSubmit(event) { event.preventDefault() if (privileges === 'owner') { setConfirmingOwnershipTransfer(true) } else { monitorRequest(() => updateMember(project, member, { privilegeLevel: privileges, }) ).then(() => { updateProject({ members: project.members.map(item => item._id === member._id ? { ...item, privileges } : item ), }) }) } } if (confirmingOwnershipTransfer) { return ( <TransferOwnershipModal member={member} cancel={() => setConfirmingOwnershipTransfer(false)} /> ) } return ( <Form horizontal id="share-project-form" onSubmit={handleSubmit}> <FormGroup className="project-member"> <Col xs={7}> <FormControl.Static>{member.email}</FormControl.Static> </Col> <Col xs={3}> <SelectPrivilege value={privileges} handleChange={event => setPrivileges(event.target.value)} /> </Col> <Col xs={2}> {privileges === member.privileges ? ( <RemoveMemberAction member={member} /> ) : ( <ChangePrivilegesActions handleReset={() => setPrivileges(member.privileges)} /> )} </Col> </FormGroup> </Form> ) } EditMember.propTypes = { member: PropTypes.shape({ _id: PropTypes.string.isRequired, email: PropTypes.string.isRequired, privileges: PropTypes.string.isRequired, }), } function SelectPrivilege({ value, handleChange }) { const { t } = useTranslation() return ( <FormControl componentClass="select" className="privileges" bsSize="sm" value={value} onChange={handleChange} > <option value="owner">{t('owner')}</option> <option value="readAndWrite">{t('can_edit')}</option> <option value="readOnly">{t('read_only')}</option> </FormControl> ) } SelectPrivilege.propTypes = { value: PropTypes.string.isRequired, handleChange: PropTypes.func.isRequired, } function RemoveMemberAction({ member }) { const { t } = useTranslation() const { updateProject, monitorRequest } = useShareProjectContext() const project = useProjectContext() function handleClick(event) { event.preventDefault() monitorRequest(() => removeMemberFromProject(project, member)).then(() => { updateProject({ members: project.members.filter(existing => existing !== member), }) }) } return ( <FormControl.Static className="text-center"> <OverlayTrigger placement="bottom" overlay={ <Tooltip id="tooltip-remove-collaborator"> <Trans i18nKey="remove_collaborator" /> </Tooltip> } > <Button type="button" bsStyle="link" onClick={handleClick} className="remove-button" aria-label={t('remove_collaborator')} > <Icon type="times" /> </Button> </OverlayTrigger> </FormControl.Static> ) } RemoveMemberAction.propTypes = { member: PropTypes.shape({ _id: PropTypes.string.isRequired, email: PropTypes.string.isRequired, privileges: PropTypes.string.isRequired, }), } function ChangePrivilegesActions({ handleReset }) { return ( <div className="text-center"> <Button type="submit" bsSize="sm" bsStyle="success"> <Trans i18nKey="change_or_cancel-change" /> </Button> <div className="text-sm"> <Trans i18nKey="change_or_cancel-or" /> &nbsp; <Button type="button" className="btn-inline-link" onClick={handleReset}> <Trans i18nKey="change_or_cancel-cancel" /> </Button> </div> </div> ) } ChangePrivilegesActions.propTypes = { handleReset: PropTypes.func.isRequired, }
overleaf/web/frontend/js/features/share-project-modal/components/edit-member.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/edit-member.js", "repo_id": "overleaf", "token_count": 2011 }
512
let _recaptchaId let _recaptchaResolve export function executeV2Captcha(disabled = false) { return new Promise((resolve, reject) => { if (disabled || !window.grecaptcha) { return resolve() } try { if (!_recaptchaId) { _recaptchaId = window.grecaptcha.render('recaptcha', { callback: token => { if (_recaptchaResolve) { _recaptchaResolve(token) _recaptchaResolve = undefined } window.grecaptcha.reset() }, }) } _recaptchaResolve = resolve } catch (error) { reject(error) } }) }
overleaf/web/frontend/js/features/share-project-modal/utils/captcha.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/utils/captcha.js", "repo_id": "overleaf", "token_count": 308 }
513
import App from '../../../base' import { react2angular } from 'react2angular' import WordCountModal from '../components/word-count-modal' App.component('wordCountModal', react2angular(WordCountModal)) export default App.controller( 'WordCountModalController', function ($scope, ide) { $scope.show = false $scope.projectId = ide.project_id $scope.handleHide = () => { $scope.$applyAsync(() => { $scope.show = false }) } $scope.openWordCountModal = () => { $scope.$applyAsync(() => { $scope.clsiServerId = ide.clsiServerId $scope.projectId = ide.project_id $scope.show = true }) } } )
overleaf/web/frontend/js/features/word-count-modal/controllers/word-count-modal-controller.js/0
{ "file_path": "overleaf/web/frontend/js/features/word-count-modal/controllers/word-count-modal-controller.js", "repo_id": "overleaf", "token_count": 271 }
514
// 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 */ /* global io */ import SocketIoShim from './SocketIoShim' let ConnectionManager const ONEHOUR = 1000 * 60 * 60 export default ConnectionManager = (function () { ConnectionManager = class ConnectionManager { static initClass() { this.prototype.disconnectAfterMs = ONEHOUR * 24 this.prototype.lastUserAction = new Date() this.prototype.MIN_RETRY_INTERVAL = 1000 // ms, rate limit on reconnects for user clicking "try now" this.prototype.BACKGROUND_RETRY_INTERVAL = 5 * 1000 this.prototype.JOIN_PROJECT_RETRY_INTERVAL = 5000 this.prototype.JOIN_PROJECT_MAX_RETRY_INTERVAL = 60000 this.prototype.RECONNECT_GRACEFULLY_RETRY_INTERVAL = 5000 // ms this.prototype.MAX_RECONNECT_GRACEFULLY_INTERVAL = 45 * 1000 } constructor(ide, $scope) { this.ide = ide this.$scope = $scope this.wsUrl = ide.wsUrl || null // websocket url (if defined) if (typeof io === 'undefined' || io === null) { if (this.wsUrl && !window.location.href.match(/ws=fallback/)) { // if we tried to boot from a custom real-time backend and failed, // try reloading and falling back to the siteUrl window.location = window.location.href + '?ws=fallback' } console.error( 'Socket.io javascript not loaded. Please check that the real-time service is running and accessible.' ) this.ide.socket = SocketIoShim.stub() this.$scope.$apply(() => { return (this.$scope.state.error = 'Could not connect to websocket server :(') }) return } setInterval(() => { return this.disconnectIfInactive() }, ONEHOUR) // trigger a reconnect immediately if network comes back online window.addEventListener('online', () => { sl_console.log('[online] browser notified online') if (!this.connected) { return this.tryReconnectWithRateLimit({ force: true }) } }) this.userIsLeavingPage = false window.addEventListener('beforeunload', () => { this.userIsLeavingPage = true }) // Don't return true or it will show a pop up this.connected = false this.userIsInactive = false this.gracefullyReconnecting = false this.shuttingDown = false this.joinProjectRetryInterval = this.JOIN_PROJECT_RETRY_INTERVAL this.$scope.connection = { debug: sl_debugging, reconnecting: false, stillReconnecting: false, // If we need to force everyone to reload the editor forced_disconnect: false, inactive_disconnect: false, jobId: 0, } this.$scope.tryReconnectNow = () => { // user manually requested reconnection via "Try now" button return this.tryReconnectWithRateLimit({ force: true }) } this.$scope.$on('cursor:editor:update', () => { this.lastUserAction = new Date() // time of last edit if (!this.connected) { // user is editing, try to reconnect return this.tryReconnectWithRateLimit() } }) document.querySelector('body').addEventListener('click', e => { if ( !this.shuttingDown && !this.connected && e.target.id !== 'try-reconnect-now-button' ) { // user is editing, try to reconnect return this.tryReconnectWithRateLimit() } }) // initial connection attempt this.updateConnectionManagerState('connecting') let parsedURL try { parsedURL = new URL(this.wsUrl || '/socket.io', window.location) } catch (e) { // hello IE11 if ( this.wsUrl && this.wsUrl.indexOf('/') !== 0 && !window.location.href.match(/ws=fallback/) ) { // do not even try parsing the wsUrl, use the fallback window.location = window.location.href + '?ws=fallback' } parsedURL = { origin: null, pathname: this.wsUrl || '/socket.io', } } this.ide.socket = SocketIoShim.connect(parsedURL.origin, { resource: parsedURL.pathname.slice(1), reconnect: false, 'connect timeout': 30 * 1000, 'force new connection': true, }) // handle network-level websocket errors (e.g. failed dns lookups) let connectionAttempt = 1 const connectionErrorHandler = err => { if ( window.wsRetryHandshake && connectionAttempt++ < window.wsRetryHandshake ) { return setTimeout(() => this.ide.socket.socket.connect(), 100) } this.updateConnectionManagerState('error') sl_console.log('socket.io error', err) if (this.wsUrl && !window.location.href.match(/ws=fallback/)) { // if we tried to load a custom websocket location and failed // try reloading and falling back to the siteUrl window.location = window.location.href + '?ws=fallback' } else { this.connected = false return this.$scope.$apply(() => { return (this.$scope.state.error = "Unable to connect, please view the <u><a href='/learn/Kb/Connection_problems'>connection problems guide</a></u> to fix the issue.") }) } } this.ide.socket.on('error', connectionErrorHandler) // The "connect" event is the first event we get back. It only // indicates that the websocket is connected, we still need to // pass authentication to join a project. this.ide.socket.on('connect', () => { // state should be 'connecting'... // remove connection error handler when connected, avoid unwanted fallbacks this.ide.socket.removeListener('error', connectionErrorHandler) sl_console.log('[socket.io connect] Connected') this.updateConnectionManagerState('authenticating') }) // The next event we should get is an authentication response // from the server, either "connectionAccepted" or // "connectionRejected". this.ide.socket.on('connectionAccepted', (_, publicId) => { this.ide.socket.publicId = publicId || this.ide.socket.socket.sessionid // state should be 'authenticating'... sl_console.log('[socket.io connectionAccepted] allowed to connect') this.connected = true this.gracefullyReconnecting = false this.ide.pushEvent('connected') this.updateConnectionManagerState('joining') this.$scope.$apply(() => { if (this.$scope.state.loading) { this.$scope.state.load_progress = 70 } }) // we have passed authentication so we can now join the project const connectionJobId = this.$scope.connection.jobId setTimeout(() => { this.joinProject(connectionJobId) }, 100) }) this.ide.socket.on('connectionRejected', err => { // state should be 'authenticating'... sl_console.log( '[socket.io connectionRejected] session not valid or other connection error' ) // real time sends a 'retry' message if the process was shutting down if (err && err.message === 'retry') { return this.tryReconnectWithRateLimit() } // we have failed authentication, usually due to an invalid session cookie return this.reportConnectionError(err) }) // Alternatively the attempt to connect can fail completely, so // we never get into the "connect" state. this.ide.socket.on('connect_failed', () => { this.updateConnectionManagerState('error') this.connected = false return this.$scope.$apply(() => { return (this.$scope.state.error = "Unable to connect, please view the <u><a href='/learn/Kb/Connection_problems'>connection problems guide</a></u> to fix the issue.") }) }) // We can get a "disconnect" event at any point after the // "connect" event. this.ide.socket.on('disconnect', () => { sl_console.log('[socket.io disconnect] Disconnected') this.connected = false this.ide.pushEvent('disconnected') if (!this.$scope.connection.state.match(/^waiting/)) { if ( !this.$scope.connection.forced_disconnect && !this.userIsInactive && !this.shuttingDown ) { this.startAutoReconnectCountdown() } else { this.updateConnectionManagerState('inactive') } } }) // Site administrators can send the forceDisconnect event to all users this.ide.socket.on('forceDisconnect', (message, delay = 10) => { this.updateConnectionManagerState('inactive') this.shuttingDown = true // prevent reconnection attempts this.$scope.$apply(() => { this.$scope.permissions.write = false return (this.$scope.connection.forced_disconnect = true) }) // flush changes before disconnecting this.ide.$scope.$broadcast('flush-changes') setTimeout(() => this.ide.socket.disconnect(), 1000) this.ide.showLockEditorMessageModal( 'Please wait', `\ We're performing maintenance on Overleaf and you need to wait a moment. Sorry for any inconvenience. The editor will refresh automatically in ${delay} seconds.\ ` ) return setTimeout(() => location.reload(), delay * 1000) }) this.ide.socket.on('reconnectGracefully', () => { sl_console.log('Reconnect gracefully') this.reconnectGracefully() }) this.ide.socket.on('unregisterServiceWorker', () => { sl_console.log('Unregister service worker') this.$scope.$broadcast('service-worker:unregister') }) } updateConnectionManagerState(state) { this.$scope.$apply(() => { this.$scope.connection.jobId += 1 const jobId = this.$scope.connection.jobId sl_console.log( `[updateConnectionManagerState ${jobId}] from ${this.$scope.connection.state} to ${state}` ) this.$scope.connection.state = state this.$scope.connection.reconnecting = false this.$scope.connection.stillReconnecting = false this.$scope.connection.inactive_disconnect = false this.$scope.connection.joining = false this.$scope.connection.reconnection_countdown = null if (state === 'connecting') { // initial connection } else if (state === 'reconnecting') { // reconnection after a connection has failed this.stopReconnectCountdownTimer() this.$scope.connection.reconnecting = true // if reconnecting takes more than 1s (it doesn't, usually) show the // 'reconnecting...' warning setTimeout(() => { if ( this.$scope.connection.reconnecting && this.$scope.connection.jobId === jobId ) { this.$scope.connection.stillReconnecting = true } }, 1000) } else if (state === 'reconnectFailed') { // reconnect attempt failed } else if (state === 'authenticating') { // socket connection has been established, trying to authenticate } else if (state === 'joining') { // authenticated, joining project this.$scope.connection.joining = true } else if (state === 'ready') { // project has been joined } else if (state === 'waitingCountdown') { // disconnected and waiting to reconnect via the countdown timer this.stopReconnectCountdownTimer() } else if (state === 'waitingGracefully') { // disconnected and waiting to reconnect gracefully this.stopReconnectCountdownTimer() } else if (state === 'inactive') { // disconnected and not trying to reconnect (inactive) } else if (state === 'error') { // something is wrong } else { sl_console.log( `[WARN] [updateConnectionManagerState ${jobId}] got unrecognised state ${state}` ) } }) } expectConnectionManagerState(state, jobId) { if ( this.$scope.connection.state === state && (!jobId || jobId === this.$scope.connection.jobId) ) { return true } sl_console.log( `[WARN] [state mismatch] expected state ${state}${ jobId ? '/' + jobId : '' } when in ${this.$scope.connection.state}/${ this.$scope.connection.jobId }` ) return false } // Error reporting, which can reload the page if appropriate reportConnectionError(err) { sl_console.log('[socket.io] reporting connection error') this.updateConnectionManagerState('error') if ( (err != null ? err.message : undefined) === 'not authorized' || (err != null ? err.message : undefined) === 'invalid session' ) { return (window.location = `/login?redir=${encodeURI( window.location.pathname )}`) } else { this.ide.socket.disconnect() return this.ide.showGenericMessageModal( 'Something went wrong connecting', `\ Something went wrong connecting to your project. Please refresh if this continues to happen.\ ` ) } } joinProject(connectionId) { sl_console.log(`[joinProject ${connectionId}] joining...`) // Note: if the "joinProject" message doesn't reach the server // (e.g. if we are in a disconnected state at this point) the // callback will never be executed if (!this.expectConnectionManagerState('joining', connectionId)) { sl_console.log( `[joinProject ${connectionId}] aborting with stale connection` ) return } const data = { project_id: this.ide.project_id, } if (window.anonymousAccessToken) { data.anonymousAccessToken = window.anonymousAccessToken } this.ide.socket.emit( 'joinProject', data, (err, project, permissionsLevel, protocolVersion) => { if (err != null || project == null) { err = err || {} if (err.code === 'ProjectNotFound') { // A stale browser tab tried to join a deleted project. // Reloading the page will render a 404. this.ide .showGenericMessageModal( 'Project has been deleted', 'This project has been deleted by the owner.' ) .result.then(() => location.reload(true)) return } if (err.code === 'TooManyRequests') { sl_console.log( `[joinProject ${connectionId}] retrying: ${err.message}` ) setTimeout( () => this.joinProject(connectionId), this.joinProjectRetryInterval ) if ( this.joinProjectRetryInterval < this.JOIN_PROJECT_MAX_RETRY_INTERVAL ) { this.joinProjectRetryInterval += this.JOIN_PROJECT_RETRY_INTERVAL } return } else { return this.reportConnectionError(err) } } this.joinProjectRetryInterval = this.JOIN_PROJECT_RETRY_INTERVAL if ( this.$scope.protocolVersion != null && this.$scope.protocolVersion !== protocolVersion ) { location.reload(true) } this.$scope.$apply(() => { this.updateConnectionManagerState('ready') this.$scope.protocolVersion = protocolVersion const defaultProjectAttributes = { rootDoc_id: null } this.$scope.project = { ...defaultProjectAttributes, ...project } this.$scope.permissionsLevel = permissionsLevel this.ide.loadingManager.socketLoaded() this.$scope.$broadcast('project:joined') }) } ) } reconnectImmediately() { this.disconnect() return this.tryReconnect() } disconnect(options) { if (options && options.permanent) { sl_console.log('[disconnect] shutting down ConnectionManager') this.updateConnectionManagerState('inactive') this.shuttingDown = true // prevent reconnection attempts } else if (this.ide.socket.socket && !this.ide.socket.socket.connected) { sl_console.log( '[socket.io] skipping disconnect because socket.io has not connected' ) return } sl_console.log('[socket.io] disconnecting client') return this.ide.socket.disconnect() } startAutoReconnectCountdown() { this.updateConnectionManagerState('waitingCountdown') const connectionId = this.$scope.connection.jobId let countdown sl_console.log('[ConnectionManager] starting autoreconnect countdown') const twoMinutes = 2 * 60 * 1000 if ( this.lastUserAction != null && new Date() - this.lastUserAction > twoMinutes ) { // between 1 minute and 3 minutes countdown = 60 + Math.floor(Math.random() * 120) } else { countdown = 3 + Math.floor(Math.random() * 7) } if (this.userIsLeavingPage) { // user will have pressed refresh or back etc return } this.$scope.$apply(() => { this.$scope.connection.reconnecting = false this.$scope.connection.stillReconnecting = false this.$scope.connection.joining = false this.$scope.connection.reconnection_countdown = countdown }) setTimeout(() => { if (!this.connected && !this.countdownTimeoutId) { this.countdownTimeoutId = setTimeout( () => this.decreaseCountdown(connectionId), 1000 ) } }, 200) } stopReconnectCountdownTimer() { // clear timeout and set to null so we know there is no countdown running if (this.countdownTimeoutId != null) { sl_console.log( '[ConnectionManager] cancelling existing reconnect timer' ) clearTimeout(this.countdownTimeoutId) this.countdownTimeoutId = null } } decreaseCountdown(connectionId) { this.countdownTimeoutId = null if (this.$scope.connection.reconnection_countdown == null) { return } if ( !this.expectConnectionManagerState('waitingCountdown', connectionId) ) { sl_console.log( `[ConnectionManager] Aborting stale countdown ${connectionId}` ) return } sl_console.log( '[ConnectionManager] decreasing countdown', this.$scope.connection.reconnection_countdown ) this.$scope.$apply(() => { this.$scope.connection.reconnection_countdown-- }) if (this.$scope.connection.reconnection_countdown <= 0) { this.$scope.connection.reconnecting = false this.$scope.$apply(() => { this.tryReconnect() }) } else { this.countdownTimeoutId = setTimeout( () => this.decreaseCountdown(connectionId), 1000 ) } } tryReconnect() { sl_console.log('[ConnectionManager] tryReconnect') if ( this.connected || this.shuttingDown || this.$scope.connection.reconnecting ) { return } this.updateConnectionManagerState('reconnecting') sl_console.log('[ConnectionManager] Starting new connection') const removeHandler = () => { this.ide.socket.removeListener('error', handleFailure) this.ide.socket.removeListener('connect', handleSuccess) } const handleFailure = () => { sl_console.log('[ConnectionManager] tryReconnect: failed') removeHandler() this.updateConnectionManagerState('reconnectFailed') this.tryReconnectWithRateLimit({ force: true }) } const handleSuccess = () => { sl_console.log('[ConnectionManager] tryReconnect: success') removeHandler() } this.ide.socket.on('error', handleFailure) this.ide.socket.on('connect', handleSuccess) // use socket.io connect() here to make a single attempt, the // reconnect() method makes multiple attempts this.ide.socket.socket.connect() // record the time of the last attempt to connect this.lastConnectionAttempt = new Date() } tryReconnectWithRateLimit(options) { // bail out if the reconnect is already in progress if (this.$scope.connection.reconnecting || this.connected) { return } // bail out if we are going to reconnect soon anyway const reconnectingSoon = this.$scope.connection.reconnection_countdown != null && this.$scope.connection.reconnection_countdown <= 5 const clickedTryNow = options != null ? options.force : undefined // user requested reconnection if (reconnectingSoon && !clickedTryNow) { return } // bail out if we tried reconnecting recently const allowedInterval = clickedTryNow ? this.MIN_RETRY_INTERVAL : this.BACKGROUND_RETRY_INTERVAL if ( this.lastConnectionAttempt != null && new Date() - this.lastConnectionAttempt < allowedInterval ) { if (this.$scope.connection.state !== 'waitingCountdown') { this.startAutoReconnectCountdown() } return } this.tryReconnect() } disconnectIfInactive() { this.userIsInactive = new Date() - this.lastUserAction > this.disconnectAfterMs if (this.userIsInactive && this.connected) { this.disconnect() return this.$scope.$apply(() => { return (this.$scope.connection.inactive_disconnect = true) }) // 5 minutes } } reconnectGracefully(force) { if (this.reconnectGracefullyStarted == null) { this.reconnectGracefullyStarted = new Date() } else { if (!force) { sl_console.log( '[reconnectGracefully] reconnection is already in process, so skipping' ) return } } const userIsInactive = new Date() - this.lastUserAction > this.RECONNECT_GRACEFULLY_RETRY_INTERVAL const maxIntervalReached = new Date() - this.reconnectGracefullyStarted > this.MAX_RECONNECT_GRACEFULLY_INTERVAL if (userIsInactive || maxIntervalReached) { sl_console.log( "[reconnectGracefully] User didn't do anything for last 5 seconds, reconnecting" ) this._reconnectGracefullyNow() } else { sl_console.log( '[reconnectGracefully] User is working, will try again in 5 seconds' ) this.updateConnectionManagerState('waitingGracefully') setTimeout(() => { this.reconnectGracefully(true) }, this.RECONNECT_GRACEFULLY_RETRY_INTERVAL) } } _reconnectGracefullyNow() { this.gracefullyReconnecting = true this.reconnectGracefullyStarted = null // Clear cookie so we don't go to the same backend server $.cookie('SERVERID', '', { expires: -1, path: '/' }) return this.reconnectImmediately() } } ConnectionManager.initClass() return ConnectionManager })()
overleaf/web/frontend/js/ide/connection/ConnectionManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/connection/ConnectionManager.js", "repo_id": "overleaf", "token_count": 9967 }
515
import _ from 'lodash' /* eslint-disable 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 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import Environments from './snippets/Environments' let staticSnippets = Array.from(Environments.withoutSnippets).map(env => ({ caption: `\\begin{${env}}...`, snippet: `\ \\begin{${env}} \t$1 \\end{${env}}\ `, meta: 'env', })) staticSnippets = staticSnippets.concat([ { caption: '\\begin{array}...', snippet: `\ \\begin{array}{\${1:cc}} \t$2 & $3 \\\\\\\\ \t$4 & $5 \\end{array}\ `, meta: 'env', }, { caption: '\\begin{figure}...', snippet: `\ \\begin{figure} \t\\centering \t\\includegraphics{$1} \t\\caption{\${2:Caption}} \t\\label{\${3:fig:my_label}} \\end{figure}\ `, meta: 'env', }, { caption: '\\begin{tabular}...', snippet: `\ \\begin{tabular}{\${1:c|c}} \t$2 & $3 \\\\\\\\ \t$4 & $5 \\end{tabular}\ `, meta: 'env', }, { caption: '\\begin{table}...', snippet: `\ \\begin{table}[$1] \t\\centering \t\\begin{tabular}{\${2:c|c}} \t\t$3 & $4 \\\\\\\\ \t\t$5 & $6 \t\\end{tabular} \t\\caption{\${7:Caption}} \t\\label{\${8:tab:my_label}} \\end{table}\ `, meta: 'env', }, { caption: '\\begin{list}...', snippet: `\ \\begin{list} \t\\item $1 \\end{list}\ `, meta: 'env', }, { caption: '\\begin{enumerate}...', snippet: `\ \\begin{enumerate} \t\\item $1 \\end{enumerate}\ `, meta: 'env', }, { caption: '\\begin{itemize}...', snippet: `\ \\begin{itemize} \t\\item $1 \\end{itemize}\ `, meta: 'env', }, { caption: '\\begin{frame}...', snippet: `\ \\begin{frame}{\${1:Frame Title}} \t$2 \\end{frame}\ `, meta: 'env', }, ]) const documentSnippet = { caption: '\\begin{document}...', snippet: `\ \\begin{document} $1 \\end{document}\ `, meta: 'env', } const bibliographySnippet = { caption: '\\begin{thebibliography}...', snippet: `\ \\begin{thebibliography}{$1} \\bibitem{$2} $3 \\end{thebibliography}\ `, meta: 'env', } staticSnippets.push(documentSnippet) const parseCustomEnvironments = function (text) { let match const re = /^\\newenvironment{(\w+)}.*$/gm const result = [] let iterations = 0 while ((match = re.exec(text))) { result.push({ name: match[1], whitespace: null }) iterations += 1 if (iterations >= 1000) { return result } } return result } const parseBeginCommands = function (text) { let match const re = /^([\t ]*)\\begin{(\w+)}.*\n([\t ]*)/gm const result = [] let iterations = 0 while ((match = re.exec(text))) { const whitespaceAlignment = match[3].replace(match[1] || '', '') if ( !Array.from(Environments.all).includes(match[2]) && match[2] !== 'document' ) { result.push({ name: match[2], whitespace: whitespaceAlignment }) iterations += 1 if (iterations >= 1000) { return result } } re.lastIndex = match.index + 1 } return result } const hasDocumentEnvironment = function (text) { const re = /^\\begin{document}/m return re.exec(text) !== null } const hasBibliographyEnvironment = function (text) { const re = /^\\begin{thebibliography}/m return re.exec(text) !== null } class EnvironmentManager { getCompletions(editor, session, pos, prefix, callback) { let ind const docText = session.getValue() const customEnvironments = parseCustomEnvironments(docText) const beginCommands = parseBeginCommands(docText) if (hasDocumentEnvironment(docText)) { ind = staticSnippets.indexOf(documentSnippet) if (ind !== -1) { staticSnippets.splice(ind, 1) } } else { staticSnippets.push(documentSnippet) } if (hasBibliographyEnvironment(docText)) { ind = staticSnippets.indexOf(bibliographySnippet) if (ind !== -1) { staticSnippets.splice(ind, 1) } } else { staticSnippets.push(bibliographySnippet) } const parsedItemsMap = {} for (const environment of Array.from(customEnvironments)) { parsedItemsMap[environment.name] = environment } for (const command of Array.from(beginCommands)) { parsedItemsMap[command.name] = command } const parsedItems = _.values(parsedItemsMap) const snippets = staticSnippets .concat( parsedItems.map(item => ({ caption: `\\begin{${item.name}}...`, snippet: `\ \\begin{${item.name}} ${item.whitespace || ''}$0 \\end{${item.name}}\ `, meta: 'env', })) ) .concat( // arguably these `end` commands shouldn't be here, as they're not snippets // but this is where we have access to the `begin` environment names // *shrug* parsedItems.map(item => ({ caption: `\\end{${item.name}}`, value: `\\end{${item.name}}`, meta: 'env', })) ) return callback(null, snippets) } } export default EnvironmentManager
overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/EnvironmentManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/EnvironmentManager.js", "repo_id": "overleaf", "token_count": 2172 }
516
/* eslint-disable camelcase, node/handle-callback-err, max-len, no-dupe-class-members, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__ * DS202: Simplify dynamic range loops * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import './directives/fileEntity' import './controllers/FileTreeController' import './controllers/FileTreeEntityController' import './controllers/FileTreeFolderController' import '../../features/file-tree/controllers/file-tree-controller' let FileTreeManager export default FileTreeManager = class FileTreeManager { constructor(ide, $scope) { this.ide = ide this.$scope = $scope this.$scope.$on('project:joined', () => { this.loadRootFolder() this.loadDeletedDocs() return this.$scope.$emit('file-tree:initialized') }) this.$scope.$on('entities:multiSelected', (_event, data) => { this.$scope.$apply(() => { this.$scope.multiSelectedCount = data.count }) }) this.$scope.$watch('rootFolder', rootFolder => { if (rootFolder != null) { return this.recalculateDocList() } }) this._bindToSocketEvents() this.$scope.multiSelectedCount = 0 $(document).on('click', () => { this.clearMultiSelectedEntities() return this.$scope.$digest() }) } _bindToSocketEvents() { this.ide.socket.on('reciveNewDoc', (parent_folder_id, doc) => { const parent_folder = this.findEntityById(parent_folder_id) || this.$scope.rootFolder return this.$scope.$apply(() => { parent_folder.children.push({ name: doc.name, id: doc._id, type: 'doc', }) return this.recalculateDocList() }) }) this.ide.socket.on( 'reciveNewFile', (parent_folder_id, file, source, linkedFileData) => { const parent_folder = this.findEntityById(parent_folder_id) || this.$scope.rootFolder return this.$scope.$apply(() => { parent_folder.children.push({ name: file.name, id: file._id, type: 'file', linkedFileData, created: file.created, }) return this.recalculateDocList() }) } ) this.ide.socket.on('reciveNewFolder', (parent_folder_id, folder) => { const parent_folder = this.findEntityById(parent_folder_id) || this.$scope.rootFolder return this.$scope.$apply(() => { parent_folder.children.push({ name: folder.name, id: folder._id, type: 'folder', children: [], }) return this.recalculateDocList() }) }) this.ide.socket.on('reciveEntityRename', (entity_id, name) => { const entity = this.findEntityById(entity_id) if (entity == null) { return } return this.$scope.$apply(() => { entity.name = name return this.recalculateDocList() }) }) this.ide.socket.on('removeEntity', entity_id => { const entity = this.findEntityById(entity_id) if (entity == null) { return } this.$scope.$apply(() => { this._deleteEntityFromScope(entity) return this.recalculateDocList() }) return this.$scope.$broadcast('entity:deleted', entity) }) return this.ide.socket.on('reciveEntityMove', (entity_id, folder_id) => { const entity = this.findEntityById(entity_id) const folder = this.findEntityById(folder_id) return this.$scope.$apply(() => { this._moveEntityInScope(entity, folder) return this.recalculateDocList() }) }) } selectEntity(entity) { this.selected_entity_id = entity.id // For reselecting after a reconnect this.ide.fileTreeManager.forEachEntity(entity => (entity.selected = false)) return (entity.selected = true) } toggleMultiSelectEntity(entity) { entity.multiSelected = !entity.multiSelected return (this.$scope.multiSelectedCount = this.multiSelectedCount()) } multiSelectedCount() { let count = 0 this.forEachEntity(function (entity) { if (entity.multiSelected) { return count++ } }) return count } getMultiSelectedEntities() { const entities = [] this.forEachEntity(function (e) { if (e.multiSelected) { return entities.push(e) } }) return entities } getFullCount() { const entities = [] this.forEachEntity(function (e) { if (!e.deleted) entities.push(e) }) return entities.length } getMultiSelectedEntityChildNodes() { // use pathnames with a leading slash to avoid // problems with reserved Object properties const entities = this.getMultiSelectedEntities() const paths = {} for (var entity of Array.from(entities)) { paths['/' + this.getEntityPath(entity)] = entity } const prefixes = {} for (var path in paths) { entity = paths[path] const parts = path.split('/') if (parts.length <= 2) { continue } else { // Record prefixes a/b/c.tex -> 'a' and 'a/b' for ( let i = 1, end = parts.length - 1, asc = end >= 1; asc ? i <= end : i >= end; asc ? i++ : i-- ) { prefixes['/' + parts.slice(0, i).join('/')] = true } } } const child_entities = [] for (path in paths) { // If the path is in the prefixes, then it's a parent folder and // should be ignore entity = paths[path] if (prefixes[path] == null) { child_entities.push(entity) } } return child_entities } clearMultiSelectedEntities() { if (this.$scope.multiSelectedCount === 0) { return } // Be efficient, this is called a lot on 'click' this.forEachEntity(entity => (entity.multiSelected = false)) return (this.$scope.multiSelectedCount = 0) } multiSelectSelectedEntity() { const entity = this.findSelectedEntity() if (entity) { entity.multiSelected = true } this.$scope.multiSelectedCount = this.multiSelectedCount() } existsInFolder(folder_id, name) { const folder = this.findEntityById(folder_id) if (folder == null) { return false } const entity = this._findEntityByPathInFolder(folder, name) return entity != null } findSelectedEntity() { let selected = null this.forEachEntity(function (entity) { if (entity.selected) { return (selected = entity) } }) return selected } findEntityById(id, options) { if (options == null) { options = {} } if (this.$scope.rootFolder.id === id) { return this.$scope.rootFolder } let entity = this._findEntityByIdInFolder(this.$scope.rootFolder, id) if (entity != null) { return entity } if (options.includeDeleted) { for (entity of Array.from(this.$scope.deletedDocs)) { if (entity.id === id) { return entity } } } return null } _findEntityByIdInFolder(folder, id) { for (const entity of Array.from(folder.children || [])) { if (entity.id === id) { return entity } else if (entity.children != null) { const result = this._findEntityByIdInFolder(entity, id) if (result != null) { return result } } } return null } findEntityByPath(path) { return this._findEntityByPathInFolder(this.$scope.rootFolder, path) } _findEntityByPathInFolder(folder, path) { if (path == null || folder == null) { return null } if (path === '') { return folder } const parts = path.split('/') const name = parts.shift() const rest = parts.join('/') if (name === '.') { return this._findEntityByPathInFolder(folder, rest) } for (const entity of Array.from(folder.children)) { if (entity.name === name) { if (rest === '') { return entity } else if (entity.type === 'folder') { return this._findEntityByPathInFolder(entity, rest) } } } return null } forEachEntity(callback) { if (callback == null) { callback = function (entity, parent_folder, path) {} } this._forEachEntityInFolder(this.$scope.rootFolder, null, callback) return (() => { const result = [] for (const entity of Array.from(this.$scope.deletedDocs || [])) { result.push(callback(entity)) } return result })() } _forEachEntityInFolder(folder, path, callback) { return (() => { const result = [] for (const entity of Array.from(folder.children || [])) { var childPath if (path != null) { childPath = path + '/' + entity.name } else { childPath = entity.name } callback(entity, folder, childPath) if (entity.children != null) { result.push(this._forEachEntityInFolder(entity, childPath, callback)) } else { result.push(undefined) } } return result })() } getEntityPath(entity) { return this._getEntityPathInFolder(this.$scope.rootFolder, entity) } _getEntityPathInFolder(folder, entity) { for (const child of Array.from(folder.children || [])) { if (child === entity) { return entity.name } else if (child.type === 'folder') { const path = this._getEntityPathInFolder(child, entity) if (path != null) { return child.name + '/' + path } } } return null } getRootDocDirname() { const rootDoc = this.findEntityById(this.$scope.project.rootDoc_id) if (rootDoc == null) { return } return this._getEntityDirname(rootDoc) } _getEntityDirname(entity) { const path = this.getEntityPath(entity) if (path == null) { return } return path.split('/').slice(0, -1).join('/') } _findParentFolder(entity) { const dirname = this._getEntityDirname(entity) if (dirname == null) { return } return this.findEntityByPath(dirname) } loadRootFolder() { return (this.$scope.rootFolder = this._parseFolder( __guard__( this.$scope != null ? this.$scope.project : undefined, x => x.rootFolder[0] ) )) } _parseFolder(rawFolder) { const folder = { name: rawFolder.name, id: rawFolder._id, type: 'folder', children: [], selected: rawFolder._id === this.selected_entity_id, } for (const doc of Array.from(rawFolder.docs || [])) { folder.children.push({ name: doc.name, id: doc._id, type: 'doc', selected: doc._id === this.selected_entity_id, }) } for (const file of Array.from(rawFolder.fileRefs || [])) { folder.children.push({ name: file.name, id: file._id, type: 'file', selected: file._id === this.selected_entity_id, linkedFileData: file.linkedFileData, created: file.created, }) } for (const childFolder of Array.from(rawFolder.folders || [])) { folder.children.push(this._parseFolder(childFolder)) } return folder } loadDeletedDocs() { this.$scope.deletedDocs = [] return Array.from(this.$scope.project.deletedDocs || []).map(doc => this.$scope.deletedDocs.push({ name: doc.name, id: doc._id, type: 'doc', deleted: true, }) ) } recalculateDocList() { this.$scope.docs = [] this.forEachEntity((entity, parentFolder, path) => { if (entity.type === 'doc' && !entity.deleted) { return this.$scope.docs.push({ doc: entity, path, }) } }) // Keep list ordered by folders, then name return this.$scope.docs.sort(function (a, b) { const aDepth = (a.path.match(/\//g) || []).length const bDepth = (b.path.match(/\//g) || []).length if (aDepth - bDepth !== 0) { return -(aDepth - bDepth) // Deeper path == folder first } else if (a.path < b.path) { return -1 } else if (a.path > b.path) { return 1 } else { return 0 } }) } getCurrentFolder() { // Return the root folder if nothing is selected return ( this._getCurrentFolder(this.$scope.rootFolder) || this.$scope.rootFolder ) } _getCurrentFolder(startFolder) { if (startFolder == null) { startFolder = this.$scope.rootFolder } for (const entity of Array.from(startFolder.children || [])) { // The 'current' folder is either the one selected, or // the one containing the selected doc/file if (entity.selected) { if (entity.type === 'folder') { return entity } else { return startFolder } } if (entity.type === 'folder') { const result = this._getCurrentFolder(entity) if (result != null) { return result } } } return null } projectContainsFolder() { for (const entity of Array.from(this.$scope.rootFolder.children)) { if (entity.type === 'folder') { return true } } return false } existsInThisFolder(folder, name) { for (const entity of Array.from( (folder != null ? folder.children : undefined) || [] )) { if (entity.name === name) { return true } } return false } nameExistsError(message) { if (message == null) { message = 'already exists' } const nameExists = this.ide.$q.defer() nameExists.reject({ data: message }) return nameExists.promise } createDoc(name, parent_folder) { // check if a doc/file/folder already exists with this name if (parent_folder == null) { parent_folder = this.getCurrentFolder() } if (this.existsInThisFolder(parent_folder, name)) { return this.nameExistsError() } // We'll wait for the socket.io notification to actually // add the doc for us. return this.ide.$http.post(`/project/${this.ide.project_id}/doc`, { name, parent_folder_id: parent_folder != null ? parent_folder.id : undefined, _csrf: window.csrfToken, }) } createFolder(name, parent_folder) { // check if a doc/file/folder already exists with this name if (parent_folder == null) { parent_folder = this.getCurrentFolder() } if (this.existsInThisFolder(parent_folder, name)) { return this.nameExistsError() } // We'll wait for the socket.io notification to actually // add the folder for us. return this.ide.$http.post(`/project/${this.ide.project_id}/folder`, { name, parent_folder_id: parent_folder != null ? parent_folder.id : undefined, _csrf: window.csrfToken, }) } createLinkedFile(name, parent_folder, provider, data) { // check if a doc/file/folder already exists with this name if (parent_folder == null) { parent_folder = this.getCurrentFolder() } if (this.existsInThisFolder(parent_folder, name)) { return this.nameExistsError() } // We'll wait for the socket.io notification to actually // add the file for us. return this.ide.$http.post( `/project/${this.ide.project_id}/linked_file`, { name, parent_folder_id: parent_folder != null ? parent_folder.id : undefined, provider, data, _csrf: window.csrfToken, }, { disableAutoLoginRedirect: true, } ) } refreshLinkedFile(file) { const parent_folder = this._findParentFolder(file) const provider = file.linkedFileData != null ? file.linkedFileData.provider : undefined if (provider == null) { console.warn(`>> no provider for ${file.name}`, file) return } return this.ide.$http.post( `/project/${this.ide.project_id}/linked_file/${file.id}/refresh`, { _csrf: window.csrfToken, }, { disableAutoLoginRedirect: true, } ) } renameEntity(entity, name, callback) { if (callback == null) { callback = function (error) {} } if (entity.name === name) { return } if (name.length >= 150) { return } // check if a doc/file/folder already exists with this name const parent_folder = this.getCurrentFolder() if (this.existsInThisFolder(parent_folder, name)) { return this.nameExistsError() } entity.renamingToName = name return this.ide.$http .post( `/project/${this.ide.project_id}/${entity.type}/${entity.id}/rename`, { name, _csrf: window.csrfToken, } ) .then(() => (entity.name = name)) .finally(() => (entity.renamingToName = null)) } deleteEntity(entity, callback) { // We'll wait for the socket.io notification to // delete from scope. if (callback == null) { callback = function (error) {} } return this.ide.queuedHttp({ method: 'DELETE', url: `/project/${this.ide.project_id}/${entity.type}/${entity.id}`, headers: { 'X-Csrf-Token': window.csrfToken, }, }) } moveEntity(entity, parent_folder) { // Abort move if the folder being moved (entity) has the parent_folder as child // since that would break the tree structure. if (this._isChildFolder(entity, parent_folder)) { return } // check if a doc/file/folder already exists with this name if (this.existsInThisFolder(parent_folder, entity.name)) { throw new Error('file exists in this location') } // Wait for the http response before doing the move this.ide.queuedHttp .post( `/project/${this.ide.project_id}/${entity.type}/${entity.id}/move`, { folder_id: parent_folder.id, _csrf: window.csrfToken, } ) .then(() => { this._moveEntityInScope(entity, parent_folder) }) } _isChildFolder(parent_folder, child_folder) { const parent_path = this.getEntityPath(parent_folder) || '' // null if root folder const child_path = this.getEntityPath(child_folder) || '' // null if root folder // is parent path the beginning of child path? return child_path.slice(0, parent_path.length) === parent_path } _deleteEntityFromScope(entity, options) { if (options == null) { options = { moveToDeleted: true } } if (entity == null) { return } let parent_folder = null this.forEachEntity(function (possible_entity, folder) { if (possible_entity === entity) { return (parent_folder = folder) } }) if (parent_folder != null) { const index = parent_folder.children.indexOf(entity) if (index > -1) { parent_folder.children.splice(index, 1) } } if (entity.type !== 'folder' && entity.selected) { this.$scope.ui.view = null } if (entity.type === 'doc' && options.moveToDeleted) { entity.deleted = true return this.$scope.deletedDocs.push(entity) } } _moveEntityInScope(entity, parent_folder) { if (Array.from(parent_folder.children).includes(entity)) { return } this._deleteEntityFromScope(entity, { moveToDeleted: false }) return parent_folder.children.push(entity) } } function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/frontend/js/ide/file-tree/FileTreeManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/file-tree/FileTreeManager.js", "repo_id": "overleaf", "token_count": 8264 }
517
/* 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 */ import App from '../../../base' const historyLabelController = function ($scope, $element, $attrs, $filter) { const ctrl = this ctrl.$onInit = () => { if (ctrl.showTooltip == null) { ctrl.showTooltip = true } if (ctrl.isPseudoCurrentStateLabel == null) { ctrl.isPseudoCurrentStateLabel = false } } } export default App.component('historyLabel', { bindings: { labelText: '<', labelOwnerName: '<?', labelCreationDateTime: '<?', isOwnedByCurrentUser: '<', isPseudoCurrentStateLabel: '<', onLabelDelete: '&', showTooltip: '<?', }, controller: historyLabelController, templateUrl: 'historyLabelTpl', })
overleaf/web/frontend/js/ide/history/components/historyLabel.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/components/historyLabel.js", "repo_id": "overleaf", "token_count": 367 }
518
import LogParser from 'libs/latex-log-parser' import ruleset from './HumanReadableLogsRules' export default { parse(rawLog, options) { let parsedLogEntries if (typeof rawLog === 'string') { parsedLogEntries = LogParser.parse(rawLog, options) } else { parsedLogEntries = rawLog } const _getRule = function (logMessage) { for (const rule of ruleset) { if (rule.regexToMatch.test(logMessage)) { return rule } } } const seenErrorTypes = {} // keep track of types of errors seen for (const entry of parsedLogEntries.all) { const ruleDetails = _getRule(entry.message) if (ruleDetails != null) { var type if (ruleDetails.ruleId != null) { entry.ruleId = ruleDetails.ruleId } else if (ruleDetails.regexToMatch != null) { entry.ruleId = `hint_${ruleDetails.regexToMatch .toString() .replace(/\s/g, '_') .slice(1, -1)}` } if (ruleDetails.newMessage != null) { entry.message = entry.message.replace( ruleDetails.regexToMatch, ruleDetails.newMessage ) } // suppress any entries that are known to cascade from previous error types if (ruleDetails.cascadesFrom != null) { for (type of ruleDetails.cascadesFrom) { if (seenErrorTypes[type]) { entry.suppressed = true } } } // record the types of errors seen if (ruleDetails.types != null) { for (type of ruleDetails.types) { seenErrorTypes[type] = true } } if (ruleDetails.humanReadableHint != null) { entry.humanReadableHint = ruleDetails.humanReadableHint } if (ruleDetails.humanReadableHintComponent != null) { entry.humanReadableHintComponent = ruleDetails.humanReadableHintComponent } if (ruleDetails.extraInfoURL != null) { entry.extraInfoURL = ruleDetails.extraInfoURL } } } // filter out the suppressed errors (from the array entries in parsedLogEntries) for (const key in parsedLogEntries) { const errors = parsedLogEntries[key] if (typeof errors === 'object' && errors.length > 0) { parsedLogEntries[key] = Array.from(errors).filter( err => !err.suppressed ) } } return parsedLogEntries }, }
overleaf/web/frontend/js/ide/human-readable-logs/HumanReadableLogs.js/0
{ "file_path": "overleaf/web/frontend/js/ide/human-readable-logs/HumanReadableLogs.js", "repo_id": "overleaf", "token_count": 1108 }
519
/* eslint-disable max-len, no-unused-vars, no-useless-constructor, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.factory('pdfSpinner', function () { let pdfSpinner return (pdfSpinner = class pdfSpinner { constructor() {} // handler for spinners add(element, options) { const size = 64 const spinner = $( `<div class="pdfng-spinner" style="position: absolute; top: 50%; left:50%; transform: translateX(-50%) translateY(-50%);"><i class="fa fa-spinner${ (options != null ? options.static : undefined) ? '' : ' fa-spin' }" style="color: #999"></i></div>` ) spinner.css({ 'font-size': size + 'px' }) return element.append(spinner) } start(element) { return element.find('.fa-spinner').addClass('fa-spin') } stop(element) { return element.find('.fa-spinner').removeClass('fa-spin') } remove(element) { return element.find('.fa-spinner').remove() } }) })
overleaf/web/frontend/js/ide/pdfng/directives/pdfSpinner.js/0
{ "file_path": "overleaf/web/frontend/js/ide/pdfng/directives/pdfSpinner.js", "repo_id": "overleaf", "token_count": 496 }
520
/* eslint-disable max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.directive('commentEntry', $timeout => ({ restrict: 'E', templateUrl: 'commentEntryTemplate', scope: { entry: '=', threads: '=', permissions: '=', onResolve: '&', onReply: '&', onIndicatorClick: '&', onSaveEdit: '&', onDelete: '&', onBodyClick: '&', }, link(scope, element, attrs) { scope.state = { animating: false } element.on('click', function (e) { if ( $(e.target).is( '.rp-entry, .rp-comment-loaded, .rp-comment-content, .rp-comment-reply, .rp-entry-metadata' ) ) { return scope.onBodyClick() } }) scope.handleCommentReplyKeyPress = function (ev) { if (ev.keyCode === 13 && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey) { ev.preventDefault() if (scope.entry.replyContent.length > 0) { ev.target.blur() return scope.onReply() } } } scope.animateAndCallOnResolve = function () { scope.state.animating = true element.find('.rp-entry').css('top', 0) $timeout(() => scope.onResolve(), 350) return true } scope.startEditing = function (comment) { comment.editing = true return setTimeout(() => scope.$emit('review-panel:layout')) } scope.saveEdit = function (comment) { comment.editing = false return scope.onSaveEdit({ comment }) } scope.confirmDelete = function (comment) { comment.deleting = true return setTimeout(() => scope.$emit('review-panel:layout')) } scope.cancelDelete = function (comment) { comment.deleting = false return setTimeout(() => scope.$emit('review-panel:layout')) } scope.doDelete = function (comment) { comment.deleting = false return scope.onDelete({ comment }) } return (scope.saveEditOnEnter = function (ev, comment) { if (ev.keyCode === 13 && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey) { ev.preventDefault() return scope.saveEdit(comment) } }) }, }))
overleaf/web/frontend/js/ide/review-panel/directives/commentEntry.js/0
{ "file_path": "overleaf/web/frontend/js/ide/review-panel/directives/commentEntry.js", "repo_id": "overleaf", "token_count": 999 }
521
// Conditionally enable Sentry based on whether the DSN token is set const reporterPromise = window.ExposedSettings.sentryDsn ? sentryReporter() : nullReporter() function sentryReporter() { return ( import(/* webpackMode: "eager" */ '@sentry/browser') .then(Sentry => { let eventCount = 0 Sentry.init({ dsn: window.ExposedSettings.sentryDsn, release: window.ExposedSettings.sentryRelease, autoSessionTracking: false, // Ignore errors unless they come from our origins // Adapted from: https://docs.sentry.io/platforms/javascript/#decluttering-sentry whitelistUrls: [ new RegExp(window.ExposedSettings.sentryAllowedOriginRegex), ], ignoreErrors: [ // Ignore very noisy error 'SecurityError: Permission denied to access property "pathname" on cross-origin object', // Ignore unhandled error that is "expected" - see https://github.com/overleaf/issues/issues/3321 /^Missing PDF/, // Ignore "expected" error from aborted fetch - see https://github.com/overleaf/issues/issues/3321 /^AbortError/, // Ignore spurious error from Ace internals - see https://github.com/overleaf/issues/issues/3321 'ResizeObserver loop limit exceeded', 'ResizeObserver loop completed with undelivered notifications.', ], beforeSend(event) { // Limit number of events sent to Sentry to 100 events "per page load", // (i.e. the cap will be reset if the page is reloaded). This prevent // hitting their server-side event cap. eventCount++ if (eventCount > 100) { return null // Block the event from sending } else { return event } }, }) Sentry.setUser({ id: window.user_id }) return Sentry }) // If Sentry fails to load, use the null reporter instead .catch(error => { console.error(error) return nullReporter() }) ) } function nullReporter() { return Promise.resolve({ captureException: console.error, captureMessage: console.error, }) } export function captureException(...args) { reporterPromise.then(reporter => reporter.captureException(...args)) } export function captureMessage(...args) { reporterPromise.then(reporter => reporter.captureMessage(...args)) }
overleaf/web/frontend/js/infrastructure/error-reporter.js/0
{ "file_path": "overleaf/web/frontend/js/infrastructure/error-reporter.js", "repo_id": "overleaf", "token_count": 1004 }
522
import _ from 'lodash' import App from '../../../base' const countriesList = [ { code: 'af', name: 'Afghanistan' }, { code: 'ax', name: 'Åland Islands' }, { code: 'al', name: 'Albania' }, { code: 'dz', name: 'Algeria' }, { code: 'as', name: 'American Samoa' }, { code: 'ad', name: 'Andorra' }, { code: 'ao', name: 'Angola' }, { code: 'ai', name: 'Anguilla' }, { code: 'aq', name: 'Antarctica' }, { code: 'ag', name: 'Antigua and Barbuda' }, { code: 'ar', name: 'Argentina' }, { code: 'am', name: 'Armenia' }, { code: 'aw', name: 'Aruba' }, { code: 'au', name: 'Australia' }, { code: 'at', name: 'Austria' }, { code: 'az', name: 'Azerbaijan' }, { code: 'bs', name: 'Bahamas' }, { code: 'bh', name: 'Bahrain' }, { code: 'bd', name: 'Bangladesh' }, { code: 'bb', name: 'Barbados' }, { code: 'by', name: 'Belarus' }, { code: 'be', name: 'Belgium' }, { code: 'bz', name: 'Belize' }, { code: 'bj', name: 'Benin' }, { code: 'bm', name: 'Bermuda' }, { code: 'bt', name: 'Bhutan' }, { code: 'bo', name: 'Bolivia' }, { code: 'bq', name: 'Bonaire, Saint Eustatius and Saba' }, { code: 'ba', name: 'Bosnia and Herzegovina' }, { code: 'bw', name: 'Botswana' }, { code: 'bv', name: 'Bouvet Island' }, { code: 'br', name: 'Brazil' }, { code: 'io', name: 'British Indian Ocean Territory' }, { code: 'vg', name: 'British Virgin Islands' }, { code: 'bn', name: 'Brunei' }, { code: 'bg', name: 'Bulgaria' }, { code: 'bf', name: 'Burkina Faso' }, { code: 'bi', name: 'Burundi' }, { code: 'kh', name: 'Cambodia' }, { code: 'cm', name: 'Cameroon' }, { code: 'ca', name: 'Canada' }, { code: 'cv', name: 'Cabo Verde' }, { code: 'ky', name: 'Cayman Islands' }, { code: 'cf', name: 'Central African Republic' }, { code: 'td', name: 'Chad' }, { code: 'cl', name: 'Chile' }, { code: 'cn', name: 'China' }, { code: 'cx', name: 'Christmas Island' }, { code: 'cc', name: 'Cocos (Keeling) Islands' }, { code: 'co', name: 'Colombia' }, { code: 'km', name: 'Comoros' }, { code: 'cg', name: 'Congo' }, { code: 'ck', name: 'Cook Islands' }, { code: 'cr', name: 'Costa Rica' }, { code: 'ci', name: "Côte d'Ivoire" }, { code: 'hr', name: 'Croatia' }, { code: 'cu', name: 'Cuba' }, { code: 'cw', name: 'Curaçao' }, { code: 'cy', name: 'Cyprus' }, { code: 'cz', name: 'Czech Republic' }, { code: 'kp', name: "Democratic People's Republic of Korea" }, { code: 'cd', name: 'Democratic Republic of the Congo' }, { code: 'dk', name: 'Denmark' }, { code: 'dj', name: 'Djibouti' }, { code: 'dm', name: 'Dominica' }, { code: 'do', name: 'Dominican Republic' }, { code: 'ec', name: 'Ecuador' }, { code: 'eg', name: 'Egypt' }, { code: 'sv', name: 'El Salvador' }, { code: 'gq', name: 'Equatorial Guinea' }, { code: 'er', name: 'Eritrea' }, { code: 'ee', name: 'Estonia' }, { code: 'et', name: 'Ethiopia' }, { code: 'fk', name: 'Falkland Islands (Malvinas)' }, { code: 'fo', name: 'Faroe Islands' }, { code: 'fj', name: 'Fiji' }, { code: 'fi', name: 'Finland' }, { code: 'fr', name: 'France' }, { code: 'gf', name: 'French Guiana' }, { code: 'pf', name: 'French Polynesia' }, { code: 'tf', name: 'French Southern Territories' }, { code: 'ga', name: 'Gabon' }, { code: 'gm', name: 'Gambia' }, { code: 'ge', name: 'Georgia' }, { code: 'de', name: 'Germany' }, { code: 'gh', name: 'Ghana' }, { code: 'gi', name: 'Gibraltar' }, { code: 'gr', name: 'Greece' }, { code: 'gl', name: 'Greenland' }, { code: 'gd', name: 'Grenada' }, { code: 'gp', name: 'Guadeloupe' }, { code: 'gu', name: 'Guam' }, { code: 'gt', name: 'Guatemala' }, { code: 'gg', name: 'Guernsey' }, { code: 'gn', name: 'Guinea' }, { code: 'gw', name: 'Guinea-Bissau' }, { code: 'gy', name: 'Guyana' }, { code: 'ht', name: 'Haiti' }, { code: 'hm', name: 'Heard Island and McDonald Islands' }, { code: 'va', name: 'Holy See (Vatican City)' }, { code: 'hn', name: 'Honduras' }, { code: 'hk', name: 'Hong Kong' }, { code: 'hu', name: 'Hungary' }, { code: 'is', name: 'Iceland' }, { code: 'in', name: 'India' }, { code: 'id', name: 'Indonesia' }, { code: 'ir', name: 'Iran' }, { code: 'iq', name: 'Iraq' }, { code: 'ie', name: 'Ireland' }, { code: 'im', name: 'Isle of Man' }, { code: 'il', name: 'Israel' }, { code: 'it', name: 'Italy' }, { code: 'jm', name: 'Jamaica' }, { code: 'jp', name: 'Japan' }, { code: 'je', name: 'Jersey' }, { code: 'jo', name: 'Jordan' }, { code: 'kz', name: 'Kazakhstan' }, { code: 'ke', name: 'Kenya' }, { code: 'ki', name: 'Kiribati' }, { code: 'xk', name: 'Kosovo' }, { code: 'kw', name: 'Kuwait' }, { code: 'kg', name: 'Kyrgyzstan' }, { code: 'la', name: 'Laos' }, { code: 'lv', name: 'Latvia' }, { code: 'lb', name: 'Lebanon' }, { code: 'ls', name: 'Lesotho' }, { code: 'lr', name: 'Liberia' }, { code: 'ly', name: 'Libya' }, { code: 'li', name: 'Liechtenstein' }, { code: 'lt', name: 'Lithuania' }, { code: 'lu', name: 'Luxembourg' }, { code: 'mo', name: 'Macao' }, { code: 'mk', name: 'Macedonia' }, { code: 'mg', name: 'Madagascar' }, { code: 'mw', name: 'Malawi' }, { code: 'my', name: 'Malaysia' }, { code: 'mv', name: 'Maldives' }, { code: 'ml', name: 'Mali' }, { code: 'mt', name: 'Malta' }, { code: 'mh', name: 'Marshall Islands' }, { code: 'mq', name: 'Martinique' }, { code: 'mr', name: 'Mauritania' }, { code: 'mu', name: 'Mauritius' }, { code: 'yt', name: 'Mayotte' }, { code: 'mx', name: 'Mexico' }, { code: 'fm', name: 'Micronesia' }, { code: 'md', name: 'Moldova' }, { code: 'mc', name: 'Monaco' }, { code: 'mn', name: 'Mongolia' }, { code: 'me', name: 'Montenegro' }, { code: 'ms', name: 'Montserrat' }, { code: 'ma', name: 'Morocco' }, { code: 'mz', name: 'Mozambique' }, { code: 'mm', name: 'Myanmar' }, { code: 'na', name: 'Namibia' }, { code: 'nr', name: 'Nauru' }, { code: 'np', name: 'Nepal' }, { code: 'nl', name: 'Netherlands' }, { code: 'an', name: 'Netherlands Antilles' }, { code: 'nc', name: 'New Caledonia' }, { code: 'nz', name: 'New Zealand' }, { code: 'ni', name: 'Nicaragua' }, { code: 'ne', name: 'Niger' }, { code: 'ng', name: 'Nigeria' }, { code: 'nu', name: 'Niue' }, { code: 'nf', name: 'Norfolk Island' }, { code: 'mp', name: 'Northern Mariana Islands' }, { code: 'no', name: 'Norway' }, { code: 'om', name: 'Oman' }, { code: 'pk', name: 'Pakistan' }, { code: 'pw', name: 'Palau' }, { code: 'ps', name: 'Palestine' }, { code: 'pa', name: 'Panama' }, { code: 'pg', name: 'Papua New Guinea' }, { code: 'py', name: 'Paraguay' }, { code: 'pe', name: 'Peru' }, { code: 'ph', name: 'Philippines' }, { code: 'pn', name: 'Pitcairn' }, { code: 'pl', name: 'Poland' }, { code: 'pt', name: 'Portugal' }, { code: 'pr', name: 'Puerto Rico' }, { code: 'qa', name: 'Qatar' }, { code: 'kr', name: 'Republic of Korea' }, { code: 're', name: 'Réunion' }, { code: 'ro', name: 'Romania' }, { code: 'ru', name: 'Russia' }, { code: 'rw', name: 'Rwanda' }, { code: 'bl', name: 'Saint Barthélemy' }, { code: 'sh', name: 'Saint Helena, Ascension and Tristan da Cunha' }, { code: 'kn', name: 'Saint Kitts and Nevis' }, { code: 'lc', name: 'Saint Lucia' }, { code: 'mf', name: 'Saint Martin' }, { code: 'pm', name: 'Saint Pierre and Miquelon' }, { code: 'vc', name: 'Saint Vincent and the Grenadines' }, { code: 'ws', name: 'Samoa' }, { code: 'sm', name: 'San Marino' }, { code: 'st', name: 'Sao Tome and Principe' }, { code: 'sa', name: 'Saudi Arabia' }, { code: 'sn', name: 'Senegal' }, { code: 'rs', name: 'Serbia' }, { code: 'sc', name: 'Seychelles' }, { code: 'sl', name: 'Sierra Leone' }, { code: 'sg', name: 'Singapore' }, { code: 'sx', name: 'Sint Maarten' }, { code: 'sk', name: 'Slovakia' }, { code: 'si', name: 'Slovenia' }, { code: 'sb', name: 'Solomon Islands' }, { code: 'so', name: 'Somalia' }, { code: 'za', name: 'South Africa' }, { code: 'gs', name: 'South Georgia and the South Sandwich Islands' }, { code: 'ss', name: 'South Sudan' }, { code: 'es', name: 'Spain' }, { code: 'lk', name: 'Sri Lanka' }, { code: 'sd', name: 'Sudan' }, { code: 'sr', name: 'Suriname' }, { code: 'sj', name: 'Svalbard and Jan Mayen' }, { code: 'sz', name: 'Swaziland' }, { code: 'se', name: 'Sweden' }, { code: 'ch', name: 'Switzerland' }, { code: 'sy', name: 'Syria' }, { code: 'tw', name: 'Taiwan' }, { code: 'tj', name: 'Tajikistan' }, { code: 'tz', name: 'Tanzania' }, { code: 'th', name: 'Thailand' }, { code: 'tl', name: 'Timor-Leste' }, { code: 'tg', name: 'Togo' }, { code: 'tk', name: 'Tokelau' }, { code: 'to', name: 'Tonga' }, { code: 'tt', name: 'Trinidad and Tobago' }, { code: 'tn', name: 'Tunisia' }, { code: 'tr', name: 'Turkey' }, { code: 'tm', name: 'Turkmenistan' }, { code: 'tc', name: 'Turks and Caicos Islands' }, { code: 'tv', name: 'Tuvalu' }, { code: 'vi', name: 'U.S. Virgin Islands' }, { code: 'ug', name: 'Uganda' }, { code: 'ua', name: 'Ukraine' }, { code: 'ae', name: 'United Arab Emirates' }, { code: 'gb', name: 'United Kingdom' }, { code: 'us', name: 'United States of America' }, { code: 'um', name: 'United States Minor Outlying Islands' }, { code: 'uy', name: 'Uruguay' }, { code: 'uz', name: 'Uzbekistan' }, { code: 'vu', name: 'Vanuatu' }, { code: 've', name: 'Venezuela' }, { code: 'vn', name: 'Vietnam' }, { code: 'wf', name: 'Wallis and Futuna' }, { code: 'eh', name: 'Western Sahara' }, { code: 'ye', name: 'Yemen' }, { code: 'zm', name: 'Zambia' }, { code: 'zw', name: 'Zimbabwe' }, ] const universities = {} const universitiesByDomain = {} const defaultRoleHints = [ 'Undergraduate Student', 'Masters Student (MSc, MA, ...)', 'Doctoral Student (PhD, EngD, ...)', 'Postdoc', 'Lecturer', 'Senior Lecturer', 'Reader', 'Associate Professor ', 'Assistant Professor ', 'Professor', 'Emeritus Professor', ] const defaultDepartmentHints = [ 'Aeronautics & Astronautics', 'Anesthesia', 'Anthropology', 'Applied Physics', 'Art & Art History', 'Biochemistry', 'Bioengineering', 'Biology', 'Business School Library', 'Business, Graduate School of', 'Cardiothoracic Surgery', 'Chemical and Systems Biology', 'Chemical Engineering', 'Chemistry', 'Civil & Environmental Engineering', 'Classics', 'Communication', 'Comparative Literature', 'Comparative Medicine', 'Computer Science', 'Dermatology', 'Developmental Biology', 'Earth System Science', 'East Asian Languages and Cultures', 'Economics', 'Education, School of', 'Electrical Engineering', 'Energy Resources Engineering', 'English', 'French and Italian', 'Genetics', 'Geological Sciences', 'Geophysics', 'German Studies', 'Health Research & Policy', 'History', 'Iberian & Latin American Cultures', 'Law Library', 'Law School', 'Linguistics', 'Management Science & Engineering', 'Materials Science & Engineering', 'Mathematics', 'Mechanical Engineering', 'Medical Library', 'Medicine', 'Microbiology & Immunology', 'Molecular & Cellular Physiology', 'Music', 'Neurobiology', 'Neurology & Neurological Sciences', 'Neurosurgery', 'Obstetrics and Gynecology', 'Ophthalmology', 'Orthopaedic Surgery', 'Otolaryngology (Head and Neck Surgery)', 'Pathology', 'Pediatrics', 'Philosophy', 'Physics', 'Political Science', 'Psychiatry and Behavioral Sciences', 'Psychology', 'Radiation Oncology', 'Radiology', 'Religious Studies', 'Slavic Languages and Literature', 'Sociology', 'University Libraries', 'Statistics', 'Structural Biology', 'Surgery', 'Theater and Performance Studies', 'Urology', ] const domainsBlackList = { 'overleaf.com': true } const commonTLDs = [ 'br', 'cn', 'co', 'co.jp', 'co.uk', 'com', 'com.au', 'de', 'fr', 'in', 'info', 'io', 'net', 'no', 'ru', 'se', 'us', 'com.tw', 'com.br', 'pl', 'it', 'co.in', 'com.mx', ] const commonDomains = [ 'gmail', 'googlemail', 'icloud', 'me', 'yahoo', 'ymail', 'yahoomail', 'hotmail', 'live', 'msn', 'outlook', 'gmx', 'mail', 'aol', '163', 'mac', 'qq', 'o2', 'libero', '126', 'protonmail', 'yandex', 'yeah', 'web', 'foxmail', ] for (const domain of commonDomains) { for (const tld of commonTLDs) { domainsBlackList[`${domain}.${tld}`] = true } } App.factory('UserAffiliationsDataService', function ($http, $q) { const getCountries = () => $q.resolve(countriesList) const getDefaultRoleHints = () => $q.resolve(defaultRoleHints) const getDefaultDepartmentHints = () => $q.resolve(defaultDepartmentHints) const getUserEmails = () => $http.get('/user/emails').then(response => response.data) const getUserEmailsEnsureAffiliation = () => $http .get('/user/emails?ensureAffiliation=true') .then(response => response.data) const getUserDefaultEmail = () => getUserEmails().then(userEmails => _.find(userEmails, userEmail => userEmail.default) ) const getUniversitiesFromCountry = function (country) { let universitiesFromCountry if (universities[country.code] != null) { universitiesFromCountry = universities[country.code] } else { universitiesFromCountry = $http .get('/institutions/list', { params: { country_code: country.code }, }) .then(response => (universities[country.code] = response.data)) } return $q.resolve(universitiesFromCountry) } const getUniversityDomainFromPartialDomainInput = function ( partialDomainInput ) { if (universitiesByDomain[partialDomainInput] != null) { return $q.resolve(universitiesByDomain[partialDomainInput]) } else { return $http .get('/institutions/domains', { params: { hostname: partialDomainInput, limit: 1 }, }) .then(function (response) { const university = response.data[0] if (university != null && !isDomainBlacklisted(university.hostname)) { universitiesByDomain[university.hostname] = university return $q.resolve(university) } else { return $q.reject(null) } }) } } const getUniversityDetails = universityId => $http .get(`/institutions/list/${universityId}`) .then(response => response.data) const addUserEmail = email => $http.post('/user/emails', { email, _csrf: window.csrfToken, }) const addUserAffiliationWithUnknownUniversity = ( email, unknownUniversityName, unknownUniversityCountryCode, role, department ) => $http.post('/user/emails', { email, university: { name: unknownUniversityName, country_code: unknownUniversityCountryCode, }, role, department, _csrf: window.csrfToken, }) const addUserAffiliation = (email, universityId, role, department) => $http.post('/user/emails', { email, university: { id: universityId, }, role, department, _csrf: window.csrfToken, }) const addRoleAndDepartment = (email, role, department) => $http.post('/user/emails/endorse', { email, role, department, _csrf: window.csrfToken, }) const setDefaultUserEmail = email => $http.post('/user/emails/default', { email, _csrf: window.csrfToken, }) const removeUserEmail = email => $http.post('/user/emails/delete', { email, _csrf: window.csrfToken, }) const resendConfirmationEmail = email => $http.post('/user/emails/resend_confirmation', { email, _csrf: window.csrfToken, }) var isDomainBlacklisted = domain => domain.toLowerCase() in domainsBlackList return { getCountries, getDefaultRoleHints, getDefaultDepartmentHints, getUserEmails, getUserEmailsEnsureAffiliation, getUserDefaultEmail, getUniversitiesFromCountry, getUniversityDomainFromPartialDomainInput, getUniversityDetails, addUserEmail, addUserAffiliationWithUnknownUniversity, addUserAffiliation, addRoleAndDepartment, setDefaultUserEmail, removeUserEmail, resendConfirmationEmail, isDomainBlacklisted, } })
overleaf/web/frontend/js/main/affiliations/factories/UserAffiliationsDataService.js/0
{ "file_path": "overleaf/web/frontend/js/main/affiliations/factories/UserAffiliationsDataService.js", "repo_id": "overleaf", "token_count": 6661 }
523
import App from '../../base' const ExposedSettings = window.ExposedSettings App.controller('NotificationsController', function ($scope, $http) { for (const notification of $scope.notifications || []) { notification.hide = false } $scope.samlInitPath = ExposedSettings.samlInitPath $scope.dismiss = notification => { if (!notification._id) { notification.hide = true return } $http({ url: `/notifications/${notification._id}`, method: 'DELETE', headers: { 'X-Csrf-Token': window.csrfToken, }, }).then(() => (notification.hide = true)) } }) App.controller( 'DismissableNotificationsController', function ($scope, localStorage) { $scope.shouldShowNotification = localStorage('dismissed-covid-19-notification-extended') !== true $scope.dismiss = () => { localStorage('dismissed-covid-19-notification-extended', true) $scope.shouldShowNotification = false } } ) App.controller('ProjectInviteNotificationController', function ($scope, $http) { // Shortcuts for translation keys $scope.projectName = $scope.notification.messageOpts.projectName $scope.userName = $scope.notification.messageOpts.userName $scope.accept = function () { $scope.notification.inflight = true return $http({ url: `/project/${$scope.notification.messageOpts.projectId}/invite/token/${$scope.notification.messageOpts.token}/accept`, method: 'POST', headers: { 'X-Csrf-Token': window.csrfToken, 'X-Requested-With': 'XMLHttpRequest', }, }) .then(() => { $scope.notification.accepted = true }) .catch(({ status }) => { if (status === 404) { // 404 probably means the invite has already been accepted and // deleted. Treat as success $scope.notification.accepted = true } else { $scope.notification.error = true } }) .finally(() => { $scope.notification.inflight = false }) } }) App.controller( 'EmailNotificationController', function ($scope, $http, UserAffiliationsDataService) { $scope.userEmails = window.data.userEmails const _ssoAvailable = email => { if (!ExposedSettings.hasSamlFeature) return false if (email.samlProviderId) return true if (!email.affiliation || !email.affiliation.institution) return false if (email.affiliation.institution.ssoEnabled) return true if ( ExposedSettings.hasSamlBeta && email.affiliation.institution.ssoBeta ) { return true } return false } $scope.showConfirmEmail = email => { if (ExposedSettings.emailConfirmationDisabled) { return false } if (!email.confirmedAt && !email.hide) { if (_ssoAvailable(email)) { return false } return true } return false } for (const userEmail of $scope.userEmails) { userEmail.hide = false } $scope.resendConfirmationEmail = function (userEmail) { userEmail.confirmationInflight = true userEmail.error = false userEmail.errorMessage = null UserAffiliationsDataService.resendConfirmationEmail(userEmail.email) .then(() => { userEmail.hide = true $scope.$emit('project-list:notifications-received') }) .catch(error => { userEmail.error = true userEmail.errorMessage = error.data.message console.error(error) $scope.$emit('project-list:notifications-received') }) .finally(() => { userEmail.confirmationInflight = false }) } } )
overleaf/web/frontend/js/main/project-list/notifications-controller.js/0
{ "file_path": "overleaf/web/frontend/js/main/project-list/notifications-controller.js", "repo_id": "overleaf", "token_count": 1506 }
524
angular.module('sessionStorage', []).value('sessionStorage', sessionStorage) /* sessionStorage can throw browser exceptions, for example if it is full We don't use sessionStorage for anything critical, on in that case just fail gracefully. */ function sessionStorage(...args) { try { return $.sessionStorage(...args) } catch (e) { console.error('sessionStorage exception', e) return null } } export default sessionStorage
overleaf/web/frontend/js/modules/sessionStorage.js/0
{ "file_path": "overleaf/web/frontend/js/modules/sessionStorage.js", "repo_id": "overleaf", "token_count": 126 }
525
import { createContext, useContext } from 'react' import PropTypes from 'prop-types' import useScopeValue from './util/scope-value-hook' export const CompileContext = createContext() CompileContext.Provider.propTypes = { value: PropTypes.shape({ pdfUrl: PropTypes.string, pdfDownloadUrl: PropTypes.string, logEntries: PropTypes.object, uncompiled: PropTypes.bool, }), } export function CompileProvider({ children }) { const [pdfUrl] = useScopeValue('pdf.url') const [pdfDownloadUrl] = useScopeValue('pdf.downloadUrl') const [logEntries] = useScopeValue('pdf.logEntries') const [uncompiled] = useScopeValue('pdf.uncompiled') const value = { pdfUrl, pdfDownloadUrl, logEntries, uncompiled, } return ( <CompileContext.Provider value={value}>{children}</CompileContext.Provider> ) } CompileProvider.propTypes = { children: PropTypes.any, } export function useCompileContext(propTypes) { const data = useContext(CompileContext) PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider') return data }
overleaf/web/frontend/js/shared/context/compile-context.js/0
{ "file_path": "overleaf/web/frontend/js/shared/context/compile-context.js", "repo_id": "overleaf", "token_count": 359 }
526
import { useRef, useEffect } from 'react' export function useRefWithAutoFocus() { const autoFocusedRef = useRef() useEffect(() => { if (autoFocusedRef.current) { window.requestAnimationFrame(() => { if (autoFocusedRef.current) { autoFocusedRef.current.focus() } }) } }, [autoFocusedRef]) return { autoFocusedRef } }
overleaf/web/frontend/js/shared/hooks/use-ref-with-auto-focus.js/0
{ "file_path": "overleaf/web/frontend/js/shared/hooks/use-ref-with-auto-focus.js", "repo_id": "overleaf", "token_count": 150 }
527
import { LinkedFileInfo } from '../../modules/tpr-webmodule/frontend/js/components/linked-file-info' export const MendeleyLinkedFile = args => { return <LinkedFileInfo {...args} /> } MendeleyLinkedFile.args = { file: { linkedFileData: { provider: 'mendeley', }, }, } export default { title: 'LinkedFileInfo', component: LinkedFileInfo, args: { file: { id: 'file-id', name: 'file.tex', created: new Date(), }, }, }
overleaf/web/frontend/stories/linked-file.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/linked-file.stories.js", "repo_id": "overleaf", "token_count": 195 }
528
import WordCountModalContent from '../js/features/word-count-modal/components/word-count-modal-content' export const Basic = args => { const data = { headers: 4, mathDisplay: 40, mathInline: 400, textWords: 4000, } return <WordCountModalContent {...args} data={data} /> } export const Loading = args => { return <WordCountModalContent {...args} loading /> } export const LoadingError = args => { return <WordCountModalContent {...args} error /> } export const Messages = args => { const messages = [ 'Lorem ipsum dolor sit amet.', 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', ].join('\n') return <WordCountModalContent {...args} data={{ messages }} /> } export default { title: 'Modals / Word Count / Content', component: WordCountModalContent, args: { animation: false, show: true, error: false, loading: false, }, argTypes: { handleHide: { action: 'hide' }, }, }
overleaf/web/frontend/stories/word-count-modal-content.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/word-count-modal-content.stories.js", "repo_id": "overleaf", "token_count": 355 }
529
@import './editor/file-tree.less'; @import './editor/history.less'; @import './editor/toolbar.less'; @import './editor/left-menu.less'; @import './editor/pdf.less'; @import './editor/share.less'; @import './editor/chat.less'; @import './editor/file-view.less'; @import './editor/search.less'; @import './editor/publish-template.less'; @import './editor/online-users.less'; @import './editor/hotkeys.less'; @import './editor/review-panel.less'; @import './editor/rich-text.less'; @import './editor/publish-modal.less'; @import './editor/outline.less'; @import './editor/logs.less'; @import './editor/symbol-palette.less'; @ui-layout-toggler-def-height: 50px; @ui-resizer-size: 7px; @keyframes blink { 0% { opacity: 0.2; } 20% { opacity: 1; } 100% { opacity: 0.2; } } .editor-menu-icon { &.fa { width: 1em; background: @editor-header-logo-background; &::before { // Disable the font-awesome icon when in Overleaf by replacing it with a // non-breakable space instead (otherwise the browser would render a // zero-width element). content: '\00a0'; } } } .full-size { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .global-alerts { height: 0; margin-top: 2px; text-align: center; .alert { display: inline-block; text-align: left; min-width: 400px; padding: @global-alerts-padding; font-size: 14px; margin-bottom: (@line-height-computed / 4); position: relative; z-index: 20; } } #try-reconnect-now-button { margin-left: 20px; } #synctex-more-info-button { margin-left: 20px; } #ide-body { background-color: @pdf-bg; .full-size; top: @ide-body-top-offset; &.ide-history-open { top: @ide-body-top-offset + @editor-toolbar-height; } } #editor, #editor-rich-text { .full-size; top: 32px; } #editor-rich-text { top: @editor-toolbar-height; } .no-history-available, .no-file-selection, .multi-selection-ongoing { &::before { .full-size; left: 20px; content: ''; background: url(/img/ol-brand/overleaf-o-grey.svg) center / 200px no-repeat; opacity: 0.2; pointer-events: none; } } .no-history-available, .no-file-selection-message, .multi-selection-message { width: 50%; margin: 0 auto; text-align: center; padding: @line-height-computed 0; } .toolbar-editor { height: @editor-toolbar-height; background-color: @editor-toolbar-bg; padding: 0 5px; overflow: hidden; position: relative; z-index: 10; // Prevent track changes showing over toolbar } .loading-screen { display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 100%; background-color: #fff; } .loading-screen-brand-container { width: 15%; min-width: 200px; text-align: center; } .loading-screen-brand { position: relative; width: 100%; padding-top: @editor-loading-logo-padding-top; height: 0; background: @editor-loading-logo-background-url no-repeat bottom / 100%; &::after { content: ''; position: absolute; height: inherit; right: 0; bottom: 0; left: 0; background: @editor-loading-logo-foreground-url no-repeat bottom / 100%; transition: height 0.5s; } } .loading-screen-label { margin: 0; padding-top: 1em; font-size: 2em; color: @gray-dark; } .loading-screen-ellip { animation: blink 1.4s both infinite; &:nth-child(2) { animation-delay: 0.2s; } &:nth-child(3) { animation-delay: 0.4s; } } .loading-screen-error { margin: 0; padding-top: 1em; color: @state-danger-text; } .loading-panel { .full-size; padding-top: 10rem; font-family: @font-family-serif; text-align: center; background-color: #fafafa; } .loading-panel-file-view { background-color: @gray-lightest; } .error-panel { .full-size; padding: @line-height-computed; background-color: #fafafa; .alert { max-width: 400px; margin: auto; } } .project-name { .name { display: inline-block; overflow: hidden; text-overflow: ellipsis; vertical-align: top; padding: 6px; color: @project-name-color; font-weight: 700; white-space: nowrap; } input { height: 30px; margin-top: 4px; text-align: center; padding: 6px; font-weight: 700; max-width: 500px; } a.rename { visibility: hidden; display: inline-block; color: @project-rename-link-color; padding: 5px; border-radius: @border-radius-small; cursor: pointer; &:hover { text-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); color: @project-rename-link-color-hover; text-decoration: none; } } &:hover { a.rename { visibility: visible; } } } /************************************** Ace ***************************************/ // The internal components of the aceEditor directive .ace-editor-wrapper { .full-size; .undo-conflict-warning { position: absolute; top: 0; right: 0; left: 0; z-index: 10; } .ace-editor-body { width: 100%; height: 100%; } .spelling-highlight { z-index: 3; position: absolute; background-image: url(/img/spellcheck-underline.png); @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { background-image: url(/img/spellcheck-underline@2x.png); background-size: 5px 4px; } background-repeat: repeat-x; background-position: bottom left; } .remote-cursor { position: absolute; border-left: 2px solid transparent; // Adds "nubbin" top right of cursor, which inherits the injected color &::before { content: ''; position: absolute; left: -2px; top: -5px; height: 5px; width: 5px; border-top-width: 3px; border-right-width: 3px; border-bottom-width: 2px; border-left-width: 2px; border-style: solid; border-color: inherit; } } .annotation-label { padding: (@line-height-computed / 4) (@line-height-computed / 2); font-size: 0.8rem; z-index: 100; font-family: @font-family-sans-serif; color: white; font-weight: 700; white-space: nowrap; } .annotation { position: absolute; z-index: 2; } .highlights-before-label, .highlights-after-label { position: absolute; right: @line-height-computed; z-index: 1; } .highlights-before-label { top: @line-height-computed / 2; } .highlights-after-label { bottom: @line-height-computed / 2; } } .strike-through-foreground::after { content: ''; position: absolute; width: 100%; top: 50%; margin-top: -1px; height: 2px; background: currentColor; } // Hack to solve an issue where scrollbars aren't visible in Safari. // Safari seems to clip part of the scrollbar element. By giving the // element a background, we're telling Safari that it *really* needs to // paint the whole area. See https://github.com/ajaxorg/ace/issues/2872 .ace_scrollbar-inner { background-color: #fff; opacity: 0.01; .ace_dark & { background-color: #000; } } /************************************** CodeMirror ***************************************/ .cm-editor-wrapper { position: relative; height: 100%; } .cm-editor-body { height: 100%; } // CM (for some reason) has height set to 300px in it's stylesheet .CodeMirror { height: 100%; } .ui-layout-resizer { width: @ui-resizer-size !important; background-color: @editor-resizer-bg-color; &.ui-layout-resizer-closed { &::before, &::after { content: none; } } &::before, &::after { content: '\2847'; display: block; position: absolute; text-align: center; left: -2px; -webkit-font-smoothing: antialiased; width: 100%; font-size: 24px; top: 25%; color: @ol-blue-gray-2; } &::after { top: 75%; } } .ui-layout-toggler { display: none !important; } .custom-toggler { position: absolute; display: flex; align-items: center; justify-content: center; width: @ui-resizer-size !important; height: 50px; margin-top: -25px; top: 50%; z-index: 3; background-color: @editor-toggler-bg-color; &:hover, &:focus { outline: none; text-decoration: none; } // Increase hit area &::before { content: ''; display: block; position: absolute; top: 0; right: -3px; bottom: 0; left: -3px; } &::after { font-family: FontAwesome; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-size: 65%; font-weight: bold; color: #fff; user-select: none; pointer-events: none; } &:hover { background-color: @editor-toggler-hover-bg-color; } } .custom-toggler-east::after { content: '\f105'; } .custom-toggler-west::after { content: '\f104'; } .custom-toggler-closed.custom-toggler-east::after { content: '\f104'; } .custom-toggler-closed.custom-toggler-west::after { content: '\f105'; } .ui-layout-resizer-dragging { background-color: @editor-resizer-bg-color-dragging; } .context-menu { position: fixed; z-index: 100; } .editor-dark { color: @gray-lighter; background-color: @editor-dark-background-color; .ui-layout-resizer { background-color: darken(@editor-dark-background-color, 10%); border: none; } .btn-default { color: white; background-color: @gray; border-color: darken(@gray-dark, 10%); &:hover { background-color: darken(@gray, 5%); border-color: darken(@gray-dark, 20%); } } } .modal-alert { margin-top: 10px; margin-bottom: 0px; } // vertically centre the "connection down" modal so it does not hide // the reconnecting indicator .modal.lock-editor-modal { display: flex !important; background-color: rgba(0, 0, 0, 0.3); overflow-y: hidden; pointer-events: none; .modal-dialog { top: @line-height-computed; } } .out-of-sync-modal { .text-preview { margin-top: @line-height-computed / 2; .scroll-container { max-height: 360px; width: 100%; background-color: white; font-size: 0.8em; line-height: 1.1em; overflow: auto; border: 1px solid @gray-lighter; padding-left: 12px; padding-right: 12px; padding-top: 8px; padding-bottom: 8px; text-align: left; white-space: pre; font-family: monospace; } } } .sl_references_search_hint { position: relative; top: 100%; } .sl_references_search_hint { position: relative; left: -1px; text-align: center; padding: 2px; background: rgb(202, 214, 250); border: 1px solid lightgray; box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.2); span { color: black; } } // -- References Search Modal -- .references-search-modal-backdrop { // don't grey out the editor when the // modal is active background-color: transparent; } .references-search-modal { // upgrade prompt .references-search-upgrade-prompt { padding: 24px; padding-bottom: 48px; .upgrade-prompt { text-align: center; width: 400px; padding-top: 14px; padding-bottom: 14px; padding-left: 38px; padding-right: 38px; margin: auto; background: white; opacity: 0.95; border-radius: 8px; .message { margin-top: 15px; &.call-to-action { font-weight: bold; } ul.list-unstyled { text-align: left; } } a.btn { opacity: 1; } } } .search-form { // position the spinner inside the input element i.fa-spinner { margin-top: -30px; } } .alert-danger { margin-top: 12px; margin-bottom: 0px; } // search result items list .search-results { font-size: 12px; .no-results-message { font-size: 16px; } .search-result-hit { &:hover { cursor: pointer; } border-bottom: 1px solid #ddd; padding: 8px; &:last-child { border-bottom: 1px solid transparent; } border-left: 4px solid transparent; &.selected-search-result-hit { color: @brand-success; } .hit-title { font-size: 1.3em; font-style: italic; } } } } .referencesImportModal { .referencesImportPreviewScroller { font-family: monospace; font-size: 0.8em; max-height: 360px; overflow: scroll; white-space: pre; padding: 8px 12px; margin-bottom: 15px; border: 1px solid @gray-lighter; background-color: @gray-lightest; } } .teaser-title, .dropbox-teaser-title { margin-top: 0; text-align: center; } .teaser-refresh-label { text-align: center; } .teaser-img, .dropbox-teaser-img { .img-responsive; margin-bottom: 5px; } .teaser-video-container, .dropbox-teaser-video-container { margin-top: -@modal-inner-padding; margin-left: -@modal-inner-padding; margin-right: -@modal-inner-padding; margin-bottom: 5px; overflow: hidden; } .teaser-video, .dropbox-teaser-video { width: 100%; height: auto; border-bottom: 1px solid @modal-header-border-color; } .spell-check-menu { > .dropdown-menu > li > a { padding: 2px 15px; } } .spell-check-menu-from-bottom { > .dropdown-menu { top: auto; bottom: 100%; } } // The source editor container is managed by jQuery's UI layout library, which adds an `overflow: hidden` // rule to it. This is problematic because we need overflowing content to be visible (the review panel // previews are shown on hover, visually outside the source editor container). As the `overflow: hidden` // rule is added automatically (inline and not configurable), the only workaround is to use `!important`. .editor-container { overflow: visible !important; }
overleaf/web/frontend/stylesheets/app/editor.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/editor.less", "repo_id": "overleaf", "token_count": 5695 }
530
.ace_search { background-color: @gray-lightest; border: 1px solid @editor-border-color; border-top: 0 none; width: 350px; overflow: hidden; position: absolute; top: 0px; z-index: 99; white-space: normal; padding: @line-height-computed / 4; font-family: @font-family-sans-serif; a, button { i { pointer-events: none; } } .ace_searchbtn_close { position: absolute; top: 6px; right: 12px; color: @gray; &:hover { color: @gray-dark; } } .ace_search_form, .ace_replace_form { margin-bottom: @line-height-computed / 4; input { width: 210px; display: inline-block; vertical-align: middle; } .btn-group { display: inline-block; } } .ace_nomatch { input { border-color: @red; } } .ace_search_options { display: flex; justify-content: space-between; } .ace_search_counter { color: @editor-search-count-color; margin: auto 0; } } .ace_search.left { border-left: 0 none; border-radius: 0px 0px @border-radius-base 0px; left: 0; } .ace_search.right { border-radius: 0px 0px 0px @border-radius-base; border-right: 0 none; right: 0; }
overleaf/web/frontend/stylesheets/app/editor/search.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/editor/search.less", "repo_id": "overleaf", "token_count": 526 }
531
dl.codebox { dt { line-height: 1; } }
overleaf/web/frontend/stylesheets/app/open-in-overleaf.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/open-in-overleaf.less", "repo_id": "overleaf", "token_count": 26 }
532
// // Alerts // -------------------------------------------------- // Base styles // ------------------------- .alert { padding: @alert-padding; margin-bottom: @line-height-computed; border-left: 3px solid transparent; border-radius: @alert-border-radius; // Headings for larger alerts h4 { margin-top: 0; // Specified for the h4 to prevent conflicts of changing @headings-color color: inherit; } // Provide class for links that match alerts .alert-link { font-weight: @alert-link-font-weight; } // Improve alignment and spacing of inner content > p, > ul { margin-bottom: 0; } > p + p { margin-top: 5px; } p:last-child { margin-bottom: 0; } } // Dismissable alerts // // Expand the right padding and account for the close button's positioning. .alert-dismissable { padding-right: (@alert-padding + 20); // Adjust close link position .close { position: relative; top: -2px; right: -21px; color: inherit; } } // Alternate styles // // Generate contextual modifier classes for colorizing the alert. .alert-success { .alert-variant(@alert-success-bg; @alert-success-border; @alert-success-text); } .btn-alert-success { .btn-alert-variant(@alert-success-bg); } .alert-info { .alert-variant(@alert-info-bg; @alert-info-border; @alert-info-text); } .btn-alert-info { .button-variant(@btn-info-color; @btn-info-bg; @btn-info-border); .alert-btn(@btn-info-bg); } .alert-warning { .alert-variant(@alert-warning-bg; @alert-warning-border; @alert-warning-text); } .btn-alert-warning { .btn-alert-variant(@alert-warning-bg); } .alert-danger { .alert-variant(@alert-danger-bg; @alert-danger-border; @alert-danger-text); } .btn-alert-danger { .btn-alert-variant(@alert-danger-bg); } .alert-alt { .alert-variant(@alert-alt-bg; @alert-alt-border; @alert-alt-text); } .btn-alert-alt { .btn-alert-variant(@alert-alt-bg); } .alert { a, .btn-inline-link { color: white; text-decoration: underline; } .btn { text-decoration: none; } }
overleaf/web/frontend/stylesheets/components/alerts.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/alerts.less", "repo_id": "overleaf", "token_count": 780 }
533
footer.site-footer { background-color: @footer-bg-color; border-top: 1px solid @gray-lighter; font-size: 0.9rem; position: absolute; bottom: 0; width: 100%; height: @footer-height; line-height: @footer-height - 1; // Hack — in Chrome, using the full @footer-height would generate vertical scrolling ul { list-style: none; margin: 0px; li { display: inline-block; margin: 0 0.5em; } i { font-size: 1.2rem; } } li.lngOption { text-align: left; display: list-item; img { vertical-align: text-bottom; } } a { color: @footer-link-color; &:hover, &:focus { color: @footer-link-hover-color; } } } .site-footer-content { .container-fluid; } .sprite-icon-lang { display: inline-block; vertical-align: middle; }
overleaf/web/frontend/stylesheets/components/footer.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/footer.less", "repo_id": "overleaf", "token_count": 364 }
534
// // Navs // -------------------------------------------------- // Base class // -------------------------------------------------- .nav { margin-bottom: 0; padding-left: 0; // Override default ul/ol list-style: none; &:extend(.clearfix all); > li { position: relative; display: block; > a { position: relative; display: block; padding: @nav-link-padding; &:hover, &:focus { text-decoration: none; background-color: @nav-link-hover-bg; color: white; } } // Disabled state sets text to gray and nukes hover/tab effects &.disabled > a { color: @nav-disabled-link-color; &:hover, &:focus { color: @nav-disabled-link-hover-color; text-decoration: none; background-color: transparent; cursor: not-allowed; } } } // Open dropdowns .open > a { &, &:hover, &:focus { background-color: @nav-link-hover-bg; border-color: @link-color; } } // Nav dividers (deprecated with v3.0.1) // // This should have been removed in v3 with the dropping of `.nav-list`, but // we missed it. We don't currently support this anywhere, but in the interest // of maintaining backward compatibility in case you use it, it's deprecated. .nav-divider { .nav-divider(); } // Prevent IE8 from misplacing imgs // // See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989 > li > a > img { max-width: none; } } // Tabs // ------------------------- // Give the tabs something to sit on .nav-tabs { border-bottom: 1px solid @nav-tabs-border-color; > li { float: left; // Make the list-items overlay the bottom border margin-bottom: -1px; // Actual tabs (as links) > a { margin-right: 2px; line-height: @line-height-base; border: 1px solid transparent; border-radius: @border-radius-base @border-radius-base 0 0; &:hover { cursor: pointer; border-color: @nav-tabs-link-hover-border-color @nav-tabs-link-hover-border-color @nav-tabs-border-color; } } // Active state, and its :hover to override normal :hover &.active > a { &, &:hover, &:focus { color: @nav-tabs-active-link-hover-color; background-color: @nav-tabs-active-link-hover-bg; border: 1px solid @nav-tabs-active-link-hover-border-color; border-bottom-color: transparent; cursor: default; } } } // pulling this in mainly for less shorthand &.nav-justified { .nav-justified(); .nav-tabs-justified(); } } // Pills // ------------------------- .nav-pills { > li { float: left; // Links rendered as pills > a { border-radius: @nav-pills-border-radius; border: 2px solid @nav-pills-link-color; color: @nav-pills-link-color; padding: 8px 13px; &:hover, &:focus { background-color: @nav-pills-link-hover-bg; border: 2px solid @nav-pills-link-hover-bg; } } + li { margin-left: 2px; } // Active state &.active > a { &, &:hover, &:focus { color: @nav-pills-active-link-hover-color; border: 2px solid @nav-pills-active-link-hover-bg; background-color: @nav-pills-active-link-hover-bg; } } } } // Stacked pills .nav-stacked { > li { float: none; + li { margin-top: 2px; margin-left: 0; // no need for this gap between nav items } } } // Nav variations // -------------------------------------------------- // Justified nav links // ------------------------- .nav-justified { width: 100%; > li { float: none; > a { text-align: center; margin-bottom: 5px; } } > .dropdown .dropdown-menu { top: auto; left: auto; } @media (min-width: @screen-sm-min) { > li { display: table-cell; width: 1%; > a { margin-bottom: 0; } } } } // Move borders to anchors instead of bottom of list // // Mixin for adding on top the shared `.nav-justified` styles for our tabs .nav-tabs-justified { border-bottom: 0; > li > a { // Override margin from .nav-tabs margin-right: 0; border-radius: @border-radius-base; } > .active > a, > .active > a:hover, > .active > a:focus { border: 1px solid @nav-tabs-justified-link-border-color; } @media (min-width: @screen-sm-min) { > li > a { border-bottom: 1px solid @nav-tabs-justified-link-border-color; border-radius: @border-radius-base @border-radius-base 0 0; } > .active > a, > .active > a:hover, > .active > a:focus { border-bottom-color: @nav-tabs-justified-active-link-border-color; } } } // Tabbable tabs // ------------------------- // Hide tabbable panes to start, show them when `.active` .tab-content { background-color: @nav-tabs-active-link-hover-bg; border: 1px solid @nav-tabs-border-color; border-top: none; padding: @line-height-computed / 2; > .tab-pane { display: none; } > .active { display: block; } } // Dropdowns // ------------------------- // Specific dropdowns .nav-tabs .dropdown-menu { // make dropdown border overlap tab border margin-top: -1px; // Remove the top rounded corners here since there is a hard edge above the menu .border-top-radius(0); }
overleaf/web/frontend/stylesheets/components/navs.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/navs.less", "repo_id": "overleaf", "token_count": 2264 }
535
.ui-select-bootstrap > .ui-select-choices, .ui-select-bootstrap > .ui-select-no-choice { width: auto; max-width: 400px; } .dropdown-menu .ui-select-choices-row { padding: 4px 0; > .ui-select-choices-row-inner { overflow: hidden; text-overflow: ellipsis; } } .ui-select-placeholder, .ui-select-match-text { overflow: hidden; text-overflow: ellipsis; font-weight: normal; } .ui-select-bootstrap { &:focus { outline: none; } > .ui-select-match { &:focus { outline: none; } &.btn-default-focus { outline: 0; box-shadow: none; background-color: transparent; > .btn { border-color: @input-border-focus; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px fade(@input-border-focus, 60%); padding-top: @input-suggestion-v-offset; } } > .btn { color: @input-color; background-color: @input-bg; border: 1px solid @input-border; padding-top: @input-suggestion-v-offset; &[disabled] { cursor: not-allowed; background-color: @input-bg-disabled; opacity: 1; } } } } .ui-select-container[tagging] { .ui-select-toggle { cursor: text; padding-top: @input-suggestion-v-offset; > i.caret.pull-right { display: none; } } }
overleaf/web/frontend/stylesheets/components/ui-select.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/components/ui-select.less", "repo_id": "overleaf", "token_count": 618 }
536
@import 'style.less'; @import 'core/ol-light-variables.less'; @is-overleaf-light: true; @show-rich-text: true;
overleaf/web/frontend/stylesheets/light-style.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/light-style.less", "repo_id": "overleaf", "token_count": 45 }
537
{ "tex_live_version": "TeX Live Version", "git": "Git", "pdf_compile_in_progress_error": "Kompiliervorgang läuft bereits in einem anderen Fenster", "pdf_compile_try_again": "Bitte warte auf deinen anderen Kompiliervorgang, bevor du es erneut versuchst.", "invalid_email": "Eine E-Mail-Adresse ist ungültig", "auto_compile": "Automatisch kompilieren", "on": "An", "tc_everyone": "Jeder", "per_user_tc_title": "Änderungsverfolgung pro Nutzer", "you_can_use_per_user_tc": "Nun kannst du Änderungen pro Nutzer verfolgen", "turn_tc_on_individuals": "Schalte die Änderungsverfolgung für individuelle Nutzer an", "keep_tc_on_like_before": "Oder lass es für alle aktiviert, wie vorher", "auto_close_brackets": "Klammern automatisch schließen", "accept_all": "Alle akzeptieren", "reject_all": "Alle verwerfen", "uncategorized": "Nicht kategorisiert", "pdf_compile_rate_limit_hit": "Limit der Kompiliervorgänge überschritten", "project_flagged_too_many_compiles": "Dieses Projekt wurde zu häufig zum Kompilieren vermerkt. Das Limit wird in Kürze aufgehoben.", "reauthorize_github_account": "Authorisiere deinen GitHub-Account erneut", "github_credentials_expired": "Deine GitHub-Authorisierungsschlüssel sind abgelaufen", "hit_enter_to_reply": "Enter drücken, um zu antworten", "add_your_comment_here": "Füge hier einen Kommentar hinzu", "resolved_comments": "Gelöste Kommentare", "try_it_for_free": "Probiere es kostenlos aus", "please_ask_the_project_owner_to_upgrade_to_track_changes": "Bitte den Projekteigentümer um ein Upgrade, um Änderungen verfolgen zu können", "mark_as_resolved": "Als gelöst markieren", "reopen": "Erneut öffnen", "add_comment": "Füge Kommentar hinzu", "no_resolved_threads": "Keine gelösten Threads", "upgrade_to_track_changes": "Upgrade, um Änderungen verfolgen zu können", "see_changes_in_your_documents_live": "Verfolge Änderungen in deinen Dokumenten, live", "track_any_change_in_real_time": "Verfolge jegliche Änderung, in Echtzeit", "review_your_peers_work": "Überprüfe die Arbeit deiner Kollegen", "accept_or_reject_each_changes_individually": "Akzeptiere oder Verwerfe jede Änderung individuell", "accept": "Akzeptieren", "reject": "Verwerfen", "no_comments": "Keine Kommentare", "edit": "Bearbeiten", "are_you_sure": "Bist du sicher?", "resolve": "Lösen", "reply": "Antworten", "quoted_text_in": "Zitierter Text in", "review": "Überprüfen", "track_changes_is_on": "Änderungen verfolgen ist <strong>an</strong>", "track_changes_is_off": "Änderungen verfolgen ist <strong>aus</strong>", "current_file": "Aktuelle Datei", "overview": "Überblick", "tracked_change_added": "Hinzugefügt", "tracked_change_deleted": "Gelöscht", "show_all": "Alles anzeigen", "show_less": "Weniger anzeigen", "dropbox_sync_error": "Dropbox-Synchronisierungsfehler", "send": "Absenden", "sending": "Wird gesendet", "invalid_password": "Falsches Passwort", "error": "Fehler", "other_actions": "Weitere Aktionen", "send_test_email": "Test-Mail senden", "email_sent": "E-Mail versendet", "create_first_admin_account": "Erstelle den ersten Admin-Account", "ldap": "LDAP", "ldap_create_admin_instructions": "Wähle eine E-Mail-Adresse für den ersten __appName__-Admin-Account. Dieser sollte bereits im SAML-System vorhanden sein. Du wirst dann aufgefordert, dich mit diesem Account einzuloggen.", "saml": "SAML", "saml_create_admin_instructions": "Wähle eine E-Mail-Adresse für den ersten __appName__-Admin-Account. Dieser sollte bereits im SAML-System vorhanden sein. Du wirst dann aufgefordert, dich mit diesem Account einzuloggen.", "admin_user_created_message": "Admin-Nutzer erstellt, <a href=\"__link__\">einloggen</a> um fortzufahren", "status_checks": "Statusüberprüfungen", "editor_resources": "Editor-Literatur", "checking": "Überprüfe", "cannot_invite_self": "Du kannst dich nicht selbst einladen", "cannot_invite_non_user": "Einladung konnte nicht gesendet werden. Empfänger muss bereits einen __appName__-Account besitzen.", "log_in_with": "Einloggen mit __provider__", "return_to_login_page": "Zurück zur Login-Seite", "login_failed": "Login fehlgeschlagen", "delete_account_warning_message_3": "Du bist dabei, <strong>alle Account-Daten</strong> permanent zu löschen, inklusive Projekte und Einstellungen. Bitte gib die E-Mail-Adresse und das Passwort deines Accounts in die Felder ein um fortzufahren.", "delete_account_warning_message_2": "Du bist dabei <strong>alle Account-Daten</strong> permanent zu löschen, inklusive Projekte und Einstellungen. Bitte gib die E-Mail-Adresse deines Accounts in das Feld ein um fortzufahren.", "your_sessions": "Deine Sessions", "clear_sessions_description": "Dies ist eine Liste anderer Sessions (Logins), die auf deinem Account aktiv sind, exklusive deiner aktuellen Session. Klicke auf \"Sessions löschen\", um sie auszuloggen.", "no_other_sessions": "Keine andere Session aktiv", "ip_address": "IP-Adresse", "session_created_at": "Session erzeugt um", "clear_sessions": "Sessions löschen", "clear_sessions_success": "Sessions gelöscht", "sessions": "Sessions", "manage_sessions": "Sessions verwalten", "syntax_validation": "Syntaxüberprüfung", "history": "Verlauf", "joining": "Trete bei", "open_project": "Öffne Projekt", "files_cannot_include_invalid_characters": "Dateien dürfen die Zeichen '*' oder '/' nicht enthalten.", "invalid_file_name": "Ungültiger Dateiname", "autocomplete_references": "Referenzautovervollständigung (in einem <code>\\cite{}</code>-Block)", "autocomplete": "Autovervollständigung", "failed_compile_check": "In deinem Projekt scheinen fatale Syntaxfehler vorzuliegen, die du beheben solltest, bevor wir es kompilieren", "failed_compile_check_try": "Versuche es trotzdem zu kompilieren", "failed_compile_option_or": "oder", "failed_compile_check_ignore": "schalte die Syntaxüberprüfung aus", "compile_time_checks": "Syntaxüberprüfungen", "stop_on_validation_error": "Überprüfe die Syntax vor dem Kompilieren", "ignore_validation_errors": "Syntaxüberprüfung deaktivieren", "run_syntax_check_now": "Syntax jetzt überprüfen", "your_billing_details_were_saved": "Deine Rechnungsdaten wurden gespeichert", "security_code": "Kartenprüfnummer", "paypal_upgrade": "Bitte klicke für das Upgrade auf den Button und logge dich bei PayPal mit deiner E-Mail-Adresse und deinem Passwort ein.", "upgrade_cc_btn": "Upgrade jetzt, zahle nach sieben Tagen", "upgrade_paypal_btn": "Fortfahren", "notification_project_invite": "<b>__userName__</b> möchte, dass du <b>__projectName__</b> beitrittst. <a class=\"btn btn-sm btn-info pull-right\" href=\"/project/__projectId__/invite/token/__token__\">Trete Projekt bei</a>", "file_restored": "Deine Datei (__filename__) wurde wiederhergestellt.", "file_restored_back_to_editor": "Du kannst zum Editor zurückkehren und es erneut bearbeiten", "file_restored_back_to_editor_btn": "Zurück zum Editor", "view_project": "Projekt ansehen", "join_project": "Projekt beitreten", "invite_not_accepted": "Einladung noch nicht angenommen", "resend": "Sende erneut", "syntax_check": "Syntaxüberprüfung", "revoke_invite": "Einladung zurückziehen", "pending": "Ausstehend", "invite_not_valid": "Dies ist keine gültige Projekteinladung", "invite_not_valid_description": "Die Einladung ist wahrscheinlich abgelaufen. Bitte kontaktiere den Projektbesitzer", "accepting_invite_as": "Du akzeptierst die Einladung als", "accept_invite": "Einladung akzeptieren", "log_hint_ask_extra_feedback": "Warum war dieser Hinweis nicht hilfreich?", "log_hint_extra_feedback_didnt_understand": "Ich habe den Hinweis nicht verstanden", "log_hint_extra_feedback_not_applicable": "Ich kann diese Lösung nicht auf mein Dokument anwenden", "log_hint_extra_feedback_incorrect": "Der Fehler wird dadurch nicht behoben", "log_hint_extra_feedback_other": "Anderes:", "log_hint_extra_feedback_submit": "Abschicken", "if_you_are_registered": "Falls du bereits registriert bist", "stop_compile": "Kompiliervorgang stoppen", "terminated": "Kompiliervorgang abgebrochen", "compile_terminated_by_user": "Der Kompiliervorgang wurde durch Klick auf den Button 'Kompiliervorgang stoppen' abgebrochen. Du kannst dir die Logs anschauen, um zu sehen, wo der Kompiliervorgang gestoppt hat.", "site_description": "Ein einfach bedienbarer Online-LaTeX-Editor. Keine Installation notwendig, Zusammenarbeit in Echtzeit, Versionskontrolle, Hunderte von LaTeX-Vorlagen und mehr", "knowledge_base": "Wissensdatenbank", "contact_message_label": "Nachricht", "kb_suggestions_enquiry": "Hast du dir schon <0>__kbLink__</0> angeschaut?", "answer_yes": "Ja", "answer_no": "Nein", "log_hint_extra_info": "Erfahre mehr", "log_hint_feedback_label": "War dieser Hinweis hilfreich?", "log_hint_feedback_gratitude": "Vielen Dank für dein Feedback!", "recompile_pdf": "PDF erneut kompilieren", "about_paulo_reis": "ist ein Frontend-Softwareentwickler and User Experience Researcher aus Aveiro, Portugal. Paulo hat einen PhD in User Experience und arbeitet leidenschaftlich an der Verbesserung menschlicher Nutzung der Technik – sowohl konzeptionell und in der Validierung, als auch im Design und der Implementierung.", "login_or_password_wrong_try_again": "Dein Benutzername oder Passwort ist nicht korrekt. Bitte versuche es erneut", "manage_beta_program_membership": "Beta-Programm-Mitgliedschaft verwalten", "beta_program_opt_out_action": "Beta-Programm verlassen", "disable_beta": "Beta deaktivieren", "beta_program_badge_description": "Während der Nutzung von __appName__ werden Beta-Funktionen durch diesen Badge markiert:", "beta_program_current_beta_features_description": "Wir testen momentan die folgenden neuen Funktionen in der Beta:", "enable_beta": "Beta aktivieren", "user_in_beta_program": "Benutzer nimmt an Beta-Programm teil", "beta_program_already_participating": "Du bist dem Beta-Programm beigetreten", "sharelatex_beta_program": "__appName__ Beta-Programm", "beta_program_benefits": "Wir verbessern __appName__ stetig. Indem du dem Beta-Programm beitrittst, hast du früheren Zugriff auf neue Funktionen und hilfst uns, deine Bedürfnisse besser zu verstehen.", "beta_program_opt_in_action": "Beta-Programm beitreten", "conflicting_paths_found": "Dateipfadkonflikte gefunden", "following_paths_conflict": "Die folgenden Dateien und Ordner weisen Konflikte mit dem gleichen Pfad auf", "open_a_file_on_the_left": "Öffne eine Datei auf der linken Seite", "reference_error_relink_hint": "Wenn dieser Fehler weiterhin auftritt, versuche dein Konto hier neu zu verlinken:", "pdf_rendering_error": "PDF-Wiedergabe-Fehler", "something_went_wrong_rendering_pdf": "Etwas ist bei der Wiedergabe dieses PDFs schiefgelaufen.", "mendeley_reference_loading_error_expired": "Mendeley-Token abgelaufen, bitte verknüpfe dein Konto neu", "zotero_reference_loading_error_expired": "Zotero-Token abgelaufen, bitte verknüpfe dein Konto neu", "mendeley_reference_loading_error_forbidden": "Referenzen konnten nicht von Mendeley geladen werden; verlinke dein Konto bitte erneut und versuche es nochmal", "zotero_reference_loading_error_forbidden": "Referenzen konnten nicht von Zotero geladen werden; verlinke dein Konto bitte erneut und versuche es nochmal", "mendeley_integration": "Mendeley-Integration", "mendeley_sync_description": "Mit Mendeley-Integration kannst du deine Referenzen von Mendeley in deine __appName__-Projekte importieren.", "mendeley_is_premium": "Mendeley-Integration ist eine Premium-Funktion", "link_to_mendeley": "Link zu Mendeley", "unlink_to_mendeley": "Link zu Mendeley entfernen", "mendeley_reference_loading": "Referenzen von Mendeley werden geladen", "mendeley_reference_loading_success": "Von Mendeley geladene Referenzen", "mendeley_reference_loading_error": "Fehler, Referenzen konnten nicht von Mendeley geladen werden", "zotero_integration": "Zotero-Integration.", "zotero_sync_description": "Mit Zotero-Integration kannst du deine Referenzen von Zotero in deine __appName__ Projekte importieren.", "zotero_is_premium": "Zotero-Integration ist eine Premium-Funktion", "link_to_zotero": "Link zu Zotero", "unlink_to_zotero": "Link zu Zotero entfernen", "zotero_reference_loading": "Referenzen von Zotero werden geladen", "zotero_reference_loading_success": "Von Zotero geladene Referenzen", "zotero_reference_loading_error": "Fehler, Referenzen konnten nicht von Mendeley geladen werden", "reference_import_button": "Referenzen importieren in", "unlink_reference": "Link zum Referenzengeber entfernen", "unlink_warning_reference": "Achtung: Wenn du dein Konto von diesem Anbieter entkoppelst, wirst du nicht in der Lage sein, Referenzen in deine Projekte zu importieren.", "mendeley": "Mendeley", "zotero": "Zotero", "suggest_new_doc": "Neues Dokument vorschlagen", "request_sent_thank_you": "Anforderung gesendet, danke.", "suggestion": "Vorschlag", "project_url": "Betroffene Projekt-URL", "subject": "Betreff", "confirm": "Bestätigen", "cancel_personal_subscription_first": "Du hast bereits ein persönliches Abonnement. Möchtest du dieses zuerst zu beenden, bevor du der Gruppenlizenz beitrittst?", "delete_projects": "Projekte löschen", "leave_projects": "Projekte verlassen", "delete_and_leave_projects": "Projekte löschen und verlassen", "too_recently_compiled": "Der Kompiliervorgang wurde übersprungen, da dieses Projekt gerade erst kompiliert wurde.", "clsi_maintenance": "Die Kompilierungsserver wurden für Wartungsarbeiten heruntergefahren und werden in Kürze zurück sein.", "references_search_hint": "Zum Suchen Strg-Space drücken", "ask_proj_owner_to_upgrade_for_references_search": "Bitte den Projekteigentümer zu aktualisieren, damit du die Referenz-Suchfunktion verwenden kannst.", "ask_proj_owner_to_upgrade_for_faster_compiles": "Bitte den Projekteigentümer zu aktualisieren, damit du schneller kompilieren und das Zeitlimit erweitern kannst.", "search_bib_files": "Nach Autor, Titel, Jahr suchen", "leave_group": "Gruppe verlassen", "leave_now": "Jetzt verlassen", "sure_you_want_to_leave_group": "Bist du sicher, dass du diese Gruppe verlassen möchtest?", "notification_group_invite": "Du wurdest zu __groupName__ eingeladen, <a href=\"‘/user/subscription/__subscription_id__/group/invited‘\">hier beitreten</a>.", "search_references": "Suche die .bib-Dateien in diesem Projekt", "no_search_results": "Keine Suchergebnisse", "email_already_registered": "Diese E-Mail-Adresse ist bereits registriert.", "compile_mode": "Kompilier-Modus", "normal": "Normal", "fast": "Schnell", "rename_folder": "Ordner umbennenen", "delete_folder": "Ordner löschen", "about_to_delete_folder": "Du bist dabei, die folgenden Ordner zu löschen (alle darin enthaltenen Projekte werden nicht gelöscht werden):", "to_modify_your_subscription_go_to": "Um dein Abo zu ändern, gehe zu", "manage_subscription": "Abo verwalten", "activate_account": "Deaktiviere dein Konto", "yes_please": "Ja, bitte.", "nearly_activated": "Du bist einen Schritt davon entfernt, dein __appName__-Konto zu aktivieren!", "please_set_a_password": "Bitte ein Passwort einrichten", "activation_token_expired": "Dein Aktivierungs-Token ist abgelaufen; du musst einen neuen anfordern.", "activate": "Aktivieren", "activating": "Aktivierung", "ill_take_it": "Ich nehme es!", "cancel_your_subscription": "Beende dein Abo", "no_thanks_cancel_now": "Nein, danke - Ich möchte nach wie vor jetzt stornieren", "cancel_my_account": "Mein Abo stornieren", "sure_you_want_to_cancel": "Willst du wirklich abbrechen?", "i_want_to_stay": "Ich möchte bleiben", "have_more_days_to_try": "Hol dir weitere <strong>__days__ Tage</strong> auf deiner Testversion!", "interested_in_cheaper_plan": "Hättest du Interesse an einem billigeren <strong>__price__</strong> Studentenplan?", "session_expired_redirecting_to_login": "Sitzung abgelaufen. Du wirst in __seconds__ Sekunden auf die Anmeldungsseite umgeleitet", "maximum_files_uploaded_together": "Maximal __max__ Dateien zusammen hochgeladen", "too_many_files_uploaded_throttled_short_period": "Zu viele Dateien hochgeladen, deine Uploads wurden für kurze Zeit gedrosselt.", "compile_larger_projects": "Größere Projekte kompilieren", "upgrade_to_get_feature": "Upgrade nötig, um __feature__ zu bekommen, sowie zusätzlich:", "new_group": "Neue Gruppe", "about_to_delete_groups": "Du bist dabei, die folgenden Gruppen zu löschen:", "removing": "Entfernen", "adding": "Hinzufügen", "groups": "Gruppen", "rename_group": "Gruppe umbennenen", "renaming": "Umbenennung", "create_group": "Gruppe erstellen", "delete_group": "Gruppe löschen", "delete_groups": "Gruppen löschen", "your_groups": "Deine Gruppen", "group_name": "Gruppenname", "no_groups": "Keine Gruppen", "Subscription": "Abonnement", "Documentation": "Dokumentation", "Universities": "Universitäten", "Account Settings": "Kontoeinstellungen", "Projects": "Projekte", "Account": "Konto", "global": "global", "Terms": "Nutzungsbedingungen", "Security": "Sicherheit", "About": "Über uns", "editor_disconected_click_to_reconnect": "Editor wurde getrennt; auf eine beliebige Stelle klicken, um die Verbindung wierderherzustellen.", "word_count": "Wortzahl", "please_compile_pdf_before_word_count": "Bitte kompiliere dein Projekt, bevor du eine Wortzählung durchführst.", "total_words": "Gesamtwortzahl", "headers": "Header", "math_inline": "Mathe-Inline", "math_display": "Mathe-Anzeige", "connected_users": "Verbundene Benutzer", "projects": "Projekte", "upload_project": "Projekt hochladen", "all_projects": "Alle Projekte", "your_projects": "Deine Projekte", "shared_with_you": "Mit dir geteilt", "deleted_projects": "Gelöschte Projekte", "templates": "Vorlagen", "new_folder": "Neuer Ordner", "create_your_first_project": "Erstelle dein erstes Projekt!", "complete": "Fertig", "on_free_sl": "Du benutzt die kostenlose Version von __appName__", "upgrade": "Upgrade", "or_unlock_features_bonus": "oder schalte kostenlose Bonus Features frei indem du", "sharing_sl": "__appName__ teilst", "add_to_folder": "Zu Ordner hinzufügen", "create_new_folder": "Neuen Ordner erstellen", "more": "Mehr", "rename": "Umbenennen", "make_copy": "Kopie erstellen", "restore": "Wiederherstellen", "title": "Titel", "last_modified": "Zuletzt bearbeitet", "no_projects": "Keine Projekte", "welcome_to_sl": "Willkommen bei __appName__!", "new_to_latex_look_at": "Neu bei LaTeX? Starte indem du einen Blick wirfst auf unser", "or": "oder", "or_create_project_left": "oder erstelle dein erstes Projekt auf der linken Seite.", "thanks_settings_updated": "Danke, deine Einstellungen wurden aktualisiert.", "update_account_info": "Kontoinformationen aktualisieren", "must_be_email_address": "Es muss eine E-Mail-Adresse sein!", "first_name": "Vorname", "last_name": "Nachname", "update": "Aktualisieren", "change_password": "Passwort ändern", "current_password": "Aktuelles Passwort", "new_password": "Neues Passwort", "confirm_new_password": "Bestätige das neue Passwort", "required": "Erforderlich", "doesnt_match": "Stimmt nicht überein", "dropbox_integration": "Dropbox-Integration", "learn_more": "Erfahre mehr", "dropbox_is_premium": "Dropbox-Synchronisation ist eine Premium-Funktion", "account_is_linked": "Account ist verknüpft", "unlink_dropbox": "Dropbox-Account trennen", "link_to_dropbox": "Dropbox-Account verknüpfen", "newsletter_info_and_unsubscribe": "Alle paar Monate verschicken wir einen Newsletter, der die neuen verfügbaren Features zusammenfasst. Wenn du diese E-Mail lieber nicht erhalten möchtest, kannst du sie jederzeit abbestellen:", "unsubscribed": "Abbestellt", "unsubscribing": "Abbestellen läuft", "unsubscribe": "Abbestellen", "need_to_leave": "Du musst gehen?", "delete_your_account": "Lösche deinen Account", "delete_account": "Account löschen", "delete_account_warning_message": "Sie sind dabei <strong>alle Account-Daten</strong> permanent zu löschen, inklusive Projekte und Einstellungen. Bitte geben Sie die E-Mail-Adresse Ihres Accounts in das Feld ein um fortzufahren.", "deleting": "Löschen", "delete": "Löschen", "sl_benefits_plans": "__appName__ ist der am einfachsten zu benutzende LaTeX-Editor der Welt. Bleibe auf dem neuesten Stand aller Änderungen deiner Projekte, und nutze unsere LaTeX-Umgebung von überall auf der Welt.", "monthly": "Monatlich", "personal": "Persönlich", "free": "Kostenlos", "one_collaborator": "Nur ein Mitarbeiter", "collaborator": "Mitarbeiter", "collabs_per_proj": "__collabcount__ Mitarbeiter pro Projekt", "full_doc_history": "Vollständiger Versionsverlauf", "sync_to_dropbox": "Synchronisierung mit Dropbox", "start_free_trial": "Starte einen kostenlosen Test!", "professional": "Professionell", "unlimited_collabs": "Unbeschränkt viele Mitarbeiter", "name": "Name", "student": "Student", "university": "Universität", "position": "Beruf", "choose_plan_works_for_you": "Wähle das Produkt, das zu dir passt, für deinen __len__-Tage-Testzeitraum. Kündigung ist jederzeit möglich.", "interested_in_group_licence": "Möchtest du __appName__ mit einem Gruppen-, einem Team- oder einem Konto für eine ganze Abteilung benutzen?", "get_in_touch_for_details": "Kontaktiere uns für Details!", "group_plan_enquiry": "Gruppen-Abo Anfrage", "enjoy_these_features": "Genieße all diese tollen Features", "create_unlimited_projects": "Erstelle so viele Projekte wie du willst.", "never_loose_work": "Verliere keine Änderung, wir speichern alles.", "access_projects_anywhere": "Greife von überall auf deine Projekte zu.", "log_in": "Anmelden", "login": "Anmelden", "logging_in": "Anmeldung", "forgot_your_password": "Passwort vergessen", "password_reset": "Passwort zurücksetzen", "password_reset_email_sent": "Dir wurde eine eMail gesendet, um dein Passwort zurückzusetzen.", "please_enter_email": "Bitte gib deine eMail-Adresse ein", "request_password_reset": "Forder die Zurücksetzung deines Passworts an", "reset_your_password": "Dein Passwort zurücksetzen", "password_has_been_reset": "Dein Passwort wurde zurückgesetzt", "login_here": "Hier anmelden", "set_new_password": "Neues Passwort eingeben", "user_wants_you_to_see_project": "__username__ möchte, dass Sie __projectname__ beitreten", "join_sl_to_view_project": "Registriere dich für __appName__, um dieses Projekt zu sehen", "register_to_edit_template": "Bitte registriere dich um die __templateName__ Vorlage zu bearbeiten", "already_have_sl_account": "Hast du bereits ein __appName__-Konto?", "register": "Registrieren", "password": "Passwort", "registering": "Registrieren", "planned_maintenance": "Geplante Wartungsarbeiten", "no_planned_maintenance": "Aktuell sind keine Wartungsarbeiten geplant", "cant_find_page": "Entschuldigung, wir können die Seite, die du suchst, nicht finden.", "take_me_home": "Bring mich nach Hause!", "no_preview_available": "Entschuldigung, es ist keine Vorschau verfügbar.", "no_messages": "Keine Nachrichten", "send_first_message": "Sende deine erste Nachricht", "account_not_linked_to_dropbox": "Dein Account ist nicht mit Dropbox verknüpft", "update_dropbox_settings": "Dropbox-Einstellungen aktualisieren", "refresh_page_after_starting_free_trial": "Bitte aktualisiere diese Seite, nachdem du deinen kostenlosen Test gestartet hast.", "checking_dropbox_status": "Dropbox-Status prüfen", "dismiss": "Ausblenden", "deleted_files": "Gelöschte Dateien", "new_file": "Neue Datei", "upload_file": "Datei hochladen", "create": "Erstellen", "creating": "Erstellung läuft", "upload_files": "Datei(en) hochladen", "sure_you_want_to_delete": "Möchtest du die folgenden Dateien wirklich löschen?", "common": "Häufige", "navigation": "Navigation", "editing": "Bearbeitung", "ok": "OK", "source": "Quelldateien", "actions": "Aktionen", "copy_project": "Projekt kopieren", "publish_as_template": "Als Vorlage veröffentlichen", "sync": "Sync", "settings": "Einstellungen", "main_document": "Hauptdokument", "off": "Aus", "auto_complete": "Auto-Vervollständigung", "theme": "Design", "font_size": "Schriftgröße", "pdf_viewer": "PDF-Betrachter", "built_in": "Eigener", "native": "nativ", "show_hotkeys": "Zeige Hotkeys", "new_name": "Neuer Name", "copying": "kopieren", "copy": "Kopieren", "compiling": "Kompilieren", "click_here_to_preview_pdf": "Hier klicken, um deine Arbeit als PDF anzuzeigen.", "server_error": "Serverfehler", "somthing_went_wrong_compiling": "Entschuldigung, es ist etwas schief gegangen und dein Projekt konnte nicht kompiliert werden. Versuche es in ein paar Minuten erneut.", "timedout": "Zeit abgelaufen", "proj_timed_out_reason": "Entschuldigung, deine Kompilation hat zu lange gedauert und das Zeitlimit wurde überschritten. Das könnte an einer großen Anzahl von hochauflösenden Bildern oder vielen komplizierten Diagrammen liegen.", "no_errors_good_job": "Keine Fehler, gute Arbeit!", "compile_error": "Fehler beim Kompilieren", "generic_failed_compile_message": "Sorry, dein LaTeX Code konnte aus irgendeinem Grund nicht kompiliert werden. Bitte überprüfe die unten genannten Fehler für Details oder schau dir die Konsolenausgabe an", "other_logs_and_files": "Andere Protokolle und Dateien", "view_raw_logs": "Zeige die Konsolenausgabe", "hide_raw_logs": "Logs ausblenden", "clear_cache": "Cache leeren", "clear_cache_explanation": "Hiermit werden alle versteckten LaTeX-Dateien (.aux, .bbl, usw.) von unserem Server gelöscht. Das musst du normalerweise nicht tun, außer, wenn es Probleme mit Referenzen gibt.", "clear_cache_is_safe": "Deine Projektdateien werden nicht gelöscht oder verändert.", "clearing": "Aufräumen", "template_description": "Vorlagenbeschreibung", "project_last_published_at": "Dein Projekt wurde zuletzt veröffentlicht am", "problem_talking_to_publishing_service": "Es gibt ein Problem mit unserem Veröffentlichungsservice. Bitte versuche es in einigen Minuten noch einmal", "unpublishing": "Veröffentlichung aufheben", "republish": "Erneut veröffentlichen", "publishing": "Veröffentlichen", "share_project": "Projekt teilen", "this_project_is_private": "Dieses Projekt ist privat und nur die unten genannten Personen können darauf zugreifen.", "make_public": "Öffentlich machen", "this_project_is_public": "Dieses Projekt ist öffentlich und kann von jedem bearbeitet werden, der die URL dazu hat.", "make_private": "Privat machen", "can_edit": "Kann bearbeiten", "share_with_your_collabs": "Mit deinen Mitarbeitern teilen", "share": "Teilen", "need_to_upgrade_for_more_collabs": "Du musst dein Konto upgraden um mehr Mitarbeiter hinzuzufügen", "make_project_public": "Projekt öffentlich machen", "make_project_public_consequences": "Wenn du dein Projekt öffentlich machst kann jeder mit der URL darauf zugreifen.", "allow_public_editing": "Erlaube öffentliches Bearbeiten", "allow_public_read_only": "Erlaube nur den öffentlichen Lesezugriff", "make_project_private": "Projekt privat machen", "make_project_private_consequences": "Wenn du das Projekt privat machst können nur die Personen, mit denen du es teilen möchtest, darauf zugreifen.", "need_to_upgrade_for_history": "Du musst dein Konto upgraden, um den Dateiversionsverlauf zu verwenden.", "ask_proj_owner_to_upgrade_for_history": "Bitte den Projekt-Besitzer upzugraden, um den Dateiversionsverlauf zu verwenden.", "anonymous": "Anonym", "generic_something_went_wrong": "Sorry, irgendetwas ist schief gelaufen", "restoring": "Wiederherstellen", "restore_to_before_these_changes": "Auf den Stand vor diesen Veränderungen wiederherstellen", "profile_complete_percentage": "Dein Profil ist zu __percentval__% vollständig.", "file_has_been_deleted": "__filename__ wurde gelöscht.", "sure_you_want_to_restore_before": "Bist du sicher, dass du <0>__filename__</0> auf den Stand vor den Veränderungen am __date__ wiederherstellen möchtest?", "rename_project": "Projekt umbenennen", "about_to_delete_projects": "Du bist kurz davor folgende Projekte zu löschen:", "about_to_leave_projects": "Du bist kurz davor folgende Projekte zu verlassen:", "upload_zipped_project": "Projekt als ZIP hochladen", "upload_a_zipped_project": "Projekt als ZIP hochladen", "your_profile": "Dein Profil", "institution": "Institution", "role": "Funktion", "folders": "Ordner", "disconnected": "Nicht verbunden", "please_refresh": "Bitte aktualisiere die Seite, um fortzufahren", "lost_connection": "Verbindung verloren", "reconnecting_in_x_secs": "Erneut verbinden in __seconds__ Sekunden", "try_now": "Jetzt versuchen", "reconnecting": "Neu verbinden", "saving_notification_with_seconds": "__docname__ speichern... (__seconds__ Sekunden ungespeicherter Änderungen)", "help_us_spread_word": "Hilf uns, __appName__ zu verbreiten", "share_sl_to_get_rewards": "Teile __appName__ mit deinen Freunden und Kollegen, um die Belohnungen unten freizuschalten.", "post_on_facebook": "Auf Facebook posten", "share_us_on_googleplus": "Auf Google+ teilen", "email_us_to_your_friends": "Per E-Mail an deine Freunde schicken", "link_to_us": "Von deiner Website verlinken", "direct_link": "Direkter Link", "sl_gives_you_free_stuff_see_progress_below": "Wenn jemand nach deiner Empfehlung beginnt, __appName__ zu nutzen, geben wir dir <strong>kostenlose Funktionen</strong>, um Danke zu sagen! Überprüfe deinen Fortschritt unten.", "spread_the_word_and_fill_bar": "Sag es weiter und fülle diesen Balken", "one_free_collab": "Ein kostenloser Mitarbeiter", "three_free_collab": "Drei kostenlose Mitarbeiter", "free_dropbox_and_history": "Kostenloser Dropbox und Dateiversionsverlauf", "you_not_introed_anyone_to_sl": "Du hast noch niemanden zu __appName__ eingeladen. Beginne zu teilen!", "you_introed_small_number": "Du hast bereits <0>__numberOfPeople__</0> Person zu __appName__ eingeladen. Gut gemacht!, aber schaffst du noch mehr?", "you_introed_high_number": "Du hast bereits <0>__numberOfPeople__</0> Personen zu __appName__ eingeladen. Super!", "link_to_sl": "Link zu __appName__", "can_link_to_sl_with_html": "Du kannst mit dem folgenden HTML-Code zu __appName__ verlinken:", "year": "Jahr", "month": "Monat", "subscribe_to_this_plan": "Dieses Produkt abonnieren.", "your_plan": "Dein Abo", "your_subscription": "Dein Abonnement", "on_free_trial_expiring_at": "Du verwendest im Moment eine kostenlose Testversion, die am __expiresAt__ ausläuft.", "choose_a_plan_below": "Wähle unten ein Produkt das du abonnieren möchtest.", "currently_subscribed_to_plan": "Du hast im Moment das <0>__planName__</0> Produkt abonniert.", "change_plan": "Abonnement ändern", "next_payment_of_x_collectected_on_y": "Die nächste Zahlung von <0>__paymentAmmount__</0> wird am <1>__collectionDate__</1> abgebucht.", "update_your_billing_details": "Deine Zahlungsinformationen aktualisieren", "subscription_canceled_and_terminate_on_x": " Dein Abonnement wurde gekündigt und wird am <0>__terminateDate__</0> enden. Keine weiteren Zahlungen werden angenommen.", "your_subscription_has_expired": "Dein Abonnement ist abgelaufen.", "create_new_subscription": "Neues Abonnement erstellen", "problem_with_subscription_contact_us": "Es gibt ein Problem mit deinem Abonnement. Bitte kontaktiere uns für mehr Informationen.", "manage_group": "Gruppe verwalten", "loading_billing_form": "Lade Zahlungsdetails von", "you_have_added_x_of_group_size_y": "Du hast <0>__addedUsersSize__</0> von <1>__groupSize__</1> verfügbaren Mitgliedern hinzugefügt", "remove_from_group": "Aus der Gruppe entfernen", "group_account": "Gruppenaccount", "registered": "Registriert", "no_members": "Keine Mitglieder", "add_more_members": "Mehr Mitglieder hinzufügen", "add": "Hinzufügen", "thanks_for_subscribing": "Danke fürs Abbonieren!", "your_card_will_be_charged_soon": "Deine Karte wird bald belastet.", "if_you_dont_want_to_be_charged": "Wenn du nicht mehr bezahlen möchtest ", "add_your_first_group_member_now": "Füge jetzt dein erstes Gruppenmitglied hinzu", "thanks_for_subscribing_you_help_sl": "Danke, dass du den __planName__-Plant abboniert hast. Die Unterstützung von Menschen wie dir macht es __appName__ möglich, zu wachsen und besser zu werden.", "back_to_your_projects": "Zurück zu deinen Projekten", "goes_straight_to_our_inboxes": "Es landet direkt in unserem Posteingang.", "need_anything_contact_us_at": "Wenn du irgendetwas benötigst, kannst du uns gern direkt kontaktieren über", "regards": "Viele Grüße", "about": "Über uns", "comment": "Kommentar", "restricted_no_permission": "Entschuldigung, du hast nicht die Berechtigung, diese Seite anzuzeigen.", "online_latex_editor": "Online-LaTeX-Editor", "meet_team_behind_latex_editor": "Lerne das Team hinter deinem Lieblings-LaTeX-Editor kennen.", "follow_me_on_twitter": "Folge mir auf Twitter", "motivation": "Motivation", "evolved": "Revolutioniert", "the_easy_online_collab_latex_editor": "Der einfach zu nutzende, kollaborative, Online-LaTeX-Editor", "get_started_now": "Fange jetzt an", "sl_used_over_x_people_at": "__appName__ wird von über __numberOfUsers__ Studenten und Professoren genutzt in:", "collaboration": "Zusammenarbeit", "work_on_single_version": "Arbeitet zusammen an einer einzigen Version", "view_collab_edits": "Zeige Änderungen aller Mitarbeiter an ", "ease_of_use": " Einfacher Gebrauch", "no_complicated_latex_install": "Keine komplizierte LaTeX-Installation", "all_packages_and_templates": "Alle Pakete und <0>__templatesLink__</0>, die du brauchst", "document_history": "Änderungsverlauf", "see_what_has_been": "Schau nach, was ", "added": "hinzugefügt", "and": "und", "removed": "gelöscht", "restore_to_any_older_version": "Stelle beliebige ältere Versionen wieder her", "work_from_anywhere": "Arbeite von überall", "acces_work_from_anywhere": "Greife auf deine Arbeit von überall auf der Welt zu", "work_offline_and_sync_with_dropbox": "Arbeite offline und synchronisiere deine Dateien über Dropbox oder GitHub", "over": "über", "view_templates": "Vorlagen anzeigen", "nothing_to_install_ready_to_go": "Du musst keine komplizierte Software installieren und du kannst <0>__start_now__</0>, auch wenn du es noch nie zuvor gesehen hast. __appName__ verfügt über eine komplette, vorbereitete LaTeX-Umgebung, die auf unseren Servern läuft.", "start_using_latex_now": "jetzt anfangen, LaTeX zu benutzen", "get_same_latex_setup": "Mit __appName__ bekommst du die gleiche LaTeX-Umgebung, wo auch immer du bist. Wenn du mit deinen Kollegen und Schülern auf __appName__ arbeitest, kannst du davon ausgehen, dass es keine Versionsinkonsistenzen oder Paketkonflikte gibt.", "support_lots_of_features": "Wir unterstützen fast alle Funktionen von LaTeX, zum Beispiel das Einfügen von Bildern, Literaturverzeichnissen, Gleichungen und vielem mehr! In unseren <0>__help_guides_link__</0> kannst du nachlesen, was du alles aufregendes in __appName__ machen kannst.", "latex_guides": "LaTeX-Anleitungen", "reset_password": "Passwort zurücksetzen", "set_password": "Passwort setzen", "updating_site": "Aktualisiere die Seite", "bonus_please_recommend_us": "Bonus - Bitte empfehle uns weiter", "admin": "Admin", "subscribe": "Abonnieren", "update_billing_details": "Zahlungsinformationen aktualisieren", "group_admin": "Gruppenadministrator", "all_templates": "Alle Vorlagen", "your_settings": "Deine Einstellungen", "maintenance": "Wartungsarbeiten", "to_many_login_requests_2_mins": "In dieses Konto wurde sich zu häufig eingeloggt. Bitte warte 2 Minuten, bevor du es noch einmal versuchst.", "email_or_password_wrong_try_again": "Deine E-Mail-Adresse oder Passwort waren falsch. Bitte versuche es erneut.", "rate_limit_hit_wait": "Beschränkung erreicht. Bitte warte ein bisschen, bevor du es noch einmal versuchst.", "problem_changing_email_address": "Es gab ein Problem beim Ändern deiner E-Mail-Adresse. Bitte versuche es in ein paar Minuten erneut. Wenn das Problem bestehen bleibt, kontaktiere uns bitte.", "single_version_easy_collab_blurb": "__appName__ sorgt dafür, dass du immer weißt, was deine Mitarbeiter tun. Es gibt nur eine einzige Version jedes Dokumentes, zu der alle Zugriff haben. Es ist unmöglich, mit einer Änderung einen Konflikt hervorzurufen, und du musst nicht auf deine Kollegen warten, dass sie dir den neuesten Entwurf schicken, bevor du weiterarbeiten kannst.", "can_see_collabs_type_blurb": "Wenn mehrere Menschen am gleichen Dokument gleichzeitig arbeiten möchten, ist das kein Problem. Du kannst direkt im Editor sehen, wo deine Kollegen schreiben und ihre Änderungen werden sofort angezeigt.", "work_directly_with_collabs": "Arbeite direkt mit deinen Mitarbeitern.", "work_with_word_users": "Arbeite mit Word-Benutzern", "work_with_word_users_blurb": "__appName__ ist so einfach zu lernen, dass du auch Kollegen, die sich mit LaTeX nicht auskennen, einladen kannst, um direkt zu deinen LaTeX-Dokumenten beizutragen. Sie werden vom ersten Tag an produktiv sein und können schnell etwas LaTeX aufschnappen, während sie arbeiten.", "view_which_changes": "Schau, was", "sl_included_history_of_changes_blurb": "__appName__ zeigt einen Verlauf all deiner Änderungen an, sodass du direkt sehen kannst, wer was wann geändert hat. Das macht es sehr leicht, auf dem neuesten Stand mit dem Fortschritt deiner Mitarbeiter zu bleiben und erlaubt es dir, die neuesten Änderungen zu überprüfen.", "can_revert_back_blurb": "Egal ob gemeinschaftlich oder allein, manchmal macht man Fehler. Es ist aber einfach, zu vorherigen Versionen zurück zu gehen und es gibt kein Risiko, Arbeit zu verlieren oder eine Änderung später zu bereuen.", "start_using_sl_now": "Fange jetzt an, __appName__ zu benutzen.", "over_x_templates_easy_getting_started": "Es gibt __over__ 400 __templates__ in unserer Vorlagengalerie, also ist es sehr leicht, loszulegen. Egal, ob du einen Zeitschriftenartikel, eine Doktorarbeit, einen Lebenslauf oder etwas anderes schreibst.", "done": "Fertig", "change": "Änderung", "page_not_found": "Seite nicht gefunden", "please_see_help_for_more_info": "Bitte schau in unserer Hilfe für mehr Informationen nach", "this_project_will_appear_in_your_dropbox_folder_at": "Diese Projekt wird in deiner Dropbox in folgendem Ordner erscheinen: ", "member_of_group_subscription": "Du bist Mitglied eines Gruppenabonnements, das von __admin_email__ verwaltet wird. Bitte kontaktiere diese Person, um dein Abonnement zu verwalten.\n", "about_henry_oswald": "ist ein Softwareentwickler, der in London lebt. Er hat den ersten Prototyp von __appName__ gebaut und war dafür verantwortlich, eine stabile und skalierbare Plattform zu erstellen. Henry ist ein Verfechter von testgetriebenem Programmieren und achtet darauf, dass wir den __appName__-Code sauber und wartbar halten.", "about_james_allen": "hat einen PhD in theoretischer Physik und eine Leidenschaft für LaTeX. Er erstellte einen der ersten Online-LaTeX-Editoren, ScribTeX, und hat eine große Rolle bei der Entwicklung der Technologien gespielt, die __appName__ möglich macht.", "two_strong_principles_behind_sl": "Es gibt zwei wichtige Prinzipien hinter unserer Arbeit an __appName__:", "want_to_improve_workflow_of_as_many_people_as_possible": "Wir wollen die Arbeit von möglichst vielen Menschen erleichtern.", "detail_on_improve_peoples_workflow": "LaTeX ist bekannt dafür, kompliziert zu sein, und Zusammenarbeit ist immer schwierig zu koordinieren. Wir denken, dass wir ein paar großartige Lösungen für Menschen, denen diese Probleme begegnen, entwickelt haben und möchten sichergehen, dass __appName__ für so viele Menschen wie möglich zugänglich ist. Wir haben versucht, unsere Preise fair zu machen und haben einen Großteil von __appName__ Open Source gemacht, sodass jeder seine eigene Version hosten kann.", "want_to_create_sustainable_lasting_legacy": "Wir möchten ein nachhaltiges und dauerhaftes Erbe schaffen.", "details_on_legacy": "Entwicklung und Pflege eines Produkts wie __appName__ braucht viel Zeit und Arbeit, also ist es wichtig, dass wir ein Geschäftsmodell können, die dies jetzt beide unterstützen wird, und auf lange Sicht. Wir möchten nicht, dass __appName__ abhängig von einer externen Finanzierung ist oder wegen eines gescheiterten Geschäftsmodells verschwindet. Ich freue mich mitzuteilen, dass wir __appName__ aktuell profitabel und nachhaltig betreiben und dass wir planen dies auch in der Zukunft zu schaffen.", "get_in_touch": "Kontaktiere uns", "want_to_hear_from_you_email_us_at": "Wir freuen uns immer, wenn uns Leute schreiben, die __appName__ nutzen oder sich über das, was wir tun, mit uns unterhalten möchten. Du kannst uns kontaktieren unter", "cant_find_email": "Diese E-Mail-Adresse ist leider nicht registriert.", "plans_amper_pricing": "Produkte und Preise", "documentation": "Dokumentation", "account": "Account", "subscription": "Abonnement", "log_out": "Abmelden", "en": "Englisch", "pt": "Portugiesisch", "es": "Spanisch", "fr": "Französisch", "de": "Deutsch", "it": "Italienisch", "da": "Dänisch", "sv": "Schwedisch", "no": "Norwegisch", "nl": "Niederländisch", "pl": "Polnisch", "ru": "Russisch", "uk": "Ukrainisch", "ro": "Rumänisch", "click_here_to_view_sl_in_lng": "Klicke hier, um __appName__ in <0>__lngName__</0> zu nutzen", "language": "Sprache", "upload": "Upload", "menu": "Menü", "full_screen": "Vollbild", "logs_and_output_files": "Logs und Ausgabedateien", "download_pdf": "PDF herunterladen", "split_screen": "Splitscreen", "clear_cached_files": "Zwischengespeicherte Dateien löschen", "go_to_code_location_in_pdf": "Gehe zur Position im PDF", "please_compile_pdf_before_download": "Bitte kompiliere dein Projekt, bevor du das PDF herunterlädst", "remove_collaborator": "Mitarbeiter entfernen", "add_to_folders": "Zu Ordnern hinzufügen", "download_zip_file": ".zip-Datei herunterladen", "price": "Preis", "close": "Schließen", "keybindings": "Tastenkombinationen", "restricted": "Geschützt", "start_x_day_trial": "Beginne heute mit der kostenlosen Testversion für __len__ Tage!", "buy_now": "Jetzt kaufen!", "cs": "Tschechisch", "view_all": "Alle anzeigen", "terms": "AGB", "privacy": "Datenschutz", "contact": "Kontakt", "change_to_this_plan": "Auf dieses Abonnement wechseln", "processing": "in Bearbeitung", "sure_you_want_to_change_plan": "Bist du sicher, dass du zum Abonnement <0>__planName__</0> wechseln möchtest?", "move_to_annual_billing": "Zur jährlichen Abrechnung wechseln", "annual_billing_enabled": "Jährliche Abrechnung aktiviert", "move_to_annual_billing_now": "Jetzt zu jährlicher Abrechnung wechseln", "change_to_annual_billing_and_save": "Spare <0>__percentage__</0> durch jährliche Abrechnung. Wenn du jetzt wechselst, sparst du <1>__yearlySaving__</1> pro Jahr.", "missing_template_question": "Fehlende Vorlage?", "tell_us_about_the_template": "Wenn eine Vorlage fehlt, schicke uns entweder eine Kopie der Vorlage, eine __appName__-URL zur Vorlage oder sag uns, wo wir die Vorlage finden können. Gib uns auch ein paar Informationen für die Beschreibung der Vorlage.", "email_us": "Schreibe uns eine E-Mail", "this_project_is_public_read_only": "Dieses Projekt ist öffentlich und kann von jedem, der die URL kennt, angesehen, aber nicht bearbeitet werden.", "tr": "Türkisch", "select_files": "Datei(en) auswählen", "drag_files": "datei(en) ziehen", "upload_failed_sorry": "Hochladen fehlgeschlagen, sorry :(", "inserting_files": "Datei wird eingefügt...", "password_reset_token_expired": "Dein Passwortzurücksetztoken ist nicht mehr gültig. Bitte fordere ein neues Passwortresetmail an und folge dem Link im Mail.", "merge_project_with_github": "Projekt mit GitHub mergen", "pull_github_changes_into_sharelatex": "GitHub-Änderungen nach __appName__ ziehen", "push_sharelatex_changes_to_github": "__appName__-Änderungen in GitHub drücken", "features": "Features", "commit": "Commit", "commiting": "am Commiten", "importing_and_merging_changes_in_github": "Änderungen werden in GitHub importiert und gemerged.", "upgrade_for_faster_compiles": "Upgrade für schnelleres Kompilieren und eine längere Timeoutlimite.", "free_accounts_have_timeout_upgrade_to_increase": "Kostenlose Benutzerkontos haben einen Timeout von einer Minute. Upgrade um deine Timeoutlimite zu erhöhen", "learn_how_to_make_documents_compile_quickly": "Erfahre wie du dein Dokument schneller kompilieren lassen kannst.", "zh-CN": "Chinesisch", "cn": "Chinesisch (vereinfacht)", "sync_to_github": "Mit GitHub synchronisieren", "sync_to_dropbox_and_github": "Mit Dropbox und Github synchronisieren", "project_too_large": "Projekt ist zu gross", "project_too_large_please_reduce": "Dieses Projekt hat zu viel editierbaren Text, bitte versuchen Sie ihn zu reduzieren. Die größten Dateien sind:", "please_ask_the_project_owner_to_link_to_github": "Bitte den Projektinhaber dieses Projekt mit GitHub zu verlinken", "go_to_pdf_location_in_code": "Gehe an den Ort des PDF im Code", "ko": "Koreanisch", "ja": "Japanisch", "about_brian_gough": "ist ein Softwareentwickler und früher ein theoritscher Starkstromphysiker in den Fermilab in Los Alamos. Über viele Jahre hinweg hat er Anleitungen für freie Software für deren Erstellung er TeX und LaTeX kommerziell einsetze. Er war auch ein Maintainer der GNU Scientific Library.", "first_few_days_free": "Erste __trialLen__ Tage sind gratis", "every": "pro", "credit_card": "Kreditkarte", "credit_card_number": "Kreditkartennummer", "invalid": "Ungültig", "expiry": "Ablaufdatum", "january": "Januar", "february": "Februar", "march": "März", "april": "April", "may": "Mai", "june": "Juni", "july": "Juli", "august": "August", "september": "September", "october": "Oktober", "november": "November", "december": "Dezember", "zip_post_code": "PLZ / Postleitzahl", "city": "Stadt", "address": "Adresse", "coupon_code": "Gutscheincode", "country": "Land", "billing_address": "Rechnungsadresse ", "upgrade_now": "Jetzt aktualisieren", "state": "Status", "vat_number": "Umsatzsteuernummer", "you_have_joined": "Du bist __groupName__ beigetreten", "claim_premium_account": "Du hast das von __groupName__ zur Verfügung gestellte Premium-Konto in anspruch genommen.", "you_are_invited_to_group": "Du wurdest eingeladen, __groupName__ beizutreten", "you_can_claim_premium_account": "Du kannst ein von __groupName__ zur Verfügung gestelltes Premium-Konto in Anspruch nehmen, indem du deine E-Mail-Adresse verifizierst.", "not_now": "Nicht jetzt", "verify_email_join_group": "E-Mail-Adresse verifizieren und Gruppe beitreten", "check_email_to_complete_group": "Bitte überprüfe deine E-Mails und vervollständige deinen Gruppeneintritt.", "verify_email_address": "E-Mail-Adresse verifizieren", "group_provides_you_with_premium_account": "__groupName__ bietet dir ein Premium-Konto. Verifiziere deine E-Mail-Adresse, um dein Konto-Upgrade durchführen zu können.", "check_email_to_complete_the_upgrade": "Bitte überprüfe deine E-Mails, um das Upgrade zu vervollständigen.", "email_link_expired": "E-Mail-Link ist abgelaufen, bitte fordere einen neuen an.", "services": "Services", "about_shane_kilkelly": "ist ein Softwareentwickler, der in Edinburgh lebt. Shane ist ein starker Befürworter funktionaler Programmierung und testbasierender Entwicklung und ist stolz auf die qualitativ hochwertige Software, die er baut.", "this_is_your_template": "Dies ist eine Vorlage aus deinem Projekt.", "links": "Links", "account_settings": "Kontoeinstellungen", "search_projects": "Projekte suchen", "clone_project": "Projekt duplizieren", "delete_project": "Projekt löschen", "download_zip": "ZIP herunterladen", "new_project": "Neues Projekt", "blank_project": "Leeres Projekt", "example_project": "Beispielprojekt", "from_template": "Aus Vorlage", "cv_or_resume": "Lebenslauf", "cover_letter": "Bewerbungsschreiben", "journal_article": "Zeitschriftenartikel", "presentation": "Präsentation", "thesis": "Doktorarbeit", "bibliographies": "Literaturverzeichnisse", "terms_of_service": "Allgemeine Geschäftsbedingungen", "privacy_policy": "Datenschutz", "plans_and_pricing": "Produkte und Preise", "university_licences": "Universitätslizenzen", "security": "Sicherheit", "contact_us": "Kontaktiere uns", "thanks": "Danke", "blog": "Blog", "latex_editor": "LaTeX-Editor", "get_free_stuff": "Verdiene dir Premiumfunktionen", "chat": "Chat", "your_message": "Deine Nachricht", "loading": "Laden", "connecting": "Verbinden", "recompile": "Aktualisieren", "download": "Herunterladen", "email": "E-Mail", "owner": "Besitzer", "read_and_write": "Lesen und Schreiben", "read_only": "nur Lesen", "publish": "Veröffentlichen", "view_in_template_gallery": "In der Vorlagengalerie anzeigen", "description": "Beschreibung", "unpublish": "Veröffentlichung aufheben", "hotkeys": "Hotkeys", "saving": "Speichern", "cancel": "Abbrechen", "project_name": "Projektname", "root_document": "Hauptdokument", "spell_check": "Rechtschreibprüfung", "compiler": "Compiler", "private": "Privat", "public": "Öffentlich", "delete_forever": "unwiderruflich löschen", "support_and_feedback": "Support und Feedback", "help": "Hilfe", "latex_templates": "LaTeX Vorlagen", "info": "Info", "latex_help_guide": "LaTeX-Anleitung", "choose_your_plan": "Wähle deinen Account-Typ", "indvidual_plans": "Einzelbenutzerabos", "free_forever": "Für immer kostenlos", "low_priority_compile": "Kompilierung mit niedriger Priorität", "unlimited_projects": "Unbegrenzte Projekte", "unlimited_compiles": "Unbegrenzte Compiles", "full_history_of_changes": "Gesamter Änderungsverlauf", "highest_priority_compiling": "Kompilierung mit höchster Priorität", "dropbox_sync": "Dropbox-Synchronisation", "beta": "Beta", "sign_up_now": "Jetzt registrieren", "annual": "Jährlich", "half_price_student": "Studenten-Tarif zum halben Preis", "about_us": "Über uns", "loading_recent_github_commits": "Neueste Commits weren geladen", "no_new_commits_in_github": "Es gibt bei GitHub keine neuen Commits seit dem letzten Merge", "dropbox_sync_description": "Behalte deine __appName__-Projekte synchron mit deiner Dropbox. Änderungen in __appName__ werden automatisch an deine Dropbox gesendet und umgekehrt.", "github_sync_description": "Mit GitHub Synchronisierung kannst du deine __appName__-Projekte mit GitHub-Repositories verlinken. Erstelle neue Commits aus __appName__ und führe sie mit offline oder in GitHub gemachten Commits zusammen.", "github_import_description": "Mit GitHub-Synchronisierung kannst du deine GitHub-Repositories in __appName__ importieren. Erstelle neue Commits aus __appName__ und führe sie mit offline oder in GitHub gemachten Commits zusammen.", "link_to_github_description": "Du musst __appName__ erlauben, auf dein GitHub-Benutzerkonto zuzugreifen und deine Projekte zu synchronisieren.", "unlink": "Link löschen", "unlink_github_warning": "Bei allen Projekten, die mit GitHub synchronisiert sind, wird die Verlinkung entfernt und nicht länger mit GitHub synchronisiert. Bist du sicher, dass du die Verbindung zu deinem GitHub-Benutzerkonto lösen möchtest?", "github_account_successfully_linked": "Das GitHub-Benutzerkonto wurde erfolgreich verbunden!", "github_successfully_linked_description": "Danke, wir haben dein GitHub-Benutzerkonto erfolgreich mit __appName__ verknüpft. Du kannst die __appName__-Projekte jetzt in GitHub exportieren oder Projekte aus deinen GitHub-Repositories importieren.", "import_from_github": "Von GitHub importieren", "github_sync_error": "Entschuldigung, es gab ein Problem bei der Kommunikation mit unserem GitHub-Dienst. Bitte versuche es später erneut.", "loading_github_repositories": "Deine GitHub-Repositories werden geladen", "select_github_repository": "Wähle ein GitHub-Repository, das du in __appName__ importieren möchtest.", "import_to_sharelatex": "In __appName__ importieren", "importing": "Importieren", "github_sync": "GitHuB Synchronisierung", "checking_project_github_status": "Status auf GitHub abfragen", "account_not_linked_to_github": "Dein Account ist nicht mit GitHub verlinkt", "project_not_linked_to_github": "Dieses Projekt ist nicht mit einem GitHub Repository verlinkt. Sie können ein neues Repository in GitHub erstellen:", "create_project_in_github": "Ein GitHub Repository erstellen", "project_synced_with_git_repo_at": "Das Projekt ist mit dem GitHub Repository verlinkt", "recent_commits_in_github": "Neueste Commits auf GitHub", "sync_project_to_github": "Projekt mit GitHub synchronisieren", "sync_project_to_github_explanation": "Alle Änderungen die du in __appName__ vornimmst werden in GitHub festgelegt und mit allen Updates in GitHub zusammengeführt.", "github_merge_failed": "Deine Änderungen in __appName__ und GitHub konnten nicht automatisch zusammengeführt werden. Bitte führe den <0>__sharelatex_branch__</0> mit dem <1>__master_branch__</1> Branch in Git zusammen. Klicke unten um fortzufahren, nachdem du manuell zusammengeführt hast.", "continue_github_merge": "Ich habe es von Hand gemerded, fortsetzen", "export_project_to_github": "Projekt nach GitHub exportieren", "github_validation_check": "Bitte prüfe ob der Repositorynome gültig ist und ob du die Rechte hast ein Gitrepository zu erstellen. ", "repository_name": "Repository Name", "optional": "Freiwillig", "github_public_description": "Jeder kann dieses Repository sehen. Du entscheidest wer commiten darf.", "github_commit_message_placeholder": "Commit-Meldung für Änderungen die in __appName__ gemacht wurden", "merge": "Mergen", "merging": "Mergen", "github_account_is_linked": "Dein GitHub-Benutzerkonto wurde erfolgreich verbunden", "unlink_github": "Löse die Verbindung deines GitHub-Benutzerkontos", "link_to_github": "Verbinde mit deinem GitHub-Benutzerkonto", "github_integration": "GitHub Einbindung", "github_is_premium": "GitHub syns ist eine Premiumfunktion", "thank_you": "Vielen Dank" }
overleaf/web/locales/de.json/0
{ "file_path": "overleaf/web/locales/de.json", "repo_id": "overleaf", "token_count": 21598 }
538
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.migrations, [ { key: { name: 1 }, unique: true, }, ]) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.migrations, [{ name: 1 }]) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190720165251_create_migrations.js/0
{ "file_path": "overleaf/web/migrations/20190720165251_create_migrations.js", "repo_id": "overleaf", "token_count": 211 }
539
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['saas'] const indexes = [ { unique: true, key: { accessToken: 1, }, name: 'accessToken_1', }, { unique: true, key: { refreshToken: 1, }, name: 'refreshToken_1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.oauthAccessTokens, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.oauthAccessTokens, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145015_create_oauthAccessTokens_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145015_create_oauthAccessTokens_indexes.js", "repo_id": "overleaf", "token_count": 270 }
540
/* eslint-disable no-unused-vars */ const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const indexes = [ { unique: true, key: { token: 1, use: 1, }, name: 'token_1_use_1', }, ] exports.migrate = async client => { const { db } = client await Helpers.addIndexesToCollection(db.tokens, indexes) } exports.rollback = async client => { const { db } = client try { await Helpers.dropIndexesFromCollection(db.tokens, indexes) } catch (err) { console.error('Something went wrong rolling back the migrations', err) } }
overleaf/web/migrations/20190912145031_create_tokens_indexes.js/0
{ "file_path": "overleaf/web/migrations/20190912145031_create_tokens_indexes.js", "repo_id": "overleaf", "token_count": 240 }
541
const Helpers = require('./lib/helpers') exports.tags = ['server-ce', 'server-pro', 'saas'] const indexes = { tokens: [ { // expire all tokens 90 days after they are created expireAfterSeconds: 90 * 24 * 60 * 60, key: { createdAt: 1, }, name: 'createdAt_1', }, ], } exports.migrate = async client => { const { db } = client await Promise.all( Object.keys(indexes).map(key => Helpers.addIndexesToCollection(db[key], indexes[key]) ) ) } exports.rollback = async client => { const { db } = client await Promise.all( Object.keys(indexes).map(key => Helpers.dropIndexesFromCollection(db[key], indexes[key]) ) ) }
overleaf/web/migrations/20210407085118_token-expiry-with-ttl-index.js/0
{ "file_path": "overleaf/web/migrations/20210407085118_token-expiry-with-ttl-index.js", "repo_id": "overleaf", "token_count": 289 }
542
/* eslint-disable no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. let Launchpad const LaunchpadRouter = require('./app/src/LaunchpadRouter') module.exports = Launchpad = { router: LaunchpadRouter }
overleaf/web/modules/launchpad/index.js/0
{ "file_path": "overleaf/web/modules/launchpad/index.js", "repo_id": "overleaf", "token_count": 92 }
543
const logger = require('logger-sharelatex') const UserActivateController = require('./UserActivateController') const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController') module.exports = { apply(webRouter) { logger.log({}, 'Init UserActivate router') webRouter.get('/user/activate', UserActivateController.activateAccountPage) AuthenticationController.addEndpointToLoginWhitelist('/user/activate') }, }
overleaf/web/modules/user-activate/app/src/UserActivateRouter.js/0
{ "file_path": "overleaf/web/modules/user-activate/app/src/UserActivateRouter.js", "repo_id": "overleaf", "token_count": 135 }
544
const Adapter = require('../migrations/lib/adapter') const fs = require('fs').promises const path = require('path') async function main(args) { if ( !args || args.length === 0 || args.includes('help') || args.includes('--help') || args.includes('-h') ) { console.log('') console.log('usage: node ./scripts/mark_migration.js migration state') console.log('') console.log(' migration: name of migration file') console.log(' state: executed | unexecuted') console.log('') return } const migration = args[0] if (!migration) { throw new Error('Error: migration must be supplied') } const state = args[1] if (!state) { throw new Error('Error: migration state must be supplied') } try { await fs.access(path.join(__dirname, '../migrations', `${migration}.js`)) } catch (err) { throw new Error( `Error: migration ${migration} does not exist on disk: ${err}` ) } console.log(`Marking ${migration} as ${state}`) process.env.SKIP_TAG_CHECK = 'true' const adapter = new Adapter() await adapter.connect() switch (state) { case 'executed': await adapter.markExecuted(migration) break case 'unexecuted': await adapter.unmarkExecuted(migration) break default: throw new Error(`invalid state "${state}"`) } console.log('Done') } if (require.main === module) { const args = process.argv.slice(2) main(args) .then(() => { process.exit(0) }) .catch(err => { console.error(err) process.exit(1) }) }
overleaf/web/scripts/mark_migration.js/0
{ "file_path": "overleaf/web/scripts/mark_migration.js", "repo_id": "overleaf", "token_count": 623 }
545
const { promises: fs } = require('fs') const oneSky = require('@brainly/onesky-utils') const sanitizeHtml = require('sanitize-html') const { withAuth } = require('./config') async function run() { try { // The recommended OneSky set-up appears to require an API request to // generate files on their side, which you could then request and use. We // only have 1 such file that appears to be misnamed (en-US, despite our // translations being marked as GB) and very out-of-date. // However by requesting the "multilingual file" for this file, we get all // of the translations const content = await oneSky.getMultilingualFile( withAuth({ fileName: 'en-US.json', }) ) const json = JSON.parse(content) for (const [code, lang] of Object.entries(json)) { if (code === 'en-GB') { // OneSky does not have read-after-write consistency. // Skip the dump of English locales, which may not include locales // that were just uploaded. continue } for (let [key, value] of Object.entries(lang.translation)) { // Handle multi-line strings as arrays by joining on newline if (Array.isArray(value)) { value = value.join('\n') } lang.translation[key] = sanitize(value) } await fs.writeFile( `${__dirname}/../../locales/${code}.json`, JSON.stringify(lang.translation, null, 2) + '\n' ) } } catch (error) { console.error(error) process.exit(1) } } run() /** * Sanitize a translation string to prevent injection attacks * * @param {string} input * @returns {string} */ function sanitize(input) { return sanitizeHtml(input, { // Allow "replacement" tags (in the format <0>, <1>, <2>, etc) used by // react-i18next to allow for HTML insertion via the Trans component. // See: https://github.com/overleaf/developer-manual/blob/master/code/translations.md // Unfortunately the sanitizeHtml library does not accept regexes or a // function for the allowedTags option, so we are limited to a hard-coded // number of "replacement" tags. allowedTags: ['b', 'strong', 'a', 'code', ...range(10)], allowedAttributes: { a: ['href', 'class'], }, textFilter(text) { return text .replace(/\{\{/, '&#123;&#123;') .replace(/\}\}/, '&#125;&#125;') }, }) } /** * Generate a range of numbers as strings up to the given size * * @param {number} size Size of range * @returns {string[]} */ function range(size) { return Array.from(Array(size).keys()).map(n => n.toString()) }
overleaf/web/scripts/translations/download.js/0
{ "file_path": "overleaf/web/scripts/translations/download.js", "repo_id": "overleaf", "token_count": 988 }
546
const { merge } = require('@overleaf/settings/merge') let features const httpAuthUser = 'sharelatex' const httpAuthPass = 'password' const httpAuthUsers = {} httpAuthUsers[httpAuthUser] = httpAuthPass module.exports = { catchErrors: false, clsiCookie: undefined, cacheStaticAssets: true, httpAuthUsers, secureCookie: false, security: { sessionSecret: 'static-secret-for-tests', }, adminDomains: process.env.ADMIN_DOMAINS ? JSON.parse(process.env.ADMIN_DOMAINS) : ['example.com'], statusPageUrl: 'status.example.com', apis: { linkedUrlProxy: { url: process.env.LINKED_URL_PROXY, }, web: { user: httpAuthUser, pass: httpAuthPass, }, }, // for registration via SL, set enableLegacyRegistration to true // for registration via Overleaf v1, set enableLegacyLogin to true // Currently, acceptance tests require enableLegacyRegistration. enableLegacyRegistration: true, features: (features = { v1_free: { collaborators: 1, dropbox: false, versioning: false, github: true, gitBridge: true, templates: false, references: false, referencesSearch: false, mendeley: true, zotero: true, compileTimeout: 60, compileGroup: 'standard', trackChanges: false, }, personal: { collaborators: 1, dropbox: false, versioning: false, github: false, gitBridge: false, templates: false, references: false, referencesSearch: false, mendeley: false, zotero: false, compileTimeout: 60, compileGroup: 'standard', trackChanges: false, }, collaborator: { collaborators: 10, dropbox: true, versioning: true, github: true, gitBridge: true, templates: true, references: true, referencesSearch: true, mendeley: true, zotero: true, compileTimeout: 180, compileGroup: 'priority', trackChanges: true, }, professional: { collaborators: -1, dropbox: true, versioning: true, github: true, gitBridge: true, templates: true, references: true, referencesSearch: true, mendeley: true, zotero: true, compileTimeout: 180, compileGroup: 'priority', trackChanges: true, }, }), defaultFeatures: features.personal, defaultPlanCode: 'personal', institutionPlanCode: 'professional', plans: [ { planCode: 'v1_free', name: 'V1 Free', price: 0, features: features.v1_free, }, { planCode: 'personal', name: 'Personal', price: 0, features: features.personal, }, { planCode: 'collaborator', name: 'Collaborator', price: 1500, features: features.collaborator, }, { planCode: 'professional', name: 'Professional', price: 3000, features: features.professional, }, ], bonus_features: { 1: { collaborators: 2, dropbox: false, versioning: false, }, 3: { collaborators: 4, dropbox: false, versioning: false, }, 6: { collaborators: 4, dropbox: true, versioning: true, }, 9: { collaborators: -1, dropbox: true, versioning: true, }, }, redirects: { '/redirect/one': '/destination/one', '/redirect/get_and_post': { methods: ['get', 'post'], url: '/destination/get_and_post', }, '/redirect/base_url': { baseUrl: 'https://example.com', url: '/destination/base_url', }, '/redirect/params/:id': { url(params) { return `/destination/${params.id}/params` }, }, '/redirect/qs': '/destination/qs', '/docs_v1': { url: '/docs', }, }, reconfirmNotificationDays: 14, unsupportedBrowsers: { ie: '<=11', }, // No email in tests email: undefined, test: { counterInit: 0, }, } module.exports.mergeWith = function (overrides) { return merge(overrides, module.exports) }
overleaf/web/test/acceptance/config/settings.test.defaults.js/0
{ "file_path": "overleaf/web/test/acceptance/config/settings.test.defaults.js", "repo_id": "overleaf", "token_count": 1746 }
547
const { exec } = require('child_process') const { promisify } = require('util') const { expect } = require('chai') const logger = require('logger-sharelatex') const { filterOutput } = require('./helpers/settings') const { db, ObjectId } = require('../../../app/src/infrastructure/mongodb') const ONE_DAY_IN_S = 60 * 60 * 24 const BATCH_SIZE = 3 function getSecondsFromObjectId(id) { return id.getTimestamp().getTime() / 1000 } function getObjectIdFromDate(date) { const seconds = new Date(date).getTime() / 1000 return ObjectId.createFromTime(seconds) } describe('DeleteOrphanedDocsOnlineCheck', function () { let docIds let projectIds let stopAtSeconds let BATCH_LAST_ID beforeEach('create docs', async function () { BATCH_LAST_ID = getObjectIdFromDate('2021-03-31T00:00:00.000Z') docIds = [] docIds[0] = getObjectIdFromDate('2021-04-01T00:00:00.000Z') docIds[1] = getObjectIdFromDate('2021-04-02T00:00:00.000Z') docIds[2] = getObjectIdFromDate('2021-04-11T00:00:00.000Z') docIds[3] = getObjectIdFromDate('2021-04-12T00:00:00.000Z') docIds[4] = getObjectIdFromDate('2021-04-13T00:00:00.000Z') docIds[5] = getObjectIdFromDate('2021-04-14T00:00:00.000Z') docIds[6] = getObjectIdFromDate('2021-04-15T00:00:00.000Z') docIds[7] = getObjectIdFromDate('2021-04-16T00:01:00.000Z') docIds[8] = getObjectIdFromDate('2021-04-16T00:02:00.000Z') docIds[9] = getObjectIdFromDate('2021-04-16T00:03:00.000Z') docIds[10] = getObjectIdFromDate('2021-04-16T00:04:00.000Z') docIds[11] = getObjectIdFromDate('2021-04-16T00:05:00.000Z') projectIds = [] projectIds[0] = getObjectIdFromDate('2021-04-01T00:00:00.000Z') projectIds[1] = getObjectIdFromDate('2021-04-02T00:00:00.000Z') projectIds[2] = getObjectIdFromDate('2021-04-11T00:00:00.000Z') projectIds[3] = getObjectIdFromDate('2021-04-12T00:00:00.000Z') projectIds[4] = getObjectIdFromDate('2021-04-13T00:00:00.000Z') projectIds[5] = getObjectIdFromDate('2021-04-14T00:00:00.000Z') projectIds[6] = getObjectIdFromDate('2021-04-15T00:00:00.000Z') projectIds[7] = getObjectIdFromDate('2021-04-16T00:01:00.000Z') projectIds[8] = getObjectIdFromDate('2021-04-16T00:02:00.000Z') projectIds[9] = getObjectIdFromDate('2021-04-16T00:03:00.000Z') // two docs in the same project projectIds[10] = projectIds[9] projectIds[11] = projectIds[4] stopAtSeconds = new Date('2021-04-17T00:00:00.000Z').getTime() / 1000 }) beforeEach('create doc stubs', async function () { await db.docs.insertMany([ // orphaned { _id: docIds[0], project_id: projectIds[0] }, { _id: docIds[1], project_id: projectIds[1] }, { _id: docIds[2], project_id: projectIds[2] }, { _id: docIds[3], project_id: projectIds[3] }, // orphaned, failed hard deletion { _id: docIds[4], project_id: projectIds[4] }, // not orphaned, live { _id: docIds[5], project_id: projectIds[5] }, // not orphaned, pending hard deletion { _id: docIds[6], project_id: projectIds[6] }, // multiple in a single batch { _id: docIds[7], project_id: projectIds[7] }, { _id: docIds[8], project_id: projectIds[8] }, { _id: docIds[9], project_id: projectIds[9] }, // two docs in one project { _id: docIds[10], project_id: projectIds[10] }, { _id: docIds[11], project_id: projectIds[11] }, ]) }) beforeEach('create project stubs', async function () { await db.projects.insertMany([ // live { _id: projectIds[5] }, ]) }) beforeEach('create deleted project stubs', async function () { await db.deletedProjects.insertMany([ // hard-deleted { deleterData: { deletedProjectId: projectIds[4] } }, // soft-deleted { deleterData: { deletedProjectId: projectIds[6] }, project: { _id: projectIds[6] }, }, ]) }) let options async function runScript(dryRun) { options = { BATCH_LAST_ID, BATCH_SIZE, DRY_RUN: dryRun, INCREMENT_BY_S: ONE_DAY_IN_S, STOP_AT_S: stopAtSeconds, // Lower concurrency to 1 for strict sequence of log messages. READ_CONCURRENCY_SECONDARY: 1, READ_CONCURRENCY_PRIMARY: 1, WRITE_CONCURRENCY: 1, // start right away LET_USER_DOUBLE_CHECK_INPUTS_FOR: 1, } let result try { result = await promisify(exec)( Object.entries(options) .map(([key, value]) => `${key}=${value}`) .concat([ // Hide verbose log messages `calling destroy for project in docstore` 'LOG_LEVEL=error', // Hide deprecation warnings for calling `db.collection.count` 'NODE_OPTIONS=--no-deprecation', ]) .concat(['node', 'scripts/delete_orphaned_docs_online_check.js']) .join(' ') ) } catch (error) { // dump details like exit code, stdErr and stdOut logger.error({ error }, 'script failed') throw error } let { stderr: stdErr, stdout: stdOut } = result stdErr = stdErr.split('\n').filter(filterOutput) stdOut = stdOut.split('\n').filter(filterOutput) const oneDayFromProjectId9InSeconds = getSecondsFromObjectId(projectIds[9]) + ONE_DAY_IN_S const oneDayFromProjectId9AsObjectId = getObjectIdFromDate( 1000 * oneDayFromProjectId9InSeconds ) expect(stdOut).to.deep.equal([ `Checking projects ["${projectIds[0]}"]`, `Deleted project ${projectIds[0]} has 1 orphaned docs: ["${docIds[0]}"]`, `Checking projects ["${projectIds[1]}"]`, `Deleted project ${projectIds[1]} has 1 orphaned docs: ["${docIds[1]}"]`, `Checking projects ["${projectIds[2]}"]`, `Deleted project ${projectIds[2]} has 1 orphaned docs: ["${docIds[2]}"]`, `Checking projects ["${projectIds[3]}"]`, `Deleted project ${projectIds[3]} has 1 orphaned docs: ["${docIds[3]}"]`, // Two docs in the same project `Checking projects ["${projectIds[4]}"]`, `Deleted project ${projectIds[4]} has 2 orphaned docs: ["${docIds[4]}","${docIds[11]}"]`, // Project 5 is live `Checking projects ["${projectIds[5]}"]`, // Project 6 is soft-deleted `Checking projects ["${projectIds[6]}"]`, // 7,8,9 are on the same day, but exceed the batch size of 2 `Checking projects ["${projectIds[7]}","${projectIds[8]}","${projectIds[9]}"]`, `Deleted project ${projectIds[7]} has 1 orphaned docs: ["${docIds[7]}"]`, `Deleted project ${projectIds[8]} has 1 orphaned docs: ["${docIds[8]}"]`, // Two docs in the same project `Deleted project ${projectIds[9]} has 2 orphaned docs: ["${docIds[9]}","${docIds[10]}"]`, '', ]) expect(stdErr).to.deep.equal([ ...`Options: ${JSON.stringify(options, null, 2)}`.split('\n'), 'Waiting for you to double check inputs for 1 ms', `Processed 1 projects (1 projects with orphaned docs/1 docs deleted) until ${getObjectIdFromDate( '2021-04-01T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-02T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-03T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-04T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-05T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-06T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-07T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-08T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-09T00:00:00.000Z' )}`, `Processed 2 projects (2 projects with orphaned docs/2 docs deleted) until ${getObjectIdFromDate( '2021-04-10T00:00:00.000Z' )}`, `Processed 3 projects (3 projects with orphaned docs/3 docs deleted) until ${getObjectIdFromDate( '2021-04-11T00:00:00.000Z' )}`, `Processed 4 projects (4 projects with orphaned docs/4 docs deleted) until ${getObjectIdFromDate( '2021-04-12T00:00:00.000Z' )}`, `Processed 5 projects (5 projects with orphaned docs/6 docs deleted) until ${getObjectIdFromDate( '2021-04-13T00:00:00.000Z' )}`, `Processed 6 projects (5 projects with orphaned docs/6 docs deleted) until ${getObjectIdFromDate( '2021-04-14T00:00:00.000Z' )}`, `Processed 7 projects (5 projects with orphaned docs/6 docs deleted) until ${getObjectIdFromDate( '2021-04-15T00:00:00.000Z' )}`, `Processed 7 projects (5 projects with orphaned docs/6 docs deleted) until ${getObjectIdFromDate( '2021-04-16T00:00:00.000Z' )}`, // 7,8,9,10 are on the same day, but exceed the batch size of 3 // Project 9 has two docs. `Processed 10 projects (8 projects with orphaned docs/10 docs deleted) until ${projectIds[9]}`, // 10 has as ready been processed as part of the last batch -- same project_id as 9. `Processed 10 projects (8 projects with orphaned docs/10 docs deleted) until ${oneDayFromProjectId9AsObjectId}`, 'Done.', '', ]) } describe('DRY_RUN=true', function () { beforeEach('run script', async function () { await runScript(true) }) it('should leave docs as is', async function () { const docs = await db.docs.find({}).toArray() expect(docs).to.deep.equal([ { _id: docIds[0], project_id: projectIds[0] }, { _id: docIds[1], project_id: projectIds[1] }, { _id: docIds[2], project_id: projectIds[2] }, { _id: docIds[3], project_id: projectIds[3] }, { _id: docIds[4], project_id: projectIds[4] }, { _id: docIds[5], project_id: projectIds[5] }, { _id: docIds[6], project_id: projectIds[6] }, { _id: docIds[7], project_id: projectIds[7] }, { _id: docIds[8], project_id: projectIds[8] }, { _id: docIds[9], project_id: projectIds[9] }, { _id: docIds[10], project_id: projectIds[10] }, { _id: docIds[11], project_id: projectIds[11] }, ]) }) }) describe('DRY_RUN=false', function () { beforeEach('run script', async function () { await runScript(false) }) it('should deleted all but docs from live/soft-deleted projects', async function () { const docs = await db.docs.find({}).toArray() expect(docs).to.deep.equal([ // not orphaned, live { _id: docIds[5], project_id: projectIds[5] }, // not orphaned, pending hard deletion { _id: docIds[6], project_id: projectIds[6] }, ]) }) }) })
overleaf/web/test/acceptance/src/DeleteOrphanedDocsOnlineCheckTests.js/0
{ "file_path": "overleaf/web/test/acceptance/src/DeleteOrphanedDocsOnlineCheckTests.js", "repo_id": "overleaf", "token_count": 4902 }
548
/* eslint-disable node/handle-callback-err, max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * 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 APP_PATH = '../../../app/src' const LockManager = require(`${APP_PATH}/infrastructure/LockManager`) const ProjectCreationHandler = require(`${APP_PATH}/Features/Project/ProjectCreationHandler.js`) const ProjectGetter = require(`${APP_PATH}/Features/Project/ProjectGetter.js`) const ProjectEntityMongoUpdateHandler = require(`${APP_PATH}/Features/Project/ProjectEntityMongoUpdateHandler.js`) const UserCreator = require(`${APP_PATH}/Features/User/UserCreator.js`) const { expect } = require('chai') const _ = require('lodash') // These tests are neither acceptance tests nor unit tests. It's difficult to // test/verify that our locking is doing what we hope. // These tests call methods in ProjectGetter and ProjectEntityMongoUpdateHandler // to see that they DO NOT work when a lock has been taken. // // It is tested that these methods DO work when the lock has not been taken in // other acceptance tests. describe('ProjectStructureMongoLock', function () { describe('whilst a project lock is taken', function () { let oldMaxLockWaitTime before(function () { oldMaxLockWaitTime = LockManager.MAX_LOCK_WAIT_TIME }) after(function () { LockManager.MAX_LOCK_WAIT_TIME = oldMaxLockWaitTime }) beforeEach(function (done) { // We want to instantly fail if the lock is taken LockManager.MAX_LOCK_WAIT_TIME = 1 this.lockValue = 'lock-value' const userDetails = { holdingAccount: false, email: 'test@example.com', } UserCreator.createNewUser(userDetails, {}, (err, user) => { this.user = user if (err != null) { throw err } return ProjectCreationHandler.createBlankProject( user._id, 'locked-project', (err, project) => { if (err != null) { throw err } this.locked_project = project const namespace = ProjectEntityMongoUpdateHandler.LOCK_NAMESPACE this.lock_key = `lock:web:${namespace}:${project._id}` return LockManager._getLock( this.lock_key, namespace, (err, lockValue) => { this.lockValue = lockValue return done() } ) } ) }) }) after(function (done) { return LockManager._releaseLock(this.lock_key, this.lockValue, done) }) describe('interacting with the locked project', function () { const LOCKING_UPDATE_METHODS = [ 'addDoc', 'addFile', 'mkdirp', 'moveEntity', 'renameEntity', 'addFolder', ] for (var methodName of Array.from(LOCKING_UPDATE_METHODS)) { it(`cannot call ProjectEntityMongoUpdateHandler.${methodName}`, function (done) { const method = ProjectEntityMongoUpdateHandler[methodName] const args = _.times(method.length - 2, _.constant(null)) return method(this.locked_project._id, args, err => { expect(err).to.be.instanceOf(Error) expect(err).to.have.property('message', 'Timeout') return done() }) }) } it('cannot get the project without a projection', function (done) { return ProjectGetter.getProject(this.locked_project._id, err => { expect(err).to.be.instanceOf(Error) expect(err).to.have.property('message', 'Timeout') return done() }) }) it('cannot get the project if rootFolder is in the projection', function (done) { return ProjectGetter.getProject( this.locked_project._id, { rootFolder: true }, err => { expect(err).to.be.instanceOf(Error) expect(err).to.have.property('message', 'Timeout') return done() } ) }) it('can get the project if rootFolder is not in the projection', function (done) { return ProjectGetter.getProject( this.locked_project._id, { _id: true }, (err, project) => { expect(err).to.equal(null) expect(project).to.have.same.id(this.locked_project) return done() } ) }) }) describe('interacting with other projects', function () { beforeEach(function (done) { return ProjectCreationHandler.createBlankProject( this.user._id, 'unlocked-project', (err, project) => { if (err != null) { throw err } this.unlocked_project = project return done() } ) }) it('can add folders to other projects', function (done) { return ProjectEntityMongoUpdateHandler.addFolder( this.unlocked_project._id, this.unlocked_project.rootFolder[0]._id, 'new folder', (err, folder) => { expect(err).to.equal(null) expect(folder).to.exist return done() } ) }) it('can get other projects without a projection', function (done) { return ProjectGetter.getProject( this.unlocked_project._id, (err, project) => { expect(err).to.equal(null) expect(project).to.have.same.id(this.unlocked_project) return done() } ) }) }) }) })
overleaf/web/test/acceptance/src/ProjectStructureMongoLockTest.js/0
{ "file_path": "overleaf/web/test/acceptance/src/ProjectStructureMongoLockTest.js", "repo_id": "overleaf", "token_count": 2537 }
549