-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbrother_ql_web.py
More file actions
executable file
·1151 lines (948 loc) · 42.5 KB
/
Copy pathbrother_ql_web.py
File metadata and controls
executable file
·1151 lines (948 loc) · 42.5 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a web service to print labels on label printers via CUPS.
"""
import copy
import textwrap
import sys, logging, random, json, argparse, requests, yaml
from io import BytesIO
from bottle import run, route, get, post, response, request, jinja2_view as view, static_file, redirect
from PIL import Image, ImageDraw, ImageFont
import glob
import os
from elements import ElementBase
from implementation_cups import implementation
from font_helpers import get_fonts
from configuration_management import (
label_sizes_list_to_dict,
reload_config,
save_config,
config_to_settings_format,
settings_format_to_config,
filter_label_sizes_for_printer,
filter_printers,
normalize_default_fonts,
validate_configuration,
compute_printer_selection,
)
logger = logging.getLogger(__name__)
instance = implementation()
# Initialize CONFIG with a safe default structure
CONFIG = {
'SERVER': {
'HOST': '0.0.0.0',
'PORT': 8013,
'LOGLEVEL': 'INFO',
'ADDITIONAL_FONT_FOLDER': '/fonts'
},
'PRINTER': {
'USE_CUPS': True,
'SERVER': 'localhost',
'PRINTER': '',
'LABEL_SIZES': [],
'ENABLED_SIZES': {},
'PRINTERS_INCLUDE': [],
'PRINTERS_EXCLUDE': [],
'LABEL_PRINTABLE_AREA': {}
},
'LABEL': {
'DEFAULT_SIZE': '62',
'DEFAULT_ORIENTATION': 'standard',
'DEFAULT_FONT_SIZE': 70,
'DEFAULT_FONTS': {'family': 'DejaVu Sans', 'style': 'Book'}
},
'WEBSITE': {
'HTML_TITLE': 'Label Designer',
'PAGE_TITLE': 'Label Designer',
'PAGE_HEADLINE': 'Design and print labels'
}
}
CONFIG_ERRORS = [] # Store configuration validation errors
CONFIG_FILE = '/appconfig/config.json'
# Try to load config file
try:
with open(CONFIG_FILE, encoding='utf-8') as fh:
CONFIG = json.load(fh)
print(f"loaded config from {CONFIG_FILE}")
except FileNotFoundError:
try:
with open('config.minimal.json', encoding='utf-8') as fh:
CONFIG = json.load(fh)
print("loaded config from config.minimal.json")
except FileNotFoundError:
error_msg = "Warning: No config file found. Using default configuration. Please configure settings on the settings page."
CONFIG_ERRORS.append(error_msg)
logger.error(error_msg)
except Exception as e:
error_msg = f"Error: Failed to parse config file: {e}"
CONFIG_ERRORS.append(error_msg)
logger.error(error_msg)
PRINTERS = None
LABEL_SIZES = None
FONTS = {} # Will be populated during initialization
# the decorator
def enable_cors(fn):
def _enable_cors(*args, **kwargs):
# set CORS headers
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
if request.method != 'OPTIONS':
# actual request; reply with the actual response
return fn(*args, **kwargs)
return _enable_cors
# Wrapper for save_config that updates global CONFIG
def save_config_with_global_update(new_config):
"""Save configuration to file and update global CONFIG."""
global CONFIG
if save_config(new_config):
CONFIG.clear()
CONFIG.update(new_config)
return True
return False
@route('/')
def index():
redirect('/labeldesigner')
@route('/static/<filename:path>')
def serve_static(filename):
return static_file(filename, root='./static')
@route('/labeldesigner')
@view('labeldesigner.jinja2')
def labeldesigner():
font_family_names = sorted(list(FONTS.keys()))
filtered_printers, default_printer, label_sizes = compute_printer_selection(instance, PRINTERS, CONFIG, logger)
# Normalize DEFAULT_FONTS to always be a dict for template compatibility
label_config = copy.deepcopy(CONFIG['LABEL'])
label_config['DEFAULT_FONTS'] = normalize_default_fonts(label_config.get('DEFAULT_FONTS', {}))
return {'font_family_names': font_family_names,
'fonts': FONTS,
'label_sizes': label_sizes,
'printers': filtered_printers,
'default_printer': default_printer,
'default_orientation': CONFIG['LABEL'].get('DEFAULT_ORIENTATION', 'standard'),
'website': CONFIG['WEBSITE'],
'label': label_config,
'has_errors': len(CONFIG_ERRORS) > 0}
@route('/api/printer/<printer_name>/media', method=['GET', 'POST', 'OPTIONS'])
@enable_cors
def get_printer_media(printer_name):
"""
API endpoint to get media details for a specific printer.
Returns label sizes and default size for the printer.
Handles URL encoding and special values (empty string, 'null').
Supports two calling modes:
- GET: Uses the global CONFIG (backward compatible)
- POST with config in body: Uses the provided configuration for accurate preview
Used by labeldesigner and settings pages.
"""
try:
# Decode printer_name in case it's URL encoded
from urllib.parse import unquote
printer_name = unquote(printer_name) if printer_name else None
# Handle empty string or 'null' as None (for default printer)
if printer_name == '' or printer_name == 'null' or printer_name == 'undefined':
printer_name = None
# Determine which configuration to use
instance_to_use = instance
config_to_use = CONFIG
# If POST request with config body, use that configuration instead of global CONFIG
if request.method == 'POST':
try:
payload = request.json
if payload and isinstance(payload, dict):
config_to_use = settings_format_to_config(payload)
temp_instance = implementation()
temp_instance.initialize(config_to_use)
instance_to_use = temp_instance
except Exception as e:
logger.warning(f"Could not parse config from request body: {e}")
# Fall back to global CONFIG on error
instance_to_use = instance
config_to_use = CONFIG
# Get label sizes for the printer
label_sizes_list = instance_to_use.get_label_sizes(printer_name)
# Filter by enabled sizes using the provided/global configuration
label_sizes_list = filter_label_sizes_for_printer(label_sizes_list, printer_name, config_to_use)
# Get default size
default_size = instance_to_use.get_default_label_size(printer_name)
# Convert list of tuples to dict for JSON response
label_sizes_dict = label_sizes_list_to_dict(label_sizes_list, logger, warn_prefix="API: ")
return {
'success': True,
'label_sizes': label_sizes_dict,
'default_size': default_size
}
except Exception as e:
response.status = 500
logger.error(f"Error getting printer media: {e}")
return {
'success': False,
'error': str(e)
}
@route("/templateprint")
@view('templateprint.jinja2')
def templatePrint():
templateFiles = [os.path.basename(file) for file in glob.glob('/appconfig/*.lbl')]
# Use shared helper to get printers, default, and label sizes
filtered_printers, default_printer, label_sizes = compute_printer_selection(instance, PRINTERS, CONFIG, logger)
# Normalize DEFAULT_FONTS to always be a dict for template compatibility
label_config = copy.deepcopy(CONFIG['LABEL'])
label_config['DEFAULT_FONTS'] = normalize_default_fonts(label_config.get('DEFAULT_FONTS', {}))
return {
'files': templateFiles,
'printers': filtered_printers,
'default_printer': default_printer,
'label_sizes': label_sizes,
'website': CONFIG['WEBSITE'],
'label': label_config,
'has_errors': len(CONFIG_ERRORS) > 0
}
#@get('/api/print/template/<templatefile>')
#@post('/api/print/template/<templatefile>')
@route('/api/print/template/<templatefile>', method=['GET', 'POST', 'OPTIONS'])
@enable_cors
def printtemplate(templatefile):
return_dict = {'Success': False}
template_data = get_template_data(templatefile)
try:
context = get_label_context(request)
except LookupError as e:
return_dict['error'] = e.message
return return_dict
try:
payload = request.json
except json.JSONDecodeError as e:
payload = {}
im = create_label_from_template(template_data, payload, **context)
if DEBUG:
im.save('sample-out.png')
return instance.print_label(im, **context)
@route('/health', method=['GET', 'POST'])
@enable_cors
def health():
response.status = '200 OK'
printers = instance.get_printers()
response.body = json.dumps({'printers': printers})
if len(printers) == 0:
response.status = '500 Internal Server Error'
@route('/api/template/<templatefile>/raw', method=['GET', 'OPTIONS'])
@enable_cors
def get_template_raw(templatefile):
"""Return the raw contents of a template file as plain text.
The file is read from /appconfig/<templatefile> inside the container.
"""
try:
path = os.path.join('/appconfig', templatefile)
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
response.content_type = 'text/plain; charset=utf-8'
return content
except FileNotFoundError:
response.status = 404
return 'Template not found'
except Exception as e:
response.status = 500
return f'Error reading template: {e}'
@post('/api/template/<templatefile>/raw')
@enable_cors
def save_template_raw(templatefile):
"""Overwrite the raw contents of a template file with the request body.
Expects the new template content as text/plain in the request body.
"""
try:
path = os.path.join('/appconfig', templatefile)
# Read entire request body as UTF-8 text
body = request.body.read()
try:
content = body.decode('utf-8')
except AttributeError:
# In case body is already str (older bottle versions)
content = body
with open(path, 'w', encoding='utf-8', newline='\n') as f:
f.write(content)
response.content_type = 'application/json'
return json.dumps({'success': True})
except Exception as e:
response.status = 500
response.content_type = 'application/json'
return json.dumps({'success': False, 'error': str(e)})
@route('/api/template/create', method=['POST', 'OPTIONS'])
@enable_cors
def create_template():
"""Create a new template file with the provided name and content.
Expects JSON body with:
- name: The name of the label (without .lbl extension)
- content: The template content
"""
try:
payload = request.json
if not payload:
response.status = 400
response.content_type = 'application/json'
return json.dumps({'success': False, 'error': 'No data provided'})
label_name = payload.get('name', '').strip()
content = payload.get('content', '')
if not isinstance(content, str):
response.status = 400
response.content_type = 'application/json'
return json.dumps({'success': False, 'error': 'Template content must be a string'})
# Validate label name is provided
if not label_name:
response.status = 400
response.content_type = 'application/json'
return json.dumps({'success': False, 'error': 'Label name is required'})
# Validate label name format (ASCII alphanumeric, hyphen, underscore only)
if (not label_name.isascii()) or (not all(c.isalnum() or c in '-_' for c in label_name)):
response.status = 400
response.content_type = 'application/json'
return json.dumps({'success': False, 'error': 'Label name can only contain letters, numbers, hyphens, and underscores'})
# Create the file path
filename = label_name + '.lbl'
path = os.path.join('/appconfig', filename)
# Write the template file (atomic create)
try:
with open(path, 'x', encoding='utf-8', newline='\n') as f:
f.write(content)
except FileExistsError:
response.status = 409
response.content_type = 'application/json'
return json.dumps({'success': False, 'error': f'A label with the name "{label_name}" already exists'})
response.content_type = 'application/json'
return json.dumps({'success': True, 'filename': filename})
except Exception as e:
response.status = 500
response.content_type = 'application/json'
logger.error(f"Error creating template: {e}")
return json.dumps({'success': False, 'error': str(e)})
@route('/api/list/templates', method=['GET', 'OPTIONS'])
@enable_cors
def list_templates():
"""Get list of available template files.
Returns JSON with:
- templates: List of template filenames
"""
try:
templateFiles = [os.path.basename(file) for file in glob.glob('/appconfig/*.lbl')]
templateFiles.sort() # Sort alphabetically for consistency
response.content_type = 'application/json'
return json.dumps({'success': True, 'templates': templateFiles})
except Exception as e:
response.status = 500
response.content_type = 'application/json'
logger.error(f"Error listing templates: {e}")
return json.dumps({'success': False, 'error': str(e)})
def get_template_data(templatefile):
"""
Deserialize data from a template file that may contain either JSON or YAML content.
Parameters:
templatefile (str): Path to the file.
Returns:
data (dict): Deserialized data structure.
"""
try:
with open('/appconfig/' + templatefile, 'r') as file:
# Try to parse the file as JSON
try:
data = json.load(file)
return data
except json.JSONDecodeError:
# If JSON parsing fails, attempt YAML parsing
file.seek(0) # Reset file pointer to the beginning
data = yaml.safe_load(file)
return data
except Exception as e:
print(f"An error occurred: {e}")
return None
def create_label_from_template(template, payload, **kwargs):
width, height = instance.get_label_width_height(ElementBase.get_value(template, kwargs, 'font_path'), **kwargs)
width = template.get('width', width)
height = template.get('height', height)
dimensions = width, height
margin_left = ElementBase.get_value(template, kwargs, 'margin_left', 15)
margin_top = ElementBase.get_value(template, kwargs, 'margin_top', 22)
margin_right = ElementBase.get_value(template, kwargs, 'margin_right', margin_left)
margin_bottom = ElementBase.get_value(template, kwargs, 'margin_bottom', margin_top)
margins = [margin_left, margin_top, margin_right, margin_bottom]
im = Image.new('RGBA', (width, height), 'white')
draw = ImageDraw.Draw(im)
elements = template.get('elements', [])
for element in elements:
ElementBase.process_with_plugins(element, im, margins, dimensions, payload, **kwargs)
return im
def get_label_context(request):
""" might raise LookupError() """
d = request.params.decode() # UTF-8 decoded form data
# Get printer name early to use for printer-specific defaults
printer_name = d.get('printer', None)
provided_font_family = d.get('font_family')
if provided_font_family is not None:
font_family = provided_font_family.rpartition('(')[0].strip()
font_style = provided_font_family.rpartition('(')[2].rstrip(')')
else:
# Normalize DEFAULT_FONTS to a dict (config may contain list)
default_fonts_cfg = normalize_default_fonts(CONFIG.get('LABEL', {}).get('DEFAULT_FONTS', {}))
font_family = default_fonts_cfg.get('family')
font_style = default_fonts_cfg.get('style')
context = {
'text': d.get('text', None),
'font_size': int(d.get('font_size', 40)),
'font_family': font_family,
'font_style': font_style,
'label_size': d.get('label_size', instance.get_default_label_size(printer_name)),
'kind': instance.get_label_kind(d.get('label_size', instance.get_default_label_size(printer_name)), printer_name),
'margin': int(d.get('margin', 10)),
'threshold': int(d.get('threshold', 70)),
'align': d.get('align', 'left'),
'orientation': d.get('orientation', 'standard'),
'margin_top': float(d.get('margin_top', 24)) / 100.,
'margin_bottom': float(d.get('margin_bottom', 45)) / 100.,
'margin_left': float(d.get('margin_left', 35)) / 100.,
'margin_right': float(d.get('margin_right', 35)) / 100.,
'grocycode': d.get('grocycode', None),
'product': d.get('product', None),
'duedate': d.get('due_date', d.get('duedate', None)),
'printer': printer_name,
'quantity': d.get('quantity', 1),
}
context['margin_top'] = int(context['font_size'] * context['margin_top'])
context['margin_bottom'] = int(context['font_size'] * context['margin_bottom'])
context['margin_left'] = int(context['font_size'] * context['margin_left'])
context['margin_right'] = int(context['font_size'] * context['margin_right'])
context['fill_color'] = (255, 0, 0) if 'red' in context['label_size'] else (0, 0, 0)
def get_font_path(font_family_name, font_style_name):
try:
if font_family_name is None or font_style_name is None or not font_family_name in FONTS or not font_style_name in \
FONTS[
font_family_name]:
# Fallback to normalized defaults if provided font missing
fallback = normalize_default_fonts(CONFIG.get('LABEL', {}).get('DEFAULT_FONTS', {}))
font_family_name = fallback.get('family')
font_style_name = fallback.get('style')
font_path = FONTS[font_family_name][font_style_name]
except KeyError:
raise LookupError("Couln't find the font & style")
return font_path
context['font_path'] = get_font_path(context['font_family'], context['font_style'])
# Get label dimensions for the specific printer
printer_name = context.get('printer')
width, height = instance.get_label_dimensions(context['label_size'], printer_name)
#print(width, ' ', height)
if height > width: width, height = height, width
if context['orientation'] == 'rotated': height, width = width, height
context['width'], context['height'] = width, height
# Add any extra parameters from the request that are not already in context
for param_name, param_value in d.items():
if param_name not in context:
context[param_name] = param_value
return context
def create_label_im(text, **kwargs):
im_font = ImageFont.truetype(kwargs['font_path'], kwargs['font_size'])
im = Image.new('L', (20, 20), 'white')
draw = ImageDraw.Draw(im)
# workaround for a bug in multiline_textsize()
# when there are empty lines in the text:
lines = []
for line in text.split('\n'):
if line == '': line = ' '
lines.append(line)
text = '\n'.join(lines)
linesize = im_font.getlength(text)
textsize = draw.multiline_textbbox((0, 0), text, font=im_font)
textsize = (textsize[2], textsize[3])
width, height = instance.get_label_width_height(textsize, **kwargs)
adjusted_text_size = ElementBase.adjust_font_to_fit(draw, kwargs['font_path'], kwargs['font_size'], text, (width, height), 2,
kwargs['margin_left'] + kwargs['margin_right'],
kwargs['margin_top'] + kwargs['margin_bottom'],
kwargs['align'])
if adjusted_text_size != textsize:
im_font = ImageFont.truetype(kwargs['font_path'], adjusted_text_size)
im = Image.new('RGB', (width, height), 'white')
draw = ImageDraw.Draw(im)
offset = instance.get_label_offset(width, height, textsize, **kwargs)
draw.multiline_text(offset, text, kwargs['fill_color'], font=im_font, align=kwargs['align'])
return im
def get_effective_printer_dpi(printer_name=None):
"""Resolve the effective DPI used for preview/print size calculations."""
try:
dpi_getter = getattr(instance, '_get_printer_dpi', None)
if callable(dpi_getter):
dpi = dpi_getter(printer_name)
if isinstance(dpi, (int, float)) and dpi > 0:
return int(dpi)
except Exception as e:
logger.debug(f"Could not determine effective printer DPI for '{printer_name}': {e}")
default_dpi = CONFIG.get('PRINTER', {}).get('DEFAULT_DPI')
if isinstance(default_dpi, (int, float)) and default_dpi > 0:
return int(default_dpi)
return 203
def set_preview_metadata_headers(context):
"""Attach preview metadata headers consumed by the UI."""
response.set_header('X-Label-DPI', str(get_effective_printer_dpi(context.get('printer'))))
response.set_header('Access-Control-Expose-Headers', 'X-Label-DPI')
@get('/api/preview/text')
@post('/api/preview/text')
@enable_cors
def get_preview_image():
context = get_label_context(request)
im = create_label_im(**context)
set_preview_metadata_headers(context)
return_format = request.query.get('return_format', 'png')
if return_format == 'base64':
import base64
response.set_header('Content-type', 'text/plain')
return base64.b64encode(image_to_png_bytes(im))
else:
response.set_header('Content-type', 'image/png')
return image_to_png_bytes(im)
@route('/api/preview/template/<templatefile>', method=['GET', 'POST', 'OPTIONS'])
@enable_cors
def get_preview_template_image(templatefile):
context = get_label_context(request)
template_data = get_template_data(templatefile)
try:
payload = request.json
except json.JSONDecodeError as e:
payload = {}
im = create_label_from_template(template_data, payload, **context)
set_preview_metadata_headers(context)
return_format = request.query.get('return_format', 'png')
if return_format == 'base64':
import base64
response.set_header('Content-type', 'text/plain')
return base64.b64encode(image_to_png_bytes(im))
else:
response.set_header('Content-type', 'image/png')
return image_to_png_bytes(im)
@route('/api/template/<templatefile>/fields', method=['GET', 'OPTIONS'])
@enable_cors
def get_template_fields(templatefile):
"""
API endpoint to get form fields required by a template
Returns a JSON object with field definitions
"""
template_data = get_template_data(templatefile)
if not template_data:
response.status = 404
return {'error': 'Template not found'}
fields = []
def extract_fields_from_elements(elements):
for element in elements:
form_elements = ElementBase.get_form_elements_with_plugins(element)
if form_elements is not None:
fields.extend(form_elements)
if 'elements' in template_data:
extract_fields_from_elements(template_data['elements'])
return {
'template_name': template_data.get('name', templatefile),
'fields': fields
}
def image_to_png_bytes(im):
image_buffer = BytesIO()
im.save(image_buffer, format="PNG")
image_buffer.seek(0)
return image_buffer.read()
@post('/api/print/text')
@get('/api/print/text')
def print_text():
"""
API to print a label
returns: JSON
Ideas for additional URL parameters:
- alignment
"""
return_dict = {'success': False}
try:
context = get_label_context(request)
except LookupError as e:
return_dict['error'] = e.message
return return_dict
if context['text'] is None:
return_dict['error'] = 'Please provide the text for the label'
return return_dict
im = create_label_im(**context)
if DEBUG: im.save('sample-out.png')
return instance.print_label(im, **context)
@route("/settings")
@view('settings.jinja2')
def settings_page():
"""Render the settings management page."""
# Normalize DEFAULT_FONTS to always be a dict for template compatibility
label_config = copy.deepcopy(CONFIG['LABEL'])
label_config['DEFAULT_FONTS'] = normalize_default_fonts(label_config.get('DEFAULT_FONTS', {}))
return {
'website': CONFIG['WEBSITE'],
'label': label_config,
'has_errors': len(CONFIG_ERRORS) > 0
}
@route('/api/config-errors', method=['GET', 'OPTIONS'])
@enable_cors
def get_config_errors():
"""Get list of configuration errors."""
return {
'errors': CONFIG_ERRORS,
'has_errors': len(CONFIG_ERRORS) > 0
}
@route('/api/settings', method=['GET', 'OPTIONS'])
@enable_cors
def get_settings():
"""Get current application settings."""
return config_to_settings_format(CONFIG)
@route('/api/settings/validate', method=['POST', 'OPTIONS'])
@enable_cors
def validate_settings_api():
"""Validate settings without saving them."""
try:
payload = request.json
# Convert frontend settings format to CONFIG format
new_config = settings_format_to_config(payload)
# Create a temporary instance for validation
temp_instance = implementation()
# Try to initialize with the new config
try:
temp_instance.initialize(new_config)
except Exception as init_err:
return {
'success': True,
'has_errors': True,
'errors': [f"Configuration initialization failed: {init_err}"]
}
# Get printers with the new config
temp_printers = temp_instance.get_printers() or []
# Get label sizes for ALL printers for comprehensive validation
all_label_sizes = {}
for printer in temp_printers:
try:
printer_label_sizes_list = temp_instance.get_label_sizes(printer)
printer_label_sizes_list = filter_label_sizes_for_printer(printer_label_sizes_list, printer, new_config)
printer_label_sizes = label_sizes_list_to_dict(printer_label_sizes_list, logger)
all_label_sizes[printer] = printer_label_sizes
except Exception as e:
logger.warning(f"Could not get label sizes for printer {printer} during validation: {e}")
all_label_sizes[printer] = {}
# Combine all label sizes from all printers for validation
combined_label_sizes = {}
for printer_sizes in all_label_sizes.values():
combined_label_sizes.update(printer_sizes)
# Get fonts for validation
temp_fonts = get_fonts()
additional_folder = new_config.get('SERVER', {}).get('ADDITIONAL_FONT_FOLDER', False)
if additional_folder:
temp_fonts.update(get_fonts(additional_folder))
# Run configuration validation with new_config
validation_errors = validate_configuration(temp_fonts, combined_label_sizes, temp_printers, new_config)
# Append initialization errors to the validation errors
if temp_instance.initialization_errors:
validation_errors.extend(temp_instance.initialization_errors)
return {
'success': True,
'has_errors': len(validation_errors) > 0,
'errors': validation_errors
}
except Exception as e:
logger.error(f"Error validating settings: {e}")
return {
'success': True,
'has_errors': True,
'errors': [f"Validation error: {str(e)}"]
}
@route('/api/settings', method=['POST', 'OPTIONS'])
@enable_cors
def save_settings_api():
"""Save application settings."""
try:
payload = request.json
# Convert frontend settings format to CONFIG format
new_config = settings_format_to_config(payload)
# Merge with existing CONFIG to preserve other settings (use deep copy to avoid mutating CONFIG)
merged_config = copy.deepcopy(CONFIG)
# Ensure critical sections exist before update
for section in ['SERVER', 'PRINTER', 'LABEL', 'WEBSITE']:
if section not in merged_config:
merged_config[section] = {}
# Deep merge to avoid completely replacing sections
for section, values in new_config.items():
if section not in merged_config:
merged_config[section] = values
elif isinstance(values, dict):
merged_config[section].update(values)
else:
merged_config[section] = values
if save_config_with_global_update(merged_config):
# Apply new settings at runtime and revalidate
global PRINTERS, LABEL_SIZES, CONFIG_ERRORS, FONTS
instance.CONFIG = CONFIG
instance.initialize(CONFIG)
PRINTERS = instance.get_printers()
default_printer = instance.selected_printer if instance.selected_printer else (PRINTERS[0] if PRINTERS else None)
label_sizes_list = instance.get_label_sizes(default_printer)
label_sizes_list = filter_label_sizes_for_printer(label_sizes_list, default_printer, CONFIG)
LABEL_SIZES = label_sizes_list_to_dict(label_sizes_list, logger)
# Reload fonts in case the font folder changed
FONTS = get_fonts()
additional_folder = CONFIG.get('SERVER', {}).get('ADDITIONAL_FONT_FOLDER', False)
if additional_folder:
FONTS.update(get_fonts(additional_folder))
# Re-run configuration validation
CONFIG_ERRORS = []
validation_errors = validate_configuration(FONTS, LABEL_SIZES, PRINTERS, CONFIG)
CONFIG_ERRORS.extend(validation_errors)
# Append initialization errors to the configuration errors
if instance.initialization_errors:
CONFIG_ERRORS.extend(instance.initialization_errors)
return {
'success': True,
'message': 'Settings saved. Some changes may require app restart.',
'has_errors': len(CONFIG_ERRORS) > 0,
'errors': CONFIG_ERRORS
}
else:
response.status = 500
return {'success': False, 'error': 'Failed to save settings'}
except Exception as e:
response.status = 400
logger.error(f"Error saving settings: {e}")
return {'success': False, 'error': str(e)}
@route('/api/settings/cups/validate', method=['POST', 'OPTIONS'])
@enable_cors
def validate_cups_server_api():
"""Validate connectivity to a CUPS server without changing current config."""
try:
result = instance.validate_connectivity(request.json)
if not result.get('success'):
response.status = 400
return result
except Exception as e:
response.status = 500
logger.error(f"Error validating CUPS server: {e}")
return {'success': False, 'error': str(e)}
@route('/api/settings/printers', method=['GET', 'POST', 'OPTIONS'])
@enable_cors
def get_settings_printers():
"""Get list of printers with their available media sizes. Optional config override.
Query/Body Parameters:
- include_disabled (GET) or include_disabled (POST body): If true, returns all available
media sizes without filtering by enabled sizes. Used by settings page to show all
media that can be enabled/disabled.
"""
try:
# Try to get full config from POST body
preview_config = None
include_disabled = False
if request.method == 'POST':
try:
payload = request.json
if payload and isinstance(payload, dict):
# Convert frontend settings format to CONFIG format
preview_config = settings_format_to_config(payload)
# Check for include_disabled flag in POST body
include_disabled = payload.get('_include_disabled', False)
except Exception as e:
logger.warning(f"Could not parse config from request body: {e}")
# Fall back to query parameters for backward compatibility
if preview_config is None:
use_cups_param = request.query.get('use_cups')
server_param = request.query.get('server')
include_disabled = request.query.get('include_disabled') == '1'
# Use existing CONFIG as base
preview_config = copy.deepcopy(CONFIG)
# Ensure PRINTER section exists and is a dict (defensive check)
if preview_config.get('PRINTER') is None:
preview_config['PRINTER'] = {}
# Apply query parameter overrides if provided
if use_cups_param is not None:
preview_config['PRINTER']['USE_CUPS'] = use_cups_param == '1'
if server_param is not None:
preview_config['PRINTER']['SERVER'] = server_param
else:
# For POST requests, also check query params for include_disabled
include_disabled = include_disabled or request.query.get('include_disabled') == '1'
# Create a temporary instance for preview (doesn't modify global state)
temp_instance = implementation()
# Initialize temporary instance with the preview config
temp_instance.initialize(preview_config)
printers = temp_instance.get_printers() or []
all_media_sizes = {}
for printer in printers:
try:
media_sizes_list = temp_instance.get_label_sizes(printer)
# Apply filtering based on the preview config, unless include_disabled is set
if not include_disabled:
media_sizes_list = filter_label_sizes_for_printer(media_sizes_list, printer, preview_config)
all_media_sizes[printer] = media_sizes_list
except Exception as e:
logger.warning(f"Could not get media sizes for printer {printer}: {e}")
all_media_sizes[printer] = []
return {
'printers': printers,
'all_media_sizes': all_media_sizes
}
except Exception as e:
response.status = 500
logger.error(f"Error getting printers: {e}")
return {'error': str(e)}
@route('/api/settings/fonts', method=['GET', 'OPTIONS'])
@enable_cors
def get_settings_fonts():
"""Get list of available fonts and their styles."""
try:
# Return fonts as { family: [style1, style2, ...] }
fonts_dict = {}
for family, styles in FONTS.items():
fonts_dict[family] = list(styles.keys())
return {
'success': True,
'fonts': fonts_dict
}
except Exception as e:
response.status = 500
logger.error(f"Error getting fonts: {e}")
return {'success': False, 'error': str(e)}
@route('/api/settings/fonts/reload', method=['POST', 'OPTIONS'])
@enable_cors
def reload_fonts_api():
"""Reload fonts from the system."""
try:
global FONTS
# Reload fonts from system
FONTS = get_fonts()
# Also reload from additional font folder if configured
additional_folder = CONFIG.get('SERVER', {}).get('ADDITIONAL_FONT_FOLDER', False)
if additional_folder:
FONTS.update(get_fonts(additional_folder))
logger.info(f"Fonts reloaded. Found {len(FONTS)} font families.")
# Return the updated fonts list
fonts_dict = {}
for family, styles in FONTS.items():
fonts_dict[family] = list(styles.keys())
return {
'success': True,
'fonts': fonts_dict,
'message': f'Successfully reloaded {len(FONTS)} font families.'
}
except Exception as e: