-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
291 lines (230 loc) · 10.4 KB
/
Copy pathapp.py
File metadata and controls
291 lines (230 loc) · 10.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
282
283
284
285
286
287
288
289
290
291
from flask import Flask, render_template, request, jsonify, redirect, url_for
import os
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import glob
import re
app = Flask(__name__)
# Path to Elite Dangerous bindings folder
# In production, this would be dynamically set or configurable
BINDINGS_PATH = r"C:\Users\ian\AppData\Local\Frontier Developments\Elite Dangerous\Options\Bindings"
@app.route('/')
def index():
"""Main page that lists all binding files"""
# Make bindings path available in templates
app.config['BINDINGS_PATH'] = BINDINGS_PATH
# Check if directory exists
if not os.path.exists(BINDINGS_PATH):
return render_template('index.html', binding_files=[],
error_message=f"The configured bindings directory does not exist: {BINDINGS_PATH}")
binding_files = get_binding_files()
print(f"Found {len(binding_files)} binding files: {binding_files}") # Debug output
if not binding_files:
# If no binding files found, show a helpful message instead of an empty list
return render_template('index.html', binding_files=[],
error_message=f"No files found in the configured directory. Please check that {BINDINGS_PATH} contains .binds, .log, or .backup files.")
return render_template('index.html', binding_files=binding_files)
@app.route('/binding/<filename>')
def view_binding(filename):
"""View a specific binding file"""
filepath = os.path.join(BINDINGS_PATH, filename)
# Check if file exists
if not os.path.exists(filepath):
return render_template('error.html', message=f"File {filename} not found")
# Read the file content
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Parse XML for structured view
try:
root = ET.fromstring(content)
preset_name = root.get('PresetName', 'Unknown')
major_version = root.get('MajorVersion', 'Unknown')
minor_version = root.get('MinorVersion', 'Unknown')
# Get all bindings for structured view
bindings = parse_bindings(root)
# Format the XML for pretty display
pretty_xml = prettify_xml(content)
# Check if corresponding log file exists
log_filename = f"{os.path.splitext(filename)[0]}.log"
log_filepath = os.path.join(BINDINGS_PATH, log_filename)
log_content = None
if os.path.exists(log_filepath):
with open(log_filepath, 'r', encoding='utf-8') as f:
log_content = f.read()
return render_template(
'binding.html',
filename=filename,
preset_name=preset_name,
major_version=major_version,
minor_version=minor_version,
raw_content=content,
pretty_content=pretty_xml,
bindings=bindings,
log_content=log_content
)
except Exception as e:
return render_template('error.html', message=f"Error parsing XML: {str(e)}")
@app.route('/view/<filetype>/<filename>')
def view_file(filename, filetype):
"""View a specific file (log, backup, or start)"""
filepath = os.path.join(BINDINGS_PATH, filename)
# Check if file exists
if not os.path.exists(filepath):
return render_template('error.html', message=f"File {filename} not found")
# Read the file content
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
# If not a text file, show a message
content = "[Binary file content cannot be displayed]"
# Get appropriate title based on file type
if filetype == 'log':
title = "Log File"
icon = "file-alt"
elif filetype == 'backup':
title = "Backup File"
icon = "file-archive"
elif filetype == 'start':
title = "Start File"
icon = "file-medical"
else:
title = "File"
icon = "file"
# Use the file viewer template
return render_template('file_viewer.html',
filename=filename,
content=content,
title=title,
icon=icon,
filetype=filetype)
@app.route('/search_replace', methods=['POST'])
def search_replace():
"""Search and replace in a binding file"""
filename = request.form.get('filename')
search_text = request.form.get('search_text')
replace_text = request.form.get('replace_text')
if not all([filename, search_text, replace_text]):
return jsonify({'success': False, 'message': 'Missing required fields'})
filepath = os.path.join(BINDINGS_PATH, filename)
try:
# Read file content
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Perform search and replace
new_content = content.replace(search_text, replace_text)
# Generate new filename
new_filename = f"{os.path.splitext(filename)[0]}_fixed.binds"
new_filepath = os.path.join(BINDINGS_PATH, new_filename)
# Write to new file
with open(new_filepath, 'w', encoding='utf-8') as f:
f.write(new_content)
return jsonify({'success': True, 'message': f'Created new binding file: {new_filename}', 'new_filename': new_filename})
except Exception as e:
return jsonify({'success': False, 'message': f'Error: {str(e)}'})
@app.route('/restore_backup', methods=['POST'])
def restore_backup():
"""Restore a backup file to create a new binding"""
filename = request.form.get('filename')
new_name = request.form.get('new_name')
if not all([filename, new_name]):
return jsonify({'success': False, 'message': 'Missing required fields'})
backup_filepath = os.path.join(BINDINGS_PATH, filename)
try:
# Read the backup file
with open(backup_filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Generate new filename
if not new_name.endswith('.binds'):
new_filename = f"{new_name}.binds"
else:
new_filename = new_name
new_filepath = os.path.join(BINDINGS_PATH, new_filename)
# Write to new file
with open(new_filepath, 'w', encoding='utf-8') as f:
f.write(content)
return jsonify({'success': True, 'message': f'Restored backup to: {new_filename}', 'new_filename': new_filename})
except Exception as e:
return jsonify({'success': False, 'message': f'Error: {str(e)}'})
@app.route('/rename_binding', methods=['POST'])
def rename_binding():
"""Rename a binding preset"""
filename = request.form.get('filename')
new_name = request.form.get('new_name')
if not all([filename, new_name]):
return jsonify({'success': False, 'message': 'Missing required fields'})
filepath = os.path.join(BINDINGS_PATH, filename)
try:
# Parse the XML
tree = ET.parse(filepath)
root = tree.getroot()
# Update the PresetName attribute
root.set('PresetName', new_name)
# Generate new filename
new_filename = f"{new_name}.{root.get('MajorVersion', '0')}.{root.get('MinorVersion', '0')}.binds"
new_filepath = os.path.join(BINDINGS_PATH, new_filename)
# Write to new file
tree.write(new_filepath, encoding='utf-8', xml_declaration=True)
return jsonify({'success': True, 'message': f'Renamed binding to: {new_filename}', 'new_filename': new_filename})
except Exception as e:
return jsonify({'success': False, 'message': f'Error: {str(e)}'})
def get_binding_files():
"""Get a list of all binding files, logs, and backups"""
binds_files = [os.path.basename(f) for f in glob.glob(os.path.join(BINDINGS_PATH, "*.binds"))]
log_files = [os.path.basename(f) for f in glob.glob(os.path.join(BINDINGS_PATH, "*.log"))]
backup_files = [os.path.basename(f) for f in glob.glob(os.path.join(BINDINGS_PATH, "*.backup"))]
start_files = [os.path.basename(f) for f in glob.glob(os.path.join(BINDINGS_PATH, "*.start"))]
# Create a combined list with file types
all_files = []
for f in binds_files:
all_files.append({"name": f, "type": "binds"})
for f in log_files:
all_files.append({"name": f, "type": "log"})
for f in backup_files:
all_files.append({"name": f, "type": "backup"})
for f in start_files:
all_files.append({"name": f, "type": "start"})
# Sort by name
all_files.sort(key=lambda x: x["name"])
return all_files
def parse_bindings(root):
"""Extract binding information from XML for structured view"""
bindings = []
# Process all child elements
for elem in root:
# Skip non-binding elements or elements without 'Device' attribute
if len(elem) == 0 or all('Device' not in child.attrib for child in elem):
continue
binding_type = elem.tag
# Process Primary/Secondary bindings
for child in elem:
if child.tag in ['Primary', 'Secondary', 'Binding'] and 'Device' in child.attrib:
device = child.get('Device', '')
key = child.get('Key', '')
binding_role = child.tag
# Check for modifiers
modifiers = []
for modifier in child:
if modifier.tag == 'Modifier' and 'Device' in modifier.attrib and 'Key' in modifier.attrib:
modifiers.append(f"{modifier.get('Device')} - {modifier.get('Key')}")
bindings.append({
'type': binding_type,
'role': binding_role,
'device': device,
'key': key,
'modifiers': modifiers
})
return bindings
def prettify_xml(xml_string):
"""Make XML string more readable with proper indentation"""
try:
parsed = minidom.parseString(xml_string)
pretty = parsed.toprettyxml(indent=" ")
# Remove extra whitespace between tags
pretty = re.sub(r'\n\s*\n', '\n', pretty)
return pretty
except:
# Return original if parsing fails
return xml_string
if __name__ == '__main__':
app.run(debug=True)