Spaces:
Running
Running
File size: 53,598 Bytes
6c8ebf4 d023036 d8bc3f6 978755f 2a83ff3 978755f 93c6dea d7da207 c305bbf 131dae9 3fed169 35fa4da e0997d1 978755f 233a7ce ed8c88b 771dd10 85e5809 771dd10 db399bf 9d2b645 ed8c88b 816e9d0 75c4dc3 a1b1f1b c305bbf c9824ff c305bbf 744a9b5 3d1ce57 744a9b5 c305bbf 0aa043b bee7181 0aa043b 656d9ed 3d1ce57 656d9ed bee7181 656d9ed 744a9b5 c305bbf 0aa043b 17a3236 3d1ce57 17a3236 3d1ce57 17a3236 978755f 1ad02e7 0aa043b 17a3236 bee7181 17a3236 1ad02e7 978755f d023036 978755f d023036 8c760f9 4c1e6b6 912ff50 4c1e6b6 815659a cd6385a 815659a cd6385a 8d841e9 cd6385a 8d841e9 cd6385a 6c4cf3a 815659a 5e452ed 815659a 5e452ed 6c4cf3a cd6385a 6c4cf3a 815e2b0 6c4cf3a cd6385a a0baead 64e6a96 815659a 64e6a96 4b831ea 815e2b0 a0baead 4b831ea bee7181 4b831ea 6c4cf3a 64e6a96 6c4cf3a 64e6a96 e305ac4 64e6a96 7de1259 04a0c89 7de1259 04a0c89 f493a93 816e9d0 f493a93 a8cd64d 04a0c89 7a10eed a8cd64d 04a0c89 5cb91d4 87eee8b 9f944f6 4b831ea 815e2b0 f3a677c 186ae69 4b831ea 9f944f6 186ae69 825ebe0 9f944f6 4b831ea 8c760f9 186ae69 4b831ea bee7181 4b831ea a1b1f1b 9f944f6 7cbdc18 b05d9e4 7cbdc18 b05d9e4 335a9ff a1b1f1b b05d9e4 4b831ea 8c760f9 4b831ea e5c4067 b05d9e4 4b831ea db3125e 6ea5d19 91b4524 ed5e23f 55fe60b 971307a 816e9d0 91b4524 4b831ea 91b4524 4b831ea 816e9d0 91b4524 ed5e23f 91b4524 5bd0ca9 91b4524 971307a 816e9d0 91b4524 4b831ea 91b4524 4b831ea 971307a 816e9d0 91b4524 6ea5d19 ed5e23f 9987d63 5bd0ca9 9987d63 971307a 816e9d0 6ea5d19 5bd0ca9 55fe60b 087bfde 55fe60b 816e9d0 6ea5d19 816e9d0 6ea5d19 5bd0ca9 6ea5d19 087bfde 5bd0ca9 6ea5d19 816e9d0 6ea5d19 087bfde 6ea5d19 816e9d0 6ea5d19 91b4524 5bd0ca9 91b4524 816e9d0 91b4524 816e9d0 d53640c 1991010 db3125e 97715fa db3125e 15fa6b0 4b43770 15fa6b0 4b43770 875f316 4b43770 d56852a a4a9b75 d56852a a6fbfdf d912429 a6fbfdf a4a9b75 d56852a 1991010 d56852a bee7181 d56852a a4a9b75 d56852a 1991010 d56852a a4a9b75 d56852a c1232eb 816e9d0 c1232eb d56852a c1232eb 816e9d0 1991010 a4a9b75 d56852a a4a9b75 d56852a c036ce6 4b43770 90322fc 1991010 90322fc 1991010 90322fc 1991010 f7ae6d8 90322fc f7ae6d8 90322fc f7ae6d8 90322fc f7ae6d8 554f2f4 f7ae6d8 90322fc 13f7129 90322fc 1991010 bad5f22 75c4dc3 90322fc 4b43770 84294e1 f517da1 4b43770 66cd523 4b43770 15fa6b0 db3125e 66cd523 db3125e 66cd523 498676e d53640c c036ce6 1232fd2 db3125e 21c7247 fad8012 19e4fdd c8e6651 e041aa2 19e4fdd 8e5a965 88624a4 c8e6651 21c7247 1232fd2 2edf1db db3125e fad8012 db3125e fad8012 d8bc3f6 7272448 d063448 7272448 335a9ff 7272448 a1b1f1b 7272448 d023036 7272448 816e9d0 7272448 978755f d023036 978755f d023036 978755f d023036 816e9d0 978755f 1991010 8ef56f6 bee7181 816e9d0 8ef56f6 816e9d0 53f7550 816e9d0 53f7550 816e9d0 53f7550 816e9d0 d4a6765 816e9d0 53f7550 816e9d0 53f7550 816e9d0 53f7550 816e9d0 03da6c5 816e9d0 90322fc 816e9d0 6379148 816e9d0 bc8716a 816e9d0 bc8716a 816e9d0 8ef56f6 978755f 7272448 978755f 06a76c5 978755f 1991010 6e1f7b2 d023036 978755f a428b58 d023036 978755f 324a1a7 978755f 816e9d0 a428b58 1991010 978755f 1991010 06a76c5 978755f 7cbdc18 d023036 978755f d023036 978755f 06a76c5 978755f 7cbdc18 978755f d023036 978755f 7916f15 5e0ef08 09cad62 978755f d023036 978755f d023036 978755f d023036 3339ecb 6e1f7b2 7916f15 978755f d023036 978755f edee65d d023036 7916f15 978755f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 |
import asyncio
import json
import os
import secrets
import signal
import subprocess
import websockets
import shutil
from connect4 import PLAYER1, PLAYER2, Connect4
from user import User
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
import math
import uuid
def is_absolute(url):
return bool(urlparse(url).netloc)
def handle_protocol_relative(url, base_url):
if url.startswith("//"):
parsed_base_url = urlparse(base_url)
return f"{parsed_base_url.scheme}:{url}"
return url
def inline_resources(soup, base_url):
# Inline CSS
for link_tag in soup.find_all('link', rel='stylesheet'):
href = link_tag.get('href')
if href:
href = handle_protocol_relative(href, base_url)
full_url = urljoin(base_url, href) if not is_absolute(href) else href
css_response = requests.get(full_url)
if css_response.status_code == 200:
style_tag = soup.new_tag('style')
style_tag.string = css_response.text
link_tag.replace_with(style_tag)
# Inline JavaScript
for script_tag in soup.find_all('script', src=True):
src = script_tag.get('src')
if src:
src = handle_protocol_relative(src, base_url)
full_url = urljoin(base_url, src) if not is_absolute(src) else src
js_response = requests.get(full_url)
if js_response.status_code == 200:
script_tag.string = js_response.text
del script_tag['src']
return soup
async def send_html_chunks(websocket, soup):
# Convert the BeautifulSoup object back to a string and split into lines
html_str = str(soup)
lines = html_str.split('\n')
# Send each line as a separate chunk
for line in lines:
line = line.strip()
if line: # Send non-empty lines
await websocket.send(json.dumps({"type": "chunk", "content": line}))
await websocket.send(json.dumps({"type": "end",}))
async def send_message_chunks(websocket, message):
msg_id = str(uuid.uuid4())
message_json = json.dumps(message)
chunks = [message_json[i:i+10] for i in range(0, len(message_json), 10)]
for i, chunk in enumerate(chunks):
chunk_data = {
'msg_id': msg_id,
'part': chunk,
'end': i == len(chunks) - 1
}
await websocket.send(json.dumps(chunk_data))
print(f"Sent chunk: {chunk_data}")
def auto_detect_mode(content):
if isinstance(content, str):
return 'w' # If content is a string, it's text
elif isinstance(content, bytes):
return 'wb' # If content is bytes, it's binary
else:
raise ValueError("Unsupported content type. Expected str or bytes.")
class FileHandler(FileSystemEventHandler):
def __init__(self, websocket,connected):
super().__init__()
self.websocket = websocket
self.connected = connected
def on_modified(self, event):
if event.is_directory:
return
with open(event.src_path, 'r', encoding='utf-8') as file:
content = file.read()
print(f'File {event.src_path} has been modified.')
new_event = {
"type": "file-modifie",
"content": content,
"path": event.src_path,
}
websockets.broadcast(self.connected,json.dumps(new_event))
# websockets.broadcast(self.connected,f'File {event.src_path} has been modified.')
def on_created(self, event):
if event.is_directory:
new_event = {
"type": "folder-create",
"path": event.src_path,
"name": event.src_path.split('/')[-1]
}
# print(new_event)
websockets.broadcast(self.connected,json.dumps(new_event))
else:
with open(event.src_path, 'r', encoding='utf-8') as file:
content = file.read()
print(f'File {event.src_path} has been created.')
new_event = {
"type": "file-create",
"content": content,
"path": event.src_path,
"name": event.src_path.split('/')[-1]
}
# print(new_event)
websockets.broadcast(self.connected,json.dumps(new_event))
# websockets.broadcast(self.connected,f'File {event.src_path} has been created.')
def on_deleted(self, event):
if event.is_directory:
new_event = {
"type": "delete",
"path": event.src_path,
"name": event.src_path.split('/')[-1],
}
websockets.broadcast(self.connected,json.dumps(new_event))
else:
print(f'File {event.src_path} has been deleted.')
new_event = {
"type": "delete",
"name": event.src_path.split('/')[-1],
"path": event.src_path,
}
print(event.src_path)
websockets.broadcast(self.connected,json.dumps(new_event))
def on_moved(self, event):
if event.is_directory:
new_event = {
"type": "rename",
"OldPath": event.src_path,
"oldname": event.src_path.split('/')[-1],
"NewPath": event.dest_path,
"newname": event.dest_path.split('/')[-1],
}
websockets.broadcast(self.connected,json.dumps(new_event))
else:
# print(f'File {event.src_path} has been renamed to {event.dest_path}.')
new_event = {
"type": "rename",
"OldPath": event.src_path,
"oldname": event.src_path.split('/')[-1],
"NewPath": event.dest_path,
"newname": event.dest_path.split('/')[-1],
}
websockets.broadcast(self.connected,json.dumps(new_event))
JOIN = {}
WATCH = {}
async def generate_file_structure(path, encoding='utf-8'):
file_structure = {'name': os.path.basename(path), 'type': 'folder', 'path': path, 'children': []}
try:
entries = os.listdir(path)
except FileNotFoundError:
return file_structure # Return an empty structure for non-existing directories
for entry in entries:
entry_path = os.path.join(path, entry)
if os.path.isdir(entry_path):
child_structure =await generate_file_structure(entry_path, encoding)
file_structure['children'].append(child_structure)
elif os.path.isfile(entry_path):
try:
with open(entry_path, 'r', encoding=encoding) as file:
content = file.read()
except UnicodeDecodeError:
content = 'Unable to read content'
file_structure['children'].append({'name': entry, 'type': 'file', 'path': entry_path, 'content': content})
return file_structure
async def rename_item(websocket, key,project_name, path,rpath,new_name,root, connected):
old_path = os.path.join(os.getcwd(),'projects', key,project_name, rpath)
new_name = new_name
new_path = os.path.join(os.path.dirname(old_path), new_name)
try:
if os.path.exists(old_path):
# Determine the new path
# Rename the file or folder
os.rename(old_path, new_path)
websockets.broadcast(connected,'success')
event = {
"type": "rename-success",
"data": f'{old_path}-->{new_path}',
"path": path,
"new_rpath":rpath,
"name": new_name,
"root":root,
}
websockets.broadcast(connected,json.dumps(event))
else:
event = {
"type": "rename-failed",
"data": f'{old_path}-->{new_path} failed Item not found',
"old_path": path,
"new_name": new_name,
}
websockets.broadcast(connected,json.dumps(event))
except Exception as e:
websockets.broadcast(connected,str(e))
async def delete_item(websocket, key,project_name, path,rpath,targetElementData, connected):
try:
item_path = os.path.join(os.getcwd(), 'projects', key,project_name, rpath)
if os.path.exists(item_path):
if os.path.isdir(item_path):
shutil.rmtree(item_path) # Remove the directory and its contents
elif os.path.isfile(item_path):
os.remove(item_path) # Remove the file
event = {
"type": "delete-success",
"data": path,
"path":path,
"targetElementData":targetElementData,
}
# print(event)
websockets.broadcast(connected,json.dumps(event))
# websockets.broadcast(connected,'success')
else:
event = {
"type": "delete-failed",
"data": f'{item_path} Item not found',
}
websockets.broadcast(connected,json.dumps(event))
except Exception as e:
# print(e)
websockets.broadcast(connected,str(e))
async def get_file_content(websocket, key,project_name, path,rpath,name,connected):
file_path = os.path.join(os.getcwd(), 'projects', key,project_name, rpath)
try:
try:
with open(file_path, 'r') as file:
content = file.read()
event = {
"type": "content",
"content": content,
'fileName':name,
'rfilePath':rpath,
'filePath':path,
}
await send_message_chunks(websocket,event)
except UnicodeDecodeError:
with open(file_path, 'rb') as file:
content = file.read()
event = {
"type": "content",
"content": content,
'fileName':name,
'rfilePath':rpath,
'filePath':path,
}
await send_message_chunks(websocket,event)
except Exception as e:
event = {
"type": "error",
"message": f"Failed to read file content: {str(e)}",
}
await send_message_chunks(websocket,event)
async def create_file(websocket, key,project_name, path,name,root,targetElementData,rpath, connected):
file_path = os.path.join(os.getcwd(), 'projects', key,project_name, rpath,name)
# Create the file
with open(file_path, 'w'):
pass
event = {
"type": "file-created",
"data": file_path,
"path": path,
"name": name,
"root":root,
"targetElementData":targetElementData,
}
websockets.broadcast(connected,json.dumps(event))
async def create_folder(websocket, key,project_name, path,name,root,targetElementData,rpath, connected):
folder_path = os.path.join(os.getcwd(), 'projects', key,project_name, rpath,name)
# Create the folder
os.makedirs(folder_path)
event = {
"type": "folder-created",
"data": folder_path,
"path": path,
"name": name,
"root":root,
"targetElementData":targetElementData,
}
# print(folder_path,'created')
websockets.broadcast(connected,json.dumps(event))
async def wirte_file(websocket, key,project_name, path, content, connected):
try:
file_path = os.path.join(os.getcwd(), 'projects', key,project_name, path)
file_content = content
mode = auto_detect_mode(content)
with open(file_path, mode) as file:
file.write(file_content)
event = {
"type": "write-success",
"data": file_path,
"path": path,
"content": content,
}
# websockets.broadcast(connected,json.dumps(event))
except FileNotFoundError as e:
event = {
"type": "write-error",
"data": e,
}
websockets.broadcast(connected,json.dumps(event))
async def read_process_output(process, websocket):
# Read the output and error byte by byte and print word by word
word = b''
while True:
char = await process.stdout.read(1)
if char == b'\n':
if word:
print(word.decode('utf-8'),1)
event = {
"type": "terminal-data",
"data": word.decode('utf-8'),
}
print('sending data',1)
await send_message_chunks(websocket,event)
word = b''
print("line is completed")
event = {
"type": "terminal-newline",
"data": "",
}
await send_message_chunks(websocket,event)
elif char == b' ':
if word:
print(word.decode('utf-8'),2)
event = {
"type": "terminal-data",
"data": word.decode('utf-8'),
}
print('sending data',2)
await send_message_chunks(websocket,event)
word = b''
print("space is occurred")
event = {
"type": "terminal-data",
"data": " ",
}
print('sending data',3)
await send_message_chunks(websocket,event)
elif char == b'':
if word:
print(word.decode('utf-8'),3)
event = {
"type": "terminal-data",
"data": word.decode('utf-8'),
}
print('sending data',4)
await send_message_chunks(websocket,event)
break
else:
word += char
while True:
char = await process.stderr.read(1)
if char == b'\n':
if word:
print(word.decode('utf-8'))
event = {
"type": "terminal-error",
"data": word.decode('utf-8'),
}
await send_message_chunks(websocket,event)
word = b''
print("line is completed")
event = {
"type": "terminal-newline",
"data": "",
}
await send_message_chunks(websocket,event)
elif char == b' ':
if word:
print(word.decode('utf-8'))
event = {
"type": "terminal-error",
"data": word.decode('utf-8'),
}
await send_message_chunks(websocket,event)
word = b''
print("space is occurred")
event = {
"type": "terminal-error",
"data": " ",
}
await send_message_chunks(websocket,event)
elif char == b'':
if word:
print(word.decode('utf-8'))
break
else:
word += char
# async for line in process.stdout:
# # print('sending line')
# event = {
# "type": "terminal-data",
# "data": line.strip().decode('utf-8'),
# }
# await send_message_chunks(websocket,event)
# async for line in process.stderr:
# # print(f'error:{line.strip()}')
# event = {
# "type": "terminal-error",
# "data": line.strip().decode('utf-8'),
# }
# await send_message_chunks(websocket,event)
async def handle_user_input(websocket,key, process, connected,process_ids):
while True:
try:
await asyncio.sleep(0.1)
if process.returncode is not None:
break
# message = await websocket.recv()
async for message in websocket:
# user_input = json.loads(message)
# print(user_input)
# print(f'Received user input: {user_input["command"]["command"]}')
# process_input(user_input["command"]["command"], process)
event = json.loads(message)
assert event["type"] == "cmd"
# command = event["command"]
print(f'Received user input: {event}')
try:
if event["command"]["type"]=="shell":
await asyncio.sleep(0.1)
if process.returncode is not None:
base_path = os.path.join(os.getcwd(), 'projects', key,event["project_name"])
directory_path = base_path
event_handler = FileHandler(websocket,connected)
observer = Observer()
observer.schedule(event_handler, path=directory_path, recursive=True)
observer.start()
try:
# await execute_command(websocket, key,event["project_name"], event["command"]["command"], connected)
# base_path = os.path.join(os.getcwd(), 'projects', key,event["project_name"])
print(base_path)
mod_command = f'cd {base_path} && {event["command"]["command"]}'
print(mod_command)
try:
process = await asyncio.create_subprocess_shell(
mod_command,
# cwd=base_path,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
# text=True,
)
id=process.pid
process_ids.append(id)
async def send_message(message):
# print('sending msg')
# await websocket.send(f'data: {message}')
websockets.broadcast(connected,json.dumps(message) )
await asyncio.gather(
handle_user_input(websocket,key, process, connected,process_ids),
read_process_output(process, websocket)
)
return_code = await process.wait()
if return_code == 0:
event = {
"type": "terminal-data-end",
}
await send_message_chunks(websocket,event)
else:
event = {
"type": "terminal-data-end",
}
await send_message_chunks(websocket,event)
process_ids.remove(id)
except Exception as e:
await error(websocket, str(e))
except KeyboardInterrupt:
pass # Handle KeyboardInterrupt to gracefully stop the observer
observer.stop()
observer.join()
else:
await process_input(event["command"]["command"], process)
elif event["command"]["type"]=="write":
await wirte_file(websocket, key,event["project_name"], event["path"], event["content"], connected)
elif event["command"]["type"] == "curl":
method = event.get("method", "GET")
url = event["url"]
body = event.get("data", "")
headers = event.get("headers", {})
if method.upper() == "GET":
response = requests.get(url, headers=headers)
elif method.upper() == "POST":
response = requests.post(url, data=body, headers=headers)
else:
response = {"error": "Unsupported method"}
if isinstance(response, dict):
response_data = {
"type": "error",
"data": response,
}
await websocket.send(json.dumps(response_data))
return
# Parse HTML content
souptmp = BeautifulSoup(response.text, "html.parser")
# Step 1: Define the initial HTML string
html_str = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
"""
# Step 2: Parse the initial HTML content
soup = BeautifulSoup(html_str, 'html.parser')
# Step 3: Replace the existing body content with the new content from souptmp
if soup.body:
soup.body.clear()
soup.body.append(souptmp)
else:
print("No <body> tag found in the HTML")
# Inline CSS and JavaScript
soup = inline_resources(soup, url)
response_data = {
"type": "web-data",
"data": str(soup),
}
await websocket.send(json.dumps(response_data))
# Convert the final soup to a string
elif event["command"]["type"]=="create":
if event["item"]=="folder":
await create_folder(websocket, key,event["project_name"], event["path"],event["name"],event['root'],event['targetElementData'],event["rpath"], connected)
else:
await create_file(websocket, key,event["project_name"], event["path"],event["name"],event['root'],event['targetElementData'],event["rpath"], connected)
elif event["command"]["type"]=="delete":
await delete_item(websocket, key,event["project_name"], event["path"],event['rpath'],event['targetElementData'], connected)
elif event["command"]["type"]=="get_content":
await get_file_content(websocket, key,event["project_name"],event["filePath"], event["rfilePath"],event["fileName"] ,connected)
elif event["command"]["type"]=="rename":
await rename_item(websocket, key,event["project_name"], event["path"],event['rpath'], event["name"], event["root"], connected)
elif event["command"]["type"]=="join":
await join(websocket, event["join"])
elif event["command"]["type"]=="sendDir":
data=json.loads(event["file_structure"])
event = {
"type": "createDir",
"path": data,
"root":event['root'],
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="createItemUI":
event = {
"type": "createItemUI",
'targetElementData':event['targetElementData'],
'data':event['data']
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="renameItemInUI":
event = {
"type": "renameItemInUI",
'path':event['path'],
'new_path':event['new_path'],
'name':event['name'],
'new_rpath':event['new_rpath'],
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="createFolderUI":
event = {
"type": "createFolderUI",
'targetElementData':event['targetElementData'],
'data':event['data']
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="removeItemFromUI":
event = {
"type": "removeItemFromUI",
'targetElementData':event['targetElementData'],
'path':event['path']
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="project":
base_path = os.path.join(os.getcwd(), 'projects',key, event["project_name"])
data=json.loads(event["file_structure"])
await create_file_structure(websocket,data, base_path=base_path)
# await rename_item(websocket, key,event["project_name"], event["path"], event["name"], connected)
elif event["command"]["type"]=="collabration":
event = {
"type": "collabration",
'name': event["name"],
'line': event["cursorPos-line"],
'ch': event["cursorPos-ch"],
'file':event["file"],
'content': event["content"],
'color':event["color"]
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="cursor":
event = {
"type": "cursor",
'offset': event["offset"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="select":
event = {
"type": "select",
'id': event["id"],
'startOffset': event["startOffset"],
'endOffset': event["endOffset"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="addselection":
event = {
"type": "addselection",
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="insert":
event = {
"type": "insert",
'index': event["index"],
'text': event["text"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="replace":
event = {
"type": "replace",
'index': event["index"],
'length': event["length"],
'text': event["text"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="edelelte":
event = {
"type": "edelelte",
'index': event["index"],
'length': event["length"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="keep-alive":
event = {
"type": "keep-alive",
}
websockets.broadcast(connected, json.dumps(event))
else:
# First player starts a new game.
pass
except Exception as exc:
# Send an "error" event if the move was illegal.
await error(websocket, str(exc))
continue
break
except websockets.ConnectionClosed:
print("WebSocket connection closed")
break
except Exception as e:
print(f"Error in input thread: {str(e)}")
pass
async def process_input(user_input, process):
if process:
try:
if user_input == 'Ctrl+C':
print('Stopping process')
# Send Ctrl+C signal to the subprocess
process.send_signal(signal.SIGINT)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
# Read output and error asynchronously
# os.kill(int(process.pid), signal.CTRL_C_EVENT)
print('stoping signal sent')
else:
print(user_input)
process.stdin.write(user_input.encode('utf-8') + b'\n')
# process.stdin.flush()
except Exception as e:
print(f"Error writing to process stdin: {str(e)}")
else:
print("No process available to write to.")
async def create_file_structure(websocket, data, base_path='.'):
if data['type'] == 'folder':
folder_path = os.path.join(base_path, data['name'])
os.makedirs(folder_path, exist_ok=True)
for child in data['children']:
await create_file_structure(websocket,child, base_path=folder_path)
elif data['type'] == 'file':
mode = auto_detect_mode(data['content'])
file_path = os.path.join(base_path, data['name'])
with open(file_path,mode) as file:
file.write(data['content'])
event = {
"type": "msg",
"message": "project created",
}
await send_message_chunks(websocket,event)
async def error(websocket, message):
"""
Send an error message.
"""
event = {
"type": "error",
"message": message,
}
await send_message_chunks(websocket,event)
async def exe(websocket,connected,key,process_ids):
"""
Receive and process moves from a player.
"""
# print('in exe')
message_parts = {}
async for message in websocket:
# Parse a "play" event from the UI.
data = json.loads(message)
msg_id = data['msg_id']
part = data['part']
if msg_id not in message_parts:
message_parts[msg_id] = []
message_parts[msg_id].append(part)
if data['end']:
full_message = ''.join(message_parts[msg_id])
print(f"Received full message: {full_message}")
event = json.loads(full_message)
del message_parts[msg_id]
assert event["type"] == "cmd"
# command = event["command"]
print(event,2)
try:
if event["command"]["type"]=="shell":
base_path = os.path.join(os.getcwd(), 'projects', key,event["project_name"])
directory_path = base_path
event_handler = FileHandler(websocket,connected)
observer = Observer()
observer.schedule(event_handler, path=directory_path, recursive=True)
observer.start()
try:
# await execute_command(websocket, key,event["project_name"], event["command"]["command"], connected)
# base_path = os.path.join(os.getcwd(), 'projects', key,event["project_name"])
print(base_path)
mod_command = f'cd {base_path} && {event["command"]["command"]}'
print(mod_command)
try:
process = await asyncio.create_subprocess_shell(
mod_command,
# cwd=base_path,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
# text=True,
)
id=process.pid
process_ids.append(id)
async def send_message(message):
# print('sending msg')
# await websocket.send(f'data: {message}')
websockets.broadcast(connected,json.dumps(message) )
await asyncio.gather(
handle_user_input(websocket,key, process, connected,process_ids),
read_process_output(process, websocket)
)
return_code = await process.wait()
if return_code == 0:
event = {
"type": "terminal-data-end",
}
await send_message_chunks(websocket,event)
else:
event = {
"type": "terminal-data-end",
}
await send_message_chunks(websocket,event)
process_ids.remove(id)
except Exception as e:
await error(websocket, str(e))
except KeyboardInterrupt:
pass # Handle KeyboardInterrupt to gracefully stop the observer
observer.stop()
observer.join()
elif event["command"]["type"]=="write":
await wirte_file(websocket, key,event["project_name"], event["path"], event["content"], connected)
elif event["command"]["type"] == "curl":
method = event.get("method", "GET")
url = event["url"]
body = event.get("data", "")
headers = event.get("headers", {})
if method.upper() == "GET":
response = requests.get(url, headers=headers)
elif method.upper() == "POST":
response = requests.post(url, data=body, headers=headers)
else:
response = {"error": "Unsupported method"}
if isinstance(response, dict):
response_data = {
"type": "error",
"data": response,
}
await websocket.send(json.dumps(response_data))
return
# Parse HTML content
souptmp = BeautifulSoup(response.text, "html.parser")
# Step 1: Define the initial HTML string
html_str = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
"""
# Step 2: Parse the initial HTML content
soup = BeautifulSoup(html_str, 'html.parser')
# Step 3: Replace the existing body content with the new content from souptmp
if soup.body:
soup.body.clear()
soup.body.append(souptmp)
else:
print("No <body> tag found in the HTML")
# Inline CSS and JavaScript
soup = inline_resources(soup, url)
response_data = {
"type": "web-data",
"data": str(soup),
}
# await websocket.send(json.dumps(response_data))
await send_html_chunks(websocket, soup)
elif event["command"]["type"]=="create":
if event["item"]=="folder":
await create_folder(websocket, key,event["project_name"], event["path"],event["name"],event['root'],event['targetElementData'],event["rpath"], connected)
else:
await create_file(websocket, key,event["project_name"], event["path"],event["name"],event['root'],event['targetElementData'],event["rpath"], connected)
elif event["command"]["type"]=="delete":
await delete_item(websocket, key,event["project_name"], event["path"],event['rpath'],event['targetElementData'], connected)
elif event["command"]["type"]=="get_content":
await get_file_content(websocket, key,event["project_name"],event["filePath"], event["rfilePath"],event["fileName"] ,connected)
elif event["command"]["type"]=="rename":
await rename_item(websocket, key,event["project_name"], event["path"],event['rpath'], event["name"], event["root"], connected)
elif event["command"]["type"]=="join":
await join(websocket, event["join"])
elif event["command"]["type"]=="sendDir":
data=json.loads(event["file_structure"])
event = {
"type": "createDir",
"path": data,
"root":event['root'],
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="createItemUI":
event = {
"type": "createItemUI",
'targetElementData':event['targetElementData'],
'data':event['data']
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="renameItemInUI":
event = {
"type": "renameItemInUI",
'path':event['path'],
'new_path':event['new_path'],
'name':event['name'],
'new_rpath':event['new_rpath'],
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="createFolderUI":
event = {
"type": "createFolderUI",
'targetElementData':event['targetElementData'],
'data':event['data']
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="removeItemFromUI":
event = {
"type": "removeItemFromUI",
'targetElementData':event['targetElementData'],
'path':event['path']
}
# websockets.broadcast(connected,json.dumps(event))
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="project":
base_path = os.path.join(os.getcwd(), 'projects',key, event["project_name"])
data=json.loads(event["file_structure"])
await create_file_structure(websocket,data, base_path=base_path)
# await rename_item(websocket, key,event["project_name"], event["path"], event["name"], connected)
elif event["command"]["type"]=="collabration":
event = {
"type": "collabration",
'name': event["name"],
'line': event["cursorPos-line"],
'ch': event["cursorPos-ch"],
'file':event["file"],
'content': event["content"],
'color':event["color"]
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="cursor":
event = {
"type": "cursor",
'offset': event["offset"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="select":
event = {
"type": "select",
'id': event["id"],
'startOffset': event["startOffset"],
'endOffset': event["endOffset"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="addselection":
event = {
"type": "addselection",
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="insert":
event = {
"type": "insert",
'index': event["index"],
'text': event["text"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
'tabStatus':event['tabStatus'],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="replace":
event = {
"type": "replace",
'index': event["index"],
'length': event["length"],
'text': event["text"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
'tabStatus':event['tabStatus'],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="edelelte":
event = {
"type": "edelelte",
'index': event["index"],
'length': event["length"],
'userid': event["userid"],
'userlabel': event["userlabel"],
'usercolor': event["usercolor"],
'fileName':event["fileName"],
}
websockets.broadcast(connected, json.dumps(event))
elif event["command"]["type"]=="keep-alive":
event = {
"type": "keep-alive",
}
else:
# First player starts a new game.
pass
except Exception as exc:
# Send an "error" event if the move was illegal.
await error(websocket, str(exc))
continue
async def start(websocket,events):
user = User()
connected = {websocket}
process_ids = []
join_key = secrets.token_urlsafe(12)
JOIN[join_key] = user, connected
try:
# Send the secret access tokens to the browser of the first player,
# where they'll be used for building "join" and "watch" links.
event = {
"type": "init",
"join": join_key,
}
await send_message_chunks(websocket,event)
await exe(websocket,connected,join_key,process_ids)
finally:
del JOIN[join_key]
project_path = os.path.join(os.getcwd(), 'projects', JOIN[join_key])
shutil.rmtree(project_path)
for id in process_ids:
os.killpg(os.getpgid(id), signal.SIGTERM)
async def join(websocket, key):
"""
Handle a connection from the second player: join an existing game.
"""
# Find the Connect Four game.
try:
user, connected = JOIN[key]
except KeyError:
await error(websocket, "collabration not found.")
return
# Register to receive moves from this game.
connected.add(websocket)
try:
event = {
"type": "sendDir",
}
websockets.broadcast(connected,json.dumps(event))
await exe(websocket,connected,key)
finally:
connected.remove(websocket)
async def handler(websocket):
"""
Handle a connection and dispatch it according to who is connecting.
"""
# Receive and parse the "init" event from the UI.
message_parts = {}
async for message in websocket:
data = json.loads(message)
msg_id = data['msg_id']
part = data['part']
if msg_id not in message_parts:
message_parts[msg_id] = []
message_parts[msg_id].append(part)
if data['end']:
full_message = ''.join(message_parts[msg_id])
print(f"Received full message: {full_message}")
event = json.loads(full_message)
if event["type"] == "init":
if "join" in event:
# Second player joins an existing game.
await join(websocket, event["join"])
else:
# First player starts a new game.
await start(websocket, full_message)
elif event["type"] == "cmd":
# print('executing commad')
# Execute a command in the project folder.
await execute_command(websocket, event["project_name"], event["command"])
async def main():
# Set the stop condition when receiving SIGTERM.
loop = asyncio.get_running_loop()
stop = loop.create_future()
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
port = int(os.environ.get("PORT", "7860"))
async with websockets.serve(handler, "0.0.0.0", port):
await stop
if __name__ == "__main__":
asyncio.run(main()) |