Spaces:
Running
Running
File size: 16,983 Bytes
978755f 7916f15 d023036 d8bc3f6 978755f 2a83ff3 978755f 93c6dea 978755f d023036 978755f d023036 8c760f9 4c1e6b6 912ff50 4c1e6b6 7cbdc18 cd6385a 7cbdc18 cd6385a 6c4cf3a 815e2b0 6c4cf3a cd6385a 6c4cf3a 815e2b0 6c4cf3a cd6385a 7cbdc18 64e6a96 7cbdc18 64e6a96 4b831ea 815e2b0 4b831ea 6c4cf3a 64e6a96 6c4cf3a 64e6a96 e305ac4 64e6a96 7cbdc18 1af0587 9f944f6 4b831ea 815e2b0 4b831ea 9f944f6 7cbdc18 9f944f6 4b831ea 8c760f9 4b831ea 9f944f6 7cbdc18 b05d9e4 7cbdc18 b05d9e4 4b831ea 8c760f9 4b831ea b05d9e4 4b831ea b05d9e4 7cbdc18 9424e52 d8bc3f6 d53640c 7cbdc18 d53640c d8bc3f6 d53640c 857b6ed 6af6756 d53640c 4b831ea 6af6756 4b831ea d53640c 4b831ea 6c4cf3a 4b831ea d53640c 6c4cf3a d53640c 6c4cf3a d53640c e183787 6c4cf3a d8bc3f6 7272448 d063448 7272448 d023036 7272448 978755f d023036 978755f d023036 978755f d023036 978755f 7cbdc18 8ef56f6 1a16e71 8ef56f6 f7febe1 8ef56f6 4070523 7cbdc18 8ef812a b05d9e4 7cbdc18 8ef812a a4ebbbd 7cbdc18 a4ebbbd 7cbdc18 9f944f6 38322b0 8ef812a 9f944f6 7cbdc18 8ef812a 9f944f6 7cbdc18 0b4dfcc 995dfe7 f0c7d85 0b4dfcc 8ef56f6 7d5e3bf 8ef812a 8ef56f6 1a16e71 978755f 7272448 978755f 93c6dea 978755f d023036 978755f d023036 978755f d023036 978755f 7272448 7cbdc18 1bf7cc6 978755f 7272448 7cbdc18 978755f 7cbdc18 d023036 978755f d023036 978755f 3cbc949 978755f 7cbdc18 978755f d023036 978755f 7916f15 cd080a4 9424e52 8c760f9 cd080a4 8c760f9 a88f9a5 8c760f9 4b5a232 04817b9 978755f ee352be 978755f 7cbdc18 01bce7c 7cbdc18 09cad62 978755f d023036 ff15b41 978755f ff15b41 978755f ff15b41 978755f d023036 978755f ff15b41 978755f d023036 978755f d023036 61c18ee 89c73c8 4f4cba2 190657e 4f4cba2 190657e 61c18ee 190657e 7916f15 4f4cba2 89c73c8 4f4cba2 89c73c8 7916f15 978755f d023036 978755f 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 |
#!/usr/bin/env python
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
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,new_name, connected):
old_path = os.path.join(os.getcwd(),'projects', key,project_name, path)
new_name = new_name
try:
if os.path.exists(old_path):
# Determine the new path
new_path = os.path.join(os.path.dirname(old_path), new_name)
# 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}',
"old_path": path,
"new_name": new_name,
}
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, connected):
try:
item_path = os.path.join(os.getcwd(), 'projects', key,project_name, path)
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,
}
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 create_file(websocket, key,project_name, path,name, connected):
file_path = os.path.join(os.getcwd(), 'projects', key,project_name, path,name)
# Create the file
with open(file_path, 'w'):
pass
event = {
"type": "file-created",
"data": file_path,
"path": path,
"name": name,
}
websockets.broadcast(connected,json.dumps(event))
async def create_folder(websocket, key,project_name, path,name, connected):
folder_path = os.path.join(os.getcwd(), 'projects', key,project_name, path,name)
# Create the folder
os.makedirs(folder_path)
event = {
"type": "folder-created",
"data": folder_path,
"path": path,
"name": name,
}
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
with open(file_path, 'w', encoding='utf-8') 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 execute_command(websocket, key,project_name, command, connected):
base_path = os.path.join(os.getcwd(), 'projects', key,project_name)
mod_command = f'cd {base_path}&& {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,
)
async def send_message(message):
print('sending msg')
# await websocket.send(f'data: {message}')
websockets.broadcast(connected,json.dumps(message) )
async for line in process.stdout:
print('sending line')
event = {
"type": "terminal-data",
"data": line.strip().decode('utf-8'),
}
await send_message(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(event)
return_code = await process.wait()
if return_code == 0:
# await send_message('Code executed successfully')
pass
else:
# await send_message(f'error:Execution failed with return code {return_code}')
pass
except Exception as e:
await error(websocket, str(e))
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':
file_path = os.path.join(base_path, data['name'])
with open(file_path, 'w', encoding='utf-8') as file:
file.write(data['content'])
event = {
"type": "msg",
"message": "project created",
}
await websocket.send(json.dumps(event))
async def error(websocket, message):
"""
Send an error message.
"""
event = {
"type": "error",
"message": message,
}
await websocket.send(json.dumps(event))
async def replay(websocket, game):
"""
Send previous moves.
"""
# Make a copy to avoid an exception if game.moves changes while iteration
# is in progress. If a move is played while replay is running, moves will
# be sent out of order but each move will be sent once and eventually the
# UI will be consistent.
for player, column, row in game.moves.copy():
event = {
"type": "play",
"player": player,
"column": column,
"row": row,
}
await websocket.send(json.dumps(event))
async def play(websocket, game, player, connected):
"""
Receive and process moves from a player.
"""
async for message in websocket:
# Parse a "play" event from the UI.
event = json.loads(message)
assert event["type"] == "play"
column = event["column"]
try:
# Play the move.
row = game.play(player, column)
except RuntimeError as exc:
# Send an "error" event if the move was illegal.
await error(websocket, str(exc))
continue
# Send a "play" event to update the UI.
event = {
"type": "play",
"player": player,
"column": column,
"row": row,
}
websockets.broadcast(connected, json.dumps(event))
# If move is winning, send a "win" event.
if game.winner is not None:
event = {
"type": "win",
"player": game.winner,
}
websockets.broadcast(connected, json.dumps(event))
async def exe(websocket,connected,key):
"""
Receive and process moves from a player.
"""
print('in exe')
async for message in websocket:
# Parse a "play" event from the UI.
event = json.loads(message)
assert event["type"] == "cmd"
# command = event["command"]
print(event)
try:
if event["command"]["type"]=="shell":
await execute_command(websocket, key,event["project_name"], event["command"]["command"], connected)
elif event["command"]["type"]=="write":
await wirte_file(websocket, key,event["project_name"], event["path"], event["content"], connected)
elif event["command"]["type"]=="create":
if event["item"]=="folder":
await create_folder(websocket, key,event["project_name"], event["path"],event["name"], connected)
else:
await create_file(websocket, key,event["project_name"], event["path"],event["name"], connected)
elif event["command"]["type"]=="delete":
await delete_item(websocket, key,event["project_name"], event["path"], connected)
elif event["command"]["type"]=="rename":
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"],
}
websockets.broadcast(connected, json.dumps(event))
else:
# First player starts a new game.
pass
except RuntimeError as exc:
# Send an "error" event if the move was illegal.
await error(websocket, str(exc))
continue
# # Send a "play" event to update the UI.
# event = {
# "type": "play",
# "player": player,
# "column": column,
# "row": row,
# }
# websockets.broadcast(connected, json.dumps(event))
# # If move is winning, send a "win" event.
# if game.winner is not None:
# event = {
# "type": "win",
# "player": game.winner,
# }
# websockets.broadcast(connected, json.dumps(event))
async def start(websocket,events):
"""
Handle a connection from the first player: start a new game.
"""
# Initialize a Connect Four game, the set of WebSocket connections
# receiving moves from this game, and secret access tokens.
game = User()
connected = {websocket}
join_key = secrets.token_urlsafe(12)
JOIN[join_key] = game, connected
watch_key = secrets.token_urlsafe(12)
WATCH[watch_key] = game, 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,
"watch": watch_key,
}
await websocket.send(json.dumps(event))
js = json.loads(events)
assert js["type"] == "init"
base_path = os.path.join(os.getcwd(), 'projects',join_key, js["project_name"])
data=json.loads(js["file_structure"])
# Receive and process moves from the first player.
# await play(websocket, game, PLAYER1, connected)
await create_file_structure(websocket,data, base_path=base_path)
await exe(websocket,connected,join_key)
finally:
del JOIN[join_key]
del WATCH[watch_key]
async def join(websocket, key):
"""
Handle a connection from the second player: join an existing game.
"""
# Find the Connect Four game.
try:
game, connected = JOIN[key]
except KeyError:
await error(websocket, "collabration not found.")
return
# Register to receive moves from this game.
connected.add(websocket)
try:
base_path = os.path.join(os.getcwd(), 'projects', key,'your_project_name')
mod_command = f'cd {base_path} && ls'
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,
)
project_name = []
async for line in process.stdout:
project_name.append(line.strip().decode('utf-8'))
return_code = await process.wait()
current_directory = f'projects/{key}/your_project_name/{project_name[0]}'
# Send the first move, in case the first player already played it.
file_structure = await generate_file_structure(current_directory)
# Receive and process moves from the second player.
event = {
"type": "join",
"file_structure": json.dumps(file_structure),
}
print('in join')
print(event)
await websocket.send(json.dumps(event))
await exe(websocket,connected,key)
finally:
connected.remove(websocket)
async def watch(websocket, watch_key):
"""
Handle a connection from a spectator: watch an existing game.
"""
# Find the Connect Four game.
try:
game, connected = WATCH[watch_key]
except KeyError:
await error(websocket, "Game not found.")
return
# Register to receive moves from this game.
connected.add(websocket)
try:
# Send previous moves, in case the game already started.
await replay(websocket, game)
# Keep the connection open, but don't receive any messages.
await websocket.wait_closed()
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 = await websocket.recv()
event = json.loads(message)
print(event)
project_name = event["project_name"]
# assert event["type"] == "init"
if event["type"] == "init":
if "join" in event:
# Second player joins an existing game.
await join(websocket, event["join"])
elif "watch" in event:
# Spectator watches an existing game.
await watch(websocket, event["watch"])
else:
# First player starts a new game.
await start(websocket, message)
elif event["type"] == "cmd":
print('executing commad')
# Execute a command in the project folder.
await execute_command(websocket, event["project_name"], event["command"])
# assert event["type"] == "cmd"
# if "command" in event:
# # Second player joins an existing game.
# await execute_command(websocket, project_name, event["command"])
# elif "watch" in event:
# # Spectator watches an existing game.
# await watch(websocket, event["watch"])
# else:
# # First player starts a new game.
# await start(websocket, message)
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()) |