-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
253 lines (197 loc) · 8.25 KB
/
main.py
File metadata and controls
253 lines (197 loc) · 8.25 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
from flask import Flask, render_template, jsonify, request, session, redirect, url_for
import json
import os
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import timedelta
app = Flask(__name__)
# Configure session
app.secret_key = 'your-secret-key-change-this-in-production'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=24)
# In-memory cache for world data
world_cache = None
def load_world_from_file():
"""Load world data from world.json file"""
try:
with open('world.json', 'r') as f:
world_data = json.load(f)
# Convert old format to new format if needed
if 'structures' not in world_data:
world_data = {
'users': {},
'structures': world_data
}
return world_data
except FileNotFoundError:
# Return empty world with new format
return {
'users': {},
'structures': {}
}
except json.JSONDecodeError:
return {
'users': {},
'structures': {}
}
def save_world_to_file():
"""Save current world state to world.json file"""
global world_cache
if world_cache is None:
print("No world data to save")
return
try:
with open('world.json', 'w') as f:
json.dump(world_cache, f, indent=2)
print("World state saved to world.json")
except Exception as e:
print(f"Failed to save world state: {e}")
@app.route('/')
def index():
# Check if user is logged in
if 'username' not in session:
return redirect(url_for('login'))
return render_template('index.html')
@app.route('/login')
def login():
return render_template('login.html')
@app.route('/login', methods=['POST'])
def do_login():
username = request.form.get('username', '').strip()
# Basic validation
if not username or len(username) < 1 or len(username) > 50:
return render_template('login.html', error='Please enter a valid username (1-50 characters)')
# Store username in session
session['username'] = username
session.permanent = True
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('login'))
@app.route('/api/user')
def get_user():
if 'username' not in session:
return jsonify({'error': 'Not logged in'}), 401
return jsonify({'username': session['username']})
@app.route('/api/update_user_position', methods=['POST'])
def update_user_position():
global world_cache
if 'username' not in session:
return jsonify({'error': 'Not logged in'}), 401
# Ensure world is loaded
if world_cache is None:
world_cache = load_world_from_file()
if world_cache is None:
return jsonify({'error': 'World not loaded'}), 500
try:
data = request.get_json()
if not data or 'position' not in data or 'rotation' not in data:
return jsonify({'error': 'Missing position or rotation data'}), 400
position = data['position']
rotation = data['rotation']
# Validate position format (should be [x, y, z])
if not isinstance(position, list) or len(position) != 3:
return jsonify({'error': 'Invalid position format'}), 400
# Validate rotation format (should be [forward, right, up] arrays)
if not isinstance(rotation, dict) or 'forward' not in rotation or 'right' not in rotation or 'up' not in rotation:
return jsonify({'error': 'Invalid rotation format'}), 400
# Update user data in world cache
username = session['username']
if username not in world_cache['users']:
world_cache['users'][username] = {}
world_cache['users'][username]['position'] = position
world_cache['users'][username]['rotation'] = rotation
return jsonify({'success': True, 'position': position, 'rotation': rotation})
except Exception as e:
return jsonify({'error': f'Failed to update user position: {str(e)}'}), 500
@app.route('/api/world')
def get_world():
global world_cache
# If world is not in memory, try to load from file
if world_cache is None:
world_cache = load_world_from_file()
if world_cache is None:
return jsonify({'error': 'world.json not found or invalid JSON'}), 404
return jsonify(world_cache)
@app.route('/api/structure/<structure_name>')
def get_structure(structure_name):
try:
structure_path = os.path.join('structures', f'{structure_name}.json')
with open(structure_path, 'r') as f:
structure_data = json.load(f)
return jsonify(structure_data)
except FileNotFoundError:
return jsonify({'error': f'Structure "{structure_name}" not found'}), 404
except json.JSONDecodeError:
return jsonify({'error': f'Invalid JSON in {structure_name}.json'}), 400
@app.route('/api/add_structure', methods=['POST'])
def add_structure():
global world_cache
# Ensure world is loaded
if world_cache is None:
world_cache = load_world_from_file()
if world_cache is None:
return jsonify({'error': 'World not loaded'}), 500
try:
data = request.get_json()
if not data or 'position' not in data or 'structure' not in data:
return jsonify({'error': 'Missing position or structure data'}), 400
position = data['position']
structure_name = data['structure']
# Validate position format (should be [x, y, z])
if not isinstance(position, list) or len(position) != 3:
return jsonify({'error': 'Invalid position format'}), 400
# Create position key
pos_key = f"{position[0]},{position[1]},{position[2]}"
# Add structure to world cache
world_cache['structures'][pos_key] = structure_name
return jsonify({'success': True, 'position': position, 'structure': structure_name})
except Exception as e:
return jsonify({'error': f'Failed to add structure: {str(e)}'}), 500
@app.route('/api/remove_structure', methods=['POST'])
def remove_structure():
global world_cache
# Ensure world is loaded
if world_cache is None:
world_cache = load_world_from_file()
if world_cache is None:
return jsonify({'error': 'World not loaded'}), 500
try:
data = request.get_json()
if not data or 'position' not in data:
return jsonify({'error': 'Missing position data'}), 400
position = data['position']
# Validate position format (should be [x, y, z])
if not isinstance(position, list) or len(position) != 3:
return jsonify({'error': 'Invalid position format'}), 400
# Create position key
pos_key = f"{position[0]},{position[1]},{position[2]}"
# Remove structure from world cache
removed_structure = world_cache['structures'].pop(pos_key, None)
if removed_structure is None:
return jsonify({'error': 'No structure found at this position'}), 404
return jsonify({'success': True, 'position': position, 'removed_structure': removed_structure})
except Exception as e:
return jsonify({'error': f'Failed to remove structure: {str(e)}'}), 500
if __name__ == '__main__':
# Set up background scheduler for periodic world saving
scheduler = BackgroundScheduler()
# Schedule world save every 10 minutes
scheduler.add_job(
func=save_world_to_file,
trigger='interval',
minutes=10,
id='world_save_job'
)
# Register save function to run on server shutdown
atexit.register(save_world_to_file)
# Start the scheduler
scheduler.start()
print("World auto-save scheduler started (every 10 minutes)")
print("World will also be saved on server shutdown")
try:
app.run(host='0.0.0.0', port=5000)
except (KeyboardInterrupt, SystemExit):
# Ensure scheduler is shut down
scheduler.shutdown()
print("Server shutdown complete")