Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
281 lines (254 loc) · 12.4 KB
/
Copy pathserver.py
File metadata and controls
281 lines (254 loc) · 12.4 KB
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
#!/usr/bin/env python3
"""
server.py - Gameboy Game Maker Server
Static files + AI proxy + game sharing via server-side storage.
"""
import asyncio
import json
import os
import hashlib
import time
import mimetypes
from aiohttp import web, ClientSession, ClientTimeout
def load_env(path='.env'):
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
if not os.path.isfile(env_path):
return
with open(env_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' in line:
key, _, value = line.partition('=')
os.environ.setdefault(key.strip(), value.strip())
load_env()
PORT = int(os.environ.get('PORT', 8777))
STATIC_DIR = os.path.dirname(os.path.abspath(__file__))
GAMES_DIR = os.path.join(STATIC_DIR, 'shared_games')
TEMPLATES_DIR = os.path.join(STATIC_DIR, 'template_games')
os.makedirs(GAMES_DIR, exist_ok=True)
os.makedirs(TEMPLATES_DIR, exist_ok=True)
SERVER_API_URL = os.environ.get('API_URL', '').strip()
SERVER_API_KEY = os.environ.get('API_KEY', '').strip()
SERVER_API_MODEL = os.environ.get('API_MODEL', 'gpt-4o-mini').strip()
def has_server_keys():
return bool(SERVER_API_URL and SERVER_API_KEY and SERVER_API_KEY != 'sk-your-api-key-here')
mimetypes.add_type('application/javascript', '.js')
mimetypes.add_type('text/css', '.css')
# Index file: hash -> game_id mapping
INDEX_FILE = os.path.join(GAMES_DIR, '_index.json')
def load_index():
if os.path.isfile(INDEX_FILE):
with open(INDEX_FILE, 'r') as f:
return json.load(f)
return {}
def save_index(index):
with open(INDEX_FILE, 'w') as f:
json.dump(index, f)
# === GAME SHARE: SAVE ===
async def save_game_handler(request):
try:
body = await request.json()
except Exception:
return web.json_response({'error': 'Invalid JSON body'}, status=400)
code = body.get('code', '')
if not code:
return web.json_response({'error': 'No game code'}, status=400)
# Hash the code (SHA256, first 8 chars)
code_hash = hashlib.sha256(code.encode('utf-8')).hexdigest()[:8]
incoming_mode = body.get('mode')
if incoming_mode not in ('8bit', '16bit'):
incoming_mode = None
# Load index — does the game already exist?
index = load_index()
if code_hash in index:
existing_id = index[code_hash]
# Bump plays counter
game_path = os.path.join(GAMES_DIR, f'{existing_id}.json')
if os.path.isfile(game_path):
with open(game_path, 'r', encoding='utf-8') as f:
game_data = json.load(f)
game_data['plays'] = game_data.get('plays', 0) + 1
# Backfill mode if the existing record doesn't have one yet
# (heals 16-bit games that were shared before mode persistence).
if incoming_mode and not game_data.get('mode'):
game_data['mode'] = incoming_mode
with open(game_path, 'w', encoding='utf-8') as f:
json.dump(game_data, f, ensure_ascii=False)
return web.json_response({'id': existing_id, 'existing': True})
# Save new game
game_id = code_hash # use hash directly as ID
game_path = os.path.join(GAMES_DIR, f'{game_id}.json')
game_data = {
'id': game_id,
'idea': body.get('idea', ''),
'genre': body.get('genre'),
'code': code,
'hash': code_hash,
'ts': body.get('ts', time.time()),
'mode': incoming_mode or '8bit',
'plays': 1
}
with open(game_path, 'w', encoding='utf-8') as f:
json.dump(game_data, f, ensure_ascii=False)
# Update index
index[code_hash] = game_id
save_index(index)
return web.json_response({'id': game_id, 'existing': False})
# === GAME SHARE: LOAD ===
async def load_game_handler(request):
game_id = request.match_info['id']
if not game_id.isalnum() or len(game_id) > 16:
return web.json_response({'error': 'Invalid game ID'}, status=400)
game_path = os.path.join(GAMES_DIR, f'{game_id}.json')
if not os.path.isfile(game_path):
return web.json_response({'error': 'Game not found'}, status=404)
with open(game_path, 'r', encoding='utf-8') as f:
game_data = json.load(f)
# Bump plays counter on load
game_data['plays'] = game_data.get('plays', 0) + 1
with open(game_path, 'w', encoding='utf-8') as f:
json.dump(game_data, f, ensure_ascii=False)
return web.json_response(game_data)
# === TEMPLATE LOAD ===
# Serves a pre-built game template for unmodified example prompts.
# Saves tokens and wait time for "just want to try it" visitors.
async def load_template_handler(request):
slug = request.match_info['slug']
mode = request.match_info['mode']
# Whitelist: only short alphanumeric slugs and the two known modes.
if not slug.isalnum() or len(slug) > 30:
return web.json_response({'error': 'Invalid slug'}, status=400)
if mode not in ('8bit', '16bit'):
return web.json_response({'error': 'Invalid mode'}, status=400)
path = os.path.join(TEMPLATES_DIR, f'{slug}_{mode}.json')
if not os.path.isfile(path):
return web.json_response({'error': 'Template not available'}, status=404)
with open(path, 'r', encoding='utf-8') as f:
return web.json_response(json.load(f))
# === API STATUS ===
async def api_status_handler(request):
return web.json_response({
'serverKeysAvailable': has_server_keys(),
'model': SERVER_API_MODEL if has_server_keys() else None
})
# === SERVER GENERATE ===
async def generate_handler(request):
if not has_server_keys():
return web.json_response({'error': 'No server API keys configured.'}, status=503)
try:
body = await request.json()
except Exception:
return web.json_response({'error': 'Invalid JSON body'}, status=400)
payload = body.get('payload', {})
if not payload:
return web.json_response({'error': 'payload missing'}, status=400)
if 'model' not in payload:
payload['model'] = SERVER_API_MODEL
headers = {'Content-Type': 'application/json', 'Authorization': f'Bearer {SERVER_API_KEY}'}
# Raise the timeout to 240 seconds (4 minutes) for complex 16-bit code generations.
timeout = ClientTimeout(total=240)
try:
async with ClientSession(timeout=timeout) as session:
async with session.post(SERVER_API_URL, json=payload, headers=headers) as resp:
resp_body = await resp.text()
try:
return web.json_response(json.loads(resp_body), status=resp.status)
except json.JSONDecodeError:
return web.Response(text=resp_body, status=resp.status, content_type='text/plain')
except asyncio.TimeoutError:
return web.json_response({'error': 'API timeout (240s)'}, status=504)
except Exception as e:
return web.json_response({'error': f'Server error: {str(e)}'}, status=502)
# === CLIENT PROXY ===
async def proxy_handler(request):
try:
body = await request.json()
except Exception:
return web.json_response({'error': 'Invalid JSON body'}, status=400)
api_url = body.get('apiUrl', '').strip()
api_key = body.get('apiKey', '').strip()
payload = body.get('payload', {})
if not api_url:
return web.json_response({'error': 'apiUrl missing'}, status=400)
if not api_key:
return web.json_response({'error': 'apiKey missing'}, status=400)
headers = {'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}'}
# Same 240s timeout for the client-side proxy.
timeout = ClientTimeout(total=240)
try:
async with ClientSession(timeout=timeout) as session:
async with session.post(api_url, json=payload, headers=headers) as resp:
resp_body = await resp.text()
try:
return web.json_response(json.loads(resp_body), status=resp.status)
except json.JSONDecodeError:
return web.Response(text=resp_body, status=resp.status, content_type='text/plain')
except asyncio.TimeoutError:
return web.json_response({'error': 'Proxy timeout (240s)'}, status=504)
except Exception as e:
return web.json_response({'error': f'Proxy error: {str(e)}'}, status=502)
# === STATIC FILES ===
async def static_handler(request):
path = request.match_info.get('path', '')
if not path or path == '/':
path = 'index.html'
path = path.lstrip('/')
if '..' in path:
return web.Response(text='Forbidden', status=403)
if path in ('.env',) or path.startswith('shared_games/') or path.startswith('template_games/'):
return web.Response(text='Forbidden', status=403)
file_path = os.path.join(STATIC_DIR, path)
if not os.path.isfile(file_path):
file_path = os.path.join(STATIC_DIR, 'index.html')
if not os.path.isfile(file_path):
return web.Response(text='Not Found', status=404)
content_type, _ = mimetypes.guess_type(file_path)
content_type = content_type or 'application/octet-stream'
with open(file_path, 'rb') as f:
content = f.read()
return web.Response(body=content, content_type=content_type)
# === APP ===
def create_app():
app = web.Application()
app.router.add_get('/api/status', api_status_handler)
app.router.add_post('/api/generate', generate_handler)
app.router.add_post('/api/proxy', proxy_handler)
app.router.add_post('/api/games', save_game_handler)
app.router.add_get('/api/games/{id}', load_game_handler)
app.router.add_get('/api/templates/{slug}/{mode}', load_template_handler)
app.router.add_get('/{path:.*}', static_handler)
app.router.add_get('/', static_handler)
return app
if __name__ == '__main__':
# ANSI colors
GREEN = '\033[38;2;155;188;15m' # Gameboy green #9bbc0f
DARK = '\033[38;2;48;98;48m' # Gameboy dark
DIM = '\033[2m'
RESET = '\033[0m'
BOLD = '\033[1m'
ascii_logo = f"""
{GREEN} ███╗ ███╗ █████╗ ██╗ ██╗███████╗{RESET}
{GREEN} ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝{RESET}
{GREEN} ██╔████╔██║███████║█████╔╝ █████╗ {RESET}
{GREEN} ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ {RESET}
{GREEN} ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗{RESET}
{GREEN} ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝{RESET}
{DARK} ███╗ ███╗██╗ ██╗{RESET}{GREEN} ██████╗ █████╗ ███╗ ███╗███████╗{RESET}
{DARK} ████╗ ████║╚██╗ ██╔╝{RESET}{GREEN} ██╔════╝██╔══██╗████╗ ████║██╔════╝{RESET}
{DARK} ██╔████╔██║ ╚████╔╝ {RESET}{GREEN} ██║ ███████║██╔████╔██║█████╗ {RESET}
{DARK} ██║╚██╔╝██║ ╚██╔╝ {RESET}{GREEN} ██║ ██╔══██║██║╚██╔╝██║██╔══╝ {RESET}
{DARK} ██║ ╚═╝ ██║ ██║ {RESET}{GREEN} ╚██████╗██║ ██║██║ ╚═╝ ██║███████╗{RESET}
{DARK} ╚═╝ ╚═╝ ╚═╝ {RESET}{GREEN} ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝{RESET}
"""
keys_status = f"{GREEN}✔ Server keys loaded{RESET}" if has_server_keys() else f"\033[33m⚠ No server keys (.env){RESET}"
print(ascii_logo)
print(f" {BOLD}🎮 MakeMyGame Server{RESET} {DIM}v2.2.0{RESET}")
print(f" {DIM}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{RESET}")
print(f" 🌐 http://0.0.0.0:{PORT}")
print(f" {keys_status}")
print(f" {DIM}Model: {SERVER_API_MODEL}{RESET}")
print(f" {DIM}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{RESET}\n")
app = create_app()
web.run_app(app, host='0.0.0.0', port=PORT, print=lambda msg: print(f' {DIM}{msg}{RESET}'))