text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
---
title: SetTimer
description: Sets a 'timer' to call a function after some time.
tags: []
---
## คำอธิบาย
Sets a 'timer' to call a function after some time. Can be set to repeat.
| Name | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------- |
| funcname[] | Name of the function to call as a string. This must be a public function (forwarded). A null string here will crash the server. |
| interval | Interval in milliseconds. |
| repeating | Boolean (true/false) on whether the timer should repeat or not. |
## ส่งคืน
The ID of the timer that was started. Timer IDs start at 1.
## ตัวอย่าง
```c
forward message();
public OnGameModeInit()
{
print("Starting timer...");
SetTimer("message", 1000, false); // Set a timer of 1000 miliseconds (1 second)
}
public message()
{
print("1 second has passed.");
}
```
## บันทึก
:::tip
Timer intervals are not accurate (roughly 25% off). There are fixes available here and here. Timer IDs are never used twice. You can use KillTimer() on a timer ID and it won't matter if it's running or not. The function that should be called, must be public, meaning it has to be forwarded. The use of many timers will result in increased memory/cpu usage.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetTimerEx: Set a timer with parameters.
- KillTimer: Stop a timer.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetTimer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetTimer.md",
"repo_id": "openmultiplayer",
"token_count": 764
} | 445 |
---
title: ShowMenuForPlayer
description: Shows a previously created menu for a player.
tags: ["player", "menu"]
---
## คำอธิบาย
Shows a previously created menu for a player.
| Name | Description |
| -------- | ---------------------------------------------------- |
| menuid | The ID of the menu to show. Returned by CreateMenu. |
| playerid | The ID of the player to whom the menu will be shown. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. Menu and/or player doesn't exist.
## ตัวอย่าง
```c
new Menu:MENU_PlayerTeleport;
public OnGameModeInit()
{
MENU_PlayerTeleport = CreateMenu(...);
return 1;
}
if (strcmp(cmdtext, "/tele", true) == 0)
{
ShowMenuForPlayer(MENU_PlayerTeleport, playerid);
return 1;
}
```
## บันทึก
:::tip
Crashes the both server and player if an invalid menu ID given.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateMenu](../../scripting/functions/CreateMenu.md): Create a menu.
- [AddMenuItem](../../scripting/functions/AddMenuItem.md): Adds an item to a specified menu.
- [SetMenuColumnHeader](../../scripting/functions/SetMenuColumnHeader.md): Set the header for one of the columns in a menu.
- [DestroyMenu](../../scripting/functions/DestroyMenu.md): Destroy a menu.
- [OnPlayerSelectedMenuRow](../../scripting/callbacks/OnPlayerSelectedMenuRow.md): Called when a player selected a row in a menu.
- [OnPlayerExitedMenu](../../scripting/callbacks/OnPlayerExitedMenu.md): Called when a player exits a menu.
| openmultiplayer/web/docs/translations/th/scripting/functions/ShowMenuForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ShowMenuForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 608
} | 446 |
---
title: TextDrawCreate
description: Creates a textdraw.
tags: ["textdraw"]
---
## คำอธิบาย
Creates a textdraw. Textdraws are, as the name implies, text (mainly - there can be boxes, sprites and model previews (skins/vehicles/weapons/objects too) that is drawn on a player's screens. See this page for extensive information about textdraws.
| Name | Description |
| ------- | -------------------------------------------------------- |
| Float:x | The X (left/right) coordinate to create the textdraw at. |
| Float:y | The Y (up/down) coordinate to create the textdraw at. |
| text[] | The text that will appear in the textdraw. |
## ส่งคืน
The ID of the created textdraw. Textdraw IDs start at 0.
## ตัวอย่าง
```c
// This variable is used to store the id of the textdraw
// so that we can use it throught the script
new Text:welcomeText;
public OnGameModeInit()
{
// This line is used to create the textdraw.
// Note: This creates a textdraw without any formatting.
welcomeText = TextDrawCreate(240.0,580.0,"Welcome to my SA-MP server");
return 1;
}
public OnPlayerConnect(playerid)
{
//This is used to show the player the textdraw when they connect.
TextDrawShowForPlayer(playerid,welcomeText);
}
```
## บันทึก
:::tip
The x,y coordinate is the top left coordinate for the text draw area based on a 640x480 "canvas" (irrespective of screen resolution). If you plan on using TextDrawAlignment with alignment 3 (right), the x,y coordinate is the top right coordinate for the text draw. This function merely CREATES the textdraw, you must use TextDrawShowForPlayer or TextDrawShowForAll to show it. It is recommended to use WHOLE numbers instead of decimal positions when creating textdraws to ensure resolution friendly design.
:::
:::warning
Keyboard key mapping codes (such as ~k~~VEHICLE_ENTER_EXIT~ don't work beyond 255th character.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw.
- [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw.
- [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw.
- [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw.
- [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw.
- [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw.
- [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw.
- [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box.
- [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline.
- [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw.
- [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio.
- [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not.
- [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw.
- [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player.
- [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player.
- [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players.
- [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawCreate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawCreate.md",
"repo_id": "openmultiplayer",
"token_count": 1192
} | 447 |
---
title: TextDrawTextSize
description: Change the size of a textdraw (box if TextDrawUseBox is enabled and/or clickable area for use with TextDrawSetSelectable).
tags: ["textdraw"]
---
## คำอธิบาย
Change the size of a textdraw (box if TextDrawUseBox is enabled and/or clickable area for use with TextDrawSetSelectable).
| Name | Description |
| ------- | -------------------------------------------------------------------------------------- |
| text | The TextDraw to set the size of. |
| Float:x | The size on the X axis (left/right) following the same 640x480 grid as TextDrawCreate. |
| Float:y | The size on the Y axis (up/down) following the same 640x480 grid as TextDrawCreate. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
new Text:MyTextdraw;
public OnGameModeInit()
{
MyTextDraw = TextDrawCreate(100.0, 33.0,"Example TextDraw");
TextDrawTextSize(MyTextDraw, 2.0, 3.6);
return 1;
}
```
## บันทึก
:::tip
The x and y have different meanings with different TextDrawAlignment values: 1 (left): they are the right-most corner of the box, absolute coordinates. 2 (center): they need to inverted (switch the two) and the x value is the overall width of the box. 3 (right): the x and y are the coordinates of the left-most corner of the box
Using font type 4 (sprite) and 5 (model preview) converts X and Y of this function from corner coordinates to WIDTH and HEIGHT (offsets). The TextDraw box starts 10.0 units up and 5.0 to the left as the origin (TextDrawCreate coordinate). This function defines the clickable area for use with TextDrawSetSelectable, whether a box is shown or not.
:::
:::tip
If you want to change the text size of a textdraw that is already shown, you don't have to recreate it. Simply use TextDrawShowForPlayer/TextDrawShowForAll after modifying the textdraw and the change will be visible.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw.
- [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw.
- [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw.
- [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw.
- [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw.
- [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw.
- [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw.
- [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw.
- [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline.
- [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw.
- [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio.
- [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not.
- [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw.
- [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player.
- [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player.
- [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players.
- [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawTextSize.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawTextSize.md",
"repo_id": "openmultiplayer",
"token_count": 1247
} | 448 |
---
title: clamp
description: Force a value to be inside a range.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Force a value to be inside a range.
| Name | Description |
| ----- | ------------------------------ |
| value | The value to force in a range. |
| min | The low bound of the range. |
| max | The high bound of the range. |
## ส่งคืน
value, if it is in the range min–max, min, if value is lower than min or max, if value is higher than max.
## ตัวอย่าง
```c
new
valueA = 3,
valueB = 7,
valueC = 100
;
printf("The value is: %d", clamp(valueA, 5, 10)); // output: "The value is: 5" because 3 is less than 5.
printf("The value is: %d", clamp(valueB, 5, 10)); // output: "The value is: 7" because 7 is between 5 and 10.
printf("The value is: %d", clamp(valueC, 5, 10)); // output: "The value is: 10" because 100 is more than 10.
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/clamp.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/clamp.md",
"repo_id": "openmultiplayer",
"token_count": 423
} | 449 |
---
title: db_num_rows
description: Returns the number of rows from a db_query.
tags: ["sqlite"]
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Returns the number of rows from a db_query
| Name | Description |
| ----------------- | ---------------------- |
| DBResult:dbresult | The result of db_query |
## ส่งคืน
The number of rows in the result.
## ตัวอย่าง
```c
// Example function
GetNameBySpawnID(spawn_id)
{
// Declare "p_name"
new p_name[MAX_PLAYER_NAME+1];
// Declare "query" and "db_result"
static query[60], DBResult:db_result;
// Formats "query"
format(query, sizeof query, "SELECT `PlayerName` FROM `spawn_log` WHERE `ID`=%d", spawn_id);
// Selects the player name by using "spawn_id"
db_result = db_query(db_handle, query);
// If there is any valid entry
if (db_num_rows(db_result))
{
// Store data from "PlayerName" into "p_name"
db_get_field(db_result, 0, p_name, sizeof p_name);
}
// Frees the result
db_free_result(db_result);
// Returns "p_name"
return p_name;
}
```
## บันทึก
:::warning
Using an invalid handle will crash your server! Get a valid handle by using db_query. But it's protected against NULL references.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- db_open: Open a connection to an SQLite database
- db_close: Close the connection to an SQLite database
- db_query: Query an SQLite database
- db_free_result: Free result memory from a db_query
- db_num_rows: Get the number of rows in a result
- db_next_row: Move to the next row
- db_num_fields: Get the number of fields in a result
- db_field_name: Returns the name of a field at a particular index
- db_get_field: Get content of field with specified ID from current result row
- db_get_field_assoc: Get content of field with specified name from current result row
- db_get_field_int: Get content of field as an integer with specified ID from current result row
- db_get_field_assoc_int: Get content of field as an integer with specified name from current result row
- db_get_field_float: Get content of field as a float with specified ID from current result row
- db_get_field_assoc_float: Get content of field as a float with specified name from current result row
- db_get_mem_handle: Get memory handle for an SQLite database that was opened with db_open.
- db_get_result_mem_handle: Get memory handle for an SQLite query that was executed with db_query.
- db_debug_openfiles
- db_debug_openresults
| openmultiplayer/web/docs/translations/th/scripting/functions/db_num_rows.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/db_num_rows.md",
"repo_id": "openmultiplayer",
"token_count": 924
} | 450 |
---
title: floatdiv
description: Divide one float by another one.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Divide one float by another one. Redundant as the division operator (/) does the same thing.
| Name | Description |
| -------------- | ----------------------------------------- |
| Float:dividend | First float. |
| Float:divisor | Second float (dividates the first float.) |
## ส่งคืน
The quotient of the two given floats.
## ตัวอย่าง
```c
public OnGameModeInit()
{
new Float:Number1 = 8.05, Float:Number2 = 3.5; //Declares two floats, Number1 (8.05) and Number2 (3.5)
new Float:Quotient;
Quotient = floatdiv(Number1, Number2); //Saves the quotient(=8.05/3.5 = 2.3) of Number1 and Number2 in the float "Quotient"
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [floatadd](../functions/floatadd): Adds two floats together.
- [floatsub](../functions/floatsub): Subtract a float from another float.
- [floatmul](../functions/floatmul): Multiply two floats.
| openmultiplayer/web/docs/translations/th/scripting/functions/floatdiv.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatdiv.md",
"repo_id": "openmultiplayer",
"token_count": 505
} | 451 |
---
title: fremove
description: Delete a file.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Delete a file.
| Name | Description |
| ------ | --------------------------------------------------------- |
| name[] | The path of the file to delete. (NOTE: NOT a file handle) |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The file doesn't exist, or you don't have permission to delete it.
## ตัวอย่าง
```c
fremove("Example.txt");
```
## บันทึก
:::tip
Files that are currently open (fopen) must be closed first (fclose) to be deleted.
:::
:::warning
The file path must be valid.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [fopen](../functions/fopen): Open a file.
- [fclose](../functions/fclose): Close a file.
- [ftemp](../functions/ftemp): Create a temporary file stream.
- [fremove](../functions/fremove): Remove a file.
- [fwrite](../functions/fwrite): Write to a file.
- [fread](../functions/fread): Read a file.
- [fputchar](../functions/fputchar): Put a character in a file.
- [fgetchar](../functions/fgetchar): Get a character from a file.
- [fblockwrite](../functions/fblockwrite): Write blocks of data into a file.
- [fblockread](../functions/fblockread): Read blocks of data from a file.
- [fseek](../functions/fseek): Jump to a specific character in a file.
- [flength](../functions/flength): Get the file length.
- [fexist](../functions/fexist): Check, if a file exists.
- [fmatch](../functions/fmatch): Check, if patterns with a file name matches.
| openmultiplayer/web/docs/translations/th/scripting/functions/fremove.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fremove.md",
"repo_id": "openmultiplayer",
"token_count": 636
} | 452 |
---
title: print
description: Prints a string to the server console (not in-game chat) and logs (server_log.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Prints a string to the server console (not in-game chat) and logs (server_log.txt).
| Name | Description |
| -------- | -------------------- |
| string[] | The string to print. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnGameModeInit( )
{
print("Gamemode started.");
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- printf: Print a formatted message into the server logs and console.
| openmultiplayer/web/docs/translations/th/scripting/functions/print.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/print.md",
"repo_id": "openmultiplayer",
"token_count": 295
} | 453 |
---
title: strval
description: Convert a string to an integer.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Convert a string to an integer.
| Name | Description |
| -------------- | --------------------------------------------- |
| const string[] | The string you want to convert to an integer. |
## ส่งคืน
The integer value of the string. '0 if the string is not numeric.
## ตัวอย่าง
```c
new string[4] = "250";
new iValue = strval(string); // iValue is now '250'
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- strcmp: Compare two strings to see if they are the same.
- strfind: Search for a substring in a string.
- strtok: Search for a variable typed after a space.
- strdel: Delete part/all of a string.
- strins: Put a string into another string.
- strlen: Check the length of a string.
- strmid: Extract characters from a string.
- strpack: Pack a string into a destination.
- strcat: Concatenate two strings into a destination reference.
| openmultiplayer/web/docs/translations/th/scripting/functions/strval.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/strval.md",
"repo_id": "openmultiplayer",
"token_count": 414
} | 454 |
---
title: Fighting Styles
---
## คำอธิบาย
Fighting Styles to be used with [SetPlayerFightingStyle](../functions/SetPlayerFightingStyle.md) and [GetPlayerFightingStyle](../functions/GetPlayerFightingStyle.md).
## Fighting Styles
```c
4 - FIGHT_STYLE_NORMAL
5 - FIGHT_STYLE_BOXING
6 - FIGHT_STYLE_KUNGFU
7 - FIGHT_STYLE_KNEEHEAD
15 - FIGHT_STYLE_GRABKICK
16 - FIGHT_STYLE_ELBOW
```
| openmultiplayer/web/docs/translations/th/scripting/resources/fightingstyles.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/fightingstyles.md",
"repo_id": "openmultiplayer",
"token_count": 158
} | 455 |
---
title: "Pickup IDs"
---
:::note
ANY valid object model can be used for [pickups](../functions/CreatePickup). This page just lists some common object models that are around the right size to be used as a pickup.
:::
## Pickup model IDs
| ID | Icon | Description |
| ----- | --------------------------------- | ---------------------------------- |
| 954 |  | Horse shoe |
| 1210 |  | Briefcase |
| 1212 |  | Money |
| 1213 |  | Landmine |
| 1239 |  | Information |
| 1240 |  | Heart |
| 1241 |  | Pill |
| 1242 |  | Body armour |
| 1247 |  | Star |
| 1248 |  | GTA III logo |
| 1252 |  | Barrel explosion |
| 1254 |  | Skull |
| 1272 |  | House (blue) |
| 1273 |  | House (green) |
| 1274 |  | Dollar |
| 1275 |  | Shirt |
| 1276 |  | Tiki |
| 1277 |  | Save disk |
| 1279 |  | Craig package |
| 1310 |  | Parachute |
| 1313 |  | Double skull (kill frenzy rampage) |
| 1314 |  | Two-player |
| 1318 |  | Arrow |
| 1550 |  | Money bag |
| 1575 |  | Drug package (white) |
| 1576 |  | Drug package (orange) |
| 1577 |  | Drug package (yellow) |
| 1578 |  | Drug package (green) |
| 1579 |  | Drug package (blue) |
| 1580 |  | Drug package (red) |
| 1581 |  | Keycard |
| 1582 |  | Pizza box |
| 1636 |  | RC bomb |
| 1650 |  | Petrol can |
| 1654 |  | Dynamite |
| 2057 |  | Flame tins |
| 2060 |  | Sandbag |
| 2061 |  | Shells |
| 2690 |  | Fire extinguisher |
| 2710 |  | Hand watch |
| 11736 |  | Medical satchel |
| 11738 |  | Medical case |
| 19130 |  | Arrow (type 1) |
| 19131 |  | Arrow (type 2) |
| 19132 |  | Arrow (type 3) |
| 19133 |  | Arrow (type 4) |
| 19134 |  | Arrow (type 5) |
| 19135 |  | Exterior marker (animated) |
| 19197 |  | Exterior marker (yellow, big) |
| 19198 |  | Exterior marker (yellow, small) |
| 19320 |  | Pumpkin |
| 19522 |  | House (red) |
| 19523 |  | House (orange) |
| 19524 |  | House (yellow) |
| 19602 |  | Landmine (type 2) |
| 19605 |  | Exterior marker (red) |
| 19606 |  | Exterior marker (green) |
| 19607 |  | Exterior marker (blue) |
| 19832 |  | Ammunation box |
## Weapon pickups
| ID | Description |
| --- | ---------------------------- |
| 321 | Regular Dildo |
| 322 | White Dildo |
| 323 | Vibrator |
| 324 | Another Vibrator |
| 325 | Flowers |
| 326 | Cane |
| 330 | CJ's Phone |
| 331 | Brass Knuckles |
| 333 | Golf Club |
| 334 | Night Stick |
| 335 | Combat Knife |
| 336 | Baseball Bat |
| 337 | Shovel |
| 338 | Pool Cue |
| 339 | Katana |
| 341 | Chainsaw |
| 342 | Frag Grenade |
| 343 | Tear Gas Grenade |
| 344 | Molotov Cocktail |
| 346 | Colt 45 Pistol |
| 347 | Silenced Colt 45 Pistol |
| 348 | Desert Eagle |
| 349 | Regular Shotgun |
| 350 | Sawn-Off Shotgun |
| 351 | SPAZ-12 Shotgun |
| 352 | Mac-10 (Or Micro-UZI) |
| 353 | MP5 |
| 354 | Hydra Flare |
| 355 | AK47 Assault Rifle |
| 356 | M4 Assault Rifle |
| 357 | Country Rifle |
| 358 | Sniper Rifle |
| 359 | Rocket Launcher |
| 360 | Heat Seeking Rocket Launcher |
| 361 | Flamethrower |
| 362 | Minigun |
| 363 | Satchel Charges |
| 364 | Detonator |
| 365 | Spray Paint Can |
| 366 | Fire Extinguisher |
| 367 | Camera |
| 368 | Night Vision Goggles |
| 369 | Infra-Red Goggles |
| 370 | Jetpack |
| 371 | Parachute |
| 372 | Tec-9 |
| openmultiplayer/web/docs/translations/th/scripting/resources/pickupids.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/pickupids.md",
"repo_id": "openmultiplayer",
"token_count": 4059
} | 456 |
---
title: Tire States
description: Information about byte size and its corresponding tire state bits.
---
:::note
To be used with [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus) and [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus).
Even vehicles with more than 4 wheels (e.g. trucks) only have 4 tire states.
:::
Each tire has two states - popped and not popped. Binary Digits (bits) also have two states - 0 and 1. A technique called [bit masking](<http://en.wikipedia.org/wiki/Mask_(computing)>) is used to store more information in less memory. Bit 1 represents a popped tire, and bit 0 represents a tire that isn't popped. For example, `0101` - two tires are popped, two are not.
[Bitwise operators](https://webcache.googleusercontent.com/search?q=cache:LMkbueHJOgcJ:https://forum.sa-mp.com/showthread.php%3Ft%3D177523+&cd=1&hl=en&ct=clnk&gl=my) can be used to work with bit masking.
Here is a visual representation of the tire states. Vehicle viewed from a top-down perspective, the top is the front of the vehicle.
**o = inflated tire**
**x = popped tire**
## 4-Wheeled Vehicles
4 binary bits for 4-wheeled vehicles: (FL)(BL)(FR)(BR) (Front-Left, Back-Left, Front-Right and Back-Right)
0: (0000)
o-o
| |
o-o
1: (0001)
o-o
| |
o-x
2: (0010)
o-x
| |
o-o
3: (0011)
o-x
| |
o-x
4: (0100)
o-o
| |
x-o
5: (0101)
o-o
| |
x-x
6: (0110)
o-x
| |
x-o
7: (0111)
o-x
| |
x-x
8: (1000)
x-o
| |
o-o
9: (1001)
x-o
| |
o-x
10: (1010)
x-x
| |
o-o
11: (1011)
x-x
| |
o-x
12: (1100)
x-o
| |
x-o
13: (1101)
x-o
| |
x-x
14: (1110)
x-x
| |
x-o
15: (1111)
x-x
| |
x-x
After 15 the values are repeated, so 16 is 0, 17 is 1 and so on.
## 2-Wheeled Vehicles (Bikes)
Bike viewed from a top-down perspective, the top is the front of the bike.
2 binary bits for 2-wheeled vehicles: (F)(B) (Front and Back)
0: (00)
o
|
o
1: (01)
o
|
x
2: (10)
x
|
o
3: (11)
x
|
x
After 3 the values are repeated, so 4 is 0, 5 is 1 and so on.
## Example Usage
To pop the back two tires of a vehicle (with 4 wheels) while keeping the front the same state:
```c
new Panels, Doors, Lights, Tires;
GetVehicleDamageStatus(vehicleid, Panels, Doors, Lights, Tires);
UpdateVehicleDamageStatus(vehicleid, Panels, Doors, Lights, (Tires | 0b0101));
```
| openmultiplayer/web/docs/translations/th/scripting/resources/tirestates.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/tirestates.md",
"repo_id": "openmultiplayer",
"token_count": 1093
} | 457 |
---
title: Server variable system
description: The server variable system (put short, SVar) is a new way of creating server variables in an efficient dynamically created method globally, meaning they can be used in server's gamemode and filterscripts at the same time.
---
The **server variable system** (put short, **SVar**) is a new way of creating server variables in an efficient dynamically created method globally, meaning they can be used in server's gamemode and filterscripts at the same time.
They are similar to [PVars](perplayervariablesystem), but are not tied to a player ID.
:::note The SVar system is the same as the PVars, although the variables created are server-wide, not attached to any playerid, and persist through gamemode changes. :::
## Advantages
The new system was introduced in SA-MP 0.3.7 R2-1.
- SVars can be shared/accessed across gamemode scripts and filterscripts.
- You can easily enumerate and print/store the SVar list. This makes debugging easier.
- Even if a SVar hasn't been created, it still will return a default value of 0.
- SVars can hold very large strings using dynamically allocated memory.
- You can Set, Get, Create SVars ingame.
## Drawbacks
- SVars are several times slower than regular variables. It is generally more favorable to trade in memory for speed, rather than the other way round.
## Functions
The functions for setting and retrieving the server variables are:
- [SetSVarInt](../scripting/functions/SetSVarInt) Set an integer for a server variable.
- [GetSVarInt](../scripting/functions/GetSVarInt) Get a player server as an integer.
- [SetSVarString](../scripting/functions/SetSVarString) Set a string for a server variable.
- [GetSVarString](../scripting/functions/GetSVarString) Get the previously set string from a server variable.
- [SetSVarFloat](../scripting/functions/SetSVarFloat) Set a float for a server variable.
- [GetSVarFloat](../scripting/functions/GetSVarFloat) Get the previously set float from a server variable
- [DeleteSVar](../scripting/functions/DeleteSVar) Delete a server variable.
```c
#define SERVER_VARTYPE_NONE (0)
#define SERVER_VARTYPE_INT (1)
#define SERVER_VARTYPE_STRING (2)
#define SERVER_VARTYPE_FLOAT (3)
```
| openmultiplayer/web/docs/translations/th/tutorials/servervariablesystem.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/tutorials/servervariablesystem.md",
"repo_id": "openmultiplayer",
"token_count": 640
} | 458 |
---
title: OnGameModeExit
description: Bu callback oyun modu sonlandığında, gmx komutu kullanıldığında, sunucu ani kapatıldığında veya GameModeExit kullanıldığında tetiklenir.
tags: []
---
## Açıklama
Bu callback oyun modu sonlandığında, gmx komutu kullanıldığında, sunucu ani kapatıldığında veya GameModeExit kullanıldığında tetiklenir.
## Örnekler
```c
public OnGameModeExit()
{
print("Gamemode ended.");
return 1;
}
```
## Notlar
:::tip
Bu callback aynı zamanda filterscript içinde changemode veya gmx gibi RCON komutlarıyla yapılan oyun modu değişimini algılamak için kullanılabilir. OnGameModeExit 'rcon gmx' konsol komutu ile tetiklendiğinde potansiyel istemci hataları oluşabileceğini unutmayın. Örneğin oyun modunda kullanılan RemoveBuildingForPlayer aşırılığı istemcinin hatalı sonlanmasına neden olabilir. Eğer istemci hatalı sonlanırsa bu callback tetiklenmez, Linux kill komutu ve Windows görevi sonlandırma işlemlerinde olduğu gibi.
:::
## Bağlantılı Fonksiyonlar
- [GameModeExit](../functions/GameModeExit.md): Mevcut oyun modundan çıkış yapar.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnGameModeExit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnGameModeExit.md",
"repo_id": "openmultiplayer",
"token_count": 476
} | 459 |
---
title: OnPlayerEnterVehicle
description: Bu callback, bir oyuncu bir araca binmeye başladığında çağırılır, oyuncu araca bindiğinde çağırılmaz, binmeye başladığında (araca doğru yürüme/koşma animasyonu başladığında) çağırılır.
tags: ["player", "vehicle"]
---
## Açıklama
Bu callback, bir oyuncu bir araca binmeye başladığında çağırılır, oyuncu araca bindiğinde çağırılmaz, binmeye başladığında (araca doğru yürüme/koşma animasyonu başladığında) çağırılır.
| İsim | Açıklama |
| ----------- | ---------------------------------------------------- |
| playerid | Araca binmeye çalışan oyuncunun ID'si. |
| vehicleid | Oyuncunun binmeye çalıştığı aracın ID'si. |
| ispassenger | Şöför koltuğuna biniyor ise 0, yolu koltuğu ise 1. |
## Çalışınca Vereceği Sonuçlar
Her zaman ilk olarak filterscriptlerde çağırılır.
## Örnekler
```c
public OnPlayerEnterVehicle(playerid, vehicleid, ispassenger)
{
new string[128];
format(string, sizeof(string), "%i ID'li araca biniyorsun.", vehicleid);
SendClientMessage(playerid, 0xFFFFFFFF, string);
return 1;
}
```
## Notlar
:::tip
Bu callback oyuncu araca binmeye BAŞLADIĞINDA çağırılır, oyuncu ARACA BİNDİĞİNDE çağırılmaz. Araca bindiğinde çağırılması için OnPlayerStateChange callbackini inceleyin. Araç kilitli veya dolu olsa bile oyuncu araca binmeye çalıştığında çağırılacaktır.
:::
## Bağlantılı Fonksiyonlar
- [PutPlayerInVehicle](../functions/PutPlayerInVehicle): Put a player in a vehicle.
- [GetPlayerVehicleSeat](../functions/GetPlayerVehicleSeat): Check what seat a player is in.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerEnterVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerEnterVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 798
} | 460 |
---
title: OnPlayerSelectedMenuRow
description: Bu fonksiyon, bir oyuncu menüden bir öğe seçtiğinde (ShowMenuForPlayer) çağrılır.
tags: ["player", "menu"]
---
## Açıklama
Bu fonksiyon, bir oyuncu menüden bir öğe seçtiğinde (ShowMenuForPlayer) çağrılır.
| Parametre | Açıklama |
| --------- | ----------------------------------------------------------- |
| playerid | Menü öğesi seçmiş olan oyuncunun ID'si. |
| row | Seçilen satırın ID'si. İlk satırın ID'si 0'dır. |
## Çalışınca Vereceği Sonuçlar
Oyun modunda her zaman ilk olarak çağrılır.
## Örnekler
```c
new Menu:MyMenu;
public OnGameModeInit()
{
MyMenu = CreateMenu("Ornek Menu", 1, 50.0, 180.0, 200.0, 200.0);
AddMenuItem(MyMenu, 0, "Oge 1");
AddMenuItem(MyMenu, 0, "Oge 2");
return 1;
}
public OnPlayerSelectedMenuRow(playerid, row)
{
if (GetPlayerMenu(playerid) == MyMenu)
{
switch(row)
{
case 0: print("Oge 1 secildi.");
case 1: print("Oge 2 secildi.");
}
}
return 1;
}
```
## Notlar
:::tip
Menü ID'si bu fonksiyona aktarılmaz. GetPlayerMenu, oyuncunun hangi menüde bir öğe seçtiğini belirlemek için kullanılmalıdır.
:::
## Bağlantılı Fonksiyonlar
- [CreateMenu](../functions/CreateMenu): Menü oluşturma.
- [DestroyMenu](../functions/DestroyMenu): Menü silme.
- [AddMenuItem](../functions/AddMenuItem): Belirtilen menüye öğe ekleme.
- [ShowMenuForPlayer](../functions/ShowMenuForPlayer): Oyuncu için menü gösterme.
- [HideMenuForPlayer](../functions/HideMenuForPlayer): Oyuncu için menü gizleme.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerSelectedMenuRow.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerSelectedMenuRow.md",
"repo_id": "openmultiplayer",
"token_count": 800
} | 461 |
---
title: OnVehiclePaintjob
description: Fonksiyon, oyuncu bulunduğu araca kaplama uygulandığında çağrılır.
tags: ["vehicle"]
---
## Açıklama
Fonksiyon, oyuncu bulunduğu araca kaplama uygulandığında çağrılır. Dikkat edin, bu fonksiyon kişi kaplamayı satın aldığında çağrılmaz.
| Parametre | Açıklama |
| ---------- | ---------------------------------------------------------------- |
| playerid | Aracına kaplama uygulayan oyuncunun ID'si. |
| vehicleid | Oyuncunun kaplama uyguladığı aracın ID'si. |
| paintjobid | Araca uygulanan kaplamanın ID'si. |
## Çalışınca Vereceği Sonuçlar
Oyun modunda her zaman ilk olarak çağrılır, bu nedenle 0 döndürülürse diğer filterscriptleri görmesi engellenir.
## Örnekler
```c
public OnVehiclePaintjob(playerid, vehicleid, paintjobid)
{
new string[128];
format(string, sizeof(string), "Araca %d numaralı kaplama uygulandı!", paintjobid);
SendClientMessage(playerid, 0x33AA33AA, string);
return 1;
}
```
## Notlar
:::tip
Bu fonksiyon ChangeVehiclePaintjob tarafından çağrılmaz. Oyuncunun kaplamayı ne zaman satın aldığını kontrol etmek için vSync'nin OnVehicleChangePaintjob'ını kullanabilirsiniz.
:::
## Bağlantılı Fonksiyonlar
- [ChangeVehiclePaintjob](../functions/ChangeVehiclePaintjob): Aracın kaplamasını değiştirme.
- [ChangeVehicleColor](../functions/ChangeVehicleColor): Aracın rengini değiştirme.
- [OnVehicleRespray](OnVehicleRespray): Bu fonksiyon, bir araç respray noktasından çıkış yaptığında çağrılır.
- [OnVehicleMod](OnVehicleMod): Bu fonksiyon, bir araç modifiye edildiğinde çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehiclePaintjob.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehiclePaintjob.md",
"repo_id": "openmultiplayer",
"token_count": 848
} | 462 |
---
title: AddVehicleComponent
description: Girilen araç idsine modifikasyon yapar.
tags: []
---
## Açıklama
Girilen araç ID'sine uygun şekilde modifikasyon yapmanızı sağlar.
| İsim | Açıklama |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| vehicleid | modifikasyon yapılacak aracın ID'si. |
| [componentid](../resources/carcomponentid) | araca yapılacak modifikasyon ID'si. |
## Çalışınca Vereceği Sonuçlar
1: Modifikasyon başarıyla araca yüklendi.
0: Modifikasyon yapılamadı çünkü böyle bir araç yok.
## Örnekler
```c
new gTaxi;
public OnGameModeInit()
{
gTaxi = AddStaticVehicle(420, -2482.4937, 2242.3936, 4.6225, 179.3656, 6, 1); // Taksi ekliyoruz
return 1;
}
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
if (newstate == PLAYER_STATE_DRIVER && oldstate == PLAYER_STATE_ONFOOT)
{
if (GetPlayerVehicleID(playerid) == gTaxi)
{
AddVehicleComponent(gTaxi, 1010); // Nitronun ID'sini (1010) kullanarak taksiye ekliyoruz
SendClientMessage(playerid, 0xFFFFFFAA, "Taksiye nitro eklendi.");
}
}
return 1;
}
```
## Notlar
:::warning
Yanlış modifikasyon ID'si kullanmak bölgedeki oyuncuların oyununun çökmesine neden olabilir ve bunu kontrol edemezsiniz.
:::
## Bağlantılı Fonksiyonlar
- [RemoveVehicleComponent](RemoveVehicleComponent.md): Araçtan bir modifikasyon silin.
- [GetVehicleComponentInSlot](GetVehicleComponentInSlot.md): Slottaki araç modifikasyonunu öğrenin.
- [GetVehicleComponentType](GetVehicleComponentType:.md): Aracın modifikasyon tipini öğrenin.
- [OnVehicleMod](../callbacks/OnVehicleMod.md): Bu callback araç modifiye edildiğinde çağrılır.
- [OnEnterExitModShop](../callbacks/OnEnterExitModShop.md): Bu callback bir araç modifiye noktasına girdiğinde/çıktığında çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/AddVehicleComponent.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AddVehicleComponent.md",
"repo_id": "openmultiplayer",
"token_count": 1126
} | 463 |
---
title: BlockIpAddress
description: IP adresini sunucu üzerinden bloklama. (with wildcards allowed).
tags: []
---
## Açıklama
IP adresini sunucudan bloklar. Belirtilen oyuncu girmeye çalıştığında sunucudan bloklandığına dair mesaj alır ve giremez. Belirtilen IP'ye sahip birisi eğer sunucu üzerinde aktifse bir kaç saniye içerisinde yasaklanır ve zaman aşımına uğrar, bir süre sonra tekrar girmeye çalıştığında yasaklandığına dair mesaj alır ve sunucuyla bağlantı kuramaz.
| Parametre | Açıklama |
| ---------- | ---------------------------------------------------------------------------------------------------------- |
| ip_address | Bloklanacak IP adresi. |
| timems | IP'nin engelleneceği süre (milisaniye cinsinden). 0, belirsiz bir süre için kullanılabilir. |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon herhangi bir değer döndürmez.
## Örnekler
```c
public OnRconLoginAttempt(ip[], password[], success)
{
if (!success) // Oyuncu eğer RCON girişi sırasında hatalı RCON parolası girerse...
{
BlockIpAddress(ip, 60 * 1000); // Hatalı RCON parolası giren oyuncu 1 dakikalığına bloklanır.
}
return 1;
}
```
## Notlar
:::tip
Joker karakterler bu fonksiyonla kullanılabilir, örneğin '6.9 ._._' IP'sinin engellenmesi, ilk iki sekizlinin sırasıyla 6 ve 9 olduğu tüm IP'leri engeller. Yıldız işareti yerine herhangi bir sayı olabilir.
:::
## Bağlantılı Fonksiyonlar
- [UnBlockIpAddress](UnBlockIpAddress): Bloklanmış bir IP'nin bloklanmasını kaldırma.
- [OnIncomingConnection](../callbacks/OnIncomingConnection): Bu fonksiyon, bir oyuncu sunucuya bağlanmaya çalışırken çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/BlockIpAddress.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/BlockIpAddress.md",
"repo_id": "openmultiplayer",
"token_count": 915
} | 464 |
---
title: GetActorHealth
description: Aktörün can değerini kontrol etme.
tags: ["actor"]
---
<VersionWarnTR version='SA-MP 0.3.7' />
## Açıklama
Aktörün can değerini çekin.
| Parametre | Açıklama |
| ------------- | ------------------------------------------------------------------------------- |
| actorid | Can değeri çekilecek aktörün ID'si. |
| &Float:health | Aktörün can değerini koruma amaçlı girilen bir float değişkeni. |
## Çalışınca Vereceği Sonuçlar
1 - Fonksiyon başarıyla çalıştı.
0 - Fonksiyon çalışmadı. (Girilen ID'ye sahip aktör yok/oluşturulmamış.)
NOTE: Aktörün can değeri dönüş değerinde değil, oluşturulan float değişkeninde saklanır.
## Örnekler
```c
new gMyActor;
public OnGameModeInit()
{
gMyActor = CreateActor(179, 316.1, -134.0, 999.6, 90.0); // Ammunation üzerinde aktörümüzü oluşturuyoruz.
SetActorHealth(gMyActor, 100); // Oluşturduğumuz aktörün can değerini 100 yapıyoruz.
new Float:actorHealth; // Aktörün can değerinin saklanması için yeni bir float değişkeni oluşturuyoruz.
GetActorHealth(gMyActor, actorHealth); // Oluşturduğumuz float değişkeniyle aktörümüzün can değerini çekiyoruz.
printf("%d ID'li aktörün %.2f canı var.", gMyActor, actorHealth); // Kontrol amaçlı debug oluşturuyoruz.
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [CreateActor](CreateActor): Aktör oluşturma (statik NPC).
- [SetActorHealth](SetActorHealth): Aktörün can değerini düzenleme.
- [SetActorInvulnerable](SetActorInvulnerable): Aktörün dokunulmazlığını düzenleme.
- [IsActorInvulnerable](IsActorInvulnerable): Aktörün dokunulmazlığını kontrol etme.
| openmultiplayer/web/docs/translations/tr/scripting/functions/GetActorHealth.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/GetActorHealth.md",
"repo_id": "openmultiplayer",
"token_count": 860
} | 465 |
---
title: "Scripting: Etiketler (Tags)"
description: Etiketlerin, Pawn dilinde farklı niyet değerleriyle çalışmak için güvenlik özellikleri sağlayan bir tür özellik olduğu bir rehber.
---
## Giriş
Bir etiket, değişkenin belirli durumlar altında özel olarak işlenmesini sağlayan bir önektir. Örneğin, bir değişkenin nerede kullanılabileceğini veya kullanılamayacağını veya iki değişkeni özel bir şekilde birleştirmenin bir yolunu tanımlamak için etiketleri kullanabilirsiniz.
İki türde etiket vardır - güçlü etiketler (büyük harfle başlar) ve zayıf etiketler (küçük harfle başlar), çoğunlukla aynı olsalar da bazı durumlarda zayıf etiketler, derleyici tarafından sessizce etiketsiz bir şekilde dönüştürülebilir, yani bir uyarı almayabilirsiniz; çoğu zaman zayıf etiketlerle, güçlü etiketlerle her zaman etiketin bilinçsiz bir şekilde değiştirilmesi bir uyarıya neden olacaktır ve bu, verinin muhtemelen yanlış kullanıldığını belirten bir uyarıdır.
Aşağıda çok basit bir örnek bulunmaktadır:
```c
new
File:myfile = fopen("file.txt", io_read);
myFile += 4;
```
`fopen` fonksiyonu, `File:` türündeki bir etiketle bir değer döndürecektir; bu satırda bir sorun yoktur çünkü dönüş değeri, aynı zamanda `File:` etiketine sahip bir değişkene depolanmaktadır (unutulmamalıdır ki durumlar da aynıdır). Ancak, bir sonraki satırda `4` değeri dosya işaretine eklenir. `4`'ün bir etiketi yoktur (aslında `_:` etiket türüdür, ancak etiketi olmayan değişkenler, değerler ve fonksiyonlar otomatik olarak buna ayarlanır ve genellikle endişelenmeniz gerekmez), ve `myFile`'ın bir `File:` etiketi vardır, açıkçası hiçbir şey ve bir şey aynı olamaz, bu nedenle derleyici bir uyarı verecektir; bu, bir dosyanın işaretinin aslında değeri açısından anlamsız olduğu ve değiştirilirse yalnızca işareti yok edeceği ve dosyanın kapatılması için artık geçerli bir işaretin olmadığı anlamına gelir.
### Güçlü Etiketler
Yukarıda belirtildiği gibi, güçlü bir etiket büyük harfle başlayan herhangi bir etikettir. SA:MP içinde bunlara örnekler şunlardır:
```c
Float:
File:
Text:
```
Bu, diğer değişken türleriyle karıştırılamaz ve her zaman böyle bir şey yapmaya çalıştığınızda bir uyarı verecektir:
```c
new
Float:myFloat,
File:myFile,
myBlank;
myFile = fopen("file.txt", io_read); // File: = File:, uyarı yok
myFloat = myFile; // Float: = File:, "etiket uyumsuzluğu" uyarısı
myFloat = 4; // Float: = _: (hiçbiri), "etiket uyumsuzluğu" uyarısı
myBlank = myFloat; // _: (hiçbiri) = Float:, "etiket uyumsuzluğu" uyarısı
```
### Zayıf Etiketler
Zayıf bir etiket çoğunlukla güçlü bir etiket gibi davranır; ancak, derleyici zayıf etiketli bir kaynağa etiketsiz bir hedef verildiğinde uyarı vermeyecektir. Örneğin, aşağıdaki güçlü ve zayıf etiketli kodları karşılaştırın, ilk güçlü etiketle uyarı verecek, ikinci zayıf etiketle uyarı vermeyecektir:
```c
new
Strong:myStrong,
weak:myWeak,
myNone;
myNone = myStrong; // Uyarı
myNone = myWeak; // Uyarı yok
```
Ancak, tersi doğru değildir:
```c
myWeak = myNone; // Uyarı
```
Bu, fonksiyonlarla da aynıdır; zayıf etiketli bir değişken geçirildiğinde, etiketsiz bir parametre uyarı vermeyecektir:
```c
new
weak:myWeak;
MyFunction(myWeak);
MyFunction(myVar)
{
// ...
}
```
Ancak, etiketli bir parametre (zayıf veya güçlü) ile bir fonksiyon çağrılırken, etiketsiz bir parametre geçirmek uyarı verecektir. SA:MP'deki zayıf etiket örnekleri genellikle pek bilinmese de sıklıkla kullanılır ve şunları içerir:
```c
bool:
filemode:
floatround_method:
```
## Kullanım
### Deklare Etme
Bir değişkeni bir etiketle tanımlamak çok basittir, sadece etiketi yazın, önceden bir etiketi tanımlamak gerekmez ancak bu mümkündür ve ilerleyen zamanlarda neden önemli olduğu anlaşılacaktır:
```c
new
Mytag:myVariable;
```
Bir değişkeni var olan etiketlerden biriyle tanımlamak, bu değişkeni zaten o etiket türü için yazılmış olan işlevler ve operatörlerle kullanmanıza olanak tanır.
### Fonksiyonlar
Bir etiketi almak veya bir etiketle dönmek için bir işlev oluşturmak çok basittir, sadece ilgili bölümü istenen etiket türüyle önce ekleyin, örneğin:
```c
Float:GetValue(File:fHnd, const name[])
{
// ...
}
```
Bu işlev, bir dosya işaretçisini alır ve bir float değeri döndürür (muhtemelen bir dosyadan okunan ve `name[]` içinde iletilen değere karşılık gelen bir değer). Bu işlev muhtemelen `floatstr` işlevini kullanacaktır, ki bu da bir dize alındıktan sonra Float: döndürür (sağ taraftaki işlev listesinde işlevin üzerine tıkladığınızda pawno'nun durum çubuğundan anlayabileceğiniz gibi), bir IEEE float değerini temsil eden bir dizeyi alır. Bu değer ardından bir hücre olarak depolanır (aslında PAWN tip yok sayma olduğu için sadece ilgili IEEE sayısına sahip aynı bit deseni olan bir tamsayı olarak depolanır, ancak bununla kısmen mücadele etmek için etiketler vardır).
### Operatörler
`+`, `==`, `>` gibi operatörler, farklı etiket türleri için aşırı yüklenebilir; yani iki Float: üzerinde `+` yapmak, iki etiketsiz değişken üzerinde yapmaktan farklı bir şey yapar. Bu özellik, özellikle float değişkenleri için önemlidir çünkü yukarıda belirtildiği gibi bunlar gerçekte birer float değildir, bunlar çok özel bir bit desenine sahip tamsayılardır. Operatörler aşırı yüklenmemiş olsaydı, operasyonlar basitçe tamsayılarda gerçekleştirilirdi ve yanıt bir float olarak yeniden yorumlandığında anlamsız olurdu. Bu nedenle, Float: etiketi, matematiği PAWN'da değil, sunucuda yapacak özel versiyonlarına sahiptir.
Bir operatör, normal bir işlev gibi aynıdır, ancak bir işlev adı yerine "**operator(sembol)**" ifadesini kullanırsınız, burada (**sembol**), üzerine yazmak istediğiniz operatördür. Geçerli operatörler şunlardır:
```c
+
-
=
++
--
==
*
/
!=
>
<
>=
<=
!
%
```
`\`, `*`, `=` gibi şeyler otomatik olarak yapılır. `&` gibi şeyler aşırı yüklenemez. Bir operatörü farklı etiket kombinasyonlarıyla birden çok kez aşırı yükleyebilirsiniz. Örneğin:
```c
stock Float:operator=(Mytag:oper)
{
return float(_:oper);
}
```
Yukarıdaki kodu eklerseniz ve şunu yaparsanız:
```c
new
Float:myFloat,
Mytag:myTag;
myFloat = myTag;
```
Artık uyarı almayacaksınız, çünkü `=` operatörü için `Float: = Mytag:` durumu artık işleniyor, bu da derleyicinin tam olarak ne yapması gerektiğini bilmesi demektir.
### Üzerine Yazma
Yukarıda aşırı yükleme örneğinde işlevsel satır şuydu:
```c
return float(_:oper);
```
Bu, etiket üzerine yazma örneğidir; oper önünde "_:" ifadesi, derleyicinin oper'in Mytag: etiketine sahip olduğunu görmezden gelmesi ve bunun yerine on
u _:(yani hiç etiket) etiketi olarak ele alması anlamına gelir. `float()` fonksiyonu bir normal sayıyı etiketler, bu nedenle ona bir tane göndermek zorundadır. Bu örnekte, `Mytag`'in normal bir tamsayı sakladığı varsayılır, ancak üzerine yazma çok dikkatlice ele alınmalıdır, örneğin aşağıdaki garip sonuçları verecektir:
```c
new
Float:f1,
Float:f2 = 4.0;
f1 = float(_:f2);
```
Mantık, `f1`'in `4.0` olarak sona ereceği yönündedir, ancak öyle olmaz. Yukarıda belirtildiği gibi, f2, `4` olarak bir tamsayıyı değil, `4.0`'ı temsil eden bir biçime sahiptir, bu da değişkenin aslında bir tamsayı olarak çok tuhaf bir sayı olduğu anlamına gelir. Dolayısıyla, derleyiciye değişkeni bir tamsayı gibi işlemesini söylüyorsanız, değişkenin içindeki bit desenini sadece değer olarak alacak, float'i bir tamsayıya dönüştürmeyecek, bu nedenle neredeyse rastgele bir sayı alacaksınız (IEEE kayan noktalı sayılara belirli bir model olduğu için aslında rastgele değildir, ancak `4.0` gibi değildir).
| openmultiplayer/web/docs/translations/tr/scripting/language/Tags.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/language/Tags.md",
"repo_id": "openmultiplayer",
"token_count": 3797
} | 466 |
---
title: OnIncomingConnection
description: 当IP地址尝试连接到服务器时,将调用这个回调函数。要阻止传入的连接,使用BlockIpAddress函数。
tags: []
---
## 描述
当 IP 地址尝试连接到服务器时,将调用这个回调函数。要阻止传入的连接,请使用 BlockIpAddress 函数。
| 参数名 | 描述 |
| ------------ | ------------------------ |
| playerid | 试图连接的玩家的 ID |
| ip_address[] | 试图连接的玩家的 IP 地址 |
| port | 试图连接的端口 |
## 返回值
1 - 将阻止其他过滤脚本接收到这个回调。
0 - 表示这个回调函数将被传递给下一个过滤脚本。
它在过滤脚本中总是先被调用。
## 案例
```c
public OnIncomingConnection(playerid, ip_address[], port)
{
printf("传入的连接为玩家ID %i [IP/port: %s:%i]", playerid, ip_address, port);
return 1;
}
```
## 相关函数
- [BlockIpAddress](../functions/BlockIpAddress): 在一定时间内阻止一个 IP 地址连接到服务器。
- [UnBlockIpAddress](../functions/UnBlockIpAddress): 解除先前阻止的 IP。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnIncomingConnection.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnIncomingConnection.md",
"repo_id": "openmultiplayer",
"token_count": 689
} | 467 |
---
title: OnPlayerDisconnect
description: 当玩家从服务器断开连接时,这个回调函数被调用。
tags: ["player"]
---
## 描述
当玩家从服务器断开连接时,这个回调函数被调用。
| 参数名 | 描述 |
| -------- | ------------------------------- |
| playerid | 从服务器断开连接的该玩家的 ID。 |
| reason | 断开连接的原因。见下表。 |
## 返回值
0 - 将阻止其他过滤脚本接收到这个回调。
1 - 表示这个回调函数将被传递给下一个过滤脚本。
它在过滤脚本中总是先被调用。
## 案例
```c
public OnPlayerDisconnect(playerid, reason)
{
new
szString[64],
playerName[MAX_PLAYER_NAME];
GetPlayerName(playerid, playerName, MAX_PLAYER_NAME);
new szDisconnectReason[3][] =
{
"超时/崩溃",
"正常退出",
"踢出/封禁"
};
format(szString, sizeof szString, "%s 离开了服务器 (%s).", playerName, szDisconnectReason[reason]);
SendClientMessageToAll(0xC4C4C4FF, szString);
return 1;
}
```
## 要点
:::tip
有些函数不能在这个回调函数中使用,因为当调用回调函数时,玩家已经断开了连接。这样,您就不能从诸如 GetPlayerIp 和 GetPlayerPos 等类似的函数得到明确的信息。
:::
## 相关回调
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerDisconnect.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerDisconnect.md",
"repo_id": "openmultiplayer",
"token_count": 823
} | 468 |
---
title: OnPlayerPickUpPickup
description: 当玩家拿到通过拾取器创建的拾取时调用。
tags: ["player"]
---
## 描述
当玩家拿到通过拾取器创建的拾取时调用。
| 参数名 | 描述 |
| -------- | --------------------------------- |
| playerid | 拿到拾取信息的玩家的 ID。 |
| pickupid | 拿到的 ID,由 CreatePickup 返回。 |
## 返回值
它在游戏模式中总是先被调用。
## 案例
```c
new pickup_Cash;
new pickup_Health;
public OnGameModeInit()
{
pickup_Cash = CreatePickup(1274, 2, 0.0, 0.0, 9.0);
pickup_Health = CreatePickup(1240, 2, 0.0, 0.0, 9.0);
return 1;
}
public OnPlayerPickUpPickup(playerid, pickupid)
{
if (pickupid == pickup_Cash)
{
GivePlayerMoney(playerid, 1000);
}
else if (pickupid == pickup_Health)
{
SetPlayerHealth(playerid, 100.0);
}
return 1;
}
```
## 相关函数
- [CreatePickup](../functions/CreatePickup): 创建一个拾取。
- [DestroyPickup](../functions/DestroyPickup): 销毁一个拾取。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerPickUpPickup.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerPickUpPickup.md",
"repo_id": "openmultiplayer",
"token_count": 567
} | 469 |
---
title: OnRecordingPlaybackEnd
description: 当使用NPC:StartRecordingPlayback复制的录制文件到达其末尾时,将调用此回调。
tags: []
---
:::warning
:::
## 描述
当使用 NPC:StartRecordingPlayback 复制的录制文件到达其末尾时,将调用此回调。
## 案例
```c
public OnRecordingPlaybackEnd()
{
StartRecordingPlayback(PLAYER_RECORDING_TYPE_DRIVER, "all_around_lv_bus"); //这将在录制的文件完成复制后再次启动。
}
```
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnRecordingPlaybackEnd.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnRecordingPlaybackEnd.md",
"repo_id": "openmultiplayer",
"token_count": 247
} | 470 |
---
title: AddSimpleModel
description: 添加新的自定义简单物体模型以供下载。
tags: []
---
<VersionWarnCN version='SA-MP 0.3.DL R1' />
## 描述
添加新的自定义简单物体模型以供下载。模型文件将以 .CRC 格式存储在玩家的 Documents\GTA San Andreas User Files\SAMP\cache 的服务器 IP 和端口的文件夹中。
| 参数名 | 说明 |
| ------------ | -------------------------------------------------------------------------------------------------------------- |
| virtualworld | 使模型可用的虚拟世界 ID。使用-1 表示所有世界。 |
| baseid | 要使用的基本物体模型 ID(下载失败时使用的原始物体)。 |
| newid | 新的物体模型 ID,范围从-1000 到-30000(共 29000 个插槽),稍后将与 CreateObject 或 CreatePlayerObject 一起使用。 |
| dffname | 默认情况下位于服务器的 models 文件夹下的 .dff 模型碰撞文件的名称(artpath 设置)。 |
| txdname | 默认情况下位于服务器的 models 文件夹下的 .txd 模型纹理文件的名称(artpath 设置)。 |
## 返回值
1:函数执行成功。
0:函数执行失败。
## 案例
```c
public OnGameModeInit()
{
AddSimpleModel(-1, 19379, -2000, "wallzzz.dff", "wallzzz.txd");
return 1;
}
```
```c
AddSimpleModel(-1, 19379, -2000, "wallzzz.dff", "wallzzz.txd");
```
## 要点
:::tip
必须首先在服务器设置中启用`useartwork`,这样才能在设置虚拟世界时工作,一旦玩家进入特定的世界,模型就会被下载
:::
:::warning
目前还没有限制何时可以调用这个函数,但请注意,如果你没有在 OnFilterScriptInit/OnGameModeInit 中调用它们,你就会面临一些已经在服务器上的玩家可能没有下载模型的风险。
:::
## 相关函数
- [OnPlayerFinishedDownloading](../callbacks/OnPlayerFinishedDownloading): 当玩家下载完成自定义模型时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddSimpleModel.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddSimpleModel.md",
"repo_id": "openmultiplayer",
"token_count": 1407
} | 471 |
---
title: BanEx
description: 以某个原因封禁玩家。
tags: ["管理员"]
---
## 描述
以某个原因封禁玩家。
| 参数名 | 说明 |
| -------- | ----------------- |
| playerid | 要封禁的玩家 ID。 |
| reason | 要封禁的原因。 |
## 返回值
该函数不返回任何特定的值。
## 案例
```c
public OnPlayerCommandText( playerid, cmdtext[] )
{
if (!strcmp(cmdtext, "/banme", true))
{
// 封禁执行此命令的玩家,并包括一个理由("请求")。
BanEx(playerid, "请求");
return 1;
}
}
/*为了在连接关闭前为玩家显示一个信息(例如原因),你必须使用一个计时器来创建一个延迟,这个延迟只需要几毫秒的时间。
这里的案例为了安全起见,延迟了整整一秒钟。*/
forward BanExPublic(playerid, reason[]);
public BanExPublic(playerid, reason[])
{
BanEx(playerid, reason);
}
stock BanExWithMessage(playerid, color, message[], reason[])
{
// reason - 用于BanEx的封禁原因。
SendClientMessage(playerid, color, message);
SetTimerEx("BanExPublic", 1000, false, "ds", playerid, reason);
}
public OnPlayerCommandText(playerid, cmdtext[])
{
if (strcmp(cmdtext, "/banme", true) == 0)
{
// 封禁执行此命令的玩家。
BanExWithMessage(playerid, 0xFF0000FF, "你被封禁了!", "请求");
return 1;
}
return 0;
}
```
## 要点
:::warning
从 SA-MP 0.3x 开始,在 BanEx() 之前的任何发送给玩家的代码(比如用 SendClientMessage 发送消息)都不会送达给玩家。必须使用计时器来延迟封禁玩家。
:::
## 相关函数
- [Ban](Ban): 封禁目前在服务器中的某个玩家。
- [Kick](Kick): 将玩家踢出服务器。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/BanEx.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/BanEx.md",
"repo_id": "openmultiplayer",
"token_count": 1036
} | 472 |
---
title: InterpolateCameraPos
description: 在设定的时间内,将玩家的视角从一个位置移动到另一个位置。
tags: []
---
## 描述
在设定的时间内,将玩家的视角从一个位置移动到另一个位置。
| 参数名 | 说明 |
| ----------- | ----------------------------------------------------------------------------------------------------- |
| playerid | 需要移动视角的玩家 ID |
| Float:FromX | 视角开始移动的 X 坐标 |
| Float:FromY | 视角开始移动的 Y 坐标 |
| Float:FromZ | 视角开始移动的 Z 坐标 |
| Float:ToX | 视角停止移动的 X 坐标 |
| Float:ToY | 视角停止移动的 Y 坐标 |
| Float:ToZ | 视角停止移动的 Z 坐标 |
| time | 以毫秒为单位的时间 |
| cut | 要使用的[跳切](./resources/cameracutstyles)。默认为 CAMERA_CUT。设置为 CAMERA_MOVE 以获得平滑的运动。 |
## 返回值
该函数不返回任何特定的值。
## 案例
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/moveme", true))
{
TogglePlayerSpectating(playerid, 1);
InterpolateCameraPos(playerid, 0.0, 0.0, 10.0, 1000.0, 1000.0, 30.0, 10000, CAMERA_MOVE);
// 在10000毫秒(10秒)内将玩家的视角从A点移动到B点。
return 1;
}
return 0;
}
```
## 要点
:::tip
使用 TogglePlayerSpectating 来使物体在视角移动时为玩家流入,并移除玩家的 HUD。可以用 SetCameraBehindPlayer 将玩家的视角重置到身后。
:::
## 相关函数
- [InterpolateCameraLookAt](InterpolateCameraLookAt): 在设定的时间内,将玩家视角的朝向从一个位置移动到另一个位置。
- [SetPlayerCameraPos](SetPlayerCameraPos): 设置玩家的视角位置。
- [SetPlayerCameraLookAt](SetPlayerCameraLookAt): 设置玩家的视角所看的方向。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/InterpolateCameraPos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/InterpolateCameraPos.md",
"repo_id": "openmultiplayer",
"token_count": 1790
} | 473 |
---
title: "控制服务器"
description: 用于控制服务器的十分有效的命令.
---
## 更改游戏模式
### 运行自定义/下载的游戏模式
- 打开您安装服务器的目录 (例如:/Rockstar Games/GTA San Andreas/server)
- 获取下载/编译的 .amx 文件并将其放在服务器的 gamemodes 文件夹中
- 使用 RCON 更改模式,如上所述 (2.1)
- 或者,您可以将新模式添加到循环中,也如上所述(2.3)
### 使用脚本
与运行自定义游戏模式相同,除了:
- 将 .amx 放在名为`filterscripts`的文件夹中
- 将以下内容添加到 server.cfg: `filterscripts <脚本名称>`
## 为您的服务器设置密码
- 如果您想添加密码以便只有您的朋友可以加入,请将其添加到 [server.cfg](server.cfg):
```
password 任意密码
```
- 这将使您的服务器受到密码保护,密码可以设置为任意内容。
- 您也可以在游戏中更改密码,使用`/rcon password 新密码`
- 您可以使用`/rcon password 0` 或通过重新启动服务器来删除密码
## 使用 RCON
### 登录
您可以在游戏中通过输入`/rcon login password` 登录,也可以在 [Remote Console](RemoteConsole) 中使用RCON 模式退出。
密码与您在 [server.cfg](server.cfg) 中设置的密码相同
### 添加封禁
##### samp.ban
samp.ban 是用于存储封禁信息的文件,包括有关封禁的以下信息:
- IP
- 日期
- 时间
- 游戏名 (玩家的游戏名或者封禁原因, 详细请查看 [BanEx](../../functions/BanEx))
- 封禁类型 (游戏内,IP封禁等等)
如果要添加禁令,只需像这样添加一行:
```
IP_HERE [28/05/09 | 13:37:00] PLAYER - BAN REASON
```
`IP_HERE` 写入您要封锁的IP地址
##### Ban() 函数
[Ban](../scripting/functions/Ban) 函数可用于禁止玩家进入脚本。 [BanEx](../scripting/functions/BanEx) 函数将添加一个可选原因,如下所示:
```
13.37.13.37 [28/05/09 | 13:37:00] Cheater - INGAME BAN
```
##### RCON 封禁命令
通过在游戏中输入 /rcon ban 或在控制台中输入“ban”来执行 RCON ban 命令,用于封禁您服务器上的特定玩家,封禁 IP 参见下一节。
只需输入:
```
# 游戏内:
/rcon ban 玩家ID
# 控制台:
ban 玩家ID
```
##### banip
RCON banip命令,通过在游戏中输入/ RCON banip 或在控制台中输入“banip”来执行,用于封禁特定的IP地址,通过ID禁止服务器上的玩家,参见前一节。将接受范围限制通配符。
只需输入:
```
# 游戏内:
/rcon banip IP
# 控制台:
banip IP
```
### 取消封禁
一旦某个玩家被封禁,有两种方法可以解除他们的封禁。
- 从 samp.ban 中移出
- RCON `unbanip`命令
#### samp.ban
samp.ban 可以在您的 sa-mp 服务器目录中找到,它包含有关每个封禁的以下信息:
- IP
- 日期
- 时间
- 游戏名 (玩家的游戏名或者封禁原因, 详细请查看 [BanEx](../../functions/BanEx))
- 封禁类型 (游戏内,IP封禁等等)
例如:
```
127.8.57.32 [13/06/09 | 69:69:69] NONE - IP BAN
13.37.13.37 [28/05/09 | 13:37:00] Kyeman - INGAME BAN
```
要解封他们,只需删除该行,然后执行 RCON reloadbans 命令使服务器重新读取 samp.ban。
#### unbanip
RCON unbnip 命令可以在游戏中使用,也可以从服务器控制台(黑框窗口)使用。 要解封某个 IP,只需在游戏中输入 `/rcon unbanip IP_HERE` 或在控制台中输入 `unbanip IP_HERE`。
例如:
```
13.37.13.37 [28/05/09 | 13:37:00] Kyeman - INGAME BAN
```
```
# 游戏内:
/rcon unbanip 13.37.13.37
# 控制台
unbanip 13.37.13.37
```
要解封他们,只需使用 `unbanip` 命令,然后执行 RCON `reloadbans` 命令使服务器重新读取 samp.ban。
#### reloadbans
`samp.ban` 是一个文件,其中包含当前被服务器封禁的 IP 的信息。 这个文件在服务器启动时被读取,所以如果你解禁一个 IP/玩家,你必须输入 RCON `reloadbans` 命令让服务器再次读取 `samp.ban` 从而允许他们加入服务器。
### RCON Commands
使用游戏中的 RCON (`/rcon cmdlist`) 为命令输入 cmdlist(或为变量输入 varlist)。
这些是您作为管理员可以使用的功能:
| 命令 | 描述 |
| --------------------------------- | ------------------------------------------------------------ |
| `/rcon cmdlist` | 显示命令列表。 |
| `/rcon varlist` | 显示包含当前变量的列表。 |
| `/rcon exit` | 关闭服务器. |
| `/rcon echo [text]` | 在服务器控制台(不是游戏中的公屏)中显示“[text]”。 |
| `/rcon hostname [name]` | 更改主机名文本(例如:/rcon hostname my server)。 |
| `/rcon gamemodetext [name]` | 更改游戏模式文本(_例如:/rcon gamemodetext my gamemode_)。 |
| `/rcon mapname [name]` | 更改地图名称文本(例如:/rcon mapname San Andreas)。 |
| `/rcon exec [filename]` | 执行包含服务器 cfg 的文件(例如:/rcon exec blah.cfg_)。 |
| `/rcon kick [ID]` | 踢出指定 ID 的玩家(_例如: /rcon kick 2_)。 |
| `/rcon ban [ID]` | 封禁指定 ID 的玩家(_例如:/rcon ban 2_)。 |
| `/rcon changemode [mode]` | 此命令会将当前游戏模式更改指定模式(_例如:如果您想玩 sftdm:/rcon changemode sftdm_)。 |
| `/rcon gmx` | 将在 [server.cfg](server.cfg) 中加载下一个游戏模式。 |
| `/rcon reloadbans` | 重新加载存储被禁止 IP 地址的 `samp.ban` 文件。 应该在解封玩家后使用。 |
| `/rcon reloadlog` | 重新加载“server_log.txt”。 对于自动日志轮换很有用。 可以通过向服务器发送 `SIGUSR1` 信号来触发(仅限 Linux 服务器)。 |
| `/rcon say` | 在游戏内公屏中向玩家显示一条消息(例如:`/rcon say hello` 将显示为 `Admin: hello`)。 |
| `/rcon players` | 显示服务器中的玩家(包括他们的游戏名、IP 和 ping)。 |
| `/rcon banip [IP]` | 封禁指定 IP(_例如:/rcon banip 127.0.0.1_)。 |
| `/rcon unbanip [IP]` | 解封指定 IP(_例如:/rcon unbanip 127.0.0.1_)。 |
| `/rcon gravity` | 更改重力(_例如:/rcon gravity 0.008_)。 |
| `/rcon weather [ID]` | 更改天气(_例如:/rcon weather 1_)。 |
| `/rcon loadfs` | 加载指定脚本(_例如:/rcon loadfs adminfs_)。 |
| `/rcon weburl [server url]` | 更改 SA-MP 客户端中显示的服务器 URL |
| `/rcon unloadfs` | 卸载指定脚本(_例如:/rcon unloadfs adminfs_)。 |
| `/rcon reloadfs` | 重新加载指定脚本(_例如:/rcon reloadfs adminfs_)。 |
| `/rcon rcon\_password [PASSWORD]` | 更改 rcon 的密码 |
| `/rcon password [password]` | 设置/重置服务器密码 |
| `/rcon messageslimit [count]` | 修改客户端每秒发送到服务器的最大消息数。 (默认 500) |
| `/rcon ackslimit [count]` | 更改 acks 的限制(默认 3000 |
| `/rcon messageholelimit [count]` | 更改消息洞的限制(默认 3000) |
| `/rcon playertimeout [limit m/s]` | 更改玩家超时时间。(以毫秒为单位,默认 1000) |
| `/rcon language [language]` | 更改服务器语言(_例如:/rcon language Chinese_)。 在服务器信息中显示。 |
上述四个限制只是为了避免一些工具攻击 SA-MP 服务器让服务器崩溃或无法进入。 因此,只需根据您的服务器设置它们即可。如果你看到任何玩家被误踢,只需尽快增加限制值,这样正常的玩家就不会被踢。 [在此处阅读更多内容](http://web-old.archive.org/web/20190426141744/https://forum.sa-mp.com/showpost.php?p=2990193&postcount=47)。
### 相关回调和函数
以下回调和函数可能很有用,因为它们以某种方式与本文相关。
#### 回调
- [OnRconLoginAttempt](../scripting/callbacks/OnRconLoginAttempt): 当尝试登录 RCON 时调用。
#### 函数
- [IsPlayerAdmin](../scripting/functions/IsPlayerAdmin): 检查玩家是否登录到 RCON。
- [SendRconCommand](../scripting/functions/SendRconCommand): 通过脚本发送 RCON 命令。
| openmultiplayer/web/docs/translations/zh-cn/server/ControllingServer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/server/ControllingServer.md",
"repo_id": "openmultiplayer",
"token_count": 5960
} | 474 |
---
title: Port Forwarding
description: Server port forwarding tutorial.
---
**Welcome to the Port Forward tutorial!**
So, you have arrived to the Port Forward tutorial, made by Leopard.
All you need is a samp-server or omp-server and a router. If you have not a router, then you don't need to port forward!
## The Start
Ok, so here's the start, start off by finding your **gateway**. Assume that you have vista. Click start, click on the search field, and write **cmd**. Then a black box appears. Enter the following; **ipconfig**. Wait for the text to load, then look though it. Keep searching until you find _**gateway**_, and don't close the black box!
When you have found it, open your favorite web browser. When it's loaded, head over to the adress bar and type in the _**gateway**_ value (example: 192.168.0.1/192.168.1.1). Press enter.
## Router Configuration
Well done, you've made it to the router's configuration page. What we've got left to do is port forward now.
So.. there are a category in that page that is named one of the followings;
- Virtual Server
- Port Forwarding
- Port Control
- Application Sharing
- Anything with `port` in its name.
If you have found it, click on it. Then, click the 'Add new', 'New Port' or some else button that will toggle opening a new port.
Enter the following details:
```
Port: YOUR_PORT (standard: 7777)
Port Type: UDP
Enabled: Yes
**IP: Continue the 3rd Step**
```
Now you need to know your computer IP address.
## Getting the IP, Continuing
Now, maximize the black box and look though the text again, until you see _IPv4_. It should be in a format like this: **192.168.0.100**. Copy it, and there you have it! Continue with the Information in the router's homepage. For example, my ip is 192.168.0.100
```
Port: YOUR_PORT (standard: 7777)
Port Type: UDP
Enabled: Yes
IP: 192.168.0.100
```
And press **save**. Then your done. AND! Don't forget to **port forward in Windows Firewall**. This is a little tutorial;
Go to the start menu, enter "firewall" in the search field and select the "Windows Firewall". Open it and click _Change preferences_. New window pop-up. Click the _Exceptions_ tab, click the _Add port.._ and then fill in this information;
```
Name: SA-MP Server (name it whatever you want)
Port Number: YOUR_PORT (standard: 7777)
Protocol: UDP
```
Then your done! Click ok and close it. Launch the server, and see if its working. If it is, go to your SA-MP Client and enter: localhost:YOUR_PORT(standard: 7777). If the ping changes, then your server is working fully. Now you just need to go to:
[WhatIsMyIP.COM](http://whatismyip.com).
## The finish
Once there, get the ip that is on your screen. Go again to your SA-MP Client, add that ip to your favorites and add YOUR_PORT (standard: 7777) at the end. If its working,
**CONGRATULATIONS**! _You have port-forwarded_!
| openmultiplayer/web/docs/tutorials/PortForwarding.md/0 | {
"file_path": "openmultiplayer/web/docs/tutorials/PortForwarding.md",
"repo_id": "openmultiplayer",
"token_count": 823
} | 475 |
---
title: 10,000 Članova!
date: "2021-07-16T02:51:00"
author: Potassium
---
Zdravo svima!
U skorije vrijeme smo stigli do jedne prekretnice: zvanično smo dostigli 10,000 članova na našem Discord serveru! 🥳🔟🥳
Mislili smo da ćemo iskoristiti ovu priliku da damo malo ažuriranje jer znamo da je prošlo dosta vremena i svi se pitaju šta se dešava!
Kako sav tim za razvojne programere ima poslove s punim radnim vremenom i druge obaveze, svi smo zaista bili zabrljani oko situacije s COVID-om. To znači da već neko vrijeme nismo imali puno vremena da se posvetimo open.mp.
Ali stvari su se nedavno ponovo pokrenule, još smo živi, projekat se zaista odvija brže nego ikad, a mi smo u posljednjih nekoliko sedmica napredovali više nego u dugo vremena!
Tako smo ponosni na rad koji je uložen u ovo, i na nevjerovatan profinjen tim koji imamo.
Detaljnije informacije ćemo dati u narednim mjesecima, ali samo smo htjeli biti sigurni da svi znaju da nismo napustili open.mp, strast je i dalje prisutna, a mi radimo najbolje što možemo. Stoga vas molimo da ostanete uz nas jer ćemo uskoro imati neke vijesti i neke snimke ekrana i video zapise!
U međuvremenu, dođite da se družite s nama na Discordu! Hvala za svih 10.000+ vas 🥰
Naš Discord server je toplo i gostoljubivo mjesto za igrače i prijatelje SVIH modova i zajednica za više igrača u San Andreasu! Neke od stvari koje promoviramo su:
✅ Zajednica: Družite se sa redovnim gostima, upoznajte nove ljude, pronađite stare prijatelje i veterane, pronađite ljude iz svoje zemlje/regiona na kanalima specifičnim za jezik, upoznajte ljude iz SA-MP / MTA / drugih modova za više igrača
✅ Skriptanje: Naučite da programirate (skriptate), zatražite pomoć, pomozite drugima
✅ Oglasi na serveru: Pokažite svoj SA-MP server na namjenskim kanalima
✅ Programiranje i tehnologija: Diskutujte i potražite pomoć oko drugih programskih jezika i razvoja softvera, tehničke podrške, upoznajte druge istomišljenike za rad
✅ Igre: Pronađite ljude s kojima ćete igrati igrice (ne samo SA!), razgovarajte o novostima o igrama i ažuriranjima
✅ Izlog: Jeste li YouTuber? Streamer? Umjetnik? Praviti cool muziku? Jeste li kuhar? Možda pecaš? Ili praviti automobile? Šta god da ste ponosni, pokažite to!
✅ open.mp: Budite u toku sa najnovijim razvojnim napretkom open.mp i GitHub pokretima, družite se sa timom, gledajte naše Discord VIP-ekskluzivne dev streamove kada se ponovo pokrenu!
| openmultiplayer/web/frontend/content/bs/blog/10k-members.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/bs/blog/10k-members.mdx",
"repo_id": "openmultiplayer",
"token_count": 1093
} | 476 |
# Open Multiplayer
Μια επερχόμενη λειτουργία για πολλους παικτες για το _Grand Theft Auto: San Andreas_ που θα είναι πλήρως συμβατή με την υπάρχον λειτουργία ονόματι _San Andreas Multiplayer._
<br />
Αυτό σημαίνει ότι ο **υπάρχων διαχειριστής SA:MP και όλα τα υπάρχοντα SA:MP scripts θα λειτουργούν με το open.mp** και, επιπλέον, πολλά bugs θα διορθωθούν επίσης μέσα στο λογισμικό διακομιστή χωρίς την ανάγκη για hacks και λύσεις.
Εάν αναρωτιέστε πότε προγραμματίζεται η δημόσια ελευθέρωση ή πώς μπορείτε να συμβάλλετε στο έργο, παρακαλούμε δείτε <a href="https://forum.open.mp/showthread.php?tid=99">αυτό το θέμα</a> για περισσότερες πληροφορίες.
# [FAQ](/faq)
| openmultiplayer/web/frontend/content/el/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/el/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 594
} | 477 |
# Open Multiplayer
A multiplayer mod for _Grand Theft Auto: San Andreas_ that is fully backwards compatible with the existing multiplayer mod _San Andreas Multiplayer._
<br />
This means **the existing SA:MP client and all existing SA:MP scripts work with open.mp** and, in addition to this, many bugs are also be fixed within the server software without the need for hacks and workarounds.
If you're wondering how to download, or how you can help contribute to the project, please see [this forum thread](https://forum.open.mp/showthread.php?tid=99) for more information.
# [FAQ](/faq)
| openmultiplayer/web/frontend/content/en/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/en/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 148
} | 478 |
# Open Multiplayer
Nadchodzący multiplayer do _Grand Theft Auto: San Andreas_, który będzie w pełni kompatybilny z aktualnie istniejącym _San Andreas Multiplayer._
<br />
Oznacza to, **że aktualny klient SA:MP i wszystkie skrypty SA:MP będą działały na open.mp**, a dodatkowo wiele błędów zostanie naprawionych bez konieczności stosowania dodatkowego oprogramowania i modyfikacji.
Jeżeli zastanawiasz się kiedy zostanie wydana oficjalna wersja projektu bądź w jaki sposób możesz się do niego przyczynić, zapoznaj się z [tym tematem na forum](https://forum.open.mp/showthread.php?tid=99), aby uzyskać niezbędne informacje.
# [FAQ](/faq)
| openmultiplayer/web/frontend/content/pl/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/pl/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 307
} | 479 |
# Open Multiplayer
เป็น Mod สำหรับการเล่นหลายคนที่กำลังจะมาถึงสำหรับ _Grand Theft Auto: San Andreas_ ที่จะเข้ากันได้กับ Mod ตัวเดิมที่มีอยู่นั้นคือ _San Andreas Multiplayer_
<br />
ซึ่งหมายความว่า **ไคลเอนต์ SA:MP ที่มีอยู่รวมถึงสคริปต์ทั้งหมดจาก SA:MP จะสามารถใช้กับ open.mp ได้** และนอกจากนี้บั๊กจำนวนมากจะถูกแก้ไข โดยไม่จำเป็นต้องใช้วิธีแฮ็กตัวโปรแกรมเซิร์ฟเวอร์เลย
หากคุณสงสัยว่าจะมีการเผยแพร่ตัวม็อดสู่สาธารณะเมื่อไหร่หรือต้องการสนับสนุนโครงการนี้ได้อย่างไร โปรดดูที่ [กระทู้นี้](https://forum.open.mp/showthread.php?tid=99) สำหรับข้อมูลเพิ่มเติม
# [FAQ](/faq)
| openmultiplayer/web/frontend/content/th/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/th/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 829
} | 480 |
# FAQ
<hr />
## Що таке open.mp?
open.mp (Open Multiplayer, OMP) — мультиплеєрний мод, що розробляється як заміна San Andreas Multiplayer. створений у відповідь на проблеми з оновленнями та розробкою SA:MP. Він повністю сумісний, що дозволяє теперішнім гравцям з клієнтом SA:MP грати на серверах OMP разом з гравцями, котрі використовують клієнт OMP. На відміну від свого аналогу, для open.mp будуть активно з'являтись оновлення.
<hr />
## Це форк?
Ні. Це повне переписування з нуля, при якому враховуються знання та досвід, накопичені за десятиліття. Спроби створити форк SA:MP мали місце раніше, але ми переконані, що у них у всіх були дві основні проблеми:
1. Вони всі були засновані на злитому коді SA:MP. Такі автори не мали законного права використовувати код SA:MP, через що були свідомо беззахисні — як з моральної, так і з юридичної точки зору. Ми категорично відмовляємось використовувати цей код. Це трішки ускладнює процес розробки, але в довгостроковій перспективі це правильне рішення.
2. Вони намагалися заново винайти занадто багато всього і відразу: додаючи нові скриптові мови, видаляючи функціонал й додаючи новий — або ж просто змінюючи що-небудь несумісним чином. Це не дозволяло серверам з великою кодовою базою і великою кількістю гравців здійснити перехід, оскільки для цього їм доводилось переписувати значні частини свого коду (якщо не весь код) — це потенційно витратна справа. З часом ми збираємось додавати новий функціонал та змінювати чинний. Ми також зосередимося на підтримці наявних серверів, дозволяючи їм використовувати наш код без потреби змінювати свій.
<hr />
## З якою метою ви це робите?
Попри спроби підштовхнути розвиток SA:MP офіційно у вигляді: порад, прохань й пропозицій допомогти з боку команди бета-тестерів, а також прохань спільноти зробити хоч щось нове — не було жодного прогресу в роботі над клієнтом. Існувала поширена думка, що причина цьому — відсутність інтересу з боку розробників клієнта, що само по собі не проблема, але і жодного поступу не було. Замість того, щоб передати розробку зацікавленим в цьому людям, засновник просто хотів піти й втягнути все за собою в прірву, при цьому затягуючи процес якомога глибше для мінімізації зусиль. Декотрі стверджують, що причина цього — пасивний дохід, але немає жодних доказів цієї версії. Всупереч зацікавленості й великій, злагодженій спільноті засновник SA:MP був переконаний, що клієнту залишилося всього 1-2 роки, вважаючи що спільнота, котра вклала багато старань, щоб зробити SA:MP таким, яким він є зараз — не заслуговує подальшого розвитку.
Ми ж цим не згодні.
<hr />
## Що думаєте про Kalcor/SA:MP/тощо?
Ми любимо SA:MP, тому ми тут. Насамперед, ми вдячні Kalcor за те, що він створив цю платформу. Він зробив величезний вклад для моду протягом багатьох років, і цей внесок не слід заперечувати чи ігнорувати. Дії, що призвели до open.mp — були вжиті, оскільки ми не погоджувалися з кількома рішеннями. Незважаючи на неодноразові спроби направити мод в іншому напрямку, вирішення не передбачалося. Таким чином, ми були змушені прийняти рішення — ми забажали розробляти SA:MP без Kalcor. Це не дії, вжиті проти нього особисто, це не повинно розглядатися як особисто напад на нього. Ми не терпимо жодних особистих образ проти будь-кого — незалежно від того, де вони стоять у питанні open.mp; ми повинні мати можливість розумно дискутувати, не вдаючись до нападів.
<hr />
## Чи це не просто розкол суспільства?
Це не наш намір. В ідеалі, в розколі взагалі відсутня необхідність. Відокремити певну частину й зберегти її краще, ніж дивитися, як все в'яне. Наприклад, з моменту оголошення розробки, велика кількість спільнот, котрі не є англійцями — знову стали спілкуватися з англійцями. Раніше різні спільноти витіснялися, тому їх повторне включення фактично знову об’єднує розколоту громаду гравців й розробників. Велика кількість людей отримала бан на офіційному форумі SA:MP (а в декотрих випадках і вся їхня історія публікацій була видалена). Сам Kalcor зазначив, що форум SA:MP не є офіційним форумом, скоріше його частина. Багато гравців та власників серверів ніколи не публікували й навіть не приєднувалися до дискусій на цьому форумі; тож повторне спілкування з цими людьми об’єднує ще більшу частину спільноти.
<hr />
Якщо це "Open" Multiplayer (переклад: "Відкритий мультиплеєр"), то це буде проєкт з відкритим
вихідним кодом?
Так, незабаром, такий наш план. Поки ж ми намагаємося забезпечити відкритість в плані зворотнього зв'язку і прозорості процесу розробки (що само по собі вже прогрес). Після цього ми перейдемо до відкриття вихідного коду, як тільки це стане можливим, а також коли будуть вирішені інші значні проблеми та вдасться домогтися стабільного процесу розробки.
<hr />
## Як я можу допомогти?
Слідкуйте за форумом. У нас є тема спеціально для цих цілей і ми будемо оновлювати її, як тільки з'явиться більше роботи. Незважаючи на те, що про проєкт стало відомо трохи раніше, ніж планувалося, ми вже на шляху до першого релізу, але це не означає, що допомога не вітається. Заздалегідь дякуємо за то, що цікавитеся і вірите в успіх проєкту:
[Назва теми: "How to help"](https://forum.open.mp/showthread.php?tid=99)
Нещодавно також з'явився офіційний форум самого open.mp й перебуває на активній стадії розробки:
[open.mp/forum](https://open.mp/uk/forum)
<hr />
## Що таке burgershot.gg?
burgershot.gg — ігровий форум, нічого більше. Багато людей пов'язані й з OMP, і з цим сайтом, а також деякий прогрес в розробці OMP публікується там, але це два незалежних один від одного проєкти. Раніше в OMP був відсутній власний форум. OMP не належить burgershot. Як тільки сайт OMP буде введений в дію, клієнт і burgershot можна буде відокремити один від одного (приблизно так само, як розробка SA:MP колись базувалася на GTAForums, доки у клієнта не з'явився власний сайт).
<hr />
## Чому не OpenMP?
"OpenMP" — це проєкт <a href="https://uk.wikipedia.org/wiki/OpenMP">Open Multiprocessing</a>. Натомість наш проєкт — "open.mp". Це дві абсолютно різні речі.
| openmultiplayer/web/frontend/content/uk/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/uk/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 6346
} | 481 |
<h1>問答集</h1>
<hr />
<h2>什麼是 open.mp?</h2>
open.mp (Open Multiplayer, OMP) 是一個聖安地列斯的多人連線模組,目的是為了代替在開發上問題不斷累積,
以及幾乎停止更新的 SA:MP。最初的發布版本只會取代伺服器端,因此現有的客戶端一樣可以連線至伺服器。 在
未來,新的 open.mp 客戶端也將會被發布,屆時會有更多討人喜歡的更新。
<hr />
<h2>這是一個分支嗎?</h2>
非也。 這將是利用我們長年累積的經驗,從零開始進行重寫。過去曾有 SA:MP 的分支,但是使用分支會存在以下
兩個問題:
<ol>
<li>
那些所使用的是非正途開源的洩漏SA:MP原始碼。
使用洩漏原始碼的模組改寫者在法律上沒有任何的保障,也因此在開發上是非常不安全的。
我們將從零開始寫起,不使用洩漏原始碼,雖然需要花費更多的時間,但是相對來說卻是最正確的選擇。
</li>
<li>
那些重新更改的地方過多。
有些是重寫了整個腳本引擎,有些寫了新功能取代舊的功能,或是用了較不好的方式更新新功能。
如果不重寫全部代碼,要完整的將代碼基礎以及玩家移到那些分支上,會是一個非常大的問題。
我們會逐步新增功能,調整及修正問題,同時我們也支持現有的伺服器,允許伺服器持有人使用我們的代碼,而不需要另外改寫。
</li>
</ol>
<hr />
<h2>為什麼要這麼做?</h2>
我們已經多次嘗試向 SA:MP 官方發起更新建議,提供日後可更新內容,以及提出幫助測試的請求,但是至今官方
並沒有跟進任何建議,也沒有處理該修正的內容。大部分的人認為原因可能是開發團隊漸漸對 SA:MP 失去興趣,
但這並不是主要的問題,主要是由於沒有其他人可以繼續開發。現在的開發者不希望自己的原始碼給其他任何人,
包括那些有意願有興趣想繼續開發的人們,從目前看來官方只想盡可能的獨自開發。有些人認為這樣的目的是為了
錢,雖然還沒有確切證據。就算整個官方討論區以及 SA:MP 相關的討論群組仍有著有心願意開發的人在,但現在
的開發者認為 SA:MP 已經無法繼續發展下去,頂多只能在持續1至2年的時間,而且那些不斷開發更新的作品也
沒有延續的價值了。
<br />
但我們並不這麼認為。
<hr />
<h2>你們對Kalcor(現SA:MP開發者)或是SA:MP是如何看待的?</h2>
我們熱愛 SA:MP,這也是為什麼我們會先在此為 Kalcor 開啟這個項目的原因。 Kalcor 長年來為 SA:MP 貢獻非
常多,我們都應該深知這點。會使我們開啟 open.mp 這個項目是因為 SA:MP 官方最近的做法讓我們不太能接受,
我們也多次嘗試給予 SA:MP 改進的建議,但始終沒有得到解決。我們唯一能做的只有啟用這個項目,雖然 Kalcor
並不會參與我們的項目幫助開發。這些並不是針對 Kalcor 所做的報復或攻擊行為。我們絕對不會允許任何言語上
的攻擊,不管在 open.mp 是什麼樣的人,我們都希望大家可以理性溝通。
<hr />
<h2>這不就是搞分裂嗎?</h2>
我們並沒有這樣的想法。其實根本不用搞分裂,保留需要的,並且拓展新的內容,總比整個都被關閉或是停下來還
要好。其實自從開始該項目後,不同語言的人們也能有更好的交流方式了,與其說是分裂,不如說是更好的團結在
一起了。有些真正有貢獻的人在 SA:MP 討論區的帳號被封鎖了,有的發文紀錄還被清光。而 Kalcor 也明確說明
,SA:MP 討論區並不代表 SA:MP,只是 SA:MP 的其中一部分而已。許多玩家或是伺服器持有者甚至沒有在官方討
論區內發表過任何文章,或是加入討論區會員,因此我們希望可以帶動更多人進行交流。
<hr />
<h2>如果Open Multiplayer是Open的,那麼最終會開放原始碼嗎?</h2>
就目前項目而言,答案是會的。開發人員正在讓開發內容能夠更加透明化以及得到更多討論,這其實也是一種改進
,只要開發以及項目漸漸穩定下來後,我們將會進行開放原始碼的動作。
<hr />
<h2>什麼時候會發佈呢?</h2>
既然是個老問題,我們也用老答案回答吧:什麼時候完成,什麼時候發佈。畢竟我們也無法預測開發所需的時間。
不過還請放心,因為我們有我們的開發策略,所以現在依然順利進行開發,速度也不慢,雖然開發人員也有該過的
現實生活,多少會影響開發進度,但是以現在來說,開發進展是有一定的可見度。
<hr />
<h2>我該如何幫助你們?</h2>
請持續關注討論區。 我們有關於該問題的詳細文章,且該文章會持續更新跟進最新進度。雖然這個項目比當初預
定的還要早開始一些,我們也已經有了個很好的開始,但這並不代表任何的幫助都會被人認為是好的。在此感謝您
對該項目的興趣,幫助該項目發展,以及感謝您相信我們:
<br />
<a href="https://forum.open.mp/showthread.php?tid=99">
<u>文章 "如何幫助"</u>
</a>
<hr />
<h2>burgershot.gg 是什麼呢?</h2>
burgershot.gg 是一個遊戲討論區,沒有別的。很多人在討論區裡發表 OMP 開發相關文章,但是 OMP 和討論區是
兩個分別不同的項目。討論區並不是 OMP 的官方討論區,OMP 也不是 burgershot 的一部分。如果 OMP 的官方討
論區開放了,兩個站點就可以完全分離開來。(比如 SA:MP 的討論本來是在 GTAForums 上進行,但後來獨立出現
在的官方討論區)
<hr />
<h2>那麼OpenMP是什麼呢?</h2>
開放多線程並發項目是"OpenMP",我們是"open.mp"。 兩者完全不一樣。
| openmultiplayer/web/frontend/content/zh-tw/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/zh-tw/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 4166
} | 482 |
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 24.3.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">
<style type="text/css">
.st0{fill:#7466D4;}
</style>
<path class="st0" d="M5.3,1L2,9.8V43h11v6h7.4l6-6h9L48,30.4V1H5.3z M11,6h32v22l-6,6H25l-6,6v-6h-8V6z M20,13v14h6V13H20z M30,13
v14h6V13H30z"/>
</svg>
| openmultiplayer/web/frontend/public/images/assets/twitch.svg/0 | {
"file_path": "openmultiplayer/web/frontend/public/images/assets/twitch.svg",
"repo_id": "openmultiplayer",
"token_count": 279
} | 483 |
import { Box, Flex, FlexProps } from "@chakra-ui/layout";
import React, { ReactElement, VFC } from "react";
import { AnimateSharedLayout, AnimatePresence, motion } from "framer-motion";
import { SystemStyleObject } from "@chakra-ui/styled-system";
import { As } from "@chakra-ui/system";
interface ChildProps {
sx: SystemStyleObject;
}
type Props = {
/** What element should the list render as? Ordered or Unordered. */
as?: "ol" | "ul";
/** What elements should the list items render as? Defaults to `article`. */
childrenAs?: As;
/** Children must contain an `sx` prop for styles. */
children: ReactElement<ChildProps>[];
} & FlexProps;
const duration = 0.1;
export const CardList: VFC<Props> = ({
as = "ol",
childrenAs = "article",
children,
...pass
}) => {
// these styles are passed to children. If the child is a Chakra component
// it will automatically apply these. If not, the component must manually
// union its props with `ChakraProps` and pass `sx` to its outermost element.
const sx = {
padding: "0.8em",
borderColor: "blackAlpha.100",
borderStyle: "solid",
borderWidth: "1px",
borderRadius: "0.5em",
};
return (
<Box className="static-container" overflowY="clip">
<AnimateSharedLayout>
<motion.div
className="animated-container"
layout
transition={{ bounce: false, duration: duration }}
>
<Flex
{...pass}
as={as}
display="flex"
margin="0"
flexDirection="column"
listStyleType="none"
gridGap="0.5em"
>
{React.Children.map(children, (child: ReactElement<ChildProps>) => {
return (
<AnimatePresence>
<motion.li
layout
key={child.key}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ bounce: false, duration: duration }}
exit={{ y: -50, opacity: 0 }}
>
<Box as={childrenAs}>
{React.cloneElement(child, {
sx,
})}
</Box>
</motion.li>
</AnimatePresence>
);
})}
</Flex>
</motion.div>
</AnimateSharedLayout>
</Box>
);
};
| openmultiplayer/web/frontend/src/components/generic/CardList.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/generic/CardList.tsx",
"repo_id": "openmultiplayer",
"token_count": 1174
} | 484 |
import { Box, Heading, Text, useColorModeValue } from "@chakra-ui/react";
import React, { FC } from "react";
const Announcement: FC = () => {
return (
<Box maxWidth="48em" mx="auto" px="0.5em">
<Box
padding="0.8em"
borderColor={useColorModeValue("blackAlpha.100", "gray.700")}
borderStyle="solid"
borderWidth="1px"
borderRadius="0.5em"
backgroundColor={useColorModeValue("blue.50", "gray.800")}
>
<Heading m="0" fontSize="1.5em">
open.mp launcher is out now and open source!
</Heading>
<Text>
open.mp released its own launcher to browse servers using a reliable
internet list and join your favorite servers!{" "}
<a href="https://github.com/openmultiplayer/launcher">
check out our github repository
</a>{" "}
<br />
<a href="https://github.com/openmultiplayer/launcher/releases/latest">
Download it from here.
</a>{" "}
</Text>
</Box>
</Box>
);
};
export default Announcement;
| openmultiplayer/web/frontend/src/components/site/Announcement.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/site/Announcement.tsx",
"repo_id": "openmultiplayer",
"token_count": 490
} | 485 |
import Admonition from "../../../Admonition";
export default function TipNpcCallback() {
return (
<Admonition type="tip">
<p>Este callback también puede ser llamado por un NPC.</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/es/npc-callbacks-tip.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/es/npc-callbacks-tip.tsx",
"repo_id": "openmultiplayer",
"token_count": 84
} | 486 |
import { formatDistanceToNow } from "date-fns";
import { GetServerSidePropsContext } from "next";
import { API_ADDRESS } from "src/config";
import { APIError, APIErrorSchema } from "src/types/_generated_Error";
import { niceDate } from "src/utils/dates";
import { z, ZodSchema } from "zod";
const DEFAULT_HEADERS = {
"Content-Type": "application/json",
};
type Opts<T> = {
// TODO: Make this mandatory for all `api` calls.
// The response object schema to validate against if there are no errors.
schema?: ZodSchema<T>;
// Query parameters, do not add these to the path manually when using swr.
query?: URLSearchParams;
};
export type APIOptions<T> = Opts<T> & RequestInit;
/**
* For general use API calls
*
* Builds a request and executes it, then processes the result by checking for
* errors, checking for rate limit violations and parsing the response using a
* supplied schema in the options.
*
* @param path API endpoint
* @param opts API options for the schema and query parameters. You don't have
* to use the query parameters here, it's fine to just stick them in
* the path for API calls outside of `useSWR`, though it does make
* it a little more ergonomic. See the `apiSWR` documentation for an
* explanation of why this option exists. The schema is for just for
* the response body JSON. It's optional.
* @returns The resulting data from the API call. Throws APIError on failure.
*/
export async function api<T>(path: string, opts?: APIOptions<T>): Promise<T> {
const withQuery = `${path}${opts?.query ? "?" + opts.query.toString() : ""}`;
const request = buildRequest(withQuery, opts);
const response = await fetch(request);
const data = await getData(response);
if (!isSuccessStatus(response.status)) {
handleError(data, response, path);
}
return opts?.schema?.parse(data) ?? (data as T);
}
const isSuccessStatus = (code: number) => code >= 200 && code <= 299;
/**
* Build a request for the API server for use on either the server or client.
* @param path The API path endpoint to call
* @param opts Request options
* @returns A Request object ready for use with `fetch`
*/
export const buildRequest = (path: string, opts?: RequestInit): Request => {
const req = new Request(`${API_ADDRESS}${path}`, {
mode: "cors",
credentials: "include",
headers: {
...DEFAULT_HEADERS,
},
...opts,
});
return req;
};
const getData = async (response: Response): Promise<unknown> => {
if (isJSON(response)) {
return response.json();
} else {
return undefined;
}
};
const isJSON = (response: Response): boolean => {
const contentType = response.headers.get("Content-Type");
return contentType === "application/json";
};
function handleError(raw: unknown, r: Response, path: string): never {
if (r.status === 429) {
throw new RateLimitError(r, path);
}
throw deriveError(raw ?? { error: `${r.status}: ${r.statusText}` });
}
/**
* For use in `useSWR` hooks ONLY.
*
* This is curried in order to remove the need to pass the options on every call
* because this messes with swr's dependency code and results in repeated calls.
*
* @param opts Set the query parameter here, not in the useSWR key if you want
* mutations to be generic and affect page updates regardless of the
* query parameters used for the page.
* @returns A fetcher function for the second argument of `useSWR`.
*/
export function apiSWR<T>(opts?: APIOptions<T>) {
return (path: string): Promise<T> => {
return api<T>(path, opts);
};
}
/**
* The server side props discriminated type union. Looks very similar to what
* `useSWR` calls to keep things consistent. If success is true, data will be
* guaranteed not undefined. Makes things nice and ergonomic in page components.
*
* Usage:
*
* ```
* type Props = SSP<User>
*
* const Page: NextPage<Props> = (props) => {
* if(!props.success) { return <ErrorBanner {...props.error} /> }
*
* return <UserView fallbackData={props.data} />
* }
*
* export const getServerSideProps: GetServerSideProps<Props> => { ... }
* ```
*/
export type SSP<T> =
| {
success: true;
data: T;
}
| {
success: false;
error: APIError;
};
/**
* For use in getServerSideProps ONLY!
*
* Makes an API call and returns a result type which is either the specified
* payload type (T) or an APIError type. The result should be returned directly
* from getServerSideProps to minimise additional code. If the data needs to be
* pre-processed on the server side before being passed, use `mapSSP` inside a
* `.then()` chain after the call:
*
* ```
* return {
* props: await apiSSP(...).then(mapSSP((data) => preProcess(data)))
* }
* ```
*
* The page component should always have props that include `data?: T` and
* `error?: APIError`. Because of the way the `SSP` type works, TypeScript will
* know that if `error` is undefined, then `data` must be defined. Check `error`
* early in the component's render and return an `<ErrorBanner {...error} />` if
* it has a value. Otherwise, `data` is ready to use.
*
* Most of the time, you'll want to pass `data` into a "View" component which
* should make use of `useSWR` - in order to make use of the server side
* rendered `data` value, pass this in to useSWR's options under `fallbackData`.
*
* When being called from getServerSideProps, the request context must be
* passed in so cookies are added to the request for authentication purposes.
*
* @param path API endpoint
* @param ctx getServerSideProps context argument (for passing cookies)
* @param opts API call options
* @returns A discriminated union with data or error (similar to swr) this
*
*/
export async function apiSSP<T>(
path: string,
ctx: GetServerSidePropsContext,
opts?: RequestInit & APIOptions<T>
): Promise<SSP<T>> {
const headers = new Headers({
...opts?.headers,
...headersFromContext(ctx),
});
return api(path, { ...opts, headers })
.then((data) => ({
success: true as const,
data,
}))
.catch((e) => ({
success: false as const,
error: deriveError(e),
}));
}
/**
* A helper function for running post-processing operations on successful calls
* to `apiSSP`. Handles success check boilerplate. For use in apiSSP().then().
* @param input The immediate return value of `apiSSP`
*/
export function mapSSP<T, U = T>(fn: (input: T) => Promise<U>) {
return async (input: SSP<T>): Promise<SSP<U>> => {
if (input.success) {
// If the API call succeeded, run the function on the data and return a
// new SSP result with the new data type U.
return {
success: true as const,
data: await fn(input.data),
};
} else {
// If the API call faled, do nothing and pass the input along unchanged.
return new Promise(() => input);
}
};
}
/**
* Builds a headers object for use in getServerSideProps.
* @param ctx Next.js server side props context.
* @returns A headers object with the cookies (if any) set correctly.
*/
const headersFromContext = (ctx: GetServerSidePropsContext): Headers => {
const headers = new Headers();
if (ctx.req.headers.cookie) {
headers.append("cookie", ctx.req.headers.cookie);
}
return headers;
};
/**
* Derives a consistent error object from exception or response input.
* @param e Exception or error response object
* @returns An APIError object either parsed from `e` or built from toString
*/
export const deriveError = (e: unknown): APIError => {
const parsed = APIErrorSchema.safeParse(e);
if (parsed.success) {
return parsed.data;
} else if (e instanceof Error) {
return { error: e.toString() };
} else if (e === undefined) {
return {
error: "Unknown error",
message: "deriveError was passed a value of `undefined`.",
};
} else {
return {
error: String(e),
message:
"deriveError was passed a value that was neither Error or APIError.",
};
}
};
/**
* This error is thrown when the API responds with a "429 Too Many Requests". It
* implements the `APIError` type and fills all the fields with some information
* about the rate limit so instances of this class can go into `<ErrorBanner />`
*/
export class RateLimitError implements APIError {
public message: string;
public error: string;
public suggested: string;
constructor(r: Response, path: string) {
const limit = r.headers.get("x-ratelimit-limit");
const reset = r.headers.get("x-ratelimit-reset");
this.message = limit
? `You have exceeded the request rate limit (${limit} requests per minute) for a particular resource (${path}) required for this page.`
: `You have exceeded the request rate limit for a particular resource (${path}) required for this page.`;
this.suggested = reset
? `Wait until ${niceDate(reset)} (${formatDistanceToNow(
new Date(reset)
)}) for the rate limit to reset`
: "Wait for a while for the rate limit to reset.";
this.error = "rate limit exceeded";
}
}
/**
* OAuth2 Callback API call for use in getServerSideProps.
*/
export const OAuthCallbackPayloadSchema = z.object({
code: z.string(),
state: z.string(),
});
export type OAuthCallbackPayload = z.infer<typeof OAuthCallbackPayloadSchema>;
export const OAuthErrorSchema = z.object({
error: z.string(),
error_description: z.string(),
});
export type OAuthError = z.infer<typeof OAuthErrorSchema>;
export async function oauth(
provider: "discord" | "github",
ctx: GetServerSidePropsContext
): Promise<string> {
const error = errorFromOAuthError(ctx.query);
if (error) {
throw error;
}
const payload = OAuthCallbackPayloadSchema.parse(ctx.query);
const cookie = ctx?.req?.headers?.cookie;
const path = `/auth/${provider}/callback`;
const request = buildRequest(path, {
method: "post",
body: JSON.stringify(payload),
headers: {
"Content-Type": "application/json",
Cookie: cookie ?? "",
},
credentials: "include",
});
const response = await fetch(request);
const data = await getData(response);
if (!isSuccessStatus(response.status)) {
throw deriveError(
data ?? { error: `${response.status}: ${response.statusText}` }
);
}
const setCookie = response.headers.get("set-cookie");
if (!setCookie) {
throw deriveError({
error: "No cookie in authentication response",
message: `The server did not respond with an authentication cookie after verifying your ${payload} account.`,
});
}
return setCookie;
}
const errorFromOAuthError = (e: unknown): APIError | undefined => {
const parse = OAuthErrorSchema.safeParse(e);
if (parse.success) {
console.error(parse.data);
return {
error: parse.data.error,
message: parse.data.error_description,
};
}
};
| openmultiplayer/web/frontend/src/fetcher/fetcher.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/fetcher/fetcher.ts",
"repo_id": "openmultiplayer",
"token_count": 3577
} | 487 |
import { GetServerSidePropsContext, GetServerSidePropsResult } from "next";
import React, { FC } from "react";
import ErrorBanner from "src/components/ErrorBanner";
import { deriveError, oauth } from "src/fetcher/fetcher";
import { APIError } from "src/types/_generated_Error";
type Props = {
error?: APIError;
};
const Page: FC<Props> = ({ error }) => <ErrorBanner {...error} />;
export const getServerSideProps = async (
ctx: GetServerSidePropsContext
): Promise<GetServerSidePropsResult<Props>> => {
try {
const cookie = await oauth("discord", ctx);
ctx.res.setHeader("set-cookie", cookie);
ctx.res.writeHead(302, { Location: "/dashboard" });
ctx.res.end();
return { props: {} };
} catch (e) {
console.error(e);
return { props: { error: deriveError(e) } };
}
};
export default Page;
| openmultiplayer/web/frontend/src/pages/auth/discord.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/auth/discord.tsx",
"repo_id": "openmultiplayer",
"token_count": 292
} | 488 |
import { Box } from "@chakra-ui/react";
import { randomBytes } from "crypto";
import { GetServerSideProps, NextPage } from "next";
import { NextSeo } from "next-seo";
import { VFC } from "react";
const UID: VFC<Props> = ({ serialised }) => {
return (
<Box as="section" maxWidth="50em" margin="auto" padding="1em 2em">
<NextSeo title="UID" />
<main>
<h1>Component UID Generator</h1>
Copy the <code>PROVIDE_UID</code> macro below in to your new component,
in place of the default UID provider macro. Each component should have
a unique UID, hence the <em>U</em> in <em>UID</em> (<em>Unique
IDentifier</em>). The default <code>PROVIDE_UID</code> is invalid and
will not compile, to avoid duplicates when creating new components from
templates.
<br />
<br />
Find this placeholder:
<pre>PROVIDE_UID(/* UID GOES HERE */);</pre>
<br />
And replace it with:
<pre>{`PROVIDE_UID(${serialised});`}</pre>
<br />
If you are modifying an existing component still do remember to replace
the existing UID, which will be a valid value not a placeholder.
</main>
</Box>
);
};
type Props = {
serialised: string;
};
const Page: NextPage<Props> = ({ serialised }: Props) => (
<UID serialised={serialised} />
);
export const getServerSideProps: GetServerSideProps<Props> = async () => {
const rnd = randomBytes(8);
function toHex(number: number): string {
return ('00' + number.toString(16)).slice(-2).toUpperCase();
}
const serialised = `0x${toHex(rnd[0])}${toHex(rnd[1])
}${toHex(rnd[2])}${toHex(rnd[3])}${toHex(rnd[4])
}${toHex(rnd[5])}${toHex(rnd[6])}${toHex(rnd[7])}`;
return {
props: {
serialised,
},
};
};
export default Page;
| openmultiplayer/web/frontend/src/pages/uid.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/uid.tsx",
"repo_id": "openmultiplayer",
"token_count": 757
} | 489 |
declare module "react-nextjs-toast" {
export interface ToastContainerProps {
align?: "left" | "center" | "right";
position?: "top" | "bottom";
id?: string;
}
declare class ToastContainer extends React.Component<
ToastContainerProps,
any
> {}
export interface ToastOptions {
duration?: number; // Number of seconds to show toast on screen
type?: string; // Type of toast - info, error, success and warning
title?: string; // The title of the toast
targetId?: string; // Target container id
position?: string; // top , bottom
}
declare namespace toast {
declare function notify(message: string, opts: ToastOptions);
}
}
declare module "@mdx-js/mdx";
declare module "@mdx-js/react" {
import * as React from "react";
type ComponentType =
| "a"
| "blockquote"
| "code"
| "del"
| "em"
| "h1"
| "h2"
| "h3"
| "h4"
| "h5"
| "h6"
| "hr"
| "img"
| "inlineCode"
| "li"
| "ol"
| "p"
| "pre"
| "strong"
| "sup"
| "table"
| "td"
| "thematicBreak"
| "tr"
| "ul";
export type Components = {
[key in ComponentType]?: React.ComponentType<any>;
};
export interface MDXProviderProps {
children?: React.ReactNode;
components: Components;
}
export class MDXProvider extends React.Component<MDXProviderProps> {}
export class mdx {}
}
declare module "@babel/preset-react";
declare module "remark-admonitions";
| openmultiplayer/web/frontend/src/types/missing.d.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/types/missing.d.ts",
"repo_id": "openmultiplayer",
"token_count": 579
} | 490 |
package config
import (
"time"
"github.com/kelseyhightower/envconfig"
"go.uber.org/zap/zapcore"
)
// Config represents environment variable configuration parameters
type Config struct {
Production bool `envconfig:"PRODUCTION" default:"false"`
LogLevel zapcore.Level `envconfig:"LOG_LEVEL" default:"info"`
DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
ListenAddr string `envconfig:"LISTEN_ADDR" default:"0.0.0.0:8000"`
CookieDomain string `envconfig:"COOKIE_DOMAIN" default:".open.mp"`
PublicWebAddress string `envconfig:"PUBLIC_WEB_ADDRESS" default:"https://open.mp"`
LauncherBackendAddress string `envconfig:"LAUNCHER_BACKEND_ADDRESS" default:"http://localhost:1420"`
PublicApiAddress string `envconfig:"PUBLIC_API_ADDRESS" default:"https://api.open.mp"`
HashKey []byte `envconfig:"HASH_KEY" required:"true"`
BlockKey []byte `envconfig:"BLOCK_KEY" required:"true"`
GithubClientID string `envconfig:"GITHUB_CLIENT_ID" required:"true"`
GithubClientSecret string `envconfig:"GITHUB_CLIENT_SECRET" required:"true"`
DiscordClientID string `envconfig:"DISCORD_CLIENT_ID" required:"true"`
DiscordClientSecret string `envconfig:"DISCORD_CLIENT_SECRET" required:"true"`
GithubToken string `envconfig:"GITHUB_TOKEN" required:"true"`
DocsSourcesPath string `envconfig:"DOCS_SOURCES_PATH" required:"false" default:"docs/"`
DocsIndexPath string `envconfig:"DOCS_INDEX_PATH" required:"false" default:"docs.bleve"`
PackagesDB string `envconfig:"PACKAGES_DB" required:"false" default:"data/packages.db"`
CachedServers string `envconfig:"CACHED_SERVERS_FILE" required:"false" default:"data/cachedServers.json"`
ServerScrapeInterval time.Duration `envconfig:"SERVER_SCRAPE_INTERVAL" required:"false" default:"30m"`
PackageSearchInterval time.Duration `envconfig:"PACKAGE_SEARCH_INTERVAL" required:"false" default:"24h"`
PackageScrapeInterval time.Duration `envconfig:"PACKAGE_SCRAPE_INTERVAL" required:"false" default:"24h"`
LauncherVersion string `envconfig:"LAUNCHER_VERSION" required:"false" default:"2"`
AuthenticatedAPIKey string `envconfig:"AUTHENTICATED_API_KEY" required:"true"`
}
func New() (c Config, err error) {
if err = envconfig.Process("", &c); err != nil {
return c, err
}
return
}
| openmultiplayer/web/internal/config/config.go/0 | {
"file_path": "openmultiplayer/web/internal/config/config.go",
"repo_id": "openmultiplayer",
"token_count": 1224
} | 491 |
generator client {
provider = "go run github.com/steebchen/prisma-client-go"
output = "../internal/bs"
binaryTargets = ["native"]
package = "bs"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL_BS")
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_adminlog {
uid Int @default(0)
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
dateline Int @default(0)
module String @default("") @db.VarChar(50)
action String @default("") @db.VarChar(50)
data String @default("")
@@ignore
}
model mybb_adminoptions {
uid Int @unique @default(0)
cpstyle String @default("") @db.VarChar(50)
cplanguage String @default("") @db.VarChar(50)
codepress Int @default(1) @db.SmallInt
notes String @default("")
permissions String @default("")
defaultviews String
loginattempts Int @default(0) @db.SmallInt
loginlockoutexpiry Int @default(0)
authsecret String @default("") @db.VarChar(16)
recovery_codes String @default("") @db.VarChar(177)
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_adminsessions {
sid String @default("") @db.VarChar(32)
uid Int @default(0)
loginkey String @default("") @db.VarChar(50)
ip Bytes @default(dbgenerated("'\\x'::bytea"))
dateline Int @default(0)
lastactive Int @default(0)
data String @default("")
useragent String @default("") @db.VarChar(200)
authenticated Int @default(0) @db.SmallInt
@@ignore
}
model mybb_adminviews {
vid Int @id @default(autoincrement())
uid Int @default(0)
title String @default("") @db.VarChar(100)
type String @default("") @db.VarChar(6)
visibility Int @default(0) @db.SmallInt
fields String
conditions String
custom_profile_fields String
sortby String @default("") @db.VarChar(20)
sortorder String @default("") @db.VarChar(4)
perpage Int @default(0) @db.SmallInt
view_type String @default("") @db.VarChar(6)
}
model mybb_announcements {
aid Int @id @default(autoincrement())
fid Int @default(0)
uid Int @default(0)
subject String @default("") @db.VarChar(120)
message String @default("")
startdate Int @default(0)
enddate Int @default(0)
allowhtml Int @default(0) @db.SmallInt
allowmycode Int @default(0) @db.SmallInt
allowsmilies Int @default(0) @db.SmallInt
}
model mybb_attachments {
aid Int @id @default(autoincrement())
pid Int @default(0)
posthash String @default("") @db.VarChar(50)
uid Int @default(0)
filename String? @default("") @db.VarChar(255)
filetype String @default("") @db.VarChar(120)
filesize Int @default(0)
attachname String? @default("") @db.VarChar(255)
downloads Int @default(0)
dateuploaded Int @default(0)
visible Int @default(0) @db.SmallInt
thumbnail String @default("") @db.VarChar(120)
}
model mybb_attachtypes {
atid Int @id @default(autoincrement())
name String @default("") @db.VarChar(120)
mimetype String @default("") @db.VarChar(120)
extension String @default("") @db.VarChar(10)
maxsize Int @default(0)
icon String @default("") @db.VarChar(100)
enabled Int @default(1) @db.SmallInt
groups String @default("-1")
forums String @default("-1")
avatarfile Int @default(0) @db.SmallInt
}
model mybb_awaitingactivation {
aid Int @id @default(autoincrement())
uid Int @default(0)
dateline Int @default(0)
code String @default("") @db.VarChar(100)
type String @default("") @db.Char(1)
validated Int @default(0) @db.SmallInt
misc String @default("") @db.VarChar(255)
}
model mybb_badwords {
bid Int @id @default(autoincrement())
badword String @default("") @db.VarChar(100)
regex Int @default(0) @db.SmallInt
replacement String @default("") @db.VarChar(100)
}
model mybb_banfilters {
fid Int @id @default(autoincrement())
filter String @default("") @db.VarChar(200)
type Int @default(0) @db.SmallInt
lastuse Int @default(0)
dateline Int @default(0)
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_banned {
uid Int @default(0)
gid Int @default(0)
oldgroup Int @default(0)
oldadditionalgroups String @default("")
olddisplaygroup Int @default(0)
admin Int @default(0)
dateline Int @default(0)
bantime String @default("") @db.VarChar(50)
lifted Int @default(0)
reason String @default("") @db.VarChar(255)
@@ignore
}
model mybb_buddyrequests {
id Int @id @default(autoincrement())
uid Int @default(0)
touid Int @default(0)
date Int @default(0)
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_calendarpermissions {
cid Int @default(autoincrement())
gid Int @default(0)
canviewcalendar Int @default(0) @db.SmallInt
canaddevents Int @default(0) @db.SmallInt
canbypasseventmod Int @default(0) @db.SmallInt
canmoderateevents Int @default(0) @db.SmallInt
@@ignore
}
model mybb_calendars {
cid Int @id @default(autoincrement())
name String @default("") @db.VarChar(100)
disporder Int @default(0) @db.SmallInt
startofweek Int @default(0) @db.SmallInt
showbirthdays Int @default(0) @db.SmallInt
eventlimit Int @default(0) @db.SmallInt
moderation Int @default(0) @db.SmallInt
allowhtml Int @default(0) @db.SmallInt
allowmycode Int @default(0) @db.SmallInt
allowimgcode Int @default(0) @db.SmallInt
allowvideocode Int @default(0) @db.SmallInt
allowsmilies Int @default(0) @db.SmallInt
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_captcha {
imagehash String @default("") @db.VarChar(32)
imagestring String @default("") @db.VarChar(8)
dateline Int @default(0)
used Int @default(0) @db.SmallInt
@@ignore
}
model mybb_datacache {
title String @id @default("") @db.VarChar(50)
cache String @default("")
}
model mybb_delayedmoderation {
did Int @id @default(autoincrement())
type String @default("") @db.VarChar(30)
delaydateline Int @default(0)
uid Int @default(0)
fid Int @default(0) @db.SmallInt
tids String
dateline Int @default(0)
inputs String @default("")
}
model mybb_events {
eid Int @id @default(autoincrement())
cid Int @default(0)
uid Int @default(0)
name String @default("") @db.VarChar(120)
description String
visible Int @default(0) @db.SmallInt
private Int @default(0) @db.SmallInt
dateline Int @default(0)
starttime Int @default(0)
endtime Int @default(0)
timezone String @default("") @db.VarChar(5)
ignoretimezone Int @default(0) @db.SmallInt
usingtime Int @default(0) @db.SmallInt
repeats String
}
model mybb_forumpermissions {
pid Int @id @default(autoincrement())
fid Int @default(0)
gid Int @default(0)
canview Int @default(0) @db.SmallInt
canviewthreads Int @default(0) @db.SmallInt
canonlyviewownthreads Int @default(0) @db.SmallInt
candlattachments Int @default(0) @db.SmallInt
canpostthreads Int @default(0) @db.SmallInt
canpostreplys Int @default(0) @db.SmallInt
canonlyreplyownthreads Int @default(0) @db.SmallInt
canpostattachments Int @default(0) @db.SmallInt
canratethreads Int @default(0) @db.SmallInt
caneditposts Int @default(0) @db.SmallInt
candeleteposts Int @default(0) @db.SmallInt
candeletethreads Int @default(0) @db.SmallInt
caneditattachments Int @default(0) @db.SmallInt
canviewdeletionnotice Int @default(0) @db.SmallInt
modposts Int @default(0) @db.SmallInt
modthreads Int @default(0) @db.SmallInt
mod_edit_posts Int @default(0) @db.SmallInt
modattachments Int @default(0) @db.SmallInt
canpostpolls Int @default(0) @db.SmallInt
canvotepolls Int @default(0) @db.SmallInt
cansearch Int @default(0) @db.SmallInt
}
model mybb_forums {
fid Int @id @default(autoincrement())
name String @default("") @db.VarChar(120)
description String @default("")
linkto String @default("") @db.VarChar(180)
type String @default("") @db.Char(1)
pid Int @default(0) @db.SmallInt
parentlist String @default("")
disporder Int @default(0) @db.SmallInt
active Int @default(0) @db.SmallInt
open Int @default(0) @db.SmallInt
threads Int @default(0)
posts Int @default(0)
lastpost Int @default(0)
lastposter String @default("") @db.VarChar(120)
lastposteruid Int @default(0)
lastposttid Int @default(0)
lastpostsubject String @default("") @db.VarChar(120)
allowhtml Int @default(0) @db.SmallInt
allowmycode Int @default(0) @db.SmallInt
allowsmilies Int @default(0) @db.SmallInt
allowimgcode Int @default(0) @db.SmallInt
allowvideocode Int @default(0) @db.SmallInt
allowpicons Int @default(0) @db.SmallInt
allowtratings Int @default(0) @db.SmallInt
usepostcounts Int @default(0) @db.SmallInt
usethreadcounts Int @default(0) @db.SmallInt
requireprefix Int @default(0) @db.SmallInt
password String @default("") @db.VarChar(50)
showinjump Int @default(0) @db.SmallInt
style Int @default(0) @db.SmallInt
overridestyle Int @default(0) @db.SmallInt
rulestype Int @default(0) @db.SmallInt
rulestitle String @default("") @db.VarChar(200)
rules String @default("")
unapprovedthreads Int @default(0)
unapprovedposts Int @default(0)
deletedthreads Int @default(0)
deletedposts Int @default(0)
defaultdatecut Int @default(0) @db.SmallInt
defaultsortby String @default("") @db.VarChar(10)
defaultsortorder String @default("") @db.VarChar(4)
enablepruning Int @default(0) @db.SmallInt
daysprune Int @default(240) @db.SmallInt
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_forumsread {
fid Int @default(0)
uid Int @default(0)
dateline Int @default(0)
@@ignore
}
model mybb_forumsubscriptions {
fsid Int @id @default(autoincrement())
fid Int @default(0) @db.SmallInt
uid Int @default(0)
}
model mybb_groupleaders {
lid Int @id @default(autoincrement())
gid Int @default(0) @db.SmallInt
uid Int @default(0)
canmanagemembers Int @default(0) @db.SmallInt
canmanagerequests Int @default(0) @db.SmallInt
caninvitemembers Int @default(0) @db.SmallInt
}
model mybb_helpdocs {
hid Int @id @default(autoincrement())
sid Int @default(0) @db.SmallInt
name String @default("") @db.VarChar(120)
description String @default("")
document String @default("")
usetranslation Int @default(0) @db.SmallInt
enabled Int @default(0) @db.SmallInt
disporder Int @default(0) @db.SmallInt
}
model mybb_helpsections {
sid Int @id @default(autoincrement())
name String @default("") @db.VarChar(120)
description String @default("")
usetranslation Int @default(0) @db.SmallInt
enabled Int @default(0) @db.SmallInt
disporder Int @default(0) @db.SmallInt
}
model mybb_icons {
iid Int @id @default(autoincrement())
name String @default("") @db.VarChar(120)
path String @default("") @db.VarChar(220)
}
model mybb_joinrequests {
rid Int @id @default(autoincrement())
uid Int @default(0)
gid Int @default(0) @db.SmallInt
reason String @default("") @db.VarChar(250)
dateline Int @default(0)
invite Int @default(0) @db.SmallInt
}
model mybb_mailerrors {
eid Int @id @default(autoincrement())
subject String @default("") @db.VarChar(200)
message String @default("")
toaddress String @default("") @db.VarChar(150)
fromaddress String @default("") @db.VarChar(150)
dateline Int @default(0)
error String @default("")
smtperror String @default("") @db.VarChar(200)
smtpcode Int @default(0) @db.SmallInt
}
model mybb_maillogs {
mid Int @id @default(autoincrement())
subject String @default("") @db.VarChar(200)
message String @default("")
dateline Int @default(0)
fromuid Int @default(0)
fromemail String @default("") @db.VarChar(200)
touid Int @default(0)
toemail String @default("") @db.VarChar(200)
tid Int @default(0)
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
type Int @default(0) @db.SmallInt
}
model mybb_mailqueue {
mid Int @id @default(autoincrement())
mailto String @db.VarChar(200)
mailfrom String @db.VarChar(200)
subject String @db.VarChar(200)
message String @default("")
headers String @default("")
}
model mybb_massemails {
mid Int @id @default(autoincrement())
uid Int @default(0)
subject String @default("") @db.VarChar(200)
message String
htmlmessage String
type Int @default(0) @db.SmallInt
format Int @default(0) @db.SmallInt
dateline Decimal @default(0) @db.Decimal(30, 0)
senddate Decimal @default(0) @db.Decimal(30, 0)
status Int @default(0) @db.SmallInt
sentcount Int @default(0)
totalcount Int @default(0)
conditions String
perpage Int @default(50)
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_moderatorlog {
uid Int @default(0)
dateline Int @default(0)
fid Int @default(0) @db.SmallInt
tid Int @default(0)
pid Int @default(0)
action String @default("")
data String
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
@@ignore
}
model mybb_moderators {
mid Int @id @default(autoincrement())
fid Int @default(0) @db.SmallInt
id Int @default(0)
isgroup Int @default(0) @db.SmallInt
caneditposts Int @default(0) @db.SmallInt
cansoftdeleteposts Int @default(0) @db.SmallInt
canrestoreposts Int @default(0) @db.SmallInt
candeleteposts Int @default(0) @db.SmallInt
cansoftdeletethreads Int @default(0) @db.SmallInt
canrestorethreads Int @default(0) @db.SmallInt
candeletethreads Int @default(0) @db.SmallInt
canviewips Int @default(0) @db.SmallInt
canviewunapprove Int @default(0) @db.SmallInt
canviewdeleted Int @default(0) @db.SmallInt
canopenclosethreads Int @default(0) @db.SmallInt
canstickunstickthreads Int @default(0) @db.SmallInt
canapproveunapprovethreads Int @default(0) @db.SmallInt
canapproveunapproveposts Int @default(0) @db.SmallInt
canapproveunapproveattachs Int @default(0) @db.SmallInt
canmanagethreads Int @default(0) @db.SmallInt
canmanagepolls Int @default(0) @db.SmallInt
canpostclosedthreads Int @default(0) @db.SmallInt
canmovetononmodforum Int @default(0) @db.SmallInt
canusecustomtools Int @default(0) @db.SmallInt
canmanageannouncements Int @default(0) @db.SmallInt
canmanagereportedposts Int @default(0) @db.SmallInt
canviewmodlog Int @default(0) @db.SmallInt
}
model mybb_modtools {
tid Int @id @default(autoincrement())
name String @db.VarChar(200)
description String @default("")
forums String @default("")
groups String @default("")
type String @default("") @db.Char(1)
postoptions String @default("")
threadoptions String @default("")
}
model mybb_mycode {
cid Int @id @default(autoincrement())
title String @default("") @db.VarChar(100)
description String @default("")
regex String @default("")
replacement String @default("")
active Int @default(0) @db.SmallInt
parseorder Int @default(0) @db.SmallInt
}
model mybb_polls {
pid Int @id @default(autoincrement())
tid Int @default(0)
question String @default("") @db.VarChar(200)
dateline Int @default(0)
options String @default("")
votes String @default("")
numoptions Int @default(0) @db.SmallInt
numvotes Int @default(0)
timeout Int @default(0)
closed Int @default(0) @db.SmallInt
multiple Int @default(0) @db.SmallInt
public Int @default(0) @db.SmallInt
maxoptions Int @default(0) @db.SmallInt
}
model mybb_pollvotes {
vid Int @id @default(autoincrement())
pid Int @default(0)
uid Int @default(0)
voteoption Int @default(0) @db.SmallInt
dateline Int @default(0)
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
}
model mybb_posts {
pid Int @id @default(autoincrement())
tid Int @default(0)
replyto Int @default(0)
fid Int @default(0) @db.SmallInt
subject String @default("") @db.VarChar(120)
icon Int @default(0) @db.SmallInt
uid Int @default(0)
username String @default("") @db.VarChar(80)
dateline Int @default(0)
message String @default("")
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
includesig Int @default(0) @db.SmallInt
smilieoff Int @default(0) @db.SmallInt
edituid Int @default(0)
edittime Int @default(0)
editreason String @default("") @db.VarChar(150)
visible Int @default(0) @db.SmallInt
}
model mybb_privatemessages {
pmid Int @id @default(autoincrement())
uid Int @default(0)
toid Int @default(0)
fromid Int @default(0)
recipients String @default("")
folder Int @default(1) @db.SmallInt
subject String @default("") @db.VarChar(120)
icon Int @default(0) @db.SmallInt
message String @default("")
dateline Int @default(0)
deletetime Int @default(0)
status Int @default(0) @db.SmallInt
statustime Int @default(0)
includesig Int @default(0) @db.SmallInt
smilieoff Int @default(0) @db.SmallInt
receipt Int @default(0) @db.SmallInt
readtime Int @default(0)
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
}
model mybb_profilefields {
fid Int @id @default(autoincrement())
name String @default("") @db.VarChar(100)
description String @default("")
disporder Int @default(0) @db.SmallInt
type String @default("")
regex String @default("")
length Int @default(0) @db.SmallInt
maxlength Int @default(0) @db.SmallInt
required Int @default(0) @db.SmallInt
registration Int @default(0) @db.SmallInt
profile Int @default(0) @db.SmallInt
postbit Int @default(0) @db.SmallInt
viewableby String @default("-1")
editableby String @default("-1")
postnum Int @default(0) @db.SmallInt
allowhtml Int @default(0) @db.SmallInt
allowmycode Int @default(0) @db.SmallInt
allowsmilies Int @default(0) @db.SmallInt
allowimgcode Int @default(0) @db.SmallInt
allowvideocode Int @default(0) @db.SmallInt
}
model mybb_promotionlogs {
plid Int @id @default(autoincrement())
pid Int @default(0)
uid Int @default(0)
oldusergroup String @default("0") @db.VarChar(200)
newusergroup Int @default(0) @db.SmallInt
dateline Int @default(0)
type String @default("primary") @db.VarChar(9)
}
model mybb_promotions {
pid Int @id @default(autoincrement())
title String @default("") @db.VarChar(120)
description String @default("")
enabled Int @default(1) @db.SmallInt
logging Int @default(0) @db.SmallInt
posts Int @default(0)
posttype String @default("") @db.VarChar(2)
threads Int @default(0)
threadtype String @default("") @db.VarChar(2)
registered Int @default(0)
registeredtype String @default("") @db.VarChar(20)
online Int @default(0)
onlinetype String @default("") @db.VarChar(20)
reputations Int @default(0)
reputationtype String @default("") @db.VarChar(2)
referrals Int @default(0)
referralstype String @default("") @db.VarChar(2)
warnings Int @default(0)
warningstype String @default("") @db.VarChar(2)
requirements String @default("") @db.VarChar(200)
originalusergroup String @default("0") @db.VarChar(120)
newusergroup Int @default(0) @db.SmallInt
usergrouptype String @default("0") @db.VarChar(120)
}
model mybb_questions {
qid Int @id @default(autoincrement())
question String @default("") @db.VarChar(200)
answer String @default("") @db.VarChar(150)
shown Int @default(0)
correct Int @default(0)
incorrect Int @default(0)
active Int @default(0) @db.SmallInt
}
model mybb_questionsessions {
sid String @unique @default("") @db.VarChar(32)
qid Int @default(0)
dateline Int @default(0)
}
model mybb_reportedcontent {
rid Int @id @default(autoincrement())
id Int @default(0)
id2 Int @default(0)
id3 Int @default(0)
uid Int @default(0)
reportstatus Int @default(0) @db.SmallInt
reasonid Int @default(0) @db.SmallInt
reason String @default("") @db.VarChar(250)
type String @default("") @db.VarChar(50)
reports Int @default(0)
reporters String @default("")
dateline Int @default(0)
lastreport Int @default(0)
}
model mybb_reportreasons {
rid Int @id @default(autoincrement())
title String @default("") @db.VarChar(250)
appliesto String @default("") @db.VarChar(250)
extra Int @default(0) @db.SmallInt
disporder Int @default(0) @db.SmallInt
}
model mybb_reputation {
rid Int @id @default(autoincrement())
uid Int @default(0)
adduid Int @default(0)
pid Int @default(0)
reputation Int @default(0) @db.SmallInt
dateline Int @default(0)
comments String @default("")
}
model mybb_searchlog {
sid String @unique @default("") @db.VarChar(32)
uid Int @default(0)
dateline Int @default(0)
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
threads String @default("")
posts String @default("")
resulttype String @default("") @db.VarChar(10)
querycache String @default("")
keywords String @default("")
}
model mybb_sessions {
sid String @unique @default("") @db.VarChar(32)
uid Int @default(0)
ip Bytes @default(dbgenerated("'\\x'::bytea"))
time Int @default(0)
location String @default("") @db.VarChar(150)
useragent String @default("") @db.VarChar(200)
anonymous Int @default(0) @db.SmallInt
nopermission Int @default(0) @db.SmallInt
location1 Int @default(0)
location2 Int @default(0)
}
model mybb_settinggroups {
gid Int @id @default(autoincrement())
name String @default("") @db.VarChar(100)
title String @default("") @db.VarChar(220)
description String @default("")
disporder Int @default(0) @db.SmallInt
isdefault Int @default(0) @db.SmallInt
}
model mybb_settings {
sid Int @id @default(autoincrement())
name String @default("") @db.VarChar(120)
title String @default("") @db.VarChar(120)
description String @default("")
optionscode String @default("")
value String @default("")
disporder Int @default(0) @db.SmallInt
gid Int @default(0) @db.SmallInt
isdefault Int @default(0) @db.SmallInt
}
model mybb_smilies {
sid Int @id @default(autoincrement())
name String @default("") @db.VarChar(120)
find String
image String @default("") @db.VarChar(220)
disporder Int @default(0) @db.SmallInt
showclickable Int @default(0) @db.SmallInt
}
model mybb_spamlog {
sid Int @id @default(autoincrement())
username String @default("") @db.VarChar(120)
email String @default("") @db.VarChar(220)
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
dateline Decimal @default(0) @db.Decimal(30, 0)
data String @default("")
}
model mybb_spiders {
sid Int @id @default(autoincrement())
name String @default("") @db.VarChar(100)
theme Int @default(0) @db.SmallInt
language String @default("") @db.VarChar(20)
usergroup Int @default(0) @db.SmallInt
useragent String @default("") @db.VarChar(200)
lastvisit Int @default(0)
}
model mybb_stats {
dateline Decimal @unique @default(0) @db.Decimal(30, 0)
numusers Decimal @default(0) @db.Decimal(10, 0)
numthreads Decimal @default(0) @db.Decimal(10, 0)
numposts Decimal @default(0) @db.Decimal(10, 0)
}
model mybb_tasklog {
lid Int @id @default(autoincrement())
tid Int @default(0)
dateline Int @default(0)
data String
}
model mybb_tasks {
tid Int @id @default(autoincrement())
title String @default("") @db.VarChar(120)
description String @default("")
file String @default("") @db.VarChar(30)
minute String @default("") @db.VarChar(200)
hour String @default("") @db.VarChar(200)
day String @default("") @db.VarChar(100)
month String @default("") @db.VarChar(30)
weekday String @default("") @db.VarChar(15)
nextrun Int @default(0)
lastrun Int @default(0)
enabled Int @default(1) @db.SmallInt
logging Int @default(0) @db.SmallInt
locked Int @default(0)
}
model mybb_templategroups {
gid Int @id @default(autoincrement())
prefix String @default("") @db.VarChar(50)
title String @default("") @db.VarChar(100)
isdefault Int @default(0) @db.SmallInt
}
model mybb_templates {
tid Int @id @default(autoincrement())
title String @default("") @db.VarChar(120)
template String @default("")
sid Int @default(0) @db.SmallInt
version String @default("0") @db.VarChar(20)
status String @default("") @db.VarChar(10)
dateline Int @default(0)
}
model mybb_templatesets {
sid Int @id @default(autoincrement())
title String @default("") @db.VarChar(120)
}
model mybb_themes {
tid Int @id @default(autoincrement())
name String @default("") @db.VarChar(100)
pid Int @default(0) @db.SmallInt
def Int @default(0) @db.SmallInt
properties String @default("")
stylesheets String @default("")
allowedgroups String @default("")
}
model mybb_themestylesheets {
sid Int @id @default(autoincrement())
name String @default("") @db.VarChar(30)
tid Decimal @default(0) @db.Decimal(10, 0)
attachedto String
stylesheet String
cachefile String @default("") @db.VarChar(100)
lastmodified Decimal @default(0) @db.Decimal(30, 0)
}
model mybb_threadprefixes {
pid Int @id @default(autoincrement())
prefix String @default("") @db.VarChar(120)
displaystyle String @default("") @db.VarChar(200)
forums String
groups String
}
model mybb_threadratings {
rid Int @id @default(autoincrement())
tid Int @default(0)
uid Int @default(0)
rating Int @default(0) @db.SmallInt
ipaddress Bytes @default(dbgenerated("'\\x'::bytea"))
}
model mybb_threads {
tid Int @id @default(autoincrement())
fid Int @default(0) @db.SmallInt
subject String @default("") @db.VarChar(120)
prefix Int @default(0) @db.SmallInt
icon Int @default(0) @db.SmallInt
poll Int @default(0)
uid Int @default(0)
username String @default("") @db.VarChar(80)
dateline Int @default(0)
firstpost Int @default(0)
lastpost Int @default(0)
lastposter String @default("") @db.VarChar(120)
lastposteruid Int @default(0)
views Int @default(0)
replies Int @default(0)
closed String @default("") @db.VarChar(30)
sticky Int @default(0) @db.SmallInt
numratings Int @default(0) @db.SmallInt
totalratings Int @default(0) @db.SmallInt
notes String @default("")
visible Int @default(0) @db.SmallInt
unapprovedposts Int @default(0)
deletedposts Int @default(0)
attachmentcount Int @default(0)
deletetime Int @default(0)
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_threadsread {
tid Int @default(0)
uid Int @default(0)
dateline Int @default(0)
@@ignore
}
model mybb_threadsubscriptions {
sid Int @id @default(autoincrement())
uid Int @default(0)
tid Int @default(0)
notification Int @default(0) @db.SmallInt
dateline Int @default(0)
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
model mybb_threadviews {
tid Int @default(0)
@@ignore
}
model mybb_upgrade_data {
title String @unique @db.VarChar(30)
contents String
}
model mybb_userfields {
ufid Int @id @default(0)
fid1 String @default("")
fid2 String @default("")
fid3 String @default("")
fid4 String?
}
model mybb_usergroups {
gid Int @id @default(autoincrement())
type Int @default(2) @db.SmallInt
title String @default("") @db.VarChar(120)
description String @default("")
namestyle String @default("{username}") @db.VarChar(200)
usertitle String @default("") @db.VarChar(120)
stars Int @default(0) @db.SmallInt
starimage String @default("") @db.VarChar(120)
image String @default("") @db.VarChar(120)
disporder Int @default(0) @db.SmallInt
isbannedgroup Int @default(0) @db.SmallInt
canview Int @default(0) @db.SmallInt
canviewthreads Int @default(0) @db.SmallInt
canviewprofiles Int @default(0) @db.SmallInt
candlattachments Int @default(0) @db.SmallInt
canviewboardclosed Int @default(0) @db.SmallInt
canpostthreads Int @default(0) @db.SmallInt
canpostreplys Int @default(0) @db.SmallInt
canpostattachments Int @default(0) @db.SmallInt
canratethreads Int @default(0) @db.SmallInt
modposts Int @default(0) @db.SmallInt
modthreads Int @default(0) @db.SmallInt
mod_edit_posts Int @default(0) @db.SmallInt
modattachments Int @default(0) @db.SmallInt
caneditposts Int @default(0) @db.SmallInt
candeleteposts Int @default(0) @db.SmallInt
candeletethreads Int @default(0) @db.SmallInt
caneditattachments Int @default(0) @db.SmallInt
canviewdeletionnotice Int @default(0) @db.SmallInt
canpostpolls Int @default(0) @db.SmallInt
canvotepolls Int @default(0) @db.SmallInt
canundovotes Int @default(0) @db.SmallInt
canusepms Int @default(0) @db.SmallInt
cansendpms Int @default(0) @db.SmallInt
cantrackpms Int @default(0) @db.SmallInt
candenypmreceipts Int @default(0) @db.SmallInt
pmquota Int @default(0)
maxpmrecipients Int @default(5)
cansendemail Int @default(0) @db.SmallInt
cansendemailoverride Int @default(0) @db.SmallInt
maxemails Int @default(5)
emailfloodtime Int @default(5)
canviewmemberlist Int @default(0) @db.SmallInt
canviewcalendar Int @default(0) @db.SmallInt
canaddevents Int @default(0) @db.SmallInt
canbypasseventmod Int @default(0) @db.SmallInt
canmoderateevents Int @default(0) @db.SmallInt
canviewonline Int @default(0) @db.SmallInt
canviewwolinvis Int @default(0) @db.SmallInt
canviewonlineips Int @default(0) @db.SmallInt
cancp Int @default(0) @db.SmallInt
issupermod Int @default(0) @db.SmallInt
cansearch Int @default(0) @db.SmallInt
canusercp Int @default(0) @db.SmallInt
canuploadavatars Int @default(0) @db.SmallInt
canratemembers Int @default(0) @db.SmallInt
canchangename Int @default(0) @db.SmallInt
canbereported Int @default(0) @db.SmallInt
canchangewebsite Int @default(1) @db.SmallInt
showforumteam Int @default(0) @db.SmallInt
usereputationsystem Int @default(0) @db.SmallInt
cangivereputations Int @default(0) @db.SmallInt
candeletereputations Int @default(0) @db.SmallInt
reputationpower Int @default(0)
maxreputationsday Int @default(0)
maxreputationsperuser Int @default(0)
maxreputationsperthread Int @default(0)
candisplaygroup Int @default(0) @db.SmallInt
attachquota Int @default(0)
cancustomtitle Int @default(0) @db.SmallInt
canwarnusers Int @default(0) @db.SmallInt
canreceivewarnings Int @default(0) @db.SmallInt
maxwarningsday Int @default(3)
canmodcp Int @default(0) @db.SmallInt
showinbirthdaylist Int @default(0) @db.SmallInt
canoverridepm Int @default(0) @db.SmallInt
canusesig Int @default(0) @db.SmallInt
canusesigxposts Int @default(0) @db.SmallInt
signofollow Int @default(0) @db.SmallInt
edittimelimit Int @default(0) @db.SmallInt
maxposts Int @default(0) @db.SmallInt
showmemberlist Int @default(1) @db.SmallInt
canmanageannounce Int @default(0) @db.SmallInt
canmanagemodqueue Int @default(0) @db.SmallInt
canmanagereportedcontent Int @default(0) @db.SmallInt
canviewmodlogs Int @default(0) @db.SmallInt
caneditprofiles Int @default(0) @db.SmallInt
canbanusers Int @default(0) @db.SmallInt
canviewwarnlogs Int @default(0) @db.SmallInt
canuseipsearch Int @default(0) @db.SmallInt
}
model mybb_users {
uid Int @id @default(autoincrement())
username String @default("") @db.VarChar(120)
password String @default("") @db.VarChar(120)
salt String @default("") @db.VarChar(10)
loginkey String @default("") @db.VarChar(50)
email String @default("") @db.VarChar(220)
postnum Int @default(0)
threadnum Int @default(0)
avatar String @default("") @db.VarChar(200)
avatardimensions String @default("") @db.VarChar(10)
avatartype String @default("0") @db.VarChar(10)
usergroup Int @default(0) @db.SmallInt
additionalgroups String @default("") @db.VarChar(200)
displaygroup Int @default(0) @db.SmallInt
usertitle String @default("") @db.VarChar(250)
regdate Int @default(0)
lastactive Int @default(0)
lastvisit Int @default(0)
lastpost Int @default(0)
website String @default("") @db.VarChar(200)
icq String @default("") @db.VarChar(10)
skype String @default("") @db.VarChar(75)
google String @default("") @db.VarChar(75)
birthday String @default("") @db.VarChar(15)
birthdayprivacy String @default("all") @db.VarChar(4)
signature String @default("")
allownotices Int @default(0) @db.SmallInt
hideemail Int @default(0) @db.SmallInt
subscriptionmethod Int @default(0) @db.SmallInt
invisible Int @default(0) @db.SmallInt
receivepms Int @default(0) @db.SmallInt
receivefrombuddy Int @default(0) @db.SmallInt
pmnotice Int @default(0) @db.SmallInt
pmnotify Int @default(0) @db.SmallInt
buddyrequestspm Int @default(1) @db.SmallInt
buddyrequestsauto Int @default(0) @db.SmallInt
threadmode String @default("") @db.VarChar(8)
showimages Int @default(0) @db.SmallInt
showvideos Int @default(0) @db.SmallInt
showsigs Int @default(0) @db.SmallInt
showavatars Int @default(0) @db.SmallInt
showquickreply Int @default(0) @db.SmallInt
showredirect Int @default(0) @db.SmallInt
ppp Int @default(0) @db.SmallInt
tpp Int @default(0) @db.SmallInt
daysprune Int @default(0) @db.SmallInt
dateformat String @default("") @db.VarChar(4)
timeformat String @default("") @db.VarChar(4)
timezone String @default("") @db.VarChar(5)
dst Int @default(0) @db.SmallInt
dstcorrection Int @default(0) @db.SmallInt
buddylist String @default("")
ignorelist String @default("")
style Int @default(0) @db.SmallInt
away Int @default(0) @db.SmallInt
awaydate Int @default(0)
returndate String @default("") @db.VarChar(15)
awayreason String @default("") @db.VarChar(200)
pmfolders String @default("")
notepad String @default("")
referrer Int @default(0)
referrals Int @default(0)
reputation Int @default(0)
regip Bytes @default(dbgenerated("'\\x'::bytea"))
lastip Bytes @default(dbgenerated("'\\x'::bytea"))
language String @default("") @db.VarChar(50)
timeonline Int @default(0)
showcodebuttons Int @default(1) @db.SmallInt
totalpms Int @default(0)
unreadpms Int @default(0)
warningpoints Int @default(0)
moderateposts Int @default(0)
moderationtime Int @default(0)
suspendposting Int @default(0) @db.SmallInt
suspensiontime Int @default(0)
suspendsignature Int @default(0) @db.SmallInt
suspendsigtime Int @default(0)
coppauser Int @default(0) @db.SmallInt
classicpostbit Int @default(0) @db.SmallInt
loginattempts Int @default(0) @db.SmallInt
loginlockoutexpiry Int @default(0)
usernotes String @default("")
sourceeditor Int @default(0) @db.SmallInt
disablegoogleanalytics Int @default(0)
}
model mybb_usertitles {
utid Int @id @default(autoincrement())
posts Int @default(0)
title String @default("") @db.VarChar(250)
stars Int @default(0) @db.SmallInt
starimage String @default("") @db.VarChar(120)
}
model mybb_warninglevels {
lid Int @id @default(autoincrement())
percentage Int @default(0) @db.SmallInt
action String
}
model mybb_warnings {
wid Int @id @default(autoincrement())
uid Int @default(0)
tid Int @default(0)
pid Int @default(0)
title String @default("") @db.VarChar(120)
points Int @default(0) @db.SmallInt
dateline Int @default(0)
issuedby Int @default(0)
expires Int @default(0)
expired Int @default(0) @db.SmallInt
daterevoked Int @default(0)
revokedby Int @default(0)
revokereason String @default("")
notes String @default("")
}
model mybb_warningtypes {
tid Int @id @default(autoincrement())
title String @default("") @db.VarChar(120)
points Int @default(0) @db.SmallInt
expirationtime Int @default(0)
}
| openmultiplayer/web/prisma/burgershot.prisma/0 | {
"file_path": "openmultiplayer/web/prisma/burgershot.prisma",
"repo_id": "openmultiplayer",
"token_count": 19621
} | 492 |
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/Southclaws/supervillain"
"github.com/openmultiplayer/web/app/resources/server"
"github.com/openmultiplayer/web/app/resources/user"
"github.com/openmultiplayer/web/app/services/docsindex"
"github.com/openmultiplayer/web/app/transports/api/auth/discord"
"github.com/openmultiplayer/web/app/transports/api/auth/github"
"github.com/openmultiplayer/web/internal/web"
)
// -
//
// What is this!?
//
// This generates TypeScript types from Go structures. This is useful for
// keeping the frontend's type signatures in line with the backend's structures.
//
// Run this task after modifying any the Prisma schema or any of the response
// payloads used by the API.
//
// If you use the Taskfile task `generate` this will be done automatically.
//
// -
func convert(name, prefix string, objs ...interface{}) {
out := fmt.Sprintf("frontend/src/types/_generated_%s.ts", name)
fmt.Println("Generating schemas for", out)
output := strings.Builder{}
output.WriteString(`import * as z from "zod"
`)
for _, v := range objs {
output.WriteString(supervillain.StructToZodSchemaWithPrefix(prefix, v))
}
ioutil.WriteFile(
out,
[]byte(output.String()),
os.ModePerm,
)
}
func main() {
convert("Error", "API", web.Error{})
convert("Server", "", server.All{})
convert("User", "", user.User{})
convert("SearchResult", "", docsindex.SearchResults{})
convert("GitHub", "", github.Link{}, github.Callback{})
convert("Discord", "", discord.Link{}, discord.Callback{})
fmt.Println("DONE")
}
| openmultiplayer/web/types.go/0 | {
"file_path": "openmultiplayer/web/types.go",
"repo_id": "openmultiplayer",
"token_count": 560
} | 493 |
DOCKER_COMPOSE_FLAGS ?= -f docker-compose.yml --log-level ERROR
BUILD_NUMBER ?= local
BRANCH_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
PROJECT_NAME = web
BUILD_DIR_NAME = $(shell pwd | xargs basename | tr -cd '[a-zA-Z0-9_.\-]')
export SHARELATEX_CONFIG ?= /app/test/acceptance/config/settings.test.saas.js
export BASE_CONFIG ?= ${SHARELATEX_CONFIG}
CFG_SAAS=/app/test/acceptance/config/settings.test.saas.js
CFG_SERVER_CE=/app/test/acceptance/config/settings.test.server-ce.js
CFG_SERVER_PRO=/app/test/acceptance/config/settings.test.server-pro.js
DOCKER_COMPOSE := BUILD_NUMBER=$(BUILD_NUMBER) \
BRANCH_NAME=$(BRANCH_NAME) \
PROJECT_NAME=$(PROJECT_NAME) \
MOCHA_GREP=${MOCHA_GREP} \
docker-compose ${DOCKER_COMPOSE_FLAGS}
MODULE_DIRS := $(shell find modules -mindepth 1 -maxdepth 1 -type d -not -name '.git' )
MODULE_MAKEFILES := $(MODULE_DIRS:=/Makefile)
MODULE_NAME=$(shell basename $(MODULE))
$(MODULE_MAKEFILES): Makefile.module
cp Makefile.module $@ || diff Makefile.module $@
#
# Clean
#
clean_ci:
$(DOCKER_COMPOSE) down -v -t 0
docker container list | grep 'days ago' | cut -d ' ' -f 1 - | xargs -r docker container stop
docker image prune -af --filter "until=48h"
docker network prune -f
#
# Tests
#
test: test_unit test_karma test_acceptance test_frontend
test_module: test_unit_module test_acceptance_module
#
# Unit tests
#
test_unit: test_unit_all
test_unit_all:
COMPOSE_PROJECT_NAME=unit_test_all_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) run --rm test_unit npm run test:unit:all
COMPOSE_PROJECT_NAME=unit_test_all_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
test_unit_all_silent:
COMPOSE_PROJECT_NAME=unit_test_all_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) run --rm test_unit npm run test:unit:all:silent
COMPOSE_PROJECT_NAME=unit_test_all_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
test_unit_app:
COMPOSE_PROJECT_NAME=unit_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
COMPOSE_PROJECT_NAME=unit_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) run --name unit_test_$(BUILD_DIR_NAME) --rm test_unit
COMPOSE_PROJECT_NAME=unit_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
TEST_SUITES = $(sort $(filter-out \
$(wildcard test/unit/src/helpers/*), \
$(wildcard test/unit/src/*/*)))
MOCHA_CMD_LINE = \
mocha \
--exit \
--file test/unit/bootstrap.js \
--grep=${MOCHA_GREP} \
--reporter spec \
--timeout 25000 \
.PHONY: $(TEST_SUITES)
$(TEST_SUITES):
$(MOCHA_CMD_LINE) $@
J ?= 1
test_unit_app_parallel_gnu_make: $(TEST_SUITES)
test_unit_app_parallel_gnu_make_docker: export COMPOSE_PROJECT_NAME = \
unit_test_parallel_make_$(BUILD_DIR_NAME)
test_unit_app_parallel_gnu_make_docker:
$(DOCKER_COMPOSE) down -v -t 0
$(DOCKER_COMPOSE) run --rm test_unit \
make test_unit_app_parallel_gnu_make --output-sync -j $(J)
$(DOCKER_COMPOSE) down -v -t 0
test_unit_app_parallel: test_unit_app_parallel_gnu_parallel
test_unit_app_parallel_gnu_parallel: export COMPOSE_PROJECT_NAME = \
unit_test_parallel_$(BUILD_DIR_NAME)
test_unit_app_parallel_gnu_parallel:
$(DOCKER_COMPOSE) down -v -t 0
$(DOCKER_COMPOSE) run --rm test_unit npm run test:unit:app:parallel
$(DOCKER_COMPOSE) down -v -t 0
TEST_UNIT_MODULES = $(MODULE_DIRS:=/test_unit)
$(TEST_UNIT_MODULES): %/test_unit: %/Makefile
test_unit_modules: $(TEST_UNIT_MODULES)
test_unit_module:
$(MAKE) modules/$(MODULE_NAME)/test_unit
#
# Karma frontend tests
#
test_karma: build_test_karma test_karma_run
test_karma_run:
COMPOSE_PROJECT_NAME=karma_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
COMPOSE_PROJECT_NAME=karma_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) run --rm test_karma
COMPOSE_PROJECT_NAME=karma_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
test_karma_build_run: build_test_karma test_karma_run
#
# Frontend tests
#
test_frontend:
COMPOSE_PROJECT_NAME=frontend_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
COMPOSE_PROJECT_NAME=frontend_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) run --rm test_frontend
COMPOSE_PROJECT_NAME=frontend_test_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
#
# Acceptance tests
#
test_acceptance: test_acceptance_app test_acceptance_modules
test_acceptance_saas: test_acceptance_app_saas test_acceptance_modules_merged_saas
test_acceptance_server_ce: test_acceptance_app_server_ce test_acceptance_modules_merged_server_ce
test_acceptance_server_pro: test_acceptance_app_server_pro test_acceptance_modules_merged_server_pro
TEST_ACCEPTANCE_APP := \
test_acceptance_app_saas \
test_acceptance_app_server_ce \
test_acceptance_app_server_pro \
test_acceptance_app: $(TEST_ACCEPTANCE_APP)
test_acceptance_app_saas: export COMPOSE_PROJECT_NAME=acceptance_test_saas_$(BUILD_DIR_NAME)
test_acceptance_app_saas: export SHARELATEX_CONFIG=$(CFG_SAAS)
test_acceptance_app_server_ce: export COMPOSE_PROJECT_NAME=acceptance_test_server_ce_$(BUILD_DIR_NAME)
test_acceptance_app_server_ce: export SHARELATEX_CONFIG=$(CFG_SERVER_CE)
test_acceptance_app_server_pro: export COMPOSE_PROJECT_NAME=acceptance_test_server_pro_$(BUILD_DIR_NAME)
test_acceptance_app_server_pro: export SHARELATEX_CONFIG=$(CFG_SERVER_PRO)
$(TEST_ACCEPTANCE_APP):
$(DOCKER_COMPOSE) down -v -t 0
$(DOCKER_COMPOSE) run --rm test_acceptance
$(DOCKER_COMPOSE) down -v -t 0
# We are using _make magic_ for turning these file-targets into calls to
# sub-Makefiles in the individual modules.
# These sub-Makefiles need to be kept in sync with the template, hence we
# add a dependency on each modules Makefile and cross-link that to the
# template at the very top of this file.
# Example: `web$ make modules/server-ce-scripts/test_acceptance_server_ce`
# Description: Run the acceptance tests of the server-ce-scripts module in a
# Server CE Environment.
# Break down:
# Target: modules/server-ce-scripts/test_acceptance_server_ce
# -> depends on modules/server-ce-scripts/Makefile
# -> add environment variable BASE_CONFIG=$(CFG_SERVER_CE)
# -> BASE_CONFIG=/app/test/acceptance/config/settings.test.server-ce.js
# -> automatic target: `make -C server-ce-scripts test_acceptance_server_ce`
# -> automatic target: run `make test_acceptance_server_ce` in module
# Target: modules/server-ce-scripts/Makefile
# -> depends on Makefile.module
# -> automatic target: copies the file when changed
TEST_ACCEPTANCE_MODULES = $(MODULE_DIRS:=/test_acceptance)
$(TEST_ACCEPTANCE_MODULES): %/test_acceptance: %/Makefile
$(TEST_ACCEPTANCE_MODULES): modules/%/test_acceptance:
$(MAKE) test_acceptance_module MODULE_NAME=$*
TEST_ACCEPTANCE_MODULES_SAAS = $(MODULE_DIRS:=/test_acceptance_saas)
$(TEST_ACCEPTANCE_MODULES_SAAS): %/test_acceptance_saas: %/Makefile
$(TEST_ACCEPTANCE_MODULES_SAAS): export BASE_CONFIG = $(CFG_SAAS)
# This line adds `/test_acceptance_saas` suffix to all items in $(MODULE_DIRS).
TEST_ACCEPTANCE_MODULES_SERVER_CE = $(MODULE_DIRS:=/test_acceptance_server_ce)
# This line adds a dependency on the modules Makefile.
$(TEST_ACCEPTANCE_MODULES_SERVER_CE): %/test_acceptance_server_ce: %/Makefile
# This line adds the environment variable BASE_CONFIG=$(CFG_SERVER_CE) to all
# invocations of `web$ make modules/foo/test_acceptance_server_ce`.
$(TEST_ACCEPTANCE_MODULES_SERVER_CE): export BASE_CONFIG = $(CFG_SERVER_CE)
TEST_ACCEPTANCE_MODULES_SERVER_PRO = $(MODULE_DIRS:=/test_acceptance_server_pro)
$(TEST_ACCEPTANCE_MODULES_SERVER_PRO): %/test_acceptance_server_pro: %/Makefile
$(TEST_ACCEPTANCE_MODULES_SERVER_PRO): export BASE_CONFIG = $(CFG_SERVER_PRO)
CLEAN_TEST_ACCEPTANCE_MODULES = $(MODULE_DIRS:=/clean_test_acceptance)
$(CLEAN_TEST_ACCEPTANCE_MODULES): %/clean_test_acceptance: %/Makefile
clean_test_acceptance_modules: $(CLEAN_TEST_ACCEPTANCE_MODULES)
clean_ci: clean_test_acceptance_modules
test_acceptance_module_noop:
@echo
@echo Module '$(MODULE_NAME)' does not run in ${LABEL}.
@echo
TEST_ACCEPTANCE_MODULE_MAYBE_IN := \
test_acceptance_module_maybe_in_saas \
test_acceptance_module_maybe_in_server_ce \
test_acceptance_module_maybe_in_server_pro \
test_acceptance_module: $(TEST_ACCEPTANCE_MODULE_MAYBE_IN)
test_acceptance_module_maybe_in_saas: export BASE_CONFIG=$(CFG_SAAS)
test_acceptance_module_maybe_in_server_ce: export BASE_CONFIG=$(CFG_SERVER_CE)
test_acceptance_module_maybe_in_server_pro: export BASE_CONFIG=$(CFG_SERVER_PRO)
# We need to figure out whether the module is loaded in a given environment.
# This information is stored in the (base-)settings.
# We get the full list of modules and check for a matching module entry.
# Either the grep will find and emit the module, or exits with code 1, which
# we handle with a fallback to a noop make target.
# Run the node command in a docker-compose container which provides the needed
# npm dependencies (from disk in dev-env or from the CI image in CI).
# Pick the test_unit service which is very light-weight -- the test_acceptance
# service would start mongo/redis.
$(TEST_ACCEPTANCE_MODULE_MAYBE_IN): test_acceptance_module_maybe_in_%:
$(MAKE) $(shell \
SHARELATEX_CONFIG=$(BASE_CONFIG) \
$(DOCKER_COMPOSE) run --rm test_unit \
node test/acceptance/getModuleTargets test_acceptance_$* \
| grep -e /$(MODULE_NAME)/ || echo test_acceptance_module_noop LABEL=$* \
)
# See docs for test_acceptance_server_ce how this works.
test_acceptance_module_saas: export BASE_CONFIG = $(CFG_SAAS)
test_acceptance_module_saas:
$(MAKE) modules/$(MODULE_NAME)/test_acceptance_saas
test_acceptance_module_server_ce: export BASE_CONFIG = $(CFG_SERVER_CE)
test_acceptance_module_server_ce:
$(MAKE) modules/$(MODULE_NAME)/test_acceptance_server_ce
test_acceptance_module_server_pro: export BASE_CONFIG = $(CFG_SERVER_PRO)
test_acceptance_module_server_pro:
$(MAKE) modules/$(MODULE_NAME)/test_acceptance_server_pro
# See docs for test_acceptance_server_ce how this works.
TEST_ACCEPTANCE_MODULES_MERGED_INNER = $(MODULE_DIRS:=/test_acceptance_merged_inner)
$(TEST_ACCEPTANCE_MODULES_MERGED_INNER): %/test_acceptance_merged_inner: %/Makefile
test_acceptance_modules_merged_inner:
$(MAKE) $(shell \
SHARELATEX_CONFIG=$(BASE_CONFIG) \
node test/acceptance/getModuleTargets test_acceptance_merged_inner \
)
# inner loop for running saas tests in parallel
no_more_targets:
# If we ever have more than 40 modules, we need to add _5 targets to all the places and have it START at 41.
test_acceptance_modules_merged_inner_1: export START=1
test_acceptance_modules_merged_inner_2: export START=11
test_acceptance_modules_merged_inner_3: export START=21
test_acceptance_modules_merged_inner_4: export START=31
TEST_ACCEPTANCE_MODULES_MERGED_INNER_SPLIT = \
test_acceptance_modules_merged_inner_1 \
test_acceptance_modules_merged_inner_2 \
test_acceptance_modules_merged_inner_3 \
test_acceptance_modules_merged_inner_4 \
# The node script prints one module per line.
# Using tail and head we skip over the first n=START entries and print the last 10.
# Finally we check with grep for any targets in a batch and print a fallback if none were found.
$(TEST_ACCEPTANCE_MODULES_MERGED_INNER_SPLIT):
$(MAKE) $(shell \
SHARELATEX_CONFIG=$(BASE_CONFIG) \
node test/acceptance/getModuleTargets test_acceptance_merged_inner \
| tail -n+$(START) | head -n 10 \
| grep -e . || echo no_more_targets \
)
# See docs for test_acceptance_server_ce how this works.
test_acceptance_modules_merged_saas: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_saas_$(BUILD_DIR_NAME)
test_acceptance_modules_merged_saas: export BASE_CONFIG = $(CFG_SAAS)
test_acceptance_modules_merged_server_ce: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_server_ce_$(BUILD_DIR_NAME)
test_acceptance_modules_merged_server_ce: export BASE_CONFIG = $(CFG_SERVER_CE)
test_acceptance_modules_merged_server_pro: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_server_pro_$(BUILD_DIR_NAME)
test_acceptance_modules_merged_server_pro: export BASE_CONFIG = $(CFG_SERVER_PRO)
# All these variants run the same command.
# Each target has a different set of environment defined above.
TEST_ACCEPTANCE_MODULES_MERGED_VARIANTS = \
test_acceptance_modules_merged_saas \
test_acceptance_modules_merged_server_ce \
test_acceptance_modules_merged_server_pro \
$(TEST_ACCEPTANCE_MODULES_MERGED_VARIANTS):
$(DOCKER_COMPOSE) down -v -t 0
$(DOCKER_COMPOSE) run --rm test_acceptance make test_acceptance_modules_merged_inner
$(DOCKER_COMPOSE) down -v -t 0
# outer loop for running saas tests in parallel
TEST_ACCEPTANCE_MODULES_MERGED_SPLIT_SAAS = \
test_acceptance_modules_merged_saas_1 \
test_acceptance_modules_merged_saas_2 \
test_acceptance_modules_merged_saas_3 \
test_acceptance_modules_merged_saas_4 \
test_acceptance_modules_merged_saas_1: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_saas_1_$(BUILD_DIR_NAME)
test_acceptance_modules_merged_saas_2: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_saas_2_$(BUILD_DIR_NAME)
test_acceptance_modules_merged_saas_3: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_saas_3_$(BUILD_DIR_NAME)
test_acceptance_modules_merged_saas_4: export COMPOSE_PROJECT_NAME = \
acceptance_test_modules_merged_saas_4_$(BUILD_DIR_NAME)
$(TEST_ACCEPTANCE_MODULES_MERGED_SPLIT_SAAS): export BASE_CONFIG = $(CFG_SAAS)
$(TEST_ACCEPTANCE_MODULES_MERGED_SPLIT_SAAS): test_acceptance_modules_merged_saas_%:
$(DOCKER_COMPOSE) down -v -t 0
$(DOCKER_COMPOSE) run --rm test_acceptance make test_acceptance_modules_merged_inner_$*
$(DOCKER_COMPOSE) down -v -t 0
test_acceptance_modules: $(TEST_ACCEPTANCE_MODULES_MERGED_VARIANTS)
#
# CI tests
#
ci:
MOCHA_ARGS="--reporter tap" \
$(MAKE) test
#
# Lint & format
#
ORG_PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
RUN_LINT_FORMAT ?= \
docker run --rm ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
NODE_MODULES_PATH := ${PATH}:${PWD}/node_modules/.bin:/app/node_modules/.bin
WITH_NODE_MODULES_PATH = \
format_backend \
format_frontend \
format_misc \
format_styles \
format_test_app_unit \
format_test_app_rest \
format_test_modules \
$(TEST_SUITES) \
$(WITH_NODE_MODULES_PATH): export PATH=$(NODE_MODULES_PATH)
lint: lint_backend
lint_backend:
npx eslint \
app.js \
'app/**/*.js' \
'modules/*/index.js' \
'modules/*/app/**/*.js' \
--max-warnings=0
lint: lint_frontend
lint_frontend:
npx eslint \
'frontend/**/*.js' \
'modules/*/frontend/**/*.js' \
--max-warnings=0
lint: lint_test
lint_test: lint_test_app
lint_test_app: lint_test_app_unit
lint_test_app_unit:
npx eslint \
'test/unit/**/*.js' \
--max-warnings=0
lint_test_app: lint_test_app_rest
lint_test_app_rest:
npx eslint \
'test/**/*.js' \
--ignore-pattern 'test/unit/**/*.js' \
--max-warnings=0
lint_test: lint_test_modules
lint_test_modules:
npx eslint \
'modules/*/test/**/*.js' \
--max-warnings=0
lint: lint_misc
# migrations, scripts, webpack config, karma config
lint_misc:
npx eslint . \
--ignore-pattern app.js \
--ignore-pattern 'app/**/*.js' \
--ignore-pattern 'modules/*/app/**/*.js' \
--ignore-pattern 'modules/*/index.js' \
--ignore-pattern 'frontend/**/*.js' \
--ignore-pattern 'modules/*/frontend/**/*.js' \
--ignore-pattern 'test/**/*.js' \
--ignore-pattern 'modules/*/test/**/*.js' \
--max-warnings=0
lint: lint_pug
lint_pug:
bin/lint_pug_templates
lint_in_docker:
$(RUN_LINT_FORMAT) make lint -j --output-sync
format: format_js
format_js:
npm run --silent format
format: format_styles
format_styles:
npm run --silent format:styles
format_fix:
npm run --silent format:fix
format_styles_fix:
npm run --silent format:styles:fix
format_in_docker:
$(RUN_LINT_FORMAT) make format -j --output-sync
#
# Build & publish
#
IMAGE_CI ?= ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
IMAGE_REPO ?= gcr.io/overleaf-ops/$(PROJECT_NAME)
IMAGE_REPO_BRANCH ?= $(IMAGE_REPO):$(BRANCH_NAME)
IMAGE_REPO_MAIN ?= $(IMAGE_REPO):main
IMAGE_REPO_MASTER ?= $(IMAGE_REPO):master
IMAGE_REPO_FINAL ?= $(IMAGE_REPO_BRANCH)-$(BUILD_NUMBER)
export SENTRY_RELEASE ?= ${COMMIT_SHA}
build_deps:
docker build --pull \
--cache-from $(IMAGE_REPO_BRANCH)-deps \
--cache-from $(IMAGE_REPO_MAIN)-deps \
--cache-from $(IMAGE_REPO_MASTER)-deps \
--tag $(IMAGE_REPO_BRANCH)-deps \
--target deps \
.
build_dev:
docker build \
--build-arg SENTRY_RELEASE \
--cache-from $(IMAGE_REPO_BRANCH)-deps \
--cache-from $(IMAGE_CI)-dev \
--tag $(IMAGE_CI) \
--tag $(IMAGE_CI)-dev \
--target dev \
.
build_webpack:
$(MAKE) build_webpack_once \
|| $(MAKE) build_webpack_once
build_webpack_once:
docker build \
--build-arg SENTRY_RELEASE \
--cache-from $(IMAGE_CI)-dev \
--cache-from $(IMAGE_CI)-webpack \
--tag $(IMAGE_CI)-webpack \
--target webpack \
.
build:
docker build \
--build-arg SENTRY_RELEASE \
--cache-from $(IMAGE_CI)-webpack \
--cache-from $(IMAGE_REPO_FINAL) \
--tag $(IMAGE_REPO_FINAL) \
.
build_test_karma:
COMPOSE_PROJECT_NAME=karma_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) build test_karma
publish:
docker push $(DOCKER_REPO)/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
tar:
COMPOSE_PROJECT_NAME=tar_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) run --rm tar
COMPOSE_PROJECT_NAME=tar_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE) down -v -t 0
MODULE_TARGETS = \
$(TEST_ACCEPTANCE_MODULES_SAAS) \
$(TEST_ACCEPTANCE_MODULES_SERVER_CE) \
$(TEST_ACCEPTANCE_MODULES_SERVER_PRO) \
$(TEST_ACCEPTANCE_MODULES_MERGED_INNER) \
$(CLEAN_TEST_ACCEPTANCE_MODULES) \
$(TEST_UNIT_MODULES) \
$(MODULE_TARGETS):
$(MAKE) -C $(dir $@) $(notdir $@) BUILD_DIR_NAME=$(BUILD_DIR_NAME)
.PHONY:
$(MODULE_TARGETS) \
compile_modules compile_modules_full clean_ci \
test test_module test_unit test_unit_app \
test_unit_modules test_unit_module test_karma test_karma_run \
test_karma_build_run test_frontend test_acceptance test_acceptance_app \
test_acceptance_modules test_acceptance_module ci format format_fix lint \
build build_test_karma publish tar
| overleaf/web/Makefile/0 | {
"file_path": "overleaf/web/Makefile",
"repo_id": "overleaf",
"token_count": 7307
} | 494 |
const PrivilegeLevels = {
NONE: false,
READ_ONLY: 'readOnly',
READ_AND_WRITE: 'readAndWrite',
OWNER: 'owner',
}
module.exports = PrivilegeLevels
| overleaf/web/app/src/Features/Authorization/PrivilegeLevels.js/0 | {
"file_path": "overleaf/web/app/src/Features/Authorization/PrivilegeLevels.js",
"repo_id": "overleaf",
"token_count": 61
} | 495 |
const logger = require('logger-sharelatex')
const { Project } = require('../../models/Project')
const ProjectGetter = require('../Project/ProjectGetter')
const UserGetter = require('../User/UserGetter')
const CollaboratorsHandler = require('./CollaboratorsHandler')
const EmailHandler = require('../Email/EmailHandler')
const Errors = require('../Errors/Errors')
const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
const ProjectAuditLogHandler = require('../Project/ProjectAuditLogHandler')
module.exports = {
promises: { transferOwnership },
}
async function transferOwnership(projectId, newOwnerId, options = {}) {
const { allowTransferToNonCollaborators, sessionUserId } = options
// Fetch project and user
const [project, newOwner] = await Promise.all([
_getProject(projectId),
_getUser(newOwnerId),
])
// Exit early if the transferee is already the project owner
const previousOwnerId = project.owner_ref
if (previousOwnerId.equals(newOwnerId)) {
return
}
// Check that user is already a collaborator
if (
!allowTransferToNonCollaborators &&
!_userIsCollaborator(newOwner, project)
) {
throw new Errors.UserNotCollaboratorError({ info: { userId: newOwnerId } })
}
// Transfer ownership
await ProjectAuditLogHandler.promises.addEntry(
projectId,
'transfer-ownership',
sessionUserId,
{ previousOwnerId, newOwnerId }
)
await _transferOwnership(projectId, previousOwnerId, newOwnerId)
// Flush project to TPDS
await TpdsProjectFlusher.promises.flushProjectToTpds(projectId)
// Send confirmation emails
const previousOwner = await UserGetter.promises.getUser(previousOwnerId)
await _sendEmails(project, previousOwner, newOwner)
}
async function _getProject(projectId) {
const project = await ProjectGetter.promises.getProject(projectId, {
owner_ref: 1,
collaberator_refs: 1,
name: 1,
})
if (project == null) {
throw new Errors.ProjectNotFoundError({ info: { projectId } })
}
return project
}
async function _getUser(userId) {
const user = await UserGetter.promises.getUser(userId)
if (user == null) {
throw new Errors.UserNotFoundError({ info: { userId } })
}
return user
}
function _userIsCollaborator(user, project) {
const collaboratorIds = project.collaberator_refs || []
return collaboratorIds.some(collaboratorId => collaboratorId.equals(user._id))
}
async function _transferOwnership(projectId, previousOwnerId, newOwnerId) {
await CollaboratorsHandler.promises.removeUserFromProject(
projectId,
newOwnerId
)
await Project.updateOne(
{ _id: projectId },
{ $set: { owner_ref: newOwnerId } }
).exec()
await CollaboratorsHandler.promises.addUserIdToProject(
projectId,
newOwnerId,
previousOwnerId,
PrivilegeLevels.READ_AND_WRITE
)
}
async function _sendEmails(project, previousOwner, newOwner) {
if (previousOwner == null) {
// The previous owner didn't exist. This is not supposed to happen, but
// since we're changing the owner anyway, we'll just warn
logger.warn(
{ projectId: project._id, ownerId: previousOwner._id },
'Project owner did not exist before ownership transfer'
)
} else {
// Send confirmation emails
await Promise.all([
EmailHandler.promises.sendEmail(
'ownershipTransferConfirmationPreviousOwner',
{
to: previousOwner.email,
project,
newOwner,
}
),
EmailHandler.promises.sendEmail('ownershipTransferConfirmationNewOwner', {
to: newOwner.email,
project,
previousOwner,
}),
])
}
}
| overleaf/web/app/src/Features/Collaborators/OwnershipTransferHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Collaborators/OwnershipTransferHandler.js",
"repo_id": "overleaf",
"token_count": 1257
} | 496 |
/* eslint-disable
camelcase,
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ProjectDownloadsController
const logger = require('logger-sharelatex')
const Metrics = require('@overleaf/metrics')
const ProjectGetter = require('../Project/ProjectGetter')
const ProjectZipStreamManager = require('./ProjectZipStreamManager')
const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
module.exports = ProjectDownloadsController = {
downloadProject(req, res, next) {
const project_id = req.params.Project_id
Metrics.inc('zip-downloads')
return DocumentUpdaterHandler.flushProjectToMongo(
project_id,
function (error) {
if (error != null) {
return next(error)
}
return ProjectGetter.getProject(
project_id,
{ name: true },
function (error, project) {
if (error != null) {
return next(error)
}
return ProjectZipStreamManager.createZipStreamForProject(
project_id,
function (error, stream) {
if (error != null) {
return next(error)
}
res.setContentDisposition('attachment', {
filename: `${project.name}.zip`,
})
res.contentType('application/zip')
return stream.pipe(res)
}
)
}
)
}
)
},
downloadMultipleProjects(req, res, next) {
const project_ids = req.query.project_ids.split(',')
Metrics.inc('zip-downloads-multiple')
return DocumentUpdaterHandler.flushMultipleProjectsToMongo(
project_ids,
function (error) {
if (error != null) {
return next(error)
}
return ProjectZipStreamManager.createZipStreamForMultipleProjects(
project_ids,
function (error, stream) {
if (error != null) {
return next(error)
}
res.setContentDisposition('attachment', {
filename: `Overleaf Projects (${project_ids.length} items).zip`,
})
res.contentType('application/zip')
return stream.pipe(res)
}
)
}
)
},
}
| overleaf/web/app/src/Features/Downloads/ProjectDownloadsController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Downloads/ProjectDownloadsController.js",
"repo_id": "overleaf",
"token_count": 1149
} | 497 |
const OError = require('@overleaf/o-error')
const settings = require('@overleaf/settings')
// Error class for legacy errors so they inherit OError while staying
// backward-compatible (can be instantiated with string as argument instead
// of object)
class BackwardCompatibleError extends OError {
constructor(messageOrOptions) {
if (typeof messageOrOptions === 'string') {
super(messageOrOptions)
} else if (messageOrOptions) {
const { message, info } = messageOrOptions
super(message, info)
} else {
super()
}
}
}
// Error class that facilitates the migration to OError v3 by providing
// a signature in which the 2nd argument can be an object containing
// the `info` object.
class OErrorV2CompatibleError extends OError {
constructor(message, options) {
if (options) {
super(message, options.info)
} else {
super(message)
}
}
}
class NotFoundError extends BackwardCompatibleError {}
class ForbiddenError extends BackwardCompatibleError {}
class ServiceNotConfiguredError extends BackwardCompatibleError {}
class TooManyRequestsError extends BackwardCompatibleError {}
class InvalidNameError extends BackwardCompatibleError {}
class UnsupportedFileTypeError extends BackwardCompatibleError {}
class FileTooLargeError extends BackwardCompatibleError {}
class UnsupportedExportRecordsError extends BackwardCompatibleError {}
class V1HistoryNotSyncedError extends BackwardCompatibleError {}
class ProjectHistoryDisabledError extends BackwardCompatibleError {}
class V1ConnectionError extends BackwardCompatibleError {}
class UnconfirmedEmailError extends BackwardCompatibleError {}
class EmailExistsError extends OErrorV2CompatibleError {
constructor(options) {
super('Email already exists', options)
}
}
class InvalidError extends BackwardCompatibleError {}
class NotInV2Error extends BackwardCompatibleError {}
class SLInV2Error extends BackwardCompatibleError {}
class SAMLIdentityExistsError extends OError {
get i18nKey() {
return 'institution_account_tried_to_add_already_registered'
}
}
class SAMLAlreadyLinkedError extends OError {
get i18nKey() {
return 'institution_account_tried_to_add_already_linked'
}
}
class SAMLEmailNotAffiliatedError extends OError {
get i18nKey() {
return 'institution_account_tried_to_add_not_affiliated'
}
}
class SAMLEmailAffiliatedWithAnotherInstitutionError extends OError {
get i18nKey() {
return 'institution_account_tried_to_add_affiliated_with_another_institution'
}
}
class SAMLSessionDataMissing extends BackwardCompatibleError {
constructor(arg) {
super(arg)
const samlSession =
typeof arg === 'object' && arg !== null && arg.samlSession
? arg.samlSession
: {}
this.tryAgain = true
const {
universityId,
universityName,
externalUserId,
institutionEmail,
} = samlSession
if (
!universityId &&
!universityName &&
!externalUserId &&
!institutionEmail
) {
this.message = 'Missing session data.'
} else if (
!institutionEmail &&
samlSession &&
samlSession.userEmailAttributeUnreliable
) {
this.tryAgain = false
this.message = `Your account settings at your institution prevent us from accessing your email address. You will need to make your email address public at your institution in order to link with ${settings.appName}. Please contact your IT department if you have any questions.`
} else if (!institutionEmail) {
this.message =
'Unable to confirm your institutional email address. The institutional identity provider did not provide an email address in the expected attribute. Please contact us if this keeps happening.'
}
}
}
class ThirdPartyIdentityExistsError extends BackwardCompatibleError {
constructor(arg) {
super(arg)
if (!this.message) {
this.message =
'provider and external id already linked to another account'
}
}
}
class ThirdPartyUserNotFoundError extends BackwardCompatibleError {
constructor(arg) {
super(arg)
if (!this.message) {
this.message = 'user not found for provider and external id'
}
}
}
class SubscriptionAdminDeletionError extends OErrorV2CompatibleError {
constructor(options) {
super('subscription admins cannot be deleted', options)
}
}
class ProjectNotFoundError extends OErrorV2CompatibleError {
constructor(options) {
super('project not found', options)
}
}
class UserNotFoundError extends OErrorV2CompatibleError {
constructor(options) {
super('user not found', options)
}
}
class UserNotCollaboratorError extends OErrorV2CompatibleError {
constructor(options) {
super('user not a collaborator', options)
}
}
class DocHasRangesError extends OErrorV2CompatibleError {
constructor(options) {
super('document has ranges', options)
}
}
class InvalidQueryError extends OErrorV2CompatibleError {
constructor(options) {
super('invalid search query', options)
}
}
class AffiliationError extends OError {}
class InvalidInstitutionalEmailError extends OError {
get i18nKey() {
return 'invalid_institutional_email'
}
}
module.exports = {
OError,
BackwardCompatibleError,
NotFoundError,
ForbiddenError,
ServiceNotConfiguredError,
TooManyRequestsError,
InvalidNameError,
UnsupportedFileTypeError,
FileTooLargeError,
UnsupportedExportRecordsError,
V1HistoryNotSyncedError,
ProjectHistoryDisabledError,
V1ConnectionError,
UnconfirmedEmailError,
EmailExistsError,
InvalidError,
NotInV2Error,
SAMLIdentityExistsError,
SAMLAlreadyLinkedError,
SAMLEmailNotAffiliatedError,
SAMLEmailAffiliatedWithAnotherInstitutionError,
SAMLSessionDataMissing,
SLInV2Error,
ThirdPartyIdentityExistsError,
ThirdPartyUserNotFoundError,
SubscriptionAdminDeletionError,
ProjectNotFoundError,
UserNotFoundError,
UserNotCollaboratorError,
DocHasRangesError,
InvalidQueryError,
AffiliationError,
InvalidInstitutionalEmailError,
}
| overleaf/web/app/src/Features/Errors/Errors.js/0 | {
"file_path": "overleaf/web/app/src/Features/Errors/Errors.js",
"repo_id": "overleaf",
"token_count": 1892
} | 498 |
const Settings = require('@overleaf/settings')
const { URL } = require('url')
function getSafeRedirectPath(value) {
const baseURL = Settings.siteUrl // base URL is required to construct URL from path
const url = new URL(value, baseURL)
let safePath = `${url.pathname}${url.search}${url.hash}`.replace(/^\/+/, '/')
if (safePath === '/') {
safePath = undefined
}
return safePath
}
const UrlHelper = {
getSafeRedirectPath,
wrapUrlWithProxy(url) {
// TODO: Consider what to do for Community and Enterprise edition?
if (!Settings.apis.linkedUrlProxy.url) {
throw new Error('no linked url proxy configured')
}
return `${Settings.apis.linkedUrlProxy.url}?url=${encodeURIComponent(url)}`
},
prependHttpIfNeeded(url) {
if (!url.match('://')) {
url = `http://${url}`
}
return url
},
}
module.exports = UrlHelper
| overleaf/web/app/src/Features/Helpers/UrlHelper.js/0 | {
"file_path": "overleaf/web/app/src/Features/Helpers/UrlHelper.js",
"repo_id": "overleaf",
"token_count": 313
} | 499 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ProjectFileAgent
const AuthorizationManager = require('../Authorization/AuthorizationManager')
const ProjectLocator = require('../Project/ProjectLocator')
const ProjectGetter = require('../Project/ProjectGetter')
const DocstoreManager = require('../Docstore/DocstoreManager')
const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
const FileStoreHandler = require('../FileStore/FileStoreHandler')
const _ = require('underscore')
const Settings = require('@overleaf/settings')
const LinkedFilesHandler = require('./LinkedFilesHandler')
const {
BadDataError,
AccessDeniedError,
BadEntityTypeError,
SourceFileNotFoundError,
ProjectNotFoundError,
V1ProjectNotFoundError,
} = require('./LinkedFilesErrors')
module.exports = ProjectFileAgent = {
createLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
) {
if (!this._canCreate(linkedFileData)) {
return callback(new AccessDeniedError())
}
return this._go(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
)
},
refreshLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
) {
return this._go(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
)
},
_prepare(project_id, linkedFileData, user_id, callback) {
if (callback == null) {
callback = function (err, linkedFileData) {}
}
return this._checkAuth(
project_id,
linkedFileData,
user_id,
(err, allowed) => {
if (err != null) {
return callback(err)
}
if (!allowed) {
return callback(new AccessDeniedError())
}
if (!this._validate(linkedFileData)) {
return callback(new BadDataError())
}
return callback(null, linkedFileData)
}
)
},
_go(project_id, linkedFileData, name, parent_folder_id, user_id, callback) {
linkedFileData = this._sanitizeData(linkedFileData)
return this._prepare(
project_id,
linkedFileData,
user_id,
(err, linkedFileData) => {
if (err != null) {
return callback(err)
}
if (!this._validate(linkedFileData)) {
return callback(new BadDataError())
}
return this._getEntity(
linkedFileData,
user_id,
(err, source_project, entity, type) => {
if (err != null) {
return callback(err)
}
if (type === 'doc') {
return DocstoreManager.getDoc(
source_project._id,
entity._id,
function (err, lines) {
if (err != null) {
return callback(err)
}
return LinkedFilesHandler.importContent(
project_id,
lines.join('\n'),
linkedFileData,
name,
parent_folder_id,
user_id,
function (err, file) {
if (err != null) {
return callback(err)
}
return callback(null, file._id)
}
)
}
) // Created
} else if (type === 'file') {
return FileStoreHandler.getFileStream(
source_project._id,
entity._id,
null,
function (err, fileStream) {
if (err != null) {
return callback(err)
}
return LinkedFilesHandler.importFromStream(
project_id,
fileStream,
linkedFileData,
name,
parent_folder_id,
user_id,
function (err, file) {
if (err != null) {
return callback(err)
}
return callback(null, file._id)
}
)
}
) // Created
} else {
return callback(new BadEntityTypeError())
}
}
)
}
)
},
_getEntity(linkedFileData, current_user_id, callback) {
if (callback == null) {
callback = function (err, entity, type) {}
}
callback = _.once(callback)
const { source_entity_path } = linkedFileData
return this._getSourceProject(linkedFileData, function (err, project) {
if (err != null) {
return callback(err)
}
const source_project_id = project._id
return DocumentUpdaterHandler.flushProjectToMongo(
source_project_id,
function (err) {
if (err != null) {
return callback(err)
}
return ProjectLocator.findElementByPath(
{
project_id: source_project_id,
path: source_entity_path,
exactCaseMatch: true,
},
function (err, entity, type) {
if (err != null) {
if (/^not found.*/.test(err.toString())) {
err = new SourceFileNotFoundError()
}
return callback(err)
}
return callback(null, project, entity, type)
}
)
}
)
})
},
_sanitizeData(data) {
return _.pick(
data,
'provider',
'source_project_id',
'v1_source_doc_id',
'source_entity_path'
)
},
_validate(data) {
return (
(data.source_project_id != null || data.v1_source_doc_id != null) &&
data.source_entity_path != null
)
},
_canCreate(data) {
// Don't allow creation of linked-files with v1 doc ids
return data.v1_source_doc_id == null
},
_getSourceProject: LinkedFilesHandler.getSourceProject,
_checkAuth(project_id, data, current_user_id, callback) {
if (callback == null) {
callback = function (error, allowed) {}
}
callback = _.once(callback)
if (!ProjectFileAgent._validate(data)) {
return callback(new BadDataError())
}
return this._getSourceProject(data, function (err, project) {
if (err != null) {
return callback(err)
}
return AuthorizationManager.canUserReadProject(
current_user_id,
project._id,
null,
function (err, canRead) {
if (err != null) {
return callback(err)
}
return callback(null, canRead)
}
)
})
},
}
| overleaf/web/app/src/Features/LinkedFiles/ProjectFileAgent.js/0 | {
"file_path": "overleaf/web/app/src/Features/LinkedFiles/ProjectFileAgent.js",
"repo_id": "overleaf",
"token_count": 3562
} | 500 |
const OError = require('@overleaf/o-error')
const { Project } = require('../../models/Project')
const MAX_AUDIT_LOG_ENTRIES = 200
module.exports = {
promises: {
addEntry,
},
}
/**
* Add an audit log entry
*
* The entry should include at least the following fields:
*
* - operation: a string identifying the type of operation
* - userId: the user on behalf of whom the operation was performed
* - message: a string detailing what happened
*/
async function addEntry(projectId, operation, initiatorId, info = {}) {
const timestamp = new Date()
const entry = {
operation,
initiatorId,
timestamp,
info,
}
const result = await Project.updateOne(
{ _id: projectId },
{
$push: {
auditLog: { $each: [entry], $slice: -MAX_AUDIT_LOG_ENTRIES },
},
}
).exec()
if (result.nModified === 0) {
throw new OError('project not found', { projectId })
}
}
| overleaf/web/app/src/Features/Project/ProjectAuditLogHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectAuditLogHandler.js",
"repo_id": "overleaf",
"token_count": 321
} | 501 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-unused-vars,
no-useless-escape,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let ProjectRootDocManager
const ProjectEntityHandler = require('./ProjectEntityHandler')
const ProjectEntityUpdateHandler = require('./ProjectEntityUpdateHandler')
const ProjectGetter = require('./ProjectGetter')
const DocumentHelper = require('../Documents/DocumentHelper')
const Path = require('path')
const fs = require('fs')
const { promisify } = require('util')
const async = require('async')
const globby = require('globby')
const _ = require('underscore')
module.exports = ProjectRootDocManager = {
setRootDocAutomatically(project_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ProjectEntityHandler.getAllDocs(project_id, function (error, docs) {
if (error != null) {
return callback(error)
}
const jobs = _.map(
docs,
(doc, path) =>
function (cb) {
if (
ProjectEntityUpdateHandler.isPathValidForRootDoc(path) &&
DocumentHelper.contentHasDocumentclass(doc.lines)
) {
async.setImmediate(function () {
cb(doc._id)
})
} else {
async.setImmediate(function () {
cb(null)
})
}
}
)
return async.series(jobs, function (root_doc_id) {
if (root_doc_id != null) {
return ProjectEntityUpdateHandler.setRootDoc(
project_id,
root_doc_id,
callback
)
} else {
return callback()
}
})
})
},
findRootDocFileFromDirectory(directoryPath, callback) {
if (callback == null) {
callback = function (error, path, content) {}
}
const filePathsPromise = globby(['**/*.{tex,Rtex}'], {
cwd: directoryPath,
followSymlinkedDirectories: false,
onlyFiles: true,
case: false,
})
// the search order is such that we prefer files closer to the project root, then
// we go by file size in ascending order, because people often have a main
// file that just includes a bunch of other files; then we go by name, in
// order to be deterministic
filePathsPromise.then(
unsortedFiles =>
ProjectRootDocManager._sortFileList(
unsortedFiles,
directoryPath,
function (err, files) {
if (err != null) {
return callback(err)
}
let doc = null
return async.until(
() => doc != null || files.length === 0,
function (cb) {
const file = files.shift()
return fs.readFile(
Path.join(directoryPath, file),
'utf8',
function (error, content) {
if (error != null) {
return cb(error)
}
content = (content || '').replace(/\r/g, '')
if (DocumentHelper.contentHasDocumentclass(content)) {
doc = { path: file, content }
}
return cb(null)
}
)
},
err =>
callback(
err,
doc != null ? doc.path : undefined,
doc != null ? doc.content : undefined
)
)
}
),
err => callback(err)
)
// coffeescript's implicit-return mechanism returns filePathsPromise from this method, which confuses mocha
return null
},
setRootDocFromName(project_id, rootDocName, callback) {
if (callback == null) {
callback = function (error) {}
}
return ProjectEntityHandler.getAllDocPathsFromProjectById(
project_id,
function (error, docPaths) {
let doc_id, path
if (error != null) {
return callback(error)
}
// strip off leading and trailing quotes from rootDocName
rootDocName = rootDocName.replace(/^\'|\'$/g, '')
// prepend a slash for the root folder if not present
if (rootDocName[0] !== '/') {
rootDocName = `/${rootDocName}`
}
// find the root doc from the filename
let root_doc_id = null
for (doc_id in docPaths) {
// docpaths have a leading / so allow matching "folder/filename" and "/folder/filename"
path = docPaths[doc_id]
if (path === rootDocName) {
root_doc_id = doc_id
}
}
// try a basename match if there was no match
if (!root_doc_id) {
for (doc_id in docPaths) {
path = docPaths[doc_id]
if (Path.basename(path) === Path.basename(rootDocName)) {
root_doc_id = doc_id
}
}
}
// set the root doc id if we found a match
if (root_doc_id != null) {
return ProjectEntityUpdateHandler.setRootDoc(
project_id,
root_doc_id,
callback
)
} else {
return callback()
}
}
)
},
ensureRootDocumentIsSet(project_id, callback) {
if (callback == null) {
callback = function (error) {}
}
return ProjectGetter.getProject(
project_id,
{ rootDoc_id: 1 },
function (error, project) {
if (error != null) {
return callback(error)
}
if (project == null) {
return callback(new Error('project not found'))
}
if (project.rootDoc_id != null) {
return callback()
} else {
return ProjectRootDocManager.setRootDocAutomatically(
project_id,
callback
)
}
}
)
},
/**
* @param {ObjectId | string} project_id
* @param {Function} callback
*/
ensureRootDocumentIsValid(project_id, callback) {
ProjectGetter.getProjectWithoutDocLines(
project_id,
function (error, project) {
if (error != null) {
return callback(error)
}
if (project == null) {
return callback(new Error('project not found'))
}
if (project.rootDoc_id != null) {
ProjectEntityHandler.getDocPathFromProjectByDocId(
project,
project.rootDoc_id,
(err, docPath) => {
if (docPath) return callback()
ProjectEntityUpdateHandler.unsetRootDoc(project_id, () =>
ProjectRootDocManager.setRootDocAutomatically(
project_id,
callback
)
)
}
)
} else {
return ProjectRootDocManager.setRootDocAutomatically(
project_id,
callback
)
}
}
)
},
_sortFileList(listToSort, rootDirectory, callback) {
if (callback == null) {
callback = function (error, result) {}
}
return async.mapLimit(
listToSort,
5,
(filePath, cb) =>
fs.stat(Path.join(rootDirectory, filePath), function (err, stat) {
if (err != null) {
return cb(err)
}
return cb(null, {
size: stat.size,
path: filePath,
elements: filePath.split(Path.sep).length,
name: Path.basename(filePath),
})
}),
function (err, files) {
if (err != null) {
return callback(err)
}
return callback(
null,
_.map(
files.sort(ProjectRootDocManager._rootDocSort),
file => file.path
)
)
}
)
},
_rootDocSort(a, b) {
// sort first by folder depth
if (a.elements !== b.elements) {
return a.elements - b.elements
}
// ensure main.tex is at the start of each folder
if (a.name === 'main.tex' && b.name !== 'main.tex') {
return -1
}
if (a.name !== 'main.tex' && b.name === 'main.tex') {
return 1
}
// prefer smaller files
if (a.size !== b.size) {
return a.size - b.size
}
// otherwise, use the full path name
return a.path.localeCompare(b.path)
},
}
const promises = {
setRootDocAutomatically: promisify(
ProjectRootDocManager.setRootDocAutomatically
),
findRootDocFileFromDirectory: directoryPath =>
new Promise((resolve, reject) => {
ProjectRootDocManager.findRootDocFileFromDirectory(
directoryPath,
(error, path, content) => {
if (error) {
reject(error)
} else {
resolve({ path, content })
}
}
)
}),
setRootDocFromName: promisify(ProjectRootDocManager.setRootDocFromName),
}
ProjectRootDocManager.promises = promises
module.exports = ProjectRootDocManager
| overleaf/web/app/src/Features/Project/ProjectRootDocManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectRootDocManager.js",
"repo_id": "overleaf",
"token_count": 4416
} | 502 |
const request = require('request')
const Settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const SessionManager = require('../Authentication/SessionManager')
const TEN_SECONDS = 1000 * 10
const languageCodeIsSupported = code =>
Settings.languages.some(lang => lang.code === code)
module.exports = {
proxyRequestToSpellingApi(req, res) {
const { language } = req.body
let url = req.url.slice('/spelling'.length)
if (url === '/check') {
if (!language) {
logger.error('"language" field should be included for spell checking')
return res.status(422).send(JSON.stringify({ misspellings: [] }))
}
if (!languageCodeIsSupported(language)) {
// this log statement can be changed to 'error' once projects with
// unsupported languages are removed from the DB
logger.info({ language }, 'language not supported')
return res.status(422).send(JSON.stringify({ misspellings: [] }))
}
}
const userId = SessionManager.getLoggedInUserId(req.session)
url = `/user/${userId}${url}`
req.headers.Host = Settings.apis.spelling.host
return request({
url: Settings.apis.spelling.url + url,
method: req.method,
headers: req.headers,
json: req.body,
timeout: TEN_SECONDS,
})
.on('error', function (error) {
logger.error({ err: error }, 'Spelling API error')
return res.status(500).end()
})
.pipe(res)
},
}
| overleaf/web/app/src/Features/Spelling/SpellingController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Spelling/SpellingController.js",
"repo_id": "overleaf",
"token_count": 557
} | 503 |
const AnalyticsManager = require('../Analytics/AnalyticsManager')
function sendRecurlyAnalyticsEvent(event, eventData) {
switch (event) {
case 'new_subscription_notification':
_sendSubscriptionStartedEvent(eventData)
break
case 'updated_subscription_notification':
_sendSubscriptionUpdatedEvent(eventData)
break
case 'canceled_subscription_notification':
_sendSubscriptionCancelledEvent(eventData)
break
case 'expired_subscription_notification':
_sendSubscriptionExpiredEvent(eventData)
break
case 'renewed_subscription_notification':
_sendSubscriptionRenewedEvent(eventData)
break
case 'reactivated_account_notification':
_sendSubscriptionReactivatedEvent(eventData)
break
case 'paid_charge_invoice_notification':
if (
eventData.invoice.state === 'paid' &&
eventData.invoice.total_in_cents > 0
) {
_sendInvoicePaidEvent(eventData)
}
break
case 'closed_invoice_notification':
if (
eventData.invoice.state === 'collected' &&
eventData.invoice.total_in_cents > 0
) {
_sendInvoicePaidEvent(eventData)
}
break
}
}
function _sendSubscriptionStartedEvent(eventData) {
const userId = _getUserId(eventData)
const { planCode, quantity, state, isTrial } = _getSubscriptionData(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-started', {
plan_code: planCode,
quantity,
is_trial: isTrial,
})
AnalyticsManager.setUserProperty(userId, 'subscription-plan-code', planCode)
AnalyticsManager.setUserProperty(userId, 'subscription-state', state)
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', isTrial)
}
function _sendSubscriptionUpdatedEvent(eventData) {
const userId = _getUserId(eventData)
const { planCode, quantity, state, isTrial } = _getSubscriptionData(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-updated', {
plan_code: planCode,
quantity,
})
AnalyticsManager.setUserProperty(userId, 'subscription-plan-code', planCode)
AnalyticsManager.setUserProperty(userId, 'subscription-state', state)
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', isTrial)
}
function _sendSubscriptionCancelledEvent(eventData) {
const userId = _getUserId(eventData)
const { planCode, quantity, state, isTrial } = _getSubscriptionData(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-cancelled', {
plan_code: planCode,
quantity,
is_trial: isTrial,
})
AnalyticsManager.setUserProperty(userId, 'subscription-state', state)
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', isTrial)
}
function _sendSubscriptionExpiredEvent(eventData) {
const userId = _getUserId(eventData)
const { planCode, quantity, state, isTrial } = _getSubscriptionData(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-expired', {
plan_code: planCode,
quantity,
is_trial: isTrial,
})
AnalyticsManager.setUserProperty(userId, 'subscription-plan-code', planCode)
AnalyticsManager.setUserProperty(userId, 'subscription-state', state)
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', isTrial)
}
function _sendSubscriptionRenewedEvent(eventData) {
const userId = _getUserId(eventData)
const { planCode, quantity, state, isTrial } = _getSubscriptionData(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-renewed', {
plan_code: planCode,
quantity,
is_trial: isTrial,
})
AnalyticsManager.setUserProperty(userId, 'subscription-plan-code', planCode)
AnalyticsManager.setUserProperty(userId, 'subscription-state', state)
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', isTrial)
}
function _sendSubscriptionReactivatedEvent(eventData) {
const userId = _getUserId(eventData)
const { planCode, quantity, state, isTrial } = _getSubscriptionData(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-reactivated', {
plan_code: planCode,
quantity,
})
AnalyticsManager.setUserProperty(userId, 'subscription-plan-code', planCode)
AnalyticsManager.setUserProperty(userId, 'subscription-state', state)
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', isTrial)
}
function _sendInvoicePaidEvent(eventData) {
const userId = _getUserId(eventData)
AnalyticsManager.recordEvent(userId, 'subscription-invoice-collected')
AnalyticsManager.setUserProperty(userId, 'subscription-is-trial', false)
}
function _getUserId(eventData) {
let userId
if (eventData && eventData.account && eventData.account.account_code) {
userId = eventData.account.account_code
} else {
throw new Error(
'account.account_code missing in event data to identity user ID'
)
}
return userId
}
function _getSubscriptionData(eventData) {
const isTrial =
eventData.subscription.trial_started_at &&
eventData.subscription.current_period_started_at &&
eventData.subscription.trial_started_at.getTime() ===
eventData.subscription.current_period_started_at.getTime()
return {
planCode: eventData.subscription.plan.plan_code,
quantity: eventData.subscription.quantity,
state: eventData.subscription.state,
isTrial,
}
}
module.exports = {
sendRecurlyAnalyticsEvent,
}
| overleaf/web/app/src/Features/Subscription/RecurlyEventHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/RecurlyEventHandler.js",
"repo_id": "overleaf",
"token_count": 1848
} | 504 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
module.exports = [
{
feature: 'number_collab',
value: 'str',
plans: {
free: '1',
personal: '1',
coll: '10',
prof: 'unlimited',
},
student: '6',
},
{
feature: 'unlimited_private',
value: 'bool',
info: 'unlimited_private_info',
plans: {
free: true,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'realtime_collab',
value: 'bool',
info: 'realtime_collab_info',
plans: {
free: true,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'thousands_templates',
value: 'bool',
info: 'hundreds_templates_info',
plans: {
free: true,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'powerful_latex_editor',
value: 'bool',
info: 'latex_editor_info',
plans: {
free: true,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'compile_timeout',
value: 'str',
plans: {
free: '1 min',
personal: '4 mins',
coll: '4 mins',
prof: '4 mins',
},
student: '4 mins',
},
{
feature: 'realtime_track_changes',
value: 'bool',
info: 'realtime_track_changes_info',
plans: {
free: false,
personal: false,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'full_doc_history',
value: 'bool',
info: 'full_doc_history_info',
plans: {
free: false,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'reference_search',
value: 'bool',
info: 'reference_search_info',
plans: {
free: false,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'reference_sync',
info: 'reference_sync_info',
value: 'bool',
plans: {
free: false,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'dropbox_integration_lowercase',
value: 'bool',
info: 'dropbox_integration_info',
plans: {
free: false,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'github_integration_lowercase',
value: 'bool',
info: 'github_integration_info',
plans: {
free: false,
personal: true,
coll: true,
prof: true,
},
student: true,
},
{
feature: 'priority_support',
value: 'bool',
plans: {
free: false,
personal: true,
coll: true,
prof: true,
},
student: true,
},
]
| overleaf/web/app/src/Features/Subscription/planFeatures.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/planFeatures.js",
"repo_id": "overleaf",
"token_count": 1340
} | 505 |
const { Project } = require('../../models/Project')
const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
const { ObjectId } = require('mongodb')
const Settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const V1Api = require('../V1/V1Api')
const crypto = require('crypto')
const { promisifyAll } = require('../../util/promises')
const Analytics = require('../Analytics/AnalyticsManager')
const READ_AND_WRITE_TOKEN_PATTERN = '([0-9]+[a-z]{6,12})'
const READ_ONLY_TOKEN_PATTERN = '([a-z]{12})'
const TokenAccessHandler = {
TOKEN_TYPES: {
READ_ONLY: PrivilegeLevels.READ_ONLY,
READ_AND_WRITE: PrivilegeLevels.READ_AND_WRITE,
},
ANONYMOUS_READ_AND_WRITE_ENABLED:
Settings.allowAnonymousReadAndWriteSharing === true,
READ_AND_WRITE_TOKEN_PATTERN,
READ_AND_WRITE_TOKEN_REGEX: new RegExp(`^${READ_AND_WRITE_TOKEN_PATTERN}$`),
READ_AND_WRITE_URL_REGEX: new RegExp(`^/${READ_AND_WRITE_TOKEN_PATTERN}$`),
READ_ONLY_TOKEN_PATTERN,
READ_ONLY_TOKEN_REGEX: new RegExp(`^${READ_ONLY_TOKEN_PATTERN}$`),
READ_ONLY_URL_REGEX: new RegExp(`^/read/${READ_ONLY_TOKEN_PATTERN}$`),
makeReadAndWriteTokenUrl(token) {
return `/${token}`
},
makeReadOnlyTokenUrl(token) {
return `/read/${token}`
},
makeTokenUrl(token) {
const tokenType = TokenAccessHandler.getTokenType(token)
if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE) {
return TokenAccessHandler.makeReadAndWriteTokenUrl(token)
} else if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_ONLY) {
return TokenAccessHandler.makeReadOnlyTokenUrl(token)
} else {
throw new Error('invalid token type')
}
},
getTokenType(token) {
if (!token) {
return null
}
if (token.match(`^${TokenAccessHandler.READ_ONLY_TOKEN_PATTERN}$`)) {
return TokenAccessHandler.TOKEN_TYPES.READ_ONLY
} else if (
token.match(`^${TokenAccessHandler.READ_AND_WRITE_TOKEN_PATTERN}$`)
) {
return TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE
}
return null
},
isReadOnlyToken(token) {
return (
TokenAccessHandler.getTokenType(token) ===
TokenAccessHandler.TOKEN_TYPES.READ_ONLY
)
},
isReadAndWriteToken(token) {
return (
TokenAccessHandler.getTokenType(token) ===
TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE
)
},
isValidToken(token) {
return TokenAccessHandler.getTokenType(token) != null
},
tokenAccessEnabledForProject(project) {
return project.publicAccesLevel === PublicAccessLevels.TOKEN_BASED
},
_projectFindOne(query, callback) {
Project.findOne(
query,
{
_id: 1,
tokens: 1,
publicAccesLevel: 1,
owner_ref: 1,
name: 1,
},
callback
)
},
getProjectByReadOnlyToken(token, callback) {
TokenAccessHandler._projectFindOne({ 'tokens.readOnly': token }, callback)
},
_extractNumericPrefix(token) {
return token.match(/^(\d+)\w+/)
},
_extractStringSuffix(token) {
return token.match(/^\d+(\w+)/)
},
getProjectByReadAndWriteToken(token, callback) {
const numericPrefixMatch = TokenAccessHandler._extractNumericPrefix(token)
if (!numericPrefixMatch) {
return callback(null, null)
}
const numerics = numericPrefixMatch[1]
TokenAccessHandler._projectFindOne(
{
'tokens.readAndWritePrefix': numerics,
},
function (err, project) {
if (err != null) {
return callback(err)
}
if (project == null) {
return callback(null, null)
}
try {
if (
!crypto.timingSafeEqual(
Buffer.from(token),
Buffer.from(project.tokens.readAndWrite)
)
) {
logger.err(
{ token },
'read-and-write token match on numeric section, but not on full token'
)
return callback(null, null)
} else {
return callback(null, project)
}
} catch (error) {
err = error
logger.err({ token, cryptoErr: err }, 'error comparing tokens')
return callback(null, null)
}
}
)
},
getProjectByToken(tokenType, token, callback) {
if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_ONLY) {
TokenAccessHandler.getProjectByReadOnlyToken(token, callback)
} else if (tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE) {
TokenAccessHandler.getProjectByReadAndWriteToken(token, callback)
} else {
return callback(new Error('invalid token type'))
}
},
addReadOnlyUserToProject(userId, projectId, callback) {
userId = ObjectId(userId.toString())
projectId = ObjectId(projectId.toString())
Analytics.recordEvent(userId, 'project-joined', { mode: 'read-only' })
Project.updateOne(
{
_id: projectId,
},
{
$addToSet: { tokenAccessReadOnly_refs: userId },
},
callback
)
},
addReadAndWriteUserToProject(userId, projectId, callback) {
userId = ObjectId(userId.toString())
projectId = ObjectId(projectId.toString())
Analytics.recordEvent(userId, 'project-joined', { mode: 'read-write' })
Project.updateOne(
{
_id: projectId,
},
{
$addToSet: { tokenAccessReadAndWrite_refs: userId },
},
callback
)
},
grantSessionTokenAccess(req, projectId, token) {
if (!req.session) {
return
}
if (!req.session.anonTokenAccess) {
req.session.anonTokenAccess = {}
}
req.session.anonTokenAccess[projectId.toString()] = token
},
getRequestToken(req, projectId) {
const token =
(req.session &&
req.session.anonTokenAccess &&
req.session.anonTokenAccess[projectId.toString()]) ||
req.headers['x-sl-anonymous-access-token']
return token
},
validateTokenForAnonymousAccess(projectId, token, callback) {
if (!token) {
return callback(null, false, false)
}
const tokenType = TokenAccessHandler.getTokenType(token)
if (!tokenType) {
return callback(new Error('invalid token type'))
}
TokenAccessHandler.getProjectByToken(tokenType, token, (err, project) => {
if (err) {
return callback(err)
}
if (
!project ||
!TokenAccessHandler.tokenAccessEnabledForProject(project) ||
project._id.toString() !== projectId.toString()
) {
return callback(null, false, false)
}
// TODO: think about cleaning up this interface and its usage in AuthorizationManager
return callback(
null,
tokenType === TokenAccessHandler.TOKEN_TYPES.READ_AND_WRITE &&
TokenAccessHandler.ANONYMOUS_READ_AND_WRITE_ENABLED,
tokenType === TokenAccessHandler.TOKEN_TYPES.READ_ONLY
)
})
},
protectTokens(project, privilegeLevel) {
if (!project || !project.tokens) {
return
}
if (privilegeLevel === PrivilegeLevels.OWNER) {
return
}
if (privilegeLevel !== PrivilegeLevels.READ_AND_WRITE) {
project.tokens.readAndWrite = ''
project.tokens.readAndWritePrefix = ''
}
if (privilegeLevel !== PrivilegeLevels.READ_ONLY) {
project.tokens.readOnly = ''
}
},
getV1DocPublishedInfo(token, callback) {
// default to allowing access
if (!Settings.apis.v1 || !Settings.apis.v1.url) {
return callback(null, { allow: true })
}
V1Api.request(
{ url: `/api/v1/sharelatex/docs/${token}/is_published` },
function (err, response, body) {
if (err != null) {
return callback(err)
}
callback(null, body)
}
)
},
getV1DocInfo(token, v2UserId, callback) {
if (!Settings.apis || !Settings.apis.v1) {
return callback(null, {
exists: true,
exported: false,
})
}
const v1Url = `/api/v1/sharelatex/docs/${token}/info`
V1Api.request({ url: v1Url }, function (err, response, body) {
if (err != null) {
return callback(err)
}
callback(null, body)
})
},
}
TokenAccessHandler.promises = promisifyAll(TokenAccessHandler, {
without: [
'getTokenType',
'tokenAccessEnabledForProject',
'_extractNumericPrefix',
'_extractStringSuffix',
'_projectFindOne',
'grantSessionTokenAccess',
'getRequestToken',
'protectTokens',
'validateTokenForAnonymousAccess',
],
})
module.exports = TokenAccessHandler
| overleaf/web/app/src/Features/TokenAccess/TokenAccessHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/TokenAccess/TokenAccessHandler.js",
"repo_id": "overleaf",
"token_count": 3638
} | 506 |
const logger = require('logger-sharelatex')
const SessionManager = require('../Authentication/SessionManager')
const UserGetter = require('./UserGetter')
const UserUpdater = require('./UserUpdater')
const UserSessionsManager = require('./UserSessionsManager')
const EmailHandler = require('../Email/EmailHandler')
const EmailHelper = require('../Helpers/EmailHelper')
const UserEmailsConfirmationHandler = require('./UserEmailsConfirmationHandler')
const { endorseAffiliation } = require('../Institutions/InstitutionsAPI')
const Errors = require('../Errors/Errors')
const HttpErrorHandler = require('../Errors/HttpErrorHandler')
const { expressify } = require('../../util/promises')
async function _sendSecurityAlertEmail(user, email) {
const emailOptions = {
to: user.email,
actionDescribed: `a secondary email address has been added to your account ${user.email}`,
message: [
`<span style="display:inline-block;padding: 0 20px;width:100%;">Added: <br/><b>${email}</b></span>`,
],
action: 'secondary email address added',
}
await EmailHandler.promises.sendEmail('securityAlert', emailOptions)
}
async function add(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const email = EmailHelper.parseEmail(req.body.email)
if (!email) {
return res.sendStatus(422)
}
const user = await UserGetter.promises.getUser(userId, { email: 1 })
const affiliationOptions = {
university: req.body.university,
role: req.body.role,
department: req.body.department,
}
try {
await UserUpdater.promises.addEmailAddress(
userId,
email,
affiliationOptions,
{
initiatorId: user._id,
ipAddress: req.ip,
}
)
} catch (error) {
return UserEmailsController._handleEmailError(error, req, res, next)
}
await _sendSecurityAlertEmail(user, email)
await UserEmailsConfirmationHandler.promises.sendConfirmationEmail(
userId,
email
)
res.sendStatus(204)
}
function resendConfirmation(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const email = EmailHelper.parseEmail(req.body.email)
if (!email) {
return res.sendStatus(422)
}
UserGetter.getUserByAnyEmail(email, { _id: 1 }, function (error, user) {
if (error) {
return next(error)
}
if (!user || user._id.toString() !== userId) {
return res.sendStatus(422)
}
UserEmailsConfirmationHandler.sendConfirmationEmail(
userId,
email,
function (error) {
if (error) {
return next(error)
}
res.sendStatus(200)
}
)
})
}
function sendReconfirmation(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const email = EmailHelper.parseEmail(req.body.email)
if (!email) {
return res.sendStatus(400)
}
UserGetter.getUserByAnyEmail(email, { _id: 1 }, function (error, user) {
if (error) {
return next(error)
}
if (!user || user._id.toString() !== userId) {
return res.sendStatus(422)
}
UserEmailsConfirmationHandler.sendReconfirmationEmail(
userId,
email,
function (error) {
if (error) {
return next(error)
}
res.sendStatus(200)
}
)
})
}
const UserEmailsController = {
list(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
UserGetter.getUserFullEmails(userId, function (error, fullEmails) {
if (error) {
return next(error)
}
res.json(fullEmails)
})
},
add: expressify(add),
remove(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const email = EmailHelper.parseEmail(req.body.email)
if (!email) {
return res.sendStatus(422)
}
UserUpdater.removeEmailAddress(userId, email, function (error) {
if (error) {
return next(error)
}
res.sendStatus(200)
})
},
setDefault(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const email = EmailHelper.parseEmail(req.body.email)
if (!email) {
return res.sendStatus(422)
}
const auditLog = {
initiatorId: userId,
ipAddress: req.ip,
}
UserUpdater.setDefaultEmailAddress(
userId,
email,
false,
auditLog,
true,
err => {
if (err) {
return UserEmailsController._handleEmailError(err, req, res, next)
}
SessionManager.setInSessionUser(req.session, { email: email })
const user = SessionManager.getSessionUser(req.session)
UserSessionsManager.revokeAllUserSessions(
user,
[req.sessionID],
err => {
if (err)
logger.warn(
{ err },
'failed revoking secondary sessions after changing default email'
)
}
)
res.sendStatus(200)
}
)
},
endorse(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const email = EmailHelper.parseEmail(req.body.email)
if (!email) {
return res.sendStatus(422)
}
endorseAffiliation(
userId,
email,
req.body.role,
req.body.department,
function (error) {
if (error) {
return next(error)
}
res.sendStatus(204)
}
)
},
resendConfirmation,
sendReconfirmation,
showConfirm(req, res, next) {
res.render('user/confirm_email', {
token: req.query.token,
title: 'confirm_email',
})
},
confirm(req, res, next) {
const { token } = req.body
if (!token) {
return res.status(422).json({
message: req.i18n.translate('confirmation_link_broken'),
})
}
UserEmailsConfirmationHandler.confirmEmailFromToken(
token,
function (error) {
if (error) {
if (error instanceof Errors.NotFoundError) {
res.status(404).json({
message: req.i18n.translate('confirmation_token_invalid'),
})
} else {
next(error)
}
} else {
res.sendStatus(200)
}
}
)
},
_handleEmailError(error, req, res, next) {
if (error instanceof Errors.UnconfirmedEmailError) {
return HttpErrorHandler.conflict(req, res, 'email must be confirmed')
} else if (error instanceof Errors.EmailExistsError) {
const message = req.i18n.translate('email_already_registered')
return HttpErrorHandler.conflict(req, res, message)
} else if (error.message === '422: Email does not belong to university') {
const message = req.i18n.translate('email_does_not_belong_to_university')
return HttpErrorHandler.conflict(req, res, message)
}
next(error)
},
}
module.exports = UserEmailsController
| overleaf/web/app/src/Features/User/UserEmailsController.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserEmailsController.js",
"repo_id": "overleaf",
"token_count": 2833
} | 507 |
const { expressify } = require('../../util/promises')
const async = require('async')
const UserMembershipAuthorization = require('./UserMembershipAuthorization')
const AuthenticationController = require('../Authentication/AuthenticationController')
const UserMembershipHandler = require('./UserMembershipHandler')
const EntityConfigs = require('./UserMembershipEntityConfigs')
const Errors = require('../Errors/Errors')
const HttpErrorHandler = require('../Errors/HttpErrorHandler')
const TemplatesManager = require('../Templates/TemplatesManager')
// set of middleware arrays or functions that checks user access to an entity
// (publisher, institution, group, template, etc.)
const UserMembershipMiddleware = {
requireTeamMetricsAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('team'),
fetchEntity(),
requireEntity(),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('groupMetrics'),
]),
],
requireGroupManagementAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('group'),
fetchEntity(),
requireEntity(),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('groupManagement'),
]),
],
requireGroupMetricsAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('group'),
fetchEntity(),
requireEntity(),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('groupMetrics'),
]),
],
requireGroupManagersManagementAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('groupManagers'),
fetchEntity(),
requireEntity(),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('groupManagement'),
]),
],
requireInstitutionMetricsAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('institution'),
fetchEntity(),
requireEntityOrCreate('institutionManagement'),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('institutionMetrics'),
]),
],
requireInstitutionManagementAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('institution'),
fetchEntity(),
requireEntityOrCreate('institutionManagement'),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('institutionManagement'),
]),
],
requireInstitutionManagementStaffAccess: [
AuthenticationController.requireLogin(),
allowAccessIfAny([
UserMembershipAuthorization.hasStaffAccess('institutionManagement'),
]),
fetchEntityConfig('institution'),
fetchEntity(),
requireEntityOrCreate('institutionManagement'),
],
requirePublisherMetricsAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('publisher'),
fetchEntity(),
requireEntityOrCreate('publisherManagement'),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('publisherMetrics'),
]),
],
requirePublisherManagementAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('publisher'),
fetchEntity(),
requireEntityOrCreate('publisherManagement'),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('publisherManagement'),
]),
],
requireConversionMetricsAccess: [
AuthenticationController.requireLogin(),
fetchEntityConfig('publisher'),
fetchEntity(),
requireEntityOrCreate('publisherManagement'),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('publisherMetrics'),
]),
],
requireAdminMetricsAccess: [
AuthenticationController.requireLogin(),
allowAccessIfAny([
UserMembershipAuthorization.hasStaffAccess('adminMetrics'),
]),
],
requireTemplateMetricsAccess: [
AuthenticationController.requireLogin(),
fetchV1Template(),
requireV1Template(),
fetchEntityConfig('publisher'),
fetchPublisherFromTemplate(),
allowAccessIfAny([
UserMembershipAuthorization.hasEntityAccess(),
UserMembershipAuthorization.hasStaffAccess('publisherMetrics'),
]),
],
requirePublisherCreationAccess: [
AuthenticationController.requireLogin(),
allowAccessIfAny([
UserMembershipAuthorization.hasStaffAccess('publisherManagement'),
]),
fetchEntityConfig('publisher'),
],
requireInstitutionCreationAccess: [
AuthenticationController.requireLogin(),
allowAccessIfAny([
UserMembershipAuthorization.hasStaffAccess('institutionManagement'),
]),
fetchEntityConfig('institution'),
],
// graphs access is an edge-case:
// - the entity id is in `req.query.resource_id`. It must be set as
// `req.params.id`
// - the entity name is in `req.query.resource_type` and is used to find the
// require middleware depending on the entity name
requireGraphAccess(req, res, next) {
req.params.id = req.query.resource_id
let entityName = req.query.resource_type
if (!entityName) {
return HttpErrorHandler.notFound(req, res, 'resource_type param missing')
}
entityName = entityName.charAt(0).toUpperCase() + entityName.slice(1)
const middleware =
UserMembershipMiddleware[`require${entityName}MetricsAccess`]
if (!middleware) {
return HttpErrorHandler.notFound(
req,
res,
`incorrect entity name: ${entityName}`
)
}
// run the list of middleware functions in series. This is essencially
// a poor man's middleware runner
async.eachSeries(middleware, (fn, callback) => fn(req, res, callback), next)
},
}
module.exports = UserMembershipMiddleware
// fetch entity config and set it in the request
function fetchEntityConfig(entityName) {
return (req, res, next) => {
const entityConfig = EntityConfigs[entityName]
req.entityName = entityName
req.entityConfig = entityConfig
next()
}
}
// fetch the entity with id and config, and set it in the request
function fetchEntity() {
return expressify(async (req, res, next) => {
const entity = await UserMembershipHandler.promises.getEntityWithoutAuthorizationCheck(
req.params.id,
req.entityConfig
)
req.entity = entity
next()
})
}
function fetchPublisherFromTemplate() {
return (req, res, next) => {
if (req.template.brand.slug) {
// set the id as the publisher's id as it's the entity used for access
// control
req.params.id = req.template.brand.slug
return fetchEntity()(req, res, next)
} else {
return next()
}
}
}
// ensure an entity was found, or fail with 404
function requireEntity() {
return (req, res, next) => {
if (req.entity) {
return next()
}
throw new Errors.NotFoundError(
`no '${req.entityName}' entity with '${req.params.id}'`
)
}
}
// ensure an entity was found or redirect to entity creation page if the user
// has permissions to create the entity, or fail with 404
function requireEntityOrCreate(creationStaffAccess) {
return (req, res, next) => {
if (req.entity) {
return next()
}
if (UserMembershipAuthorization.hasStaffAccess(creationStaffAccess)(req)) {
res.redirect(`/entities/${req.entityName}/create/${req.params.id}`)
return
}
throw new Errors.NotFoundError(
`no '${req.entityName}' entity with '${req.params.id}'`
)
}
}
// fetch the template from v1, and set it in the request
function fetchV1Template() {
return expressify(async (req, res, next) => {
const templateId = req.params.id
const body = await TemplatesManager.promises.fetchFromV1(templateId)
req.template = {
id: body.id,
title: body.title,
brand: body.brand,
}
next()
})
}
// ensure a template was found, or fail with 404
function requireV1Template() {
return (req, res, next) => {
if (req.template.id) {
return next()
}
throw new Errors.NotFoundError('no template found')
}
}
// run a serie of synchronous access functions and call `next` if any of the
// retur values is truly. Redirect to restricted otherwise
function allowAccessIfAny(accessFunctions) {
return (req, res, next) => {
for (const accessFunction of accessFunctions) {
if (accessFunction(req)) {
return next()
}
}
HttpErrorHandler.forbidden(req, res)
}
}
| overleaf/web/app/src/Features/UserMembership/UserMembershipMiddleware.js/0 | {
"file_path": "overleaf/web/app/src/Features/UserMembership/UserMembershipMiddleware.js",
"repo_id": "overleaf",
"token_count": 2839
} | 508 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
module.exports = {
user(user) {
if (user == null) {
return null
}
if (user._id == null) {
user = { _id: user }
}
return {
id: user._id,
email: user.email,
first_name: user.name,
last_name: user.name,
}
},
project(project) {
if (project == null) {
return null
}
if (project._id == null) {
project = { _id: project }
}
return {
id: project._id,
name: project.name,
}
},
docs(docs) {
if ((docs != null ? docs.map : undefined) == null) {
return
}
return docs.map(doc => ({
path: doc.path,
id: doc.doc,
}))
},
files(files) {
if ((files != null ? files.map : undefined) == null) {
return
}
return files.map(file => ({
path: file.path,
id: file.file,
}))
},
}
| overleaf/web/app/src/infrastructure/LoggerSerializers.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/LoggerSerializers.js",
"repo_id": "overleaf",
"token_count": 501
} | 509 |
const Bowser = require('bowser')
const Settings = require('@overleaf/settings')
const Url = require('url')
const { getSafeRedirectPath } = require('../Features/Helpers/UrlHelper')
function unsupportedBrowserMiddleware(req, res, next) {
if (!Settings.unsupportedBrowsers) return next()
const userAgent = req.headers['user-agent']
if (!userAgent) return next()
const parser = Bowser.getParser(userAgent)
// Allow bots through by only ignoring bots or unrecognised UA strings
const isBot = parser.isPlatform('bot') || !parser.getBrowserName()
if (isBot) return next()
const isUnsupported = parser.satisfies(Settings.unsupportedBrowsers)
if (isUnsupported) {
return res.redirect(
Url.format({
pathname: '/unsupported-browser',
query: { fromURL: req.originalUrl },
})
)
}
next()
}
function renderUnsupportedBrowserPage(req, res) {
let fromURL
if (typeof req.query.fromURL === 'string') {
try {
fromURL = Settings.siteUrl + getSafeRedirectPath(req.query.fromURL)
} catch (e) {}
}
res.render('general/unsupported-browser', { fromURL })
}
module.exports = {
renderUnsupportedBrowserPage,
unsupportedBrowserMiddleware,
}
| overleaf/web/app/src/infrastructure/UnsupportedBrowserMiddleware.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/UnsupportedBrowserMiddleware.js",
"repo_id": "overleaf",
"token_count": 398
} | 510 |
const mongoose = require('../infrastructure/Mongoose')
const _ = require('underscore')
const { FolderSchema } = require('./Folder')
const Errors = require('../Features/Errors/Errors')
const concreteObjectId = mongoose.Types.ObjectId
const { Schema } = mongoose
const { ObjectId } = Schema
const DeletedDocSchema = new Schema({
name: String,
deletedAt: { type: Date },
})
const DeletedFileSchema = new Schema({
name: String,
created: {
type: Date,
},
linkedFileData: { type: Schema.Types.Mixed },
hash: {
type: String,
},
deletedAt: { type: Date },
})
const AuditLogEntrySchema = new Schema({
_id: false,
operation: { type: String },
initiatorId: { type: Schema.Types.ObjectId },
timestamp: { type: Date },
info: { type: Object },
})
const ProjectSchema = new Schema({
name: { type: String, default: 'new project' },
lastUpdated: {
type: Date,
default() {
return new Date()
},
},
lastUpdatedBy: { type: ObjectId, ref: 'User' },
lastOpened: { type: Date },
active: { type: Boolean, default: true },
owner_ref: { type: ObjectId, ref: 'User' },
collaberator_refs: [{ type: ObjectId, ref: 'User' }],
readOnly_refs: [{ type: ObjectId, ref: 'User' }],
rootDoc_id: { type: ObjectId },
rootFolder: [FolderSchema],
version: { type: Number }, // incremented for every change in the project structure (folders and filenames)
publicAccesLevel: { type: String, default: 'private' },
compiler: { type: String, default: 'pdflatex' },
spellCheckLanguage: { type: String, default: 'en' },
deletedByExternalDataSource: { type: Boolean, default: false },
description: { type: String, default: '' },
archived: { type: Schema.Types.Mixed },
trashed: [{ type: ObjectId, ref: 'User' }],
deletedDocs: [DeletedDocSchema],
deletedFiles: [DeletedFileSchema],
imageName: { type: String },
brandVariationId: { type: String },
track_changes: { type: Object },
tokens: {
readOnly: {
type: String,
index: {
unique: true,
partialFilterExpression: { 'tokens.readOnly': { $exists: true } },
},
},
readAndWrite: {
type: String,
index: {
unique: true,
partialFilterExpression: { 'tokens.readAndWrite': { $exists: true } },
},
},
readAndWritePrefix: {
type: String,
index: {
unique: true,
partialFilterExpression: {
'tokens.readAndWritePrefix': { $exists: true },
},
},
},
},
tokenAccessReadOnly_refs: [{ type: ObjectId, ref: 'User' }],
tokenAccessReadAndWrite_refs: [{ type: ObjectId, ref: 'User' }],
fromV1TemplateId: { type: Number },
fromV1TemplateVersionId: { type: Number },
overleaf: {
id: { type: Number },
imported_at_ver_id: { type: Number },
token: { type: String },
read_token: { type: String },
history: {
id: { type: Number },
display: { type: Boolean },
upgradedAt: { type: Date },
},
},
collabratecUsers: [
{
user_id: { type: ObjectId, ref: 'User' },
collabratec_document_id: { type: String },
collabratec_privategroup_id: { type: String },
added_at: {
type: Date,
default() {
return new Date()
},
},
},
],
auditLog: [AuditLogEntrySchema],
deferredTpdsFlushCounter: { type: Number },
})
ProjectSchema.statics.getProject = function (projectOrId, fields, callback) {
if (projectOrId._id != null) {
callback(null, projectOrId)
} else {
try {
concreteObjectId(projectOrId.toString())
} catch (e) {
return callback(new Errors.NotFoundError(e.message))
}
this.findById(projectOrId, fields, callback)
}
}
function applyToAllFilesRecursivly(folder, fun) {
_.each(folder.fileRefs, file => fun(file))
_.each(folder.folders, folder => applyToAllFilesRecursivly(folder, fun))
}
ProjectSchema.statics.applyToAllFilesRecursivly = applyToAllFilesRecursivly
exports.Project = mongoose.model('Project', ProjectSchema)
exports.ProjectSchema = ProjectSchema
| overleaf/web/app/src/models/Project.js/0 | {
"file_path": "overleaf/web/app/src/models/Project.js",
"repo_id": "overleaf",
"token_count": 1558
} | 511 |
\documentclass{article}
\usepackage[utf8]{inputenc}
\title{<%= project_name %>}
\author{<%= user.first_name %> <%= user.last_name %>}
\date{<%= month %> <%= year %>}
\begin{document}
\maketitle
\section{Introduction}
\end{document}
| overleaf/web/app/templates/project_files/mainbasic.tex/0 | {
"file_path": "overleaf/web/app/templates/project_files/mainbasic.tex",
"repo_id": "overleaf",
"token_count": 103
} | 512 |
extends ../layout
block content
main.content.content-alt#main-content
.container
.error-container
.error-details
p.error-status Not found
p.error-description #{translate("cant_find_page")}
a.error-btn(href="/") Home
| overleaf/web/app/views/general/404.pug/0 | {
"file_path": "overleaf/web/app/views/general/404.pug",
"repo_id": "overleaf",
"token_count": 98
} | 513 |
aside.editor-sidebar.full-size(
ng-controller="FileTreeController"
ng-class="{ 'multi-selected': multiSelectedCount > 0 }"
ng-show="ui.view == 'history' && !history.isV2"
)
.file-tree
.file-tree-inner(
ng-if="rootFolder",
ng-class="no-toolbar"
)
ul.list-unstyled.file-tree-list
file-entity(
entity="entity",
ng-repeat="entity in rootFolder.children | orderBy:[orderByFoldersFirst, 'name']"
)
li(ng-show="deletedDocs.length > 0 && ui.view == 'history'")
h3 #{translate("deleted_files")}
li(
ng-class="{ 'selected': entity.selected }",
ng-repeat="entity in deletedDocs | orderBy:'name'",
ng-controller="FileTreeEntityController",
ng-show="ui.view == 'history'"
)
.entity
.entity-name(
ng-click="select($event)"
)
//- Just a spacer to align with folders
i.fa.fa-fw.toggle
i.fa.fa-fw.fa-file
span {{ entity.name }}
script(type='text/ng-template', id='entityListItemTemplate')
li(
ng-class="{ 'selected': entity.selected, 'multi-selected': entity.multiSelected }",
ng-controller="FileTreeEntityController"
)
.entity(ng-if="entity.type != 'folder'")
.entity-name(
ng-click="select($event)"
context-menu
data-target="context-menu-{{ entity.id }}"
context-menu-container="body"
context-menu-disabled="true"
)
//- Just a spacer to align with folders
i.fa.fa-fw.toggle(ng-if="entity.type != 'folder'")
i.fa.fa-fw(ng-if="entity.type != 'folder'", ng-class="'fa-' + iconTypeFromName(entity.name)")
i.fa.fa-external-link-square.fa-rotate-180.linked-file-highlight(
ng-if="entity.linkedFileData.provider"
)
span(
ng-hide="entity.renaming"
) {{ entity.renamingToName || entity.name }}
.entity(ng-if="entity.type == 'folder'", ng-controller="FileTreeFolderController")
.entity-name(
ng-click="select($event)"
)
div(
context-menu
data-target="context-menu-{{ entity.id }}"
context-menu-container="body"
context-menu-disabled="true"
)
i.fa.fa-fw.toggle(
ng-if="entity.type == 'folder'"
ng-class="{'fa-angle-right': !expanded, 'fa-angle-down': expanded}"
ng-click="toggleExpanded()"
)
i.fa.fa-fw(
ng-if="entity.type == 'folder'"
ng-class="{\
'fa-folder': !expanded, \
'fa-folder-open': expanded \
}"
ng-click="select($event)"
)
span(
ng-hide="entity.renaming"
) {{ entity.renamingToName || entity.name }}
ul.list-unstyled(
ng-if="entity.type == 'folder' && (depth == null || depth < MAX_DEPTH)"
ng-show="expanded"
)
file-entity(
entity="child",
ng-repeat="child in entity.children | orderBy:[orderByFoldersFirst, 'name']"
depth="(depth || 0) + 1"
)
.entity-limit-hit(
ng-if="depth === MAX_DEPTH"
ng-show="expanded"
)
i.fa.fa-fw
span.entity-limit-hit-message
| Some files might be hidden
|
i.fa.fa-question-circle.entity-limit-hit-tooltip-trigger(
tooltip="Your project has hit Overleaf's maximum file depth limit. Files within this folder won't be visible."
tooltip-append-to-body="true"
aria-hidden="true"
)
span.sr-only
| Your project has hit Overleaf's maximum file depth limit. Files within this folder won't be visible.
| overleaf/web/app/views/project/editor/file-tree-history.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/file-tree-history.pug",
"repo_id": "overleaf",
"token_count": 1501
} | 514 |
#review-panel
.rp-in-editor-widgets
a.rp-track-changes-indicator(
href
ng-if="editor.wantTrackChanges"
ng-click="toggleReviewPanel();"
ng-class="{ 'rp-track-changes-indicator-on-dark' : darkTheme }"
) !{translate("track_changes_is_on")}
a.rp-bulk-actions-btn(
href
ng-if="reviewPanel.nVisibleSelectedChanges > 1"
ng-click="showBulkAcceptDialog();"
)
i.fa.fa-check
| #{translate("accept_all")}
| ({{ reviewPanel.nVisibleSelectedChanges }})
a.rp-bulk-actions-btn(
href
ng-if="reviewPanel.nVisibleSelectedChanges > 1"
ng-click="showBulkRejectDialog();"
)
i.fa.fa-times
| #{translate("reject_all")}
| ({{ reviewPanel.nVisibleSelectedChanges }})
if hasFeature('track-changes')
a.rp-add-comment-btn(
href
ng-if="reviewPanel.entries[editor.open_doc_id]['add-comment'] != null && permissions.comment"
ng-click="addNewComment();"
)
i.fa.fa-comment
| #{translate("add_comment")}
a.review-panel-toggler(
href
ng-click="handleTogglerClick($event);"
)
.review-panel-toolbar
resolved-comments-dropdown(
class="rp-flex-block"
entries="reviewPanel.resolvedComments"
threads="reviewPanel.commentThreads"
resolved-ids="reviewPanel.resolvedThreadIds"
docs="docs"
on-open="refreshResolvedCommentsDropdown();"
on-unresolve="unresolveComment(threadId);"
on-delete="deleteThread(entryId, docId, threadId);"
is-loading="reviewPanel.dropdown.loading"
permissions="permissions"
)
span.review-panel-toolbar-label
span.review-panel-toolbar-icon-on(
ng-if="editor.wantTrackChanges === true"
)
i.fa.fa-circle
span(ng-click="toggleFullTCStateCollapse();")
span(ng-if="editor.wantTrackChanges === false") !{translate("track_changes_is_off")}
span(ng-if="editor.wantTrackChanges === true") !{translate("track_changes_is_on")}
span.rp-tc-state-collapse(
ng-class="{ 'rp-tc-state-collapse-on': reviewPanel.fullTCStateCollapsed }"
)
i.fa.fa-angle-down
ul.rp-tc-state(
review-panel-collapse-height="reviewPanel.fullTCStateCollapsed"
)
li.rp-tc-state-item.rp-tc-state-item-everyone
span.rp-tc-state-item-name(
tooltip=translate('tc_switch_everyone_tip')
tooltip-placement="left"
tooltip-append-to-body="true"
tooltip-popup-delay="1000"
) !{translate("tc_everyone")}
review-panel-toggle(
description="Track changes for everyone"
ng-model="reviewPanel.trackChangesOnForEveryone"
on-toggle="toggleTrackChangesForEveryone(isOn);"
is-disabled="!project.features.trackChanges || !permissions.write"
)
li.rp-tc-state-item(
ng-repeat="member in reviewPanel.formattedProjectMembers"
)
span.rp-tc-state-item-name(
ng-class="{ 'rp-tc-state-item-name-disabled' : reviewPanel.trackChangesOnForEveryone}"
style="color: hsl({{ member.hue }}, 70%, 40%);"
tooltip=translate('tc_switch_user_tip')
tooltip-placement="left"
tooltip-append-to-body="true"
tooltip-popup-delay="1000"
) {{ member.name }}
review-panel-toggle(
description="Track changes for {{ member.name }}"
ng-model="reviewPanel.trackChangesState[member.id].value"
on-toggle="toggleTrackChangesForUser(isOn, member.id);"
is-disabled="reviewPanel.trackChangesOnForEveryone || !project.features.trackChanges || !permissions.write"
)
li.rp-tc-state-separator
li.rp-tc-state-item.rp-tc-state-item-guests
span.rp-tc-state-item-name(
ng-class="{ 'rp-tc-state-item-name-disabled' : reviewPanel.trackChangesOnForEveryone}"
tooltip=translate('tc_switch_guests_tip')
tooltip-placement="left"
tooltip-append-to-body="true"
tooltip-popup-delay="1000"
) !{translate("tc_guests")}
review-panel-toggle(
description="Track changes for guests"
ng-model="reviewPanel.trackChangesOnForGuests"
on-toggle="toggleTrackChangesForGuests(isOn);"
is-disabled="reviewPanel.trackChangesOnForEveryone || !project.features.trackChanges || !permissions.write || !reviewPanel.trackChangesForGuestsAvailable"
)
.rp-entry-list(
review-panel-sorted
ng-if="reviewPanel.subView === SubViews.CUR_FILE"
)
.rp-entry-list-inner
.rp-entry-wrapper(
ng-repeat="(entry_id, entry) in reviewPanel.entries[editor.open_doc_id]"
ng-if="entry.visible"
)
div(ng-if="entry.type === 'insert' || entry.type === 'delete'")
change-entry(
entry="entry"
user="users[entry.metadata.user_id]"
on-reject="rejectChanges(entry.entry_ids);"
on-accept="acceptChanges(entry.entry_ids);"
on-indicator-click="toggleReviewPanel();"
on-body-click="gotoEntry(editor.open_doc_id, entry)"
permissions="permissions"
)
div(ng-if="entry.type === 'aggregate-change'")
aggregate-change-entry(
entry="entry"
user="users[entry.metadata.user_id]"
on-reject="rejectChanges(entry.entry_ids);"
on-accept="acceptChanges(entry.entry_ids);"
on-indicator-click="toggleReviewPanel();"
on-body-click="gotoEntry(editor.open_doc_id, entry)"
permissions="permissions"
)
div(ng-if="entry.type === 'comment'")
comment-entry(
entry="entry"
threads="reviewPanel.commentThreads"
on-resolve="resolveComment(entry, entry_id)"
on-reply="submitReply(entry, entry_id);"
on-indicator-click="toggleReviewPanel();"
on-save-edit="saveEdit(entry.thread_id, comment)"
on-delete="deleteComment(entry.thread_id, comment)"
on-body-click="gotoEntry(editor.open_doc_id, entry)"
permissions="permissions"
ng-if="!reviewPanel.loadingThreads"
)
div(ng-if="entry.type === 'add-comment' && permissions.comment")
add-comment-entry(
on-start-new="startNewComment();"
on-submit="submitNewComment(content);"
on-cancel="cancelNewComment();"
)
div(ng-if="entry.type === 'bulk-actions'")
bulk-actions-entry(
on-bulk-accept="showBulkAcceptDialog();"
on-bulk-reject="showBulkRejectDialog();"
n-entries="reviewPanel.nVisibleSelectedChanges"
)
.rp-entry-list(
ng-if="reviewPanel.subView === SubViews.OVERVIEW"
)
.rp-loading(ng-if="reviewPanel.overview.loading")
i.fa.fa-spinner.fa-spin
.rp-overview-file(
ng-repeat="doc in docs"
ng-if="!reviewPanel.overview.loading"
)
.rp-overview-file-header(
ng-if="(reviewPanel.entries[doc.doc.id] != null) && (reviewPanel.entries[doc.doc.id] | notEmpty)"
ng-click="reviewPanel.overview.docsCollapsedState[doc.doc.id] = ! reviewPanel.overview.docsCollapsedState[doc.doc.id]"
)
span.rp-overview-file-header-collapse(
ng-class="{ 'rp-overview-file-header-collapse-on': reviewPanel.overview.docsCollapsedState[doc.doc.id] }"
)
i.fa.fa-angle-down
| {{ doc.path }}
span.rp-overview-file-num-entries(
ng-show="reviewPanel.overview.docsCollapsedState[doc.doc.id]"
) ({{ reviewPanel.entries[doc.doc.id] | numKeys }})
.rp-overview-file-entries(
review-panel-collapse-height="reviewPanel.overview.docsCollapsedState[doc.doc.id]"
)
.rp-entry-wrapper(
ng-repeat="(entry_id, entry) in reviewPanel.entries[doc.doc.id] | orderOverviewEntries"
ng-if="!(entry.type === 'comment' && reviewPanel.commentThreads[entry.thread_id].resolved === true)"
)
div(ng-if="entry.type === 'insert' || entry.type === 'delete'")
change-entry(
entry="entry"
user="users[entry.metadata.user_id]"
ng-click="gotoEntry(doc.doc.id, entry)"
permissions="permissions"
)
div(ng-if="entry.type === 'aggregate-change'")
aggregate-change-entry(
entry="entry"
user="users[entry.metadata.user_id]"
ng-click="gotoEntry(editor.open_doc_id, entry)"
permissions="permissions"
)
div(ng-if="entry.type === 'comment'")
comment-entry(
entry="entry"
threads="reviewPanel.commentThreads"
on-reply="submitReply(entry, entry_id);"
on-save-edit="saveEdit(entry.thread_id, comment)"
on-delete="deleteComment(entry.thread_id, comment)"
ng-click="gotoEntry(doc.doc.id, entry)"
permissions="permissions"
)
.rp-nav
a.rp-nav-item(
href
ng-click="setSubView(SubViews.CUR_FILE);"
ng-class="{ 'rp-nav-item-active' : reviewPanel.subView === SubViews.CUR_FILE }"
)
i.fa.fa-file-text-o
span.rp-nav-label #{translate("current_file")}
a.rp-nav-item(
href
ng-click="setSubView(SubViews.OVERVIEW);"
ng-class="{ 'rp-nav-item-active' : reviewPanel.subView === SubViews.OVERVIEW }"
)
i.fa.fa-list
span.rp-nav-label #{translate("overview")}
.rp-unsupported-msg-wrapper
.rp-unsupported-msg
i.fa.fa-5x.fa-exclamation-triangle
p.rp-unsupported-msg-title Track Changes support in rich text mode is a work in progress.
p You can see tracked insertions and deletions, but you can't see comments and changes in this side bar yet.
p We're working hard to add them as soon as they're ready.
script(type='text/ng-template', id='changeEntryTemplate')
div
.rp-entry-callout(
ng-class="'rp-entry-callout-' + entry.type"
)
.rp-entry-indicator(
ng-switch="entry.type"
ng-class="{ 'rp-entry-indicator-focused': entry.focused }"
ng-click="onIndicatorClick();"
)
i.fa.fa-pencil(ng-switch-when="insert")
i.rp-icon-delete(ng-switch-when="delete")
.rp-entry(
ng-class="[ 'rp-entry-' + entry.type, (entry.focused ? 'rp-entry-focused' : '')]"
)
.rp-entry-body
.rp-entry-action-icon(ng-switch="entry.type")
i.fa.fa-pencil(ng-switch-when="insert")
i.rp-icon-delete(ng-switch-when="delete")
.rp-entry-details
.rp-entry-description(ng-switch="entry.type")
span(ng-switch-when="insert") #{translate("tracked_change_added")}
ins.rp-content-highlight {{ entry.content | limitTo:(isCollapsed ? contentLimit : entry.content.length) }}
a.rp-collapse-toggle(
href
ng-if="needsCollapsing"
ng-click="toggleCollapse();"
) {{ isCollapsed ? '… (#{translate("show_all")})' : ' (#{translate("show_less")})' }}
span(ng-switch-when="delete") #{translate("tracked_change_deleted")}
del.rp-content-highlight {{ entry.content | limitTo:(isCollapsed ? contentLimit : entry.content.length) }}
a.rp-collapse-toggle(
href
ng-if="needsCollapsing"
ng-click="toggleCollapse();"
) {{ isCollapsed ? '… (#{translate("show_all")})' : ' (#{translate("show_less")})' }}
.rp-entry-metadata
| {{ entry.metadata.ts | date : 'MMM d, y h:mm a' }} •
span.rp-entry-user(ng-switch="user.name" style="color: hsl({{ user.hue }}, 70%, 40%);")
span(ng-switch-when="undefined") #{translate("anonymous")}
span(ng-switch-default) {{ user.name }}
.rp-entry-actions(ng-if="permissions.write")
a.rp-entry-button(href, ng-click="onReject();")
i.fa.fa-times
| #{translate("reject")}
a.rp-entry-button(href, ng-click="onAccept();")
i.fa.fa-check
| #{translate("accept")}
script(type='text/ng-template', id='aggregateChangeEntryTemplate')
div
.rp-entry-callout.rp-entry-callout-aggregate
.rp-entry-indicator(
ng-class="{ 'rp-entry-indicator-focused': entry.focused }"
ng-click="onIndicatorClick();"
)
i.fa.fa-pencil
.rp-entry.rp-entry-aggregate(
ng-class="{ 'rp-entry-focused': entry.focused }"
)
.rp-entry-body
.rp-entry-action-icon
i.fa.fa-pencil
.rp-entry-details
.rp-entry-description
| #{translate("aggregate_changed")}
del.rp-content-highlight
| {{ entry.metadata.replaced_content | limitTo:(isDeletionCollapsed ? contentLimit : entry.metadata.replaced_contentlength) }}
a.rp-collapse-toggle(
href
ng-if="deletionNeedsCollapsing"
ng-click="toggleDeletionCollapse();"
) {{ isDeletionCollapsed ? '… (#{translate("show_all")})' : ' (#{translate("show_less")})' }}
| #{translate("aggregate_to")}
ins.rp-content-highlight
| {{ entry.content | limitTo:(isInsertionCollapsed ? contentLimit : entry.contentlength) }}
a.rp-collapse-toggle(
href
ng-if="insertionNeedsCollapsing"
ng-click="toggleInsertionCollapse();"
) {{ isInsertionCollapsed ? '… (#{translate("show_all")})' : ' (#{translate("show_less")})' }}
.rp-entry-metadata
| {{ entry.metadata.ts | date : 'MMM d, y h:mm a' }} •
span.rp-entry-user(ng-switch="user.name" style="color: hsl({{ user.hue }}, 70%, 40%);")
span(ng-switch-when="undefined") #{translate("anonymous")}
span(ng-switch-default) {{ user.name }}
.rp-entry-actions(ng-if="permissions.write")
a.rp-entry-button(href, ng-click="onReject();")
i.fa.fa-times
| #{translate("reject")}
a.rp-entry-button(href, ng-click="onAccept();")
i.fa.fa-check
| #{translate("accept")}
script(type='text/ng-template', id='commentEntryTemplate')
.rp-comment-wrapper(
ng-class="{ 'rp-comment-wrapper-resolving': state.animating }"
)
.rp-entry-callout.rp-entry-callout-comment
.rp-entry-indicator(
ng-class="{ 'rp-entry-indicator-focused': entry.focused }"
ng-click="onIndicatorClick();"
)
i.fa.fa-comment
.rp-entry.rp-entry-comment(
ng-class="{ 'rp-entry-focused': entry.focused, 'rp-entry-comment-resolving': state.animating }"
)
.rp-loading(ng-if="!threads[entry.thread_id].submitting && (!threads[entry.thread_id] || threads[entry.thread_id].messages.length == 0)")
| #{translate("no_comments")}
.rp-comment-loaded
.rp-comment(
ng-repeat="comment in threads[entry.thread_id].messages track by comment.id"
)
p.rp-comment-content
span(ng-if="!comment.editing")
span.rp-entry-user(
style="color: hsl({{ comment.user.hue }}, 70%, 40%);",
) {{ comment.user.name }}:
span(ng-bind-html="comment.content | linky:'_blank':{rel: 'noreferrer noopener'}")
textarea.rp-comment-input(
expandable-text-area
ng-if="comment.editing"
ng-model="comment.content"
ng-keypress="saveEditOnEnter($event, comment);"
ng-blur="saveEdit(comment)"
autofocus
stop-propagation="click"
)
.rp-entry-metadata(ng-if="!comment.editing")
span(ng-if="!comment.deleting") {{ comment.timestamp | date : 'MMM d, y h:mm a' }}
span.rp-comment-actions(ng-if="comment.user.isSelf && !comment.deleting")
| •
a(href, ng-click="startEditing(comment)") #{translate("edit")}
span(ng-if="threads[entry.thread_id].messages.length > 1")
| •
a(href, ng-click="confirmDelete(comment)") #{translate("delete")}
span.rp-confim-delete(ng-if="comment.user.isSelf && comment.deleting")
| #{translate("are_you_sure")}
| •
a(href, ng-click="doDelete(comment)") #{translate("delete")}
| •
a(href, ng-click="cancelDelete(comment)") #{translate("cancel")}
.rp-loading(ng-if="threads[entry.thread_id].submitting")
i.fa.fa-spinner.fa-spin
.rp-comment-reply(ng-if="permissions.comment")
textarea.rp-comment-input(
expandable-text-area
ng-model="entry.replyContent"
ng-keypress="handleCommentReplyKeyPress($event);"
stop-propagation="click"
placeholder=translate("hit_enter_to_reply")
)
.rp-entry-actions
button.rp-entry-button(
ng-click="animateAndCallOnResolve();"
ng-if="permissions.comment && permissions.write"
)
i.fa.fa-inbox
| #{translate("resolve")}
button.rp-entry-button(
ng-click="onReply();"
ng-if="permissions.comment"
ng-disabled="!entry.replyContent.length"
)
i.fa.fa-reply
| #{translate("reply")}
script(type='text/ng-template', id='resolvedCommentEntryTemplate')
.rp-resolved-comment
div
.rp-resolved-comment-context
| #{translate("quoted_text_in")}
span.rp-resolved-comment-context-file {{ thread.docName }}
p.rp-resolved-comment-context-quote
span {{ thread.content | limitTo:(isCollapsed ? contentLimit : thread.content.length)}}
a.rp-collapse-toggle(
href
ng-if="needsCollapsing"
ng-click="toggleCollapse();"
) {{ isCollapsed ? '… (#{translate("show_all")})' : ' (#{translate("show_less")})' }}
.rp-comment(
ng-repeat="comment in thread.messages track by comment.id"
)
p.rp-comment-content
span.rp-entry-user(
style="color: hsl({{ comment.user.hue }}, 70%, 40%);"
ng-if="$first || comment.user.id !== thread.messages[$index - 1].user.id"
) {{ comment.user.name }}:
span(ng-bind-html="comment.content | linky:'_blank':{rel: 'noreferrer noopener'}")
.rp-entry-metadata
| {{ comment.timestamp | date : 'MMM d, y h:mm a' }}
.rp-comment.rp-comment-resolver
p.rp-comment-resolver-content
span.rp-entry-user(
style="color: hsl({{ thread.resolved_by_user.hue }}, 70%, 40%);"
) {{ thread.resolved_by_user.name }}:
| #{translate("mark_as_resolved")}.
.rp-entry-metadata
| {{ thread.resolved_at | date : 'MMM d, y h:mm a' }}
.rp-entry-actions(ng-if="permissions.comment && permissions.write")
a.rp-entry-button(
href
ng-click="onUnresolve({ 'threadId': thread.threadId });"
)
| #{translate("reopen")}
a.rp-entry-button(
href
ng-click="onDelete({ 'entryId': thread.entryId, 'docId': thread.docId, 'threadId': thread.threadId });"
)
| #{translate("delete")}
script(type='text/ng-template', id='addCommentEntryTemplate')
div
.rp-entry-callout.rp-entry-callout-add-comment
.rp-entry.rp-entry-add-comment(
ng-class="[ (state.isAdding ? 'rp-entry-adding-comment' : ''), (entry.focused ? 'rp-entry-focused' : '')]"
)
a.rp-add-comment-btn(
href
ng-if="!state.isAdding"
ng-click="startNewComment();"
)
i.fa.fa-comment
| #{translate("add_comment")}
div(ng-if="state.isAdding")
.rp-new-comment
textarea.rp-comment-input(
expandable-text-area
ng-model="state.content"
ng-keypress="handleCommentKeyPress($event);"
placeholder=translate("add_your_comment_here")
focus-on="comment:new:open"
)
.rp-entry-actions
button.rp-entry-button.rp-entry-button-cancel(
ng-click="cancelNewComment();"
)
i.fa.fa-times
| #{translate("cancel")}
button.rp-entry-button(
ng-click="submitNewComment()"
ng-disabled="!state.content.length"
)
i.fa.fa-comment
| #{translate("comment")}
script(type='text/ng-template', id='bulkActionsEntryTemplate')
div(ng-if="nEntries > 1")
.rp-entry-callout.rp-entry-callout-bulk-actions
.rp-entry.rp-entry-bulk-actions
a.rp-bulk-actions-btn(
href
ng-click="bulkReject();"
)
i.fa.fa-times
| #{translate("reject_all")}
| ({{ nEntries }})
a.rp-bulk-actions-btn(
href
ng-click="bulkAccept();"
)
i.fa.fa-check
| #{translate("accept_all")}
| ({{ nEntries }})
script(type='text/ng-template', id='resolvedCommentsDropdownTemplate')
.resolved-comments
.resolved-comments-backdrop(
ng-class="{ 'resolved-comments-backdrop-visible' : state.isOpen }"
ng-click="state.isOpen = false"
)
a.resolved-comments-toggle(
href
ng-click="toggleOpenState();"
tooltip=translate("resolved_comments")
tooltip-placement="bottom"
tooltip-append-to-body="true"
)
i.fa.fa-inbox
.resolved-comments-dropdown(
ng-class="{ 'resolved-comments-dropdown-open' : state.isOpen }"
)
.rp-loading(ng-if="isLoading")
i.fa.fa-spinner.fa-spin
.resolved-comments-scroller(
ng-if="!isLoading"
)
resolved-comment-entry(
ng-repeat="thread in resolvedComments | orderBy:'resolved_at':true"
thread="thread"
on-unresolve="handleUnresolve(threadId);"
on-delete="handleDelete(entryId, docId, threadId);"
permissions="permissions"
)
.rp-loading(ng-if="!resolvedComments.length")
| #{translate("no_resolved_threads")}.
script(type="text/ng-template", id="trackChangesUpgradeModalTemplate")
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 #{translate("upgrade_to_track_changes")}
.modal-body
.teaser-video-container
video.teaser-video(autoplay, loop)
source(ng-src="{{ '/img/teasers/track-changes/teaser-track-changes.mp4' }}", type="video/mp4")
img(src="/img/teasers/track-changes/teaser-track-changes.gif")
h4.teaser-title #{translate("see_changes_in_your_documents_live")}
p.small(ng-show="startedFreeTrial")
| #{translate("refresh_page_after_starting_free_trial")}
.row
.col-md-10.col-md-offset-1
ul.list-unstyled
li
i.fa.fa-check
| #{translate("track_any_change_in_real_time")}
li
i.fa.fa-check
| #{translate("review_your_peers_work")}
li
i.fa.fa-check
| #{translate("accept_or_reject_each_changes_individually")}
.row.text-center
div(ng-show="user.allowedFreeTrial" ng-controller="FreeTrialModalController")
a.btn.btn-success(
href
ng-click="startFreeTrial('track-changes')"
ng-show="project.owner._id == user.id"
) #{translate("try_it_for_free")}
div(ng-show="!user.allowedFreeTrial" ng-controller="UpgradeModalController")
a.btn.btn-success(
href
ng-click="upgradePlan('project-sharing')"
ng-show="project.owner._id == user.id"
) #{translate("upgrade")}
p(ng-show="project.owner._id != user.id"): strong #{translate("please_ask_the_project_owner_to_upgrade_to_track_changes")}
.modal-footer()
button.btn.btn-default(
ng-click="cancel()"
)
span #{translate("close")}
script(type="text/ng-template", id="bulkActionsModalTemplate")
.modal-header
button.close(
type="button"
data-dismiss="modal"
ng-click="cancel()"
aria-label="Close"
)
span(aria-hidden="true") ×
h3 {{ isAccept ? '#{translate("accept_all")}' : '#{translate("reject_all")}' }}
.modal-body
p(ng-if="isAccept") #{translate("bulk_accept_confirm", { nChanges: "{{ nChanges }}"})}
p(ng-if="!isAccept") #{translate("bulk_reject_confirm", { nChanges: "{{ nChanges }}"})}
.modal-footer()
button.btn.btn-default(
ng-click="cancel()"
)
span #{translate("cancel")}
button.btn.btn-primary(
ng-click="confirm()"
)
span #{translate("ok")}
| overleaf/web/app/views/project/editor/review-panel.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/review-panel.pug",
"repo_id": "overleaf",
"token_count": 10249
} | 515 |
.faq
.row.row-spaced-large
.col-md-12
.page-header.plans-header.plans-subheader.text-centered
h2 FAQ
.row
.col-md-6
h3 #{translate("faq_how_free_trial_works_question")}
p #{translate('faq_how_does_free_trial_works_answer', { appName:'{{settings.appName}}', len:'{{trial_len}}' })}
.col-md-6
h3 #{translate('faq_change_plans_question')}
p #{translate('faq_change_plans_answer')}
.row
.col-md-6
h3 #{translate('faq_do_collab_need_premium_question')}
p #{translate('faq_do_collab_need_premium_answer')}
.col-md-6
h3 #{translate('faq_need_more_collab_question')}
p !{translate('faq_need_more_collab_answer', { referFriendsLink: translate('referring_your_friends') })}
.row
.col-md-6
h3 #{translate('faq_purchase_more_licenses_question')}
p !{translate('faq_purchase_more_licenses_answer', { groupLink: translate('discounted_group_accounts') })}
a(href='#groups', ng-click="openGroupPlanModal()") #{translate("get_in_touch_for_details")}
.col-md-6
h3 #{translate('faq_monthly_or_annual_question')}
p #{translate('faq_monthly_or_annual_answer')}
.row
.col-md-6
h3 #{translate('faq_how_to_pay_question')}
p #{translate('faq_how_to_pay_answer')}
.col-md-6
h3 #{translate('faq_pay_by_invoice_question')}
p !{translate('faq_pay_by_invoice_answer', {}, [{ name: 'a', attrs: { href: "#pay-by-invoice", 'ng-controller': "ContactGeneralModal", 'ng-click': "openModal()" }}])}
| overleaf/web/app/views/subscriptions/_plans_faq.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/_plans_faq.pug",
"repo_id": "overleaf",
"token_count": 669
} | 516 |
-if (user.email !== personalSubscription.recurly.account.email)
div
hr
form(async-form="updateAccountEmailAddress", name="updateAccountEmailAddress", action='/user/subscription/account/email', method="POST")
input(name='_csrf', type='hidden', value=csrfToken)
.form-group
form-messages(for="updateAccountEmailAddress")
.alert.alert-success(ng-show="updateAccountEmailAddress.response.success")
| #{translate('recurly_email_updated')}
div(ng-hide="updateAccountEmailAddress.response.success")
p(ng-non-bindable) !{translate("recurly_email_update_needed", { recurlyEmail: personalSubscription.recurly.account.email, userEmail: user.email }, ['em', 'em'])}
.actions
button.btn-primary.btn(
type='submit',
ng-disabled="updateAccountEmailAddress.inflight"
)
span(ng-show="!updateAccountEmailAddress.inflight") #{translate("update")}
span(ng-show="updateAccountEmailAddress.inflight") #{translate("updating")}…
| overleaf/web/app/views/subscriptions/dashboard/_personal_subscription_recurly_sync_email.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard/_personal_subscription_recurly_sync_email.pug",
"repo_id": "overleaf",
"token_count": 370
} | 517 |
extends ../layout
block content
- var email = reconfirm_email ? reconfirm_email : ""
- var showCaptcha = settings.recaptcha && settings.recaptcha.siteKey && !(settings.recaptcha.disabled && settings.recaptcha.disabled.passwordReset)
if showCaptcha
script(type="text/javascript", nonce=scriptNonce, src="https://www.recaptcha.net/recaptcha/api.js?render=explicit")
div(
id="recaptcha"
class="g-recaptcha"
data-sitekey=settings.recaptcha.siteKey
data-size="invisible"
data-badge="inline"
)
main.content.content-alt#main-content
.container
.row
.col-sm-12.col-md-6.col-md-offset-3
.card
h1.card-header.text-capitalize #{translate("reconfirm")} #{translate("Account")}
p #{translate('reconfirm_explained')}
a(href=`mailto:${settings.adminEmail}`, ng-non-bindable) #{settings.adminEmail}
| .
form(
async-form="reconfirm-account-request",
name="reconfirmAccountForm"
action="/user/reconfirm",
method="POST",
ng-cloak
ng-init="email='"+email+"'"
aria-label=translate('request_reconfirmation_email')
captcha=(showCaptcha ? '' : false),
captcha-action-name=(showCaptcha ? "passwordReset" : false),
)
input(type="hidden", name="_csrf", value=csrfToken)
form-messages(for="reconfirmAccountForm" role="alert")
.form-group
label(for='email') #{translate("please_enter_email")}
input.form-control(
aria-label="email"
type='email',
name='email',
placeholder='email@example.com',
required,
ng-model="email",
autofocus
)
span.small.text-primary(
ng-show="reconfirmAccountForm.email.$invalid && reconfirmAccountForm.email.$dirty"
) #{translate("must_be_email_address")}
.actions
button.btn.btn-primary(
type='submit',
ng-disabled="reconfirmAccountForm.$invalid"
aria-label=translate('request_password_reset_to_reconfirm')
) #{translate('request_password_reset_to_reconfirm')}
| overleaf/web/app/views/user/reconfirm.pug/0 | {
"file_path": "overleaf/web/app/views/user/reconfirm.pug",
"repo_id": "overleaf",
"token_count": 957
} | 518 |
#!/bin/bash
set -e
if [[ -z "$BRANCH_NAME" ]]; then
BRANCH_NAME=master
fi
if [[ `git status --porcelain=2 locales/` ]]; then
git add locales/*
git commit -m "auto update translation"
git push "$UPSTREAM_REPO" "HEAD:$BRANCH_NAME"
else
echo 'No changes'
fi
| overleaf/web/bin/push-translations-changes.sh/0 | {
"file_path": "overleaf/web/bin/push-translations-changes.sh",
"repo_id": "overleaf",
"token_count": 108
} | 519 |
@font-face {
font-family: "Stix Two Math";
src: url("./STIXTwoMath/STIXTwoMath-Regular.woff2")
format("woff2");
}
| overleaf/web/frontend/fonts/stix-two-math.css/0 | {
"file_path": "overleaf/web/frontend/fonts/stix-two-math.css",
"repo_id": "overleaf",
"token_count": 52
} | 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
* 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('selectAllList', () => ({
controller: [
'$scope',
function ($scope) {
// Selecting or deselecting all should apply to all projects
this.selectAll = () => $scope.$broadcast('select-all:select')
this.deselectAll = () => $scope.$broadcast('select-all:deselect')
this.clearSelectAllState = () => $scope.$broadcast('select-all:clear')
},
],
link(scope, element, attrs) {},
}))
App.directive('selectAll', () => ({
require: '^selectAllList',
link(scope, element, attrs, selectAllListController) {
scope.$on('select-all:clear', () => element.prop('checked', false))
return element.change(function () {
if (element.is(':checked')) {
selectAllListController.selectAll()
} else {
selectAllListController.deselectAll()
}
return true
})
},
}))
App.directive('selectIndividual', () => ({
require: '^selectAllList',
scope: {
ngModel: '=',
},
link(scope, element, attrs, selectAllListController) {
let ignoreChanges = false
scope.$watch('ngModel', function (value) {
if (value != null && !ignoreChanges) {
return selectAllListController.clearSelectAllState()
}
})
scope.$on('select-all:select', function () {
if (element.prop('disabled')) {
return
}
ignoreChanges = true
scope.$apply(() => (scope.ngModel = true))
return (ignoreChanges = false)
})
scope.$on('select-all:deselect', function () {
if (element.prop('disabled')) {
return
}
ignoreChanges = true
scope.$apply(() => (scope.ngModel = false))
return (ignoreChanges = false)
})
return scope.$on('select-all:row-clicked', function () {
if (element.prop('disabled')) {
return
}
ignoreChanges = true
scope.$apply(function () {
scope.ngModel = !scope.ngModel
if (!scope.ngModel) {
return selectAllListController.clearSelectAllState()
}
})
return (ignoreChanges = false)
})
},
}))
export default App.directive('selectRow', () => ({
scope: true,
link(scope, element, attrs) {
return element.on('click', e => scope.$broadcast('select-all:row-clicked'))
},
}))
| overleaf/web/frontend/js/directives/selectAll.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/selectAll.js",
"repo_id": "overleaf",
"token_count": 1016
} | 521 |
import { postJSON } from '../../../infrastructure/fetch-json'
export function cloneProject(projectId, cloneName) {
return postJSON(`/project/${projectId}/clone`, {
body: {
projectName: cloneName,
},
})
}
| overleaf/web/frontend/js/features/clone-project-modal/utils/api.js/0 | {
"file_path": "overleaf/web/frontend/js/features/clone-project-modal/utils/api.js",
"repo_id": "overleaf",
"token_count": 80
} | 522 |
import PropTypes from 'prop-types'
import { Alert } from 'react-bootstrap'
export default function DangerMessage({ children }) {
return <Alert bsStyle="danger">{children}</Alert>
}
DangerMessage.propTypes = {
children: PropTypes.any.isRequired,
}
| overleaf/web/frontend/js/features/file-tree/components/file-tree-create/danger-message.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/danger-message.js",
"repo_id": "overleaf",
"token_count": 75
} | 523 |
import { useEffect, createRef } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
import { useFileTreeMainContext } from '../../contexts/file-tree-main'
import { useDraggable } from '../../contexts/file-tree-draggable'
import FileTreeItemName from './file-tree-item-name'
import FileTreeItemMenu from './file-tree-item-menu'
import { useFileTreeSelectable } from '../../contexts/file-tree-selectable'
function FileTreeItemInner({ id, name, isSelected, icons }) {
const { hasWritePermissions, setContextMenuCoords } = useFileTreeMainContext()
const { selectedEntityIds } = useFileTreeSelectable()
const hasMenu =
hasWritePermissions && isSelected && selectedEntityIds.size === 1
const { isDragging, dragRef, setIsDraggable } = useDraggable(id)
const itemRef = createRef()
useEffect(() => {
const item = itemRef.current
if (isSelected && item) {
// we're delaying scrolling due to a race condition with other elements,
// mainly the Outline, being resized inside the same panel, causing the
// FileTree to have its viewport shrinked after the selected item is
// scrolled into the view, hiding it again.
// See `left-pane-resize-all` in `file-tree-controller` for more information.
setTimeout(() => {
if (item) {
scrollIntoViewIfNeeded(item, {
scrollMode: 'if-needed',
})
}
}, 100)
}
}, [isSelected, itemRef])
function handleContextMenu(ev) {
ev.preventDefault()
setContextMenuCoords({
top: ev.pageY,
left: ev.pageX,
})
}
return (
<div
className={classNames('entity', {
'dnd-draggable-dragging': isDragging,
})}
role="presentation"
ref={dragRef}
onContextMenu={handleContextMenu}
>
<div
className="entity-name entity-name-react"
role="presentation"
ref={itemRef}
>
{icons}
<FileTreeItemName
name={name}
isSelected={isSelected}
setIsDraggable={setIsDraggable}
/>
{hasMenu ? <FileTreeItemMenu id={id} /> : null}
</div>
</div>
)
}
FileTreeItemInner.propTypes = {
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
isSelected: PropTypes.bool.isRequired,
icons: PropTypes.node,
}
export default FileTreeItemInner
| overleaf/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-inner.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-inner.js",
"repo_id": "overleaf",
"token_count": 956
} | 524 |
import {
createContext,
useCallback,
useContext,
useReducer,
useEffect,
useMemo,
useState,
} from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { findInTree } from '../util/find-in-tree'
import { useFileTreeMutable } from './file-tree-mutable'
import { useFileTreeMainContext } from './file-tree-main'
import usePersistedState from '../../../shared/hooks/use-persisted-state'
const FileTreeSelectableContext = createContext()
const ACTION_TYPES = {
SELECT: 'SELECT',
MULTI_SELECT: 'MULTI_SELECT',
UNSELECT: 'UNSELECT',
}
function fileTreeSelectableReadWriteReducer(selectedEntityIds, action) {
switch (action.type) {
case ACTION_TYPES.SELECT: {
// reset selection
return new Set([action.id])
}
case ACTION_TYPES.MULTI_SELECT: {
const selectedEntityIdsCopy = new Set(selectedEntityIds)
if (selectedEntityIdsCopy.has(action.id)) {
// entity already selected
if (selectedEntityIdsCopy.size > 1) {
// entity already multi-selected; remove from set
selectedEntityIdsCopy.delete(action.id)
}
} else {
// entity not selected: add to set
selectedEntityIdsCopy.add(action.id)
}
return selectedEntityIdsCopy
}
case ACTION_TYPES.UNSELECT: {
const selectedEntityIdsCopy = new Set(selectedEntityIds)
selectedEntityIdsCopy.delete(action.id)
return selectedEntityIdsCopy
}
default:
throw new Error(`Unknown selectable action type: ${action.type}`)
}
}
function fileTreeSelectableReadOnlyReducer(selectedEntityIds, action) {
switch (action.type) {
case ACTION_TYPES.SELECT:
return new Set([action.id])
case ACTION_TYPES.MULTI_SELECT:
case ACTION_TYPES.UNSELECT:
return selectedEntityIds
default:
throw new Error(`Unknown selectable action type: ${action.type}`)
}
}
export function FileTreeSelectableProvider({
hasWritePermissions,
rootDocId,
onSelect,
children,
}) {
const { projectId } = useFileTreeMainContext()
const [initialSelectedEntityId] = usePersistedState(
`doc.open_id.${projectId}`,
rootDocId
)
const { fileTreeData } = useFileTreeMutable()
const [selectedEntityIds, dispatch] = useReducer(
hasWritePermissions
? fileTreeSelectableReadWriteReducer
: fileTreeSelectableReadOnlyReducer,
null,
() => {
if (!initialSelectedEntityId) return new Set()
// the entity with id=initialSelectedEntityId might not exist in the tree
// anymore. This checks that it exists before initialising the reducer
// with the id.
if (findInTree(fileTreeData, initialSelectedEntityId))
return new Set([initialSelectedEntityId])
// the entity doesn't exist anymore; don't select any files
return new Set()
}
)
const [selectedEntityParentIds, setSelectedEntityParentIds] = useState(
new Set()
)
// fills `selectedEntityParentIds` set
useEffect(() => {
const ids = new Set()
selectedEntityIds.forEach(id => {
const found = findInTree(fileTreeData, id)
if (found) {
found.path.forEach(pathItem => ids.add(pathItem))
}
})
setSelectedEntityParentIds(ids)
}, [fileTreeData, selectedEntityIds])
// calls `onSelect` on entities selection
useEffect(() => {
const selectedEntities = Array.from(selectedEntityIds)
.map(id => findInTree(fileTreeData, id))
.filter(Boolean)
onSelect(selectedEntities)
}, [fileTreeData, selectedEntityIds, onSelect])
useEffect(() => {
// listen for `editor.openDoc` and selected that doc
function handleOpenDoc(ev) {
const found = findInTree(fileTreeData, ev.detail)
if (!found) return
dispatch({ type: ACTION_TYPES.SELECT, id: found.entity._id })
}
window.addEventListener('editor.openDoc', handleOpenDoc)
return () => window.removeEventListener('editor.openDoc', handleOpenDoc)
}, [fileTreeData])
const select = useCallback(id => {
dispatch({ type: ACTION_TYPES.SELECT, id })
}, [])
const unselect = useCallback(id => {
dispatch({ type: ACTION_TYPES.UNSELECT, id })
}, [])
const selectOrMultiSelectEntity = useCallback((id, isMultiSelect) => {
const actionType = isMultiSelect
? ACTION_TYPES.MULTI_SELECT
: ACTION_TYPES.SELECT
dispatch({ type: actionType, id })
}, [])
const value = {
selectedEntityIds,
selectedEntityParentIds,
select,
unselect,
selectOrMultiSelectEntity,
}
return (
<FileTreeSelectableContext.Provider value={value}>
{children}
</FileTreeSelectableContext.Provider>
)
}
FileTreeSelectableProvider.propTypes = {
hasWritePermissions: PropTypes.bool.isRequired,
rootDocId: PropTypes.string,
onSelect: PropTypes.func.isRequired,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]).isRequired,
}
export function useSelectableEntity(id) {
const { selectedEntityIds, selectOrMultiSelectEntity } = useContext(
FileTreeSelectableContext
)
const isSelected = selectedEntityIds.has(id)
const handleEvent = useCallback(
ev => {
selectOrMultiSelectEntity(id, ev.ctrlKey || ev.metaKey)
},
[id, selectOrMultiSelectEntity]
)
const handleClick = useCallback(
ev => {
handleEvent(ev)
},
[handleEvent]
)
const handleKeyPress = useCallback(
ev => {
if (ev.key === 'Enter' || ev.key === ' ') {
handleEvent(ev)
}
},
[handleEvent]
)
const handleContextMenu = useCallback(
ev => {
// make sure the right-clicked entity gets selected
if (!selectedEntityIds.has(id)) {
handleEvent(ev)
}
},
[id, handleEvent, selectedEntityIds]
)
const props = useMemo(
() => ({
className: classNames({ selected: isSelected }),
'aria-selected': isSelected,
onClick: handleClick,
onContextMenu: handleContextMenu,
onKeyPress: handleKeyPress,
}),
[handleClick, handleContextMenu, handleKeyPress, isSelected]
)
return { isSelected, props }
}
export function useFileTreeSelectable() {
const context = useContext(FileTreeSelectableContext)
if (!context) {
throw new Error(
`useFileTreeSelectable is only available inside FileTreeSelectableProvider`
)
}
return context
}
| overleaf/web/frontend/js/features/file-tree/contexts/file-tree-selectable.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/contexts/file-tree-selectable.js",
"repo_id": "overleaf",
"token_count": 2351
} | 525 |
import PropTypes from 'prop-types'
import { useProjectContext } from '../../../shared/context/project-context'
export default function FileViewImage({ fileName, fileId, onLoad, onError }) {
const { _id: projectId } = useProjectContext({
_id: PropTypes.string.isRequired,
})
return (
<img
src={`/project/${projectId}/file/${fileId}`}
onLoad={onLoad}
onError={onError}
onAbort={onError}
alt={fileName}
/>
)
}
FileViewImage.propTypes = {
fileName: PropTypes.string.isRequired,
fileId: PropTypes.string.isRequired,
onLoad: PropTypes.func.isRequired,
onError: PropTypes.func.isRequired,
}
| overleaf/web/frontend/js/features/file-view/components/file-view-image.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-view/components/file-view-image.js",
"repo_id": "overleaf",
"token_count": 242
} | 526 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import Icon from '../../../shared/components/icon'
import PreviewLogsPaneEntry from './preview-logs-pane-entry'
import { OverlayTrigger, Tooltip } from 'react-bootstrap'
function PreviewFirstErrorPopUp({
logEntry,
nErrors,
onGoToErrorLocation,
onViewLogs,
onClose,
}) {
const { t } = useTranslation()
function handleGoToErrorLocation() {
const { file, line, column } = logEntry
onGoToErrorLocation({ file, line, column })
}
return (
<div
className="first-error-popup"
role="alertdialog"
aria-label={t('first_error_popup_label')}
>
<PreviewLogsPaneEntry
headerTitle={logEntry.message}
headerIcon={<FirstErrorPopUpInfoBadge />}
rawContent={logEntry.content}
formattedContent={logEntry.humanReadableHintComponent}
extraInfoURL={logEntry.extraInfoURL}
level={logEntry.level}
showLineAndNoLink={false}
showCloseButton
customClass="log-entry-first-error-popup"
onClose={onClose}
/>
<div className="first-error-popup-actions">
<button
className="btn btn-info btn-xs first-error-btn"
type="button"
onClick={handleGoToErrorLocation}
>
<Icon type="chain" />
{t('go_to_error_location')}
</button>
<button
className="btn btn-info btn-xs first-error-btn"
type="button"
onClick={onViewLogs}
>
<Icon type="file-text-o" />
{t('view_error', { count: nErrors })}
</button>
</div>
</div>
)
}
function FirstErrorPopUpInfoBadge() {
const { t } = useTranslation()
const logsPaneInfoMessage = t('logs_pane_info_message_popup')
const tooltip = (
<Tooltip id="file-tree-badge-tooltip">{logsPaneInfoMessage}</Tooltip>
)
return (
<OverlayTrigger placement="bottom" overlay={tooltip} delayHide={100}>
<a
href="https://forms.gle/AUbDDRvroQ7KFwHR9"
target="_blank"
rel="noopener noreferrer"
className="info-badge-fade-bg"
>
<span className="sr-only">{logsPaneInfoMessage}</span>
</a>
</OverlayTrigger>
)
}
PreviewFirstErrorPopUp.propTypes = {
logEntry: PropTypes.object.isRequired,
nErrors: PropTypes.number.isRequired,
onGoToErrorLocation: PropTypes.func.isRequired,
onViewLogs: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
}
export default PreviewFirstErrorPopUp
| overleaf/web/frontend/js/features/preview/components/preview-first-error-pop-up.js/0 | {
"file_path": "overleaf/web/frontend/js/features/preview/components/preview-first-error-pop-up.js",
"repo_id": "overleaf",
"token_count": 1123
} | 527 |
import { Col, Row } from 'react-bootstrap'
import PropTypes from 'prop-types'
import { Trans } from 'react-i18next'
import { useProjectContext } from '../../../shared/context/project-context'
export default function SendInvitesNotice() {
const project = useProjectContext()
return (
<Row className="public-access-level public-access-level--notice">
<Col xs={12} className="text-center">
<AccessLevel level={project.publicAccesLevel} />
</Col>
</Row>
)
}
function AccessLevel({ level }) {
switch (level) {
case 'private':
return <Trans i18nKey="to_add_more_collaborators" />
case 'tokenBased':
return <Trans i18nKey="to_change_access_permissions" />
default:
return null
}
}
AccessLevel.propTypes = {
level: PropTypes.string,
}
| overleaf/web/frontend/js/features/share-project-modal/components/send-invites-notice.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/components/send-invites-notice.js",
"repo_id": "overleaf",
"token_count": 285
} | 528 |
import { useCallback, useEffect, useState } from 'react'
import PropTypes from 'prop-types'
import SymbolPaletteItem from './symbol-palette-item'
export default function SymbolPaletteItems({
items,
handleSelect,
focusInput,
}) {
const [focusedIndex, setFocusedIndex] = useState(0)
// reset the focused item when the list of items changes
useEffect(() => {
setFocusedIndex(0)
}, [items])
// navigate through items with left and right arrows
const handleKeyDown = useCallback(
event => {
if (event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) {
return
}
switch (event.key) {
// focus previous item
case 'ArrowLeft':
case 'ArrowUp':
setFocusedIndex(index => (index > 0 ? index - 1 : items.length - 1))
break
// focus next item
case 'ArrowRight':
case 'ArrowDown':
setFocusedIndex(index => (index < items.length - 1 ? index + 1 : 0))
break
// focus first item
case 'Home':
setFocusedIndex(0)
break
// focus last item
case 'End':
setFocusedIndex(items.length - 1)
break
// allow the default action
case 'Enter':
case ' ':
break
// any other key returns focus to the input
default:
focusInput()
break
}
},
[focusInput, items.length]
)
return (
<div className="symbol-palette-items" role="listbox" aria-label="Symbols">
{items.map((symbol, index) => (
<SymbolPaletteItem
key={symbol.codepoint}
symbol={symbol}
handleSelect={symbol => {
handleSelect(symbol)
setFocusedIndex(index)
}}
handleKeyDown={handleKeyDown}
focused={index === focusedIndex}
/>
))}
</div>
)
}
SymbolPaletteItems.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
codepoint: PropTypes.string.isRequired,
})
).isRequired,
handleSelect: PropTypes.func.isRequired,
focusInput: PropTypes.func.isRequired,
}
| overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-items.js/0 | {
"file_path": "overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-items.js",
"repo_id": "overleaf",
"token_count": 929
} | 529 |
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let SafariScrollPatcher
export default SafariScrollPatcher = class SafariScrollPatcher {
constructor($scope) {
this.isOverAce = false // Flag to control if the pointer is over Ace.
this.pdfDiv = null
this.aceDiv = null
// Start listening to PDF wheel events when the pointer leaves the PDF region.
// P.S. This is the problem in a nutshell: although the pointer is elsewhere,
// wheel events keep being dispatched to the PDF.
this.handlePdfDivMouseLeave = () => {
return this.pdfDiv.addEventListener('wheel', this.dispatchToAce)
}
// Stop listening to wheel events when the pointer enters the PDF region. If
// the pointer is over the PDF, native behaviour is adequate.
this.handlePdfDivMouseEnter = () => {
return this.pdfDiv.removeEventListener('wheel', this.dispatchToAce)
}
// Set the "pointer over Ace" flag as false, when the mouse leaves its area.
this.handleAceDivMouseLeave = () => {
return (this.isOverAce = false)
}
// Set the "pointer over Ace" flag as true, when the mouse enters its area.
this.handleAceDivMouseEnter = () => {
return (this.isOverAce = true)
}
// Grab the elements (pdfDiv, aceDiv) and set the "hover" event listeners.
// If elements are already defined, clear existing event listeners and do
// the process again (grab elements, set listeners).
this.setListeners = () => {
this.isOverAce = false
// If elements aren't null, remove existing listeners.
if (this.pdfDiv != null) {
this.pdfDiv.removeEventListener(
'mouseleave',
this.handlePdfDivMouseLeave
)
this.pdfDiv.removeEventListener(
'mouseenter',
this.handlePdfDivMouseEnter
)
}
if (this.aceDiv != null) {
this.aceDiv.removeEventListener(
'mouseleave',
this.handleAceDivMouseLeave
)
this.aceDiv.removeEventListener(
'mouseenter',
this.handleAceDivMouseEnter
)
}
// Grab elements.
this.pdfDiv = document.querySelector('.pdfjs-viewer') // Grab the PDF div.
this.aceDiv = document.querySelector('.ace_content') // Also the editor.
// Set hover-related listeners.
if (this.pdfDiv != null) {
this.pdfDiv.addEventListener('mouseleave', this.handlePdfDivMouseLeave)
this.pdfDiv.addEventListener('mouseenter', this.handlePdfDivMouseEnter)
}
if (this.aceDiv != null) {
this.aceDiv.addEventListener('mouseleave', this.handleAceDivMouseLeave)
this.aceDiv.addEventListener('mouseenter', this.handleAceDivMouseEnter)
}
}
// Handler for wheel events on the PDF.
// If the pointer is over Ace, grab the event, prevent default behaviour
// and dispatch it to Ace.
this.dispatchToAce = e => {
if (this.isOverAce) {
// If this is logged, the problem just happened: the event arrived
// here (the PDF wheel handler), but it should've gone to Ace.
// Small timeout - if we dispatch immediately, an exception is thrown.
window.setTimeout(() => {
// Dispatch the exact same event to Ace (this will keep values
// values e.g. `wheelDelta` consistent with user interaction).
return this.aceDiv.dispatchEvent(e)
}, 1)
// Avoid scrolling the PDF, as we assume this was intended to the
// editor.
return e.preventDefault()
}
}
// "loaded" event is emitted from the pdfViewer controller $scope. This means
// that the previous PDF DOM element was destroyed and a new one is available,
// so we need to grab the elements and set the listeners again.
$scope.$on('loaded', () => {
return this.setListeners()
})
}
}
| overleaf/web/frontend/js/ide/SafariScrollPatcher.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/SafariScrollPatcher.js",
"repo_id": "overleaf",
"token_count": 1534
} | 530 |
import App from '../../base'
const layoutOptions = {
center: {
paneSelector: '[vertical-resizable-top]',
paneClass: 'vertical-resizable-top',
size: 'auto',
},
south: {
paneSelector: '[vertical-resizable-bottom]',
paneClass: 'vertical-resizable-bottom',
resizerClass: 'vertical-resizable-resizer',
resizerCursor: 'ns-resize',
size: 'auto',
resizable: true,
closable: false,
slidable: false,
spacing_open: 6,
spacing_closed: 6,
maxSize: '75%',
},
}
export default App.directive('verticalResizablePanes', (localStorage, ide) => ({
restrict: 'A',
link(scope, element, attrs) {
const name = attrs.verticalResizablePanes
const minSize = attrs.verticalResizablePanesMinSize
const maxSize = attrs.verticalResizablePanesMaxSize
const defaultSize = attrs.verticalResizablePanesDefaultSize
let storedSize = null
let manualResizeIncoming = false
if (name) {
const storageKey = `vertical-resizable:${name}:south-size`
storedSize = localStorage(storageKey)
$(window).unload(() => {
if (storedSize) {
localStorage(storageKey, storedSize)
}
})
}
const toggledExternally = attrs.verticalResizablePanesToggledExternallyOn
const hiddenExternally = attrs.verticalResizablePanesHiddenExternallyOn
const hiddenInitially = attrs.verticalResizablePanesHiddenInitially
const resizeOn = attrs.verticalResizablePanesResizeOn
const resizerDisabledClass = `${layoutOptions.south.resizerClass}-disabled`
function enableResizer() {
if (layoutHandle.resizers && layoutHandle.resizers.south) {
layoutHandle.resizers.south.removeClass(resizerDisabledClass)
}
}
function disableResizer() {
if (layoutHandle.resizers && layoutHandle.resizers.south) {
layoutHandle.resizers.south.addClass(resizerDisabledClass)
}
}
function handleDragEnd() {
manualResizeIncoming = true
}
function handleResize(paneName, paneEl, paneState) {
if (manualResizeIncoming) {
storedSize = paneState.size
}
manualResizeIncoming = false
}
if (toggledExternally) {
scope.$on(toggledExternally, (e, open) => {
let newSize = 'auto'
if (open) {
if (storedSize) {
newSize = storedSize
}
enableResizer()
} else {
disableResizer()
}
layoutHandle.sizePane('south', newSize)
})
}
if (hiddenExternally) {
ide.$scope.$on(hiddenExternally, (e, open) => {
if (open) {
layoutHandle.show('south')
} else {
layoutHandle.hide('south')
}
})
}
if (resizeOn) {
scope.$on(resizeOn, () => {
layoutHandle.resizeAll()
})
}
if (maxSize) {
layoutOptions.south.maxSize = maxSize
}
if (minSize) {
layoutOptions.south.minSize = minSize
}
if (defaultSize) {
layoutOptions.south.size = defaultSize
}
// The `drag` event fires only when the user manually resizes the panes; the `resize` event fires even when
// the layout library internally resizes itself. In order to get explicit user-initiated resizes, we need to
// listen to `drag` events. However, when the `drag` event fires, the panes aren't yet finished sizing so we
// get the pane size *before* the resize happens. We do get the correct size in the next `resize` event.
// The solution to work around this is to set up a flag in `drag` events which tells the next `resize` event
// that it was user-initiated (therefore, storing the value).
layoutOptions.south.ondrag_end = handleDragEnd
layoutOptions.south.onresize = handleResize
const layoutHandle = element.layout(layoutOptions)
if (hiddenInitially === 'true') {
layoutHandle.hide('south')
}
},
}))
| overleaf/web/frontend/js/ide/directives/verticalResizablePanes.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/directives/verticalResizablePanes.js",
"repo_id": "overleaf",
"token_count": 1535
} | 531 |
/* eslint-disable
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let CursorPositionManager
export default CursorPositionManager = class CursorPositionManager {
constructor($scope, adapter, localStorage) {
this.storePositionAndLine = this.storePositionAndLine.bind(this)
this.jumpToPositionInNewDoc = this.jumpToPositionInNewDoc.bind(this)
this.onUnload = this.onUnload.bind(this)
this.onCursorChange = this.onCursorChange.bind(this)
this.onSyncToPdf = this.onSyncToPdf.bind(this)
this.$scope = $scope
this.adapter = adapter
this.localStorage = localStorage
this.$scope.$on('editorInit', this.jumpToPositionInNewDoc)
this.$scope.$on('beforeChangeDocument', this.storePositionAndLine)
this.$scope.$on('afterChangeDocument', this.jumpToPositionInNewDoc)
this.$scope.$on('changeEditor', this.storePositionAndLine)
this.$scope.$on(
`${this.$scope.name}:gotoLine`,
(e, line, column, syncToPdf) => {
if (line != null) {
return setTimeout(() => {
this.adapter.gotoLine(line, column)
if (syncToPdf) this.onSyncToPdf()
}, 10)
}
}
) // Hack: Must happen after @gotoStoredPosition
this.$scope.$on(`${this.$scope.name}:gotoOffset`, (e, offset) => {
if (offset != null) {
return setTimeout(() => {
return this.adapter.gotoOffset(offset)
}, 10)
}
}) // Hack: Must happen after @gotoStoredPosition
this.$scope.$on(`${this.$scope.name}:clearSelection`, e => {
return this.adapter.clearSelection()
})
}
storePositionAndLine() {
this.storeCursorPosition()
return this.storeFirstVisibleLine()
}
jumpToPositionInNewDoc() {
this.doc_id =
this.$scope.sharejsDoc != null ? this.$scope.sharejsDoc.doc_id : undefined
return setTimeout(() => {
return this.gotoStoredPosition()
}, 0)
}
onUnload() {
this.storeCursorPosition()
return this.storeFirstVisibleLine()
}
onCursorChange() {
return this.emitCursorUpdateEvent()
}
onSyncToPdf() {
return this.$scope.$emit(`cursor:${this.$scope.name}:syncToPdf`)
}
storeFirstVisibleLine() {
if (this.doc_id != null) {
const docPosition = this.localStorage(`doc.position.${this.doc_id}`) || {}
docPosition.firstVisibleLine = this.adapter.getEditorScrollPosition()
return this.localStorage(`doc.position.${this.doc_id}`, docPosition)
}
}
storeCursorPosition() {
if (this.doc_id != null) {
const docPosition = this.localStorage(`doc.position.${this.doc_id}`) || {}
docPosition.cursorPosition = this.adapter.getCursor()
return this.localStorage(`doc.position.${this.doc_id}`, docPosition)
}
}
emitCursorUpdateEvent() {
const cursor = this.adapter.getCursor()
return this.$scope.$emit(`cursor:${this.$scope.name}:update`, cursor)
}
gotoStoredPosition() {
if (this.doc_id == null) {
return
}
const pos = this.localStorage(`doc.position.${this.doc_id}`) || {}
this.adapter.setCursor(pos)
return this.adapter.setEditorScrollPosition(pos)
}
}
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/cursor-position/CursorPositionManager.js",
"repo_id": "overleaf",
"token_count": 1330
} | 532 |
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS103: Rewrite code to no longer use __guard__
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let iconTypeFromName
export default iconTypeFromName = function (name) {
const ext = __guard__(name.split('.').pop(), x => x.toLowerCase())
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'
}
}
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/frontend/js/ide/file-tree/util/iconTypeFromName.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/file-tree/util/iconTypeFromName.js",
"repo_id": "overleaf",
"token_count": 352
} | 533 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.controller(
'HistoryV2FileTreeController',
function ($scope, ide) {
$scope.handleFileSelection = file => {
ide.historyManager.selectFile(file)
}
}
)
| overleaf/web/frontend/js/ide/history/controllers/HistoryV2FileTreeController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/controllers/HistoryV2FileTreeController.js",
"repo_id": "overleaf",
"token_count": 200
} | 534 |
/* eslint-disable
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import './controllers/PdfController'
import './controllers/PdfViewToggleController'
import '../pdfng/directives/pdfJs'
let PdfManager
export default PdfManager = class PdfManager {
constructor(ide, $scope) {
this.ide = ide
this.$scope = $scope
this.$scope.pdf = {
url: null, // Pdf Url
error: false, // Server error
timeout: false, // Server timed out
failure: false, // PDF failed to compile
compiling: false,
uncompiled: true,
logEntries: {},
logEntryAnnotations: {},
rawLog: '',
validation: {},
view: null, // 'pdf' 'logs'
showRawLog: false,
highlights: [],
position: null,
lastCompileTimestamp: null,
}
}
}
| overleaf/web/frontend/js/ide/pdf/PdfManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/pdf/PdfManager.js",
"repo_id": "overleaf",
"token_count": 399
} | 535 |
import _ from 'lodash'
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* 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
*/
import CryptoJSSHA1 from 'crypto-js/sha1'
let ReferencesManager
export default ReferencesManager = class ReferencesManager {
constructor(ide, $scope) {
this.ide = ide
this.$scope = $scope
this.$scope.$root._references = this.state = { keys: [] }
this.existingIndexHash = {}
this.$scope.$on('document:closed', (e, doc) => {
let entity
if (doc.doc_id) {
entity = this.ide.fileTreeManager.findEntityById(doc.doc_id)
}
if (
__guard__(entity != null ? entity.name : undefined, x =>
x.match(/.*\.bib$/)
)
) {
return this.indexReferencesIfDocModified(doc, true)
}
})
this.$scope.$on('references:should-reindex', (e, data) => {
return this.indexAllReferences(true)
})
// When we join the project:
// index all references files
// and don't broadcast to all clients
this.inited = false
this.$scope.$on('project:joined', e => {
// We only need to grab the references when the editor first loads,
// not on every reconnect
if (!this.inited) {
this.inited = true
this.ide.socket.on('references:keys:updated', keys =>
this._storeReferencesKeys(keys)
)
this.indexAllReferences(false)
}
})
}
_storeReferencesKeys(newKeys) {
// console.log '>> storing references keys'
const oldKeys = this.$scope.$root._references.keys
return (this.$scope.$root._references.keys = _.union(oldKeys, newKeys))
}
indexReferencesIfDocModified(doc, shouldBroadcast) {
// avoid reindexing references if the bib file has not changed since the
// last time they were indexed
const docId = doc.doc_id
const snapshot = doc._doc.snapshot
const now = Date.now()
const sha1 = CryptoJSSHA1(
'blob ' + snapshot.length + '\x00' + snapshot
).toString()
const CACHE_LIFETIME = 6 * 3600 * 1000 // allow reindexing every 6 hours
const cacheEntry = this.existingIndexHash[docId]
const isCached =
cacheEntry &&
cacheEntry.timestamp > now - CACHE_LIFETIME &&
cacheEntry.hash === sha1
if (!isCached) {
this.indexReferences([docId], shouldBroadcast)
this.existingIndexHash[docId] = { hash: sha1, timestamp: now }
}
}
indexReferences(docIds, shouldBroadcast) {
const opts = {
docIds,
shouldBroadcast,
_csrf: window.csrfToken,
}
return this.ide.$http
.post(`/project/${this.$scope.project_id}/references/index`, opts)
.then(response => {
return this._storeReferencesKeys(response.data.keys)
})
}
indexAllReferences(shouldBroadcast) {
const opts = {
shouldBroadcast,
_csrf: window.csrfToken,
}
return this.ide.$http
.post(`/project/${this.$scope.project_id}/references/indexAll`, opts)
.then(response => {
return this._storeReferencesKeys(response.data.keys)
})
}
}
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/frontend/js/ide/references/ReferencesManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/references/ReferencesManager.js",
"repo_id": "overleaf",
"token_count": 1382
} | 536 |
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
export default App.filter('notEmpty', () => object =>
!angular.equals({}, object)
)
| overleaf/web/frontend/js/ide/review-panel/filters/notEmpty.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/review-panel/filters/notEmpty.js",
"repo_id": "overleaf",
"token_count": 120
} | 537 |
export default function withoutPropagation(callback) {
return ev => {
ev.stopPropagation()
if (callback) callback(ev)
}
}
| overleaf/web/frontend/js/infrastructure/without-propagation.js/0 | {
"file_path": "overleaf/web/frontend/js/infrastructure/without-propagation.js",
"repo_id": "overleaf",
"token_count": 46
} | 538 |
const validTeXFileRegExp = new RegExp(
`\\.(${window.ExposedSettings.validRootDocExtensions.join('|')})$`,
'i'
)
function isValidTeXFile(filename) {
return validTeXFileRegExp.test(filename)
}
export default isValidTeXFile
| overleaf/web/frontend/js/main/is-valid-tex-file.js/0 | {
"file_path": "overleaf/web/frontend/js/main/is-valid-tex-file.js",
"repo_id": "overleaf",
"token_count": 78
} | 539 |
import _ from 'lodash'
/* global recurly */
/* eslint-disable
camelcase,
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS204: Change includes calls to have a more natural evaluation order
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../base'
import getMeta from '../utils/meta'
const SUBSCRIPTION_URL = '/user/subscription/update'
const ensureRecurlyIsSetup = _.once(() => {
if (typeof recurly === 'undefined' || !recurly) {
return false
}
recurly.configure(getMeta('ol-recurlyApiKey'))
return true
})
App.controller('MetricsEmailController', function ($scope, $http) {
$scope.institutionEmailSubscription = function (institutionId) {
var inst = _.find(window.managedInstitutions, function (institution) {
return institution.v1Id === parseInt(institutionId)
})
if (inst.metricsEmail.optedOutUserIds.includes(window.user_id)) {
return 'Subscribe'
} else {
return 'Unsubscribe'
}
}
$scope.changeInstitutionalEmailSubscription = function (institutionId) {
$scope.subscriptionChanging = true
return $http({
method: 'POST',
url: `/institutions/${institutionId}/emailSubscription`,
headers: {
'X-CSRF-Token': window.csrfToken,
},
}).then(function successCallback(response) {
window.managedInstitutions = _.map(
window.managedInstitutions,
function (institution) {
if (institution.v1Id === parseInt(institutionId)) {
institution.metricsEmail.optedOutUserIds = response.data
}
return institution
}
)
$scope.subscriptionChanging = false
})
}
})
App.factory('RecurlyPricing', function ($q, MultiCurrencyPricing) {
return {
loadDisplayPriceWithTax: function (planCode, currency, taxRate) {
if (!ensureRecurlyIsSetup()) return
const currencySymbol = MultiCurrencyPricing.plans[currency].symbol
const pricing = recurly.Pricing()
return $q(function (resolve, reject) {
pricing
.plan(planCode, { quantity: 1 })
.currency(currency)
.done(function (price) {
const totalPriceExTax = parseFloat(price.next.total)
let taxAmmount = totalPriceExTax * taxRate
if (isNaN(taxAmmount)) {
taxAmmount = 0
}
let total = totalPriceExTax + taxAmmount
if (total % 1 !== 0) {
total = total.toFixed(2)
}
resolve(`${currencySymbol}${total}`)
})
})
},
}
})
App.controller(
'ChangePlanFormController',
function ($scope, $modal, RecurlyPricing) {
if (!ensureRecurlyIsSetup()) return
$scope.changePlan = () =>
$modal.open({
templateUrl: 'confirmChangePlanModalTemplate',
controller: 'ConfirmChangePlanController',
scope: $scope,
})
$scope.cancelPendingPlanChange = () =>
$modal.open({
templateUrl: 'cancelPendingPlanChangeModalTemplate',
controller: 'CancelPendingPlanChangeController',
scope: $scope,
})
$scope.$watch('plan', function (plan) {
if (!plan) return
const planCodesChangingAtTermEnd = getMeta(
'ol-planCodesChangingAtTermEnd'
)
$scope.planChangesAtTermEnd = false
if (
planCodesChangingAtTermEnd &&
planCodesChangingAtTermEnd.indexOf(plan.planCode) > -1
) {
$scope.planChangesAtTermEnd = true
}
const planCode = plan.planCode
const subscription = getMeta('ol-subscription')
const { currency, taxRate } = subscription.recurly
$scope.price = '...' // Placeholder while we talk to recurly
RecurlyPricing.loadDisplayPriceWithTax(planCode, currency, taxRate).then(
price => {
$scope.price = price
}
)
})
}
)
App.controller(
'ConfirmChangePlanController',
function ($scope, $modalInstance, $http) {
$scope.confirmChangePlan = function () {
const body = {
plan_code: $scope.plan.planCode,
_csrf: window.csrfToken,
}
$scope.genericError = false
$scope.inflight = true
return $http
.post(`${SUBSCRIPTION_URL}?origin=confirmChangePlan`, body)
.then(() => location.reload())
.catch(() => {
$scope.genericError = true
$scope.inflight = false
})
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
App.controller(
'CancelPendingPlanChangeController',
function ($scope, $modalInstance, $http) {
$scope.confirmCancelPendingPlanChange = function () {
const body = {
_csrf: window.csrfToken,
}
$scope.genericError = false
$scope.inflight = true
return $http
.post('/user/subscription/cancel-pending', body)
.then(() => location.reload())
.catch(() => {
$scope.genericError = true
$scope.inflight = false
})
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
App.controller(
'LeaveGroupModalController',
function ($scope, $modalInstance, $http) {
$scope.confirmLeaveGroup = function () {
$scope.inflight = true
return $http({
url: '/subscription/group/user',
method: 'DELETE',
params: {
subscriptionId: $scope.subscriptionId,
_csrf: window.csrfToken,
},
})
.then(() => location.reload())
.catch(() => console.log('something went wrong changing plan'))
}
return ($scope.cancel = () => $modalInstance.dismiss('cancel'))
}
)
App.controller('GroupMembershipController', function ($scope, $modal) {
$scope.removeSelfFromGroup = function (subscriptionId) {
$scope.subscriptionId = subscriptionId
return $modal.open({
templateUrl: 'LeaveGroupModalTemplate',
controller: 'LeaveGroupModalController',
scope: $scope,
})
}
})
App.controller('RecurlySubscriptionController', function ($scope) {
const recurlyIsSetup = ensureRecurlyIsSetup()
const subscription = getMeta('ol-subscription')
$scope.showChangePlanButton = recurlyIsSetup && !subscription.groupPlan
if (
window.subscription.recurly.account.has_past_due_invoice &&
window.subscription.recurly.account.has_past_due_invoice._ === 'true'
) {
$scope.showChangePlanButton = false
}
$scope.recurlyLoadError = !recurlyIsSetup
$scope.switchToDefaultView = () => {
$scope.showCancellation = false
$scope.showChangePlan = false
}
$scope.switchToDefaultView()
$scope.switchToCancellationView = () => {
$scope.showCancellation = true
$scope.showChangePlan = false
}
$scope.switchToChangePlanView = () => {
$scope.showCancellation = false
$scope.showChangePlan = true
}
})
App.controller(
'RecurlyCancellationController',
function ($scope, RecurlyPricing, $http) {
if (!ensureRecurlyIsSetup()) return
const subscription = getMeta('ol-subscription')
const sevenDaysTime = new Date()
sevenDaysTime.setDate(sevenDaysTime.getDate() + 7)
const freeTrialEndDate = new Date(subscription.recurly.trial_ends_at)
const freeTrialInFuture = freeTrialEndDate > new Date()
const freeTrialExpiresUnderSevenDays = freeTrialEndDate < sevenDaysTime
const isMonthlyCollab =
subscription.plan.planCode.indexOf('collaborator') !== -1 &&
subscription.plan.planCode.indexOf('ann') === -1 &&
!subscription.groupPlan
const stillInFreeTrial = freeTrialInFuture && freeTrialExpiresUnderSevenDays
if (isMonthlyCollab && stillInFreeTrial) {
$scope.showExtendFreeTrial = true
} else if (isMonthlyCollab && !stillInFreeTrial) {
$scope.showDowngradeToStudent = true
} else {
$scope.showBasicCancel = true
}
const { currency, taxRate } = subscription.recurly
$scope.studentPrice = '...' // Placeholder while we talk to recurly
RecurlyPricing.loadDisplayPriceWithTax('student', currency, taxRate).then(
price => {
$scope.studentPrice = price
}
)
$scope.downgradeToStudent = function () {
const body = {
plan_code: 'student',
_csrf: window.csrfToken,
}
$scope.inflight = true
return $http
.post(`${SUBSCRIPTION_URL}?origin=downgradeToStudent`, body)
.then(() => location.reload())
.catch(() => console.log('something went wrong changing plan'))
}
$scope.cancelSubscription = function () {
const body = { _csrf: window.csrfToken }
$scope.inflight = true
return $http
.post('/user/subscription/cancel', body)
.then(() => (location.href = '/user/subscription/canceled'))
.catch(() => console.log('something went wrong changing plan'))
}
$scope.extendTrial = function () {
const body = { _csrf: window.csrfToken }
$scope.inflight = true
return $http
.put('/user/subscription/extend', body)
.then(() => location.reload())
.catch(() => console.log('something went wrong changing plan'))
}
}
)
| overleaf/web/frontend/js/main/subscription-dashboard.js/0 | {
"file_path": "overleaf/web/frontend/js/main/subscription-dashboard.js",
"repo_id": "overleaf",
"token_count": 3802
} | 540 |
/* 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'
export default App.factory('waitFor', function ($q) {
const waitFor = function (testFunction, timeout, pollInterval) {
if (pollInterval == null) {
pollInterval = 500
}
const iterationLimit = Math.floor(timeout / pollInterval)
let iterations = 0
return $q(function (resolve, reject) {
let tryIteration
return (tryIteration = function () {
if (iterations > iterationLimit) {
return reject(
new Error(
`waiting too long, ${JSON.stringify({ timeout, pollInterval })}`
)
)
}
iterations += 1
const result = testFunction()
if (result != null) {
return resolve(result)
} else {
return setTimeout(tryIteration, pollInterval)
}
})()
})
}
return waitFor
})
| overleaf/web/frontend/js/services/wait-for.js/0 | {
"file_path": "overleaf/web/frontend/js/services/wait-for.js",
"repo_id": "overleaf",
"token_count": 482
} | 541 |
import PropTypes from 'prop-types'
import createSharedContext from 'react2angular-shared-context'
import { UserProvider } from './user-context'
import { IdeProvider } from './ide-context'
import { EditorProvider } from './editor-context'
import { CompileProvider } from './compile-context'
import { LayoutProvider } from './layout-context'
import { ChatProvider } from '../../features/chat/context/chat-context'
import { ProjectProvider } from './project-context'
export function ContextRoot({ children, ide, settings }) {
return (
<IdeProvider ide={ide}>
<UserProvider>
<ProjectProvider>
<EditorProvider settings={settings}>
<CompileProvider>
<LayoutProvider>
<ChatProvider>{children}</ChatProvider>
</LayoutProvider>
</CompileProvider>
</EditorProvider>
</ProjectProvider>
</UserProvider>
</IdeProvider>
)
}
ContextRoot.propTypes = {
children: PropTypes.any,
ide: PropTypes.any.isRequired,
settings: PropTypes.any.isRequired,
}
export const rootContext = createSharedContext(ContextRoot)
| overleaf/web/frontend/js/shared/context/root-context.js/0 | {
"file_path": "overleaf/web/frontend/js/shared/context/root-context.js",
"repo_id": "overleaf",
"token_count": 402
} | 542 |
<div class="autocomplete {{ attrs.class }}" id="{{ attrs.id }}">
<input
type="text"
ng-model="searchParam"
placeholder="{{ attrs.placeholder }}"
class="{{ attrs.inputclass }}"
id="{{ attrs.inputid }}"/>
<ul ng-show="completing">
<li
suggestion
ng-repeat="suggestion in suggestions | filter:searchFilter | orderBy:'toString()' track by $index"
index="{{ $index }}"
val="{{ suggestion }}"
ng-class="{ active: ($index === selectedIndex) }"
ng-click="select(suggestion)"
ng-bind-html="suggestion | highlight:searchParam"></li>
</ul>
</div>
| overleaf/web/frontend/js/vendor/libs/angular-autocomplete/ac_template.html/0 | {
"file_path": "overleaf/web/frontend/js/vendor/libs/angular-autocomplete/ac_template.html",
"repo_id": "overleaf",
"token_count": 237
} | 543 |
import ToolbarHeader from '../js/features/editor-navigation-toolbar/components/toolbar-header'
import { setupContext } from './fixtures/context'
setupContext()
export const UpToThreeConnectedUsers = args => {
return <ToolbarHeader {...args} />
}
UpToThreeConnectedUsers.args = {
onlineUsers: ['a', 'c', 'd'].map(c => ({
user_id: c,
name: `${c}_user name`,
})),
}
export const ManyConnectedUsers = args => {
return <ToolbarHeader {...args} />
}
ManyConnectedUsers.args = {
onlineUsers: ['a', 'c', 'd', 'e', 'f'].map(c => ({
user_id: c,
name: `${c}_user name`,
})),
}
export default {
title: 'EditorNavigationToolbar',
component: ToolbarHeader,
argTypes: {
goToUser: { action: 'goToUser' },
renameProject: { action: 'renameProject' },
toggleHistoryOpen: { action: 'toggleHistoryOpen' },
toggleReviewPanelOpen: { action: 'toggleReviewPanelOpen' },
toggleChatOpen: { action: 'toggleChatOpen' },
togglePdfView: { action: 'togglePdfView' },
openShareModal: { action: 'openShareModal' },
onShowLeftMenuClick: { action: 'onShowLeftMenuClick' },
},
args: {
projectName: 'Overleaf Project',
onlineUsers: [{ user_id: 'abc', name: 'overleaf' }],
unreadMessageCount: 0,
},
}
| overleaf/web/frontend/stories/editor-navigation-toolbar.stories.js/0 | {
"file_path": "overleaf/web/frontend/stories/editor-navigation-toolbar.stories.js",
"repo_id": "overleaf",
"token_count": 463
} | 544 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.