2016-07-11 23:01:57 +02:00
#!/usr/bin/env python3
2017-02-15 15:56:02 +01:00
# Copyright (C) 2016-2017 Florian Festi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2023-01-08 19:41:02 +01:00
from __future__ import annotations
2016-03-04 12:10:59 +01:00
import argparse
2022-12-31 15:52:55 +01:00
import gettext
import glob
2019-12-21 17:39:19 +01:00
import html
2022-12-31 15:52:55 +01:00
import mimetypes
2016-10-08 15:08:30 +02:00
import os.path
2022-12-31 15:52:55 +01:00
import re
import sys
import tempfile
2016-06-02 21:57:55 +02:00
import threading
import time
2019-11-23 14:28:51 +01:00
import traceback
2023-01-29 21:38:15 +01:00
from typing import Any, NoReturn
2019-12-21 17:42:36 +01:00
from urllib.parse import parse_qs
2022-12-31 15:52:55 +01:00
from urllib.parse import unquote_plus, quote
2016-03-04 12:10:59 +01:00
from wsgiref.simple_server import make_server
2022-12-31 15:52:55 +01:00
import markdown
2016-03-04 12:10:59 +01:00
2016-03-25 17:49:33 +01:00
try:
import boxes.generators
except ImportError:
2018-08-26 11:01:23 +02:00
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
2016-03-25 17:49:33 +01:00
import boxes.generators
2023-01-29 21:38:14 +01:00
2016-06-02 21:57:55 +02:00
class FileChecker(threading.Thread):
2023-01-29 21:38:15 +01:00
def __init__(self, files=[], checkmodules: bool = True) -> None:
2023-01-13 15:32:33 +01:00
super().__init__()
2016-06-02 21:57:55 +02:00
self.checkmodules = checkmodules
self.timestamps = {}
2022-08-28 11:24:21 +02:00
self._stopped = False
2016-06-02 21:57:55 +02:00
for path in files:
self.timestamps[path] = os.stat(path).st_mtime
if checkmodules:
self._addModules()
2023-01-29 21:38:15 +01:00
def _addModules(self) -> None:
2016-06-02 21:57:55 +02:00
for name, module in sys.modules.items():
path = getattr(module, "__file__", None)
if not path:
continue
if path not in self.timestamps:
2023-01-29 21:38:14 +01:00
self.timestamps[path] = os.stat(path).st_mtime
2016-06-02 21:57:55 +02:00
2023-01-29 21:38:15 +01:00
def filesOK(self) -> bool:
2016-06-02 21:57:55 +02:00
if self.checkmodules:
self._addModules()
for path, timestamp in self.timestamps.items():
2016-06-30 11:54:24 +02:00
try:
if os.stat(path).st_mtime != timestamp:
return False
except FileNotFoundError:
2016-06-02 21:57:55 +02:00
return False
return True
2023-01-29 21:38:15 +01:00
def run(self) -> None:
2022-08-28 11:24:21 +02:00
while not self._stopped:
2016-06-02 21:57:55 +02:00
if not self.filesOK():
os.execv(__file__, sys.argv)
time.sleep(1)
2023-01-29 21:38:15 +01:00
def stop(self) -> None:
2022-08-28 11:24:21 +02:00
self._stopped = True
2023-01-29 21:38:14 +01:00
2016-03-04 12:10:59 +01:00
class ArgumentParserError(Exception): pass
2023-01-29 21:38:14 +01:00
2016-03-04 12:10:59 +01:00
class ThrowingArgumentParser(argparse.ArgumentParser):
2023-01-29 21:38:15 +01:00
def error(self, message) -> NoReturn:
2016-03-04 12:10:59 +01:00
raise ArgumentParserError(message)
2023-01-29 21:38:14 +01:00
2022-12-31 19:20:55 +01:00
# Evil hack
boxes.ArgumentParser = ThrowingArgumentParser # type: ignore
2016-03-04 12:10:59 +01:00
2023-01-02 21:12:59 +01:00
2016-03-04 12:10:59 +01:00
class BServer:
2019-04-21 10:57:50 +02:00
lang_re = re.compile(r"([a-z]{2,3}(-[-a-zA-Z0-9]*)?)\s*(;\s*q=(\d\.?\d*))?")
2023-01-11 22:26:47 +01:00
def __init__(self, url_prefix="", static_url="static") -> None:
2023-01-29 21:38:14 +01:00
self.boxes = {b.__name__: b for b in boxes.generators.getAllBoxGenerators().values() if b.webinterface}
2023-01-08 19:41:02 +01:00
self.boxes['TrayLayout2'] = boxes.generators.traylayout.TrayLayout2 # type: ignore # no attribute "traylayout"
2017-02-13 17:31:58 +01:00
self.groups = boxes.generators.ui_groups
self.groups_by_name = boxes.generators.ui_groups_by_name
for name, box in self.boxes.items():
self.groups_by_name.get(box.ui_group,
self.groups_by_name["Misc"]).add(box)
2016-07-31 17:18:17 +02:00
2017-05-04 23:02:59 +02:00
self.staticdir = os.path.join(os.path.dirname(__file__), '../static/')
2019-08-24 00:05:18 +02:00
self._languages = None
2023-01-08 19:41:02 +01:00
self._cache: dict[Any, Any] = {}
2023-01-11 22:26:47 +01:00
self.url_prefix = url_prefix
self.static_url = static_url
2019-08-24 00:05:18 +02:00
def getLanguages(self, domain=None, localedir=None):
if self._languages is not None:
return self._languages
self._languages = []
domain = "boxes.py"
for localedir in ["locale", gettext._default_localedir]:
files = glob.glob(os.path.join(localedir, '*', 'LC_MESSAGES', '%s.mo' % domain))
self._languages.extend([file.split(os.path.sep)[-3] for file in files])
self._languages.sort()
return self._languages
def getLanguage(self, args, accept_language):
lang = None
langs = []
for i, arg in enumerate(args):
if arg.startswith("language="):
lang = arg[len("language="):]
del args[i]
break
if lang:
try:
2023-01-29 21:38:14 +01:00
return gettext.translation('boxes.py', localedir='locale', languages=[lang])
2019-08-24 00:05:18 +02:00
except OSError:
pass
try:
return gettext.translation('boxes.py', languages=[lang])
except OSError:
pass
2017-05-04 23:02:59 +02:00
2019-08-24 00:05:18 +02:00
# selected language not found try browser default
2019-04-21 10:57:50 +02:00
languages = accept_language.split(",")
for l in languages:
m = self.lang_re.match(l.strip())
if m:
langs.append((float(m.group(4) or 1.0), m.group(1)))
2019-08-24 00:05:18 +02:00
2019-04-21 10:57:50 +02:00
langs.sort(reverse=True)
langs = [l[1].replace("-", "_") for l in langs]
2019-08-24 00:05:18 +02:00
2019-04-21 10:57:50 +02:00
try:
2023-01-29 21:38:14 +01:00
return gettext.translation('boxes.py', localedir='locale', languages=langs)
2019-04-21 10:57:50 +02:00
except OSError:
return gettext.translation('boxes.py', languages=langs, fallback=True)
2023-01-29 21:38:14 +01:00
def arg2html(self, a, prefix, defaults={}, _=lambda s: s):
2016-03-08 21:50:47 +01:00
name = a.option_strings[0].replace("-", "")
2016-03-04 12:10:59 +01:00
if isinstance(a, argparse._HelpAction):
return ""
2016-10-31 22:08:23 +01:00
viewname = name
if prefix and name.startswith(prefix + '_'):
2023-01-29 21:38:14 +01:00
viewname = name[len(prefix) + 1:]
2016-10-31 22:08:23 +01:00
2018-08-13 16:19:06 +02:00
default = defaults.get(name, None)
2022-08-30 00:59:57 +02:00
row = """<tr><td id="%s"><label for="%s">%s</label></td><td>%%s</td><td id="%s">%s</td></tr>\n""" % \
2023-01-29 21:38:14 +01:00
(name + "_id", name, _(viewname), name + "_description", "" if not a.help else markdown.markdown(_(a.help)))
2016-06-21 21:51:55 +02:00
if (isinstance(a, argparse._StoreAction) and
2023-01-29 21:38:14 +01:00
hasattr(a.type, "html")):
2020-04-13 18:45:17 +02:00
input = a.type.html(name, default or a.default, _)
2016-04-10 22:51:57 +02:00
elif a.dest == "layout":
2018-08-27 17:11:20 +02:00
val = (default or a.default).split("\n")
2022-08-30 00:59:57 +02:00
input = """<textarea name="%s" id="%s" aria-labeledby="%s %s" cols="%s" rows="%s">%s</textarea>""" % \
2023-01-29 21:38:14 +01:00
(name, name, name + "_id", name + "_description", max(len(l) for l in val) + 10, len(val) + 1, default or a.default)
2016-06-27 09:09:28 +02:00
elif a.choices:
options = "\n".join(
2023-01-13 15:32:32 +01:00
"""<option value="%s"%s>%s</option>""" %
2023-01-29 21:38:14 +01:00
(e, ' selected="selected"' if (e == (default or a.default)) or (str(e) == str(default or a.default)) else "",
_(e)) for e in a.choices)
2023-01-29 21:38:15 +01:00
input = """<select name="{}" id="{}" aria-labeledby="{} {}" size="1" >\n{}</select>\n""".format(name, name, name + "_id", name + "_description", options)
2016-04-10 22:51:57 +02:00
else:
2023-01-29 21:38:14 +01:00
input = """<input name="%s" id="%s" aria-labeledby="%s %s" type="text" value="%s" >""" % \
(name, name, name + "_id", name + "_description", default or a.default)
2016-04-10 22:51:57 +02:00
return row % input
2016-10-31 22:08:23 +01:00
2017-02-13 17:31:58 +01:00
scripts = """
2020-07-15 14:30:04 +02:00
<script>
2017-02-13 17:31:58 +01:00
function showHide(id) {
2016-10-31 22:08:23 +01:00
var e = document.getElementById(id);
2018-06-14 22:09:41 +02:00
var h = document.getElementById("h-" + id);
2016-10-31 22:08:23 +01:00
if(e.style.display == null || e.style.display == "none") {
e.style.display = "block";
2018-06-14 22:09:41 +02:00
h.classList.add("open");
2022-09-06 20:22:26 +02:00
h.setAttribute("aria-expanded","true");
2016-10-31 22:08:23 +01:00
} else {
e.style.display = "none";
2018-06-14 22:09:41 +02:00
h.classList.remove("open");
2022-09-06 20:22:26 +02:00
h.setAttribute("aria-expanded","false");
2016-10-31 22:08:23 +01:00
}
}
2016-11-01 16:58:48 +01:00
function hideargs() {
2017-02-13 17:31:58 +01:00
for ( i=0; i<%i; i++) {
2016-11-01 16:58:48 +01:00
showHide(i);
}
}
2017-02-13 17:31:58 +01:00
</script>
"""
2023-01-02 22:08:12 +01:00
def args2html_cached(self, name, box, lang, action="", defaults={}):
if defaults == {}:
key = (name, lang.info().get('language', None), action)
if key not in self._cache:
self._cache[key] = list(self.args2html(name, box, lang, action, defaults))
return self._cache[key]
return self.args2html(name, box, lang, action, defaults)
2019-08-24 00:05:18 +02:00
def args2html(self, name, box, lang, action="", defaults={}):
_ = lang.gettext
lang_name = lang.info().get('language', None)
2023-01-24 22:12:01 +01:00
langparam = ""
lang_attr = ""
2019-08-24 00:05:18 +02:00
if lang_name:
langparam = "?language=" + lang_name
2023-01-24 22:12:01 +01:00
lang_attr = f" lang=\"{lang_name}\""
2019-08-24 00:05:18 +02:00
2023-01-02 20:56:24 +01:00
result = [f"""<!DOCTYPE html>
2023-01-24 22:12:01 +01:00
<html{lang_attr}>
2018-03-05 19:48:09 +01:00
<head>
2023-01-22 15:42:51 +01:00
<title>{_("%s - Boxes") % _(name)}</title>
2021-11-11 00:46:03 +01:00
<meta charset="utf-8">
2023-01-11 22:26:47 +01:00
<link rel="icon" type="image/svg+xml" href="{self.static_url}/boxes-logo.svg" sizes="any">
<link rel="icon" type="image/x-icon" href="{self.static_url}/favicon.ico">
2023-01-24 22:12:01 +01:00
{self.genHTMLMetaLanguageLink()}
2023-01-11 22:26:47 +01:00
<link rel="stylesheet" href="{self.static_url}/self.css">
2023-01-29 21:38:14 +01:00
{self.scripts % (len(box.argparser._action_groups) - 3)}
2023-01-02 20:56:24 +01:00
<meta name="flattr:id" content="456799">
2016-09-20 23:14:24 +02:00
</head>
2016-11-01 16:58:48 +01:00
<body onload="hideargs()">
2016-09-20 23:14:24 +02:00
<div class="container" style="background-color: #FFF8EA;">
2016-12-18 21:22:15 +01:00
<div style="float: left;">
2023-01-02 20:56:24 +01:00
<a href="./{langparam}"><h1>{_("Boxes.py")}</h1></a>
2016-09-20 23:14:24 +02:00
</div>
2018-09-23 14:14:19 +02:00
<div style="width: 120px; float: right;">
2023-01-11 22:26:47 +01:00
<img alt="self-Logo" src="{self.static_url}/boxes-logo.svg" width="120" >
2016-09-20 23:14:24 +02:00
</div>
<div>
<div class="clear"></div>
2021-11-11 00:46:03 +01:00
<hr>
2023-01-02 20:56:24 +01:00
<h2 style="margin: 0px 0px 0px 20px;" >{_(name)}</h2>
<p>{_(box.__doc__) if box.__doc__ else ""}</p>
2023-01-09 16:56:21 +01:00
<form action="{action}" method="GET" rel="nofollow">
2023-01-02 20:56:24 +01:00
"""]
2016-10-31 22:08:23 +01:00
groupid = 0
2016-11-01 16:58:48 +01:00
for group in box.argparser._action_groups[3:] + box.argparser._action_groups[:3]:
2016-10-30 15:27:16 +01:00
if not group._group_actions:
2016-03-04 12:10:59 +01:00
continue
2018-10-27 13:05:02 +02:00
if len(group._group_actions) == 1 and isinstance(group._group_actions[0], argparse._HelpAction):
continue
2022-08-30 00:59:57 +02:00
prefix = getattr(group, "prefix", None)
2023-01-02 20:56:24 +01:00
result.append(f'''<h3 id="h-{groupid}" role="button" aria-expanded="true" tabindex="0" class="open" onclick="showHide({groupid})" onkeypress="if(event.keyCode == 13) showHide({groupid})">{_(group.title)}</h3>\n<table role="presentation" id="{groupid}">\n''')
2022-08-31 19:44:17 +02:00
2016-10-30 15:27:16 +01:00
for a in group._group_actions:
if a.dest in ("input", "output"):
continue
2019-04-21 10:57:50 +02:00
result.append(self.arg2html(a, prefix, defaults, _))
2016-10-30 15:27:16 +01:00
result.append("</table>")
2017-02-13 17:31:58 +01:00
groupid += 1
2023-01-02 20:56:24 +01:00
result.append(f"""
2020-08-26 08:33:19 +02:00
<p>
2023-01-02 20:56:24 +01:00
<button name="render" value="1" formtarget="_blank">{_("Generate")}</button>
<button name="render" value="2" formtarget="_self">{_("Download")}</button>
<button name="render" value="0" formtarget="_self">{_("Save to URL")}</button>
2020-08-26 08:33:19 +02:00
</p>
2016-03-04 12:10:59 +01:00
</form>
2016-09-20 23:14:24 +02:00
</div>
2023-01-03 11:48:15 +01:00
2016-09-20 23:14:24 +02:00
<div class="clear"></div>
2021-11-11 00:46:03 +01:00
<hr>
2021-09-19 20:38:35 +02:00
<div class="description">
2017-11-30 22:40:45 +01:00
""")
2023-01-24 22:28:43 +01:00
no_img_msg = _('There is no image yet. Please donate an image of your project on <a href="https://github.com/florianfesti/boxes/issues/140" target="_blank" rel="noopener">GitHub</a>!')
2020-05-24 13:52:24 +02:00
2021-03-14 23:59:52 +01:00
if box.description:
2023-01-03 11:09:44 +01:00
result.append(
markdown.markdown(_(box.description), extensions=["extra"])
2023-01-11 22:26:47 +01:00
.replace('src="static/', f'src="{self.static_url}/'))
2021-03-14 23:59:52 +01:00
2020-05-24 13:52:24 +02:00
result.append(f'''<div>
2023-01-11 22:26:47 +01:00
<img src="{self.static_url}/samples/{box.__class__.__name__}.jpg" width="100%" onerror="this.parentElement.innerHTML = '{no_img_msg}';">
2020-05-24 13:52:24 +02:00
</div>
2018-03-06 11:07:10 +01:00
</div>
2021-09-19 20:38:35 +02:00
</div>
2023-01-02 20:56:24 +01:00
{self.footer(lang)}</body>
2016-03-04 12:10:59 +01:00
</html>
2023-01-29 21:38:14 +01:00
''')
2016-03-04 12:10:59 +01:00
return (s.encode("utf-8") for s in result)
2018-06-14 22:09:41 +02:00
2019-08-24 00:05:18 +02:00
def menu(self, lang):
_ = lang.gettext
lang_name = lang.info().get('language', None)
2023-01-24 22:12:01 +01:00
langparam = ""
lang_attr = ""
2019-08-24 00:05:18 +02:00
if lang_name:
langparam = "?language=" + lang_name
2023-01-24 22:12:01 +01:00
lang_attr = f" lang=\"{lang_name}\""
2018-06-14 22:09:41 +02:00
2023-01-02 20:56:24 +01:00
result = [f"""<!DOCTYPE html>
2023-01-24 22:12:01 +01:00
<html{lang_attr}>
2018-03-05 19:48:09 +01:00
<head>
2023-01-02 20:56:24 +01:00
<title>{_("Boxes.py")}</title>
2021-11-11 00:46:03 +01:00
<meta charset="utf-8">
2023-01-11 22:26:47 +01:00
<link rel="icon" type="image/svg+xml" href="{self.static_url}/boxes-logo.svg" sizes="any">
<link rel="icon" type="image/x-icon" href="{self.static_url}/favicon.ico">
2023-01-24 22:12:01 +01:00
{self.genHTMLMetaLanguageLink()}
2023-01-11 22:26:47 +01:00
<link rel="stylesheet" href="{self.static_url}/self.css">
2023-01-24 22:12:01 +01:00
""",
2023-01-02 20:56:24 +01:00
""" <script>
2017-05-07 16:18:44 +02:00
function change(group, img_link){
document.getElementById("sample-"+group).src = img_link;
document.getElementById("sample-"+group).style.height = "auto";
}
2018-06-14 22:09:41 +02:00
2017-05-07 16:18:44 +02:00
function changeback(group){
2023-01-02 21:12:59 +01:00
document.getElementById("sample-" + group).src= "%s/nothing.png";
2017-05-07 16:18:44 +02:00
document.getElementById("sample-" + group).style.height= "0px";
}
2023-01-11 22:26:47 +01:00
""" % self.static_url,
2023-01-02 20:56:24 +01:00
f""" </script>{self.scripts % len(self.groups)}
2018-03-05 19:49:13 +01:00
<meta name="flattr:id" content="456799">
2016-09-20 23:14:24 +02:00
</head>
2017-02-13 17:31:58 +01:00
<body onload="hideargs()">
2016-09-20 23:14:24 +02:00
<div class="container" style="background-color: #FFF8EA;">
2018-09-23 14:14:19 +02:00
<div style="width: 75%; float: left;">
2023-01-02 20:56:24 +01:00
<h1>{_("Boxes.py")}</h1>
<p>{_("Create boxes and more with a laser cutter!")}</p>
2017-02-15 15:56:38 +01:00
<p>
2023-01-02 20:56:24 +01:00
{_('''
<a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more.''')}
2016-03-15 21:29:03 +01:00
</p>
2016-09-20 23:14:24 +02:00
</div>
2023-01-02 20:56:24 +01:00
2018-09-23 14:14:19 +02:00
<div style="width: 25%; float: left;">
2023-01-11 22:26:47 +01:00
<img alt="self-Logo" src="{self.static_url}/boxes-logo.svg" width="250" >
2016-09-20 23:14:24 +02:00
</div>
<div>
<div class="clear"></div>
2021-11-11 00:46:03 +01:00
<hr>
2020-09-26 11:43:31 +02:00
<div class="menu" style="width: 100%">
2023-01-29 21:38:14 +01:00
"""]
2017-02-13 17:31:58 +01:00
for nr, group in enumerate(self.groups):
2020-11-14 16:41:41 +01:00
result.append(f'''
2022-09-06 20:22:26 +02:00
<h3 id="h-{nr}" role="button" aria-expanded="false" class="open" tabindex="0" onclick="showHide('{nr}')" onkeypress="if(event.keyCode == 13) showHide('{nr}')"
2023-01-11 22:26:47 +01:00
onmouseenter="change('{group.name}', '{self.static_url}/samples/{group.thumbnail}')"
2021-06-05 18:22:05 +02:00
onmouseleave="changeback('{group.name}')">{_(group.title)}</h3>
2023-01-11 22:26:47 +01:00
<img style="width: 200px;" id="sample-{group.name}" src="{self.static_url}/nothing.png" alt="">
2021-06-05 18:22:05 +02:00
<div id="{nr}"><ul>''')
2017-02-13 17:31:58 +01:00
for box in group.generators:
2019-04-21 14:53:22 +02:00
name = box.__name__
2023-01-29 21:38:14 +01:00
if name in ("TrayLayout2",):
2017-02-13 17:31:58 +01:00
continue
docs = ""
if box.__doc__:
2019-04-21 10:57:50 +02:00
docs = " - " + _(box.__doc__)
2020-11-14 16:41:41 +01:00
result.append(f"""
2023-01-11 22:26:47 +01:00
<li onmouseenter="change('{group.name}', '{self.static_url}/samples/{name}-thumb.jpg')" onmouseleave="changeback('{group.name}')"><a href="{name}{langparam}">{_(name)}</a>{docs}</li>""")
2023-01-02 20:56:24 +01:00
result.append("\n</ul></div>\n")
result.append(f"""
2016-09-20 23:14:24 +02:00
</div>
<div style="width: 5%; float: left;"></div>
<div class="clear"></div>
2021-11-11 00:46:03 +01:00
<hr>
2018-03-09 16:15:52 +01:00
</div>
2023-01-02 20:56:24 +01:00
</div>
{self.footer(lang)}
2016-03-04 12:10:59 +01:00
</body>
</html>
""")
return (s.encode("utf-8") for s in result)
2023-01-24 22:12:01 +01:00
def genHTMLMetaLanguageLink(self) -> str:
"""Generates meta language list for search engines."""
languages = self.getLanguages()
s = ""
for language in languages:
s += f"<link rel='alternate' hreflang='{language}' href='https://www.festi.info/boxes.py/?language={language}'>\n"
return s
2016-03-09 19:36:33 +01:00
2023-01-24 22:12:01 +01:00
def genHTMLLanguageSelection(self, lang) -> str:
"""Generates a dropdown selection for the language change."""
current_language = lang.info().get('language', '')
languages = self.getLanguages()
if len(languages) < 2:
return "<!-- No other languages to select found. -->"
html_option = ""
for language in languages:
html_option += f"<option value='{language}'{' selected' if language == current_language else ''}>{language}</option>\n"
return """
<form>
<select name="language" onchange='if(this.value != \"""" + current_language + """\") { this.form.submit(); }'>
""" + html_option + """
</select>
</form>
"""
def footer(self, lang) -> str:
2019-08-24 00:05:18 +02:00
_ = lang.gettext
2023-01-24 22:12:01 +01:00
2019-04-21 10:57:50 +02:00
return """
<div class="footer container">
<ul>
2023-01-24 22:12:01 +01:00
<li>""" + self.genHTMLLanguageSelection(lang) + """</li>
2023-01-24 22:28:43 +01:00
<li><a href="https://florianfesti.github.io/boxes/html/usermanual.html" target="_blank" rel="noopener">""" + _("Help") + """</a></li>
<li><a href="https://hackaday.io/project/10649-boxespy" target="_blank" rel="noopener">""" + _("Home Page") + """</a></li>
<li><a href="https://florianfesti.github.io/boxes/html/index.html" target="_blank" rel="noopener">""" + _("Documentation") + """</a></li>
<li><a href="https://github.com/florianfesti/boxes" target="_blank" rel="noopener">""" + _("Sources") + """</a></li>
2019-04-21 10:57:50 +02:00
</ul>
</div>
"""
def errorMessage(self, name, e, _):
2023-01-02 20:56:24 +01:00
return [(f"""<html>
2018-03-05 19:49:13 +01:00
<head>
2023-01-02 20:56:24 +01:00
<title>{_("Error generating %s") % _(name)}</title>
2018-03-05 19:49:13 +01:00
<meta name="flattr:id" content="456799">
</head>
2016-03-09 19:36:33 +01:00
<body>
2023-01-02 20:56:24 +01:00
<h1>{_("An error occurred!")}</h1>""" +
2023-01-13 15:32:33 +01:00
"".join("<p>%s</p>" % html.escape(s) for s in str(e).split("\n")) +
2019-10-22 21:12:26 +02:00
"""
2016-03-09 19:36:33 +01:00
</body>
</html>
2019-10-22 21:12:26 +02:00
""").encode("utf-8") ]
2016-03-09 19:36:33 +01:00
2017-05-04 23:02:59 +02:00
def serveStatic(self, environ, start_response):
filename = environ["PATH_INFO"][len("/static/"):]
path = os.path.join(self.staticdir, filename)
2017-05-04 23:09:25 +02:00
if (not re.match(r"[a-zA-Z0-9_/-]+\.[a-zA-Z0-9]+", filename) or
2023-01-29 21:38:14 +01:00
not os.path.exists(path)):
2020-03-07 20:14:38 +01:00
if re.match(r"samples/.*-thumb.jpg", filename):
path = os.path.join(self.staticdir, "nothing.png")
else:
2023-01-29 21:38:14 +01:00
start_response("404 Not Found", [('Content-type', 'text/plain')])
2020-03-07 20:14:38 +01:00
return [b"Not found"]
2017-05-04 23:02:59 +02:00
type_, encoding = mimetypes.guess_type(filename)
if encoding is None:
2021-11-11 00:53:29 +01:00
encoding = "utf-8"
2017-05-04 23:02:59 +02:00
2021-11-11 00:53:29 +01:00
# Images do not have charset. Just bytes. Except text based svg.
# Todo: fallback if type_ is None?
if type_ is not None and "image" in type_ and type_ != "image/svg+xml":
start_response("200 OK", [('Content-type', "%s" % type_)])
else:
2023-01-29 21:38:15 +01:00
start_response("200 OK", [('Content-type', f"{type_}; charset={encoding}")])
2017-05-04 23:02:59 +02:00
f = open(path, 'rb')
2023-01-29 21:38:14 +01:00
return environ['wsgi.file_wrapper'](f, 512 * 1024)
2017-05-04 23:02:59 +02:00
2023-01-29 21:38:15 +01:00
def getURL(self, environ) -> str:
2023-01-29 21:38:14 +01:00
url = environ['wsgi.url_scheme'] + '://'
2019-07-06 11:47:41 +02:00
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
2017-05-04 23:02:59 +02:00
2019-07-06 11:47:41 +02:00
if environ['wsgi.url_scheme'] == 'https':
if environ['SERVER_PORT'] != '443':
url += ':' + environ['SERVER_PORT']
else:
if environ['SERVER_PORT'] != '80':
url += ':' + environ['SERVER_PORT']
2023-01-11 22:26:47 +01:00
url += quote(self.url_prefix)
2019-07-06 11:47:41 +02:00
url += quote(environ.get('SCRIPT_NAME', ''))
url += quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
return url
def serve(self, environ, start_response):
2023-01-11 22:26:47 +01:00
# serve favicon from static for generated SVGs
if environ["PATH_INFO"] == "favicon.ico":
environ["PATH_INFO"] = "/static/favicon.ico"
2017-05-04 23:02:59 +02:00
if environ["PATH_INFO"].startswith("/static/"):
return self.serveStatic(environ, start_response)
2016-03-04 12:10:59 +01:00
status = '200 OK'
2018-10-01 13:43:30 +02:00
headers = [('Content-type', 'text/html; charset=utf-8'), ('X-XSS-Protection', '1; mode=block'), ('X-Content-Type-Options', 'nosniff'), ('x-frame-options', 'SAMEORIGIN'), ('Referrer-Policy', 'no-referrer')]
2017-05-04 23:02:59 +02:00
2019-12-14 12:16:25 +01:00
d = parse_qs(environ.get('QUERY_STRING', ''))
2016-03-09 19:36:33 +01:00
name = environ["PATH_INFO"][1:]
2019-08-24 00:05:18 +02:00
args = [unquote_plus(arg) for arg in
2019-12-14 12:16:25 +01:00
environ.get('QUERY_STRING', '').split("&")]
2022-12-25 16:32:51 +01:00
render = "0"
for arg in args:
if arg.startswith("render="):
render = arg[len("render="):]
2017-05-04 23:02:59 +02:00
2019-08-24 00:05:18 +02:00
lang = self.getLanguage(args, environ.get("HTTP_ACCEPT_LANGUAGE", ""))
_ = lang.gettext
2019-04-21 10:57:50 +02:00
2019-04-21 14:53:22 +02:00
box_cls = self.boxes.get(name, None)
if not box_cls:
2016-03-09 19:36:33 +01:00
start_response(status, headers)
2023-01-02 22:08:12 +01:00
lang_name = lang.info().get('language', None)
if lang_name not in self._cache:
self._cache[lang_name] = list(self.menu(lang))
return self._cache[lang_name]
2018-06-14 22:09:41 +02:00
2019-04-21 14:53:22 +02:00
if name == "TrayLayout2":
box = box_cls(self, webargs=True)
else:
box = box_cls()
2022-12-25 16:32:51 +01:00
if render == "0":
2023-01-29 21:38:14 +01:00
defaults = {}
2018-08-13 16:19:06 +02:00
for a in args:
kv = a.split('=')
if len(kv) == 2:
k, v = kv
2019-12-21 17:39:19 +01:00
defaults[k] = html.escape(v, True)
2016-03-09 19:36:33 +01:00
start_response(status, headers)
2023-01-02 22:08:12 +01:00
return self.args2html_cached(name, box, lang, "./" + name, defaults=defaults)
2016-05-21 20:31:04 +02:00
else:
2023-01-29 21:38:14 +01:00
args = ["--" + arg for arg in args if not arg.startswith("render=")]
2016-03-04 12:10:59 +01:00
try:
box.parseArgs(args)
except (ArgumentParserError) as e:
2016-03-09 19:36:33 +01:00
start_response(status, headers)
2019-04-21 10:57:50 +02:00
return self.errorMessage(name, e, _)
2016-03-16 10:16:56 +01:00
if name == "TrayLayout":
start_response(status, headers)
box.fillDefault(box.x, box.y)
2019-04-21 14:53:22 +02:00
layout2 = boxes.generators.traylayout.TrayLayout2(self, webargs=True)
layout2.argparser.set_defaults(layout=str(box))
2023-01-29 21:38:14 +01:00
return self.args2html(name, layout2, lang, action="TrayLayout2")
2016-03-16 10:16:56 +01:00
if name == "TrayLayout2":
try:
2016-12-11 18:05:19 +01:00
box.parse(box.layout.split("\n"))
2016-03-16 10:16:56 +01:00
except Exception as e:
start_response(status, headers)
2019-12-13 19:58:55 +01:00
return self.errorMessage(name, e, _)
2016-03-16 10:16:56 +01:00
2019-08-15 23:05:21 +02:00
try:
2019-11-23 14:28:51 +01:00
fd, box.output = tempfile.mkstemp()
box.metadata["url"] = self.getURL(environ)
box.open()
box.render()
2019-08-15 23:05:21 +02:00
box.close()
2019-11-23 14:28:51 +01:00
except Exception as e:
2019-12-14 12:32:01 +01:00
if not isinstance(e, ValueError):
2019-12-17 11:48:12 +01:00
print("Exception during rendering:")
2019-12-14 12:32:01 +01:00
traceback.print_exc()
2019-08-15 23:05:21 +02:00
start_response("500 Internal Server Error",
2019-12-14 12:32:01 +01:00
headers)
return self.errorMessage(name, e, _)
2019-08-15 23:05:21 +02:00
2019-08-17 23:50:11 +02:00
http_headers = box.formats.http_headers.get(
box.format,
2019-08-18 13:56:04 +02:00
[('Content-type', 'application/unknown; charset=utf-8')])[:]
2023-01-09 16:56:21 +01:00
# Prevent crawlers.
http_headers.append(('X-Robots-Tag', 'noindex,nofollow'))
2019-08-17 23:50:11 +02:00
2022-12-25 16:32:51 +01:00
if box.format != "svg" or render == "2":
2019-08-17 23:50:11 +02:00
extension = box.format
if extension == "svg_Ponoko":
extension = "svg"
2023-01-29 21:38:15 +01:00
http_headers.append(('Content-Disposition', f'attachment; filename="{box.__class__.__name__}.{extension}"'))
2019-08-17 23:50:11 +02:00
start_response(status, http_headers)
2020-04-20 23:38:00 +02:00
result = open(box.output, 'rb').readlines()
2016-03-04 12:10:59 +01:00
os.close(fd)
2018-01-16 18:58:19 +01:00
os.remove(box.output)
2020-04-20 23:38:00 +02:00
return (l for l in result)
2021-11-10 22:49:56 +01:00
2023-01-11 22:26:47 +01:00
2023-01-29 21:38:14 +01:00
if __name__ == "__main__":
2023-01-11 22:26:47 +01:00
parser = argparse.ArgumentParser()
2023-01-17 07:04:36 +01:00
parser.add_argument("--host", default="")
2023-01-11 22:26:47 +01:00
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--url_prefix", default="",
help="URL path to Boxes.py instance")
parser.add_argument("--static_url", default="static",
help="URL of static content")
args = parser.parse_args()
boxserver = BServer(url_prefix=args.url_prefix, static_url=args.static_url)
2017-05-04 23:09:25 +02:00
fc = FileChecker()
2016-06-02 21:57:55 +02:00
fc.start()
2023-01-11 22:26:47 +01:00
httpd = make_server(args.host, args.port, boxserver.serve)
print(f"BoxesServer serving on {args.host}:{args.port}...")
2022-08-28 11:24:21 +02:00
try:
httpd.serve_forever()
except KeyboardInterrupt:
fc.stop()
httpd.server_close()
print("BoxesServer stops.")
2016-05-20 20:55:02 +02:00
else:
2023-01-11 22:26:47 +01:00
boxserver = BServer(url_prefix='/boxes.py', static_url="https://florianfesti.github.io/boxes/static")
application = boxserver.serve