diff --git a/GzipSimpleHTTPServer.py b/GzipSimpleHTTPServer.py index 45101d5..3e9b038 100644 --- a/GzipSimpleHTTPServer.py +++ b/GzipSimpleHTTPServer.py @@ -1,36 +1,22 @@ -"""Simple HTTP Server. -This module builds on BaseHTTPServer by implementing the standard GET -and HEAD requests in a fairly straightforward manner. - -""" - - -__version__ = "0.6" - -__all__ = ["SimpleHTTPRequestHandler"] +__version__ = '0.00.001' +SERVER_PORT = 8000 +encoding_type = 'gzip' +source = '' +source_files = ['index.html', 'index.htm', 'index.html.gz', 'index.htm.gz', 'index.gz'] import os import posixpath -import BaseHTTPServer import urllib -import cgi +import html import sys import mimetypes import zlib import webbrowser +import io +from http.server import HTTPServer, BaseHTTPRequestHandler from optparse import OptionParser -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO - -SERVER_PORT = 8000 -encoding_type = 'gzip' -source = '' -source_files = ['index.html', 'index.htm', 'index.html.gz', 'index.htm.gz', 'index.gz'] - def parse_options(): # Option parsing logic. parser = OptionParser() @@ -64,7 +50,6 @@ def parse_options(): sys.stderr.write("Usage: python GzipSimpleHTTPServer.py --encoding=\n") sys.exit() - def zlib_encode(content): zlib_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS) data = zlib_compress.compress(content) + zlib_compress.flush() @@ -82,24 +67,15 @@ def gzip_encode(content): data = gzip_compress.compress(content) + gzip_compress.flush() return data +class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): -class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): - """Simple HTTP request handler with GET and HEAD commands. - - This serves files from the current directory and any of its - subdirectories. The MIME type for files is determined by - calling the .guess_type() method. - - The GET and HEAD requests are identical except that the HEAD - request omits the actual contents of the file. - - """ - - server_version = "SimpleHTTP/" + __version__ + server_version = 'SimpleHTTP/' + __version__ def do_GET(self): """Serve a GET request.""" content = self.send_head() + if isinstance(content, str): + content = content.encode() if content: self.wfile.write(content) @@ -108,24 +84,14 @@ def do_HEAD(self): content = self.send_head() def send_head(self): - """Common code for GET and HEAD commands. - - This sends the response code and MIME headers. - Return value is either a file object (which has to be copied - to the outputfile by the caller unless the command was HEAD, - and must be closed by the caller under all circumstances), or - None, in which case the caller has nothing further to do. - - """ path = self.translate_path(self.path) f = None type = 'normal' if os.path.isdir(path): if not self.path.endswith('/'): - # redirect browser - doing basically what apache does self.send_response(301) - self.send_header("Location", self.path + "/") + self.send_header('Location', self.path + '/') self.end_headers() return None if not source == '': @@ -151,92 +117,78 @@ def send_head(self): type = source_type ctype = self.guess_type(path, type) - print("Serving path '%s'" % path) + print('Serving path "%s"' % path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: - self.send_error(404, "File not found") + self.send_error(404, 'File not found') return None self.send_response(200) - self.send_header("Content-type", ctype) - self.send_header("Content-Encoding", encoding_type) + self.send_header('Content-type', ctype) + self.send_header('Content-Encoding', encoding_type) fs = os.fstat(f.fileno()) raw_content_length = fs[6] content = f.read() - if type == 'normal': # Encode content based on runtime arg - if encoding_type == "gzip": + if encoding_type == 'gzip': content = gzip_encode(content) - elif encoding_type == "deflate": + elif encoding_type == 'deflate': content = deflate_encode(content) - elif encoding_type == "zlib": + elif encoding_type == 'zlib': content = zlib_encode(content) compressed_content_length = len(content) - f.close() - self.send_header("Content-Length", max(raw_content_length, compressed_content_length)) - self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) + self.send_header('Content-Length', max(raw_content_length, compressed_content_length)) + self.send_header('Last-Modified', self.date_time_string(fs.st_mtime)) self.end_headers() return content def list_directory(self, path): - """Helper to produce a directory listing (absent index.html). - Return value is either a file object, or None (indicating an - error). In either case, the headers are sent, making the - interface the same as for send_head(). - - """ try: list = os.listdir(path) except os.error: - self.send_error(404, "No permission to list directory") + self.send_error(404, 'No permission to list directory') return None list.sort(key=lambda a: a.lower()) - f = StringIO() - displaypath = cgi.escape(urllib.unquote(self.path)) + f = io.StringIO() + displaypath = html.escape(urllib.parse.unquote(self.path)) f.write('') - f.write("\nGUI Easy %s\n" % displaypath) - f.write("\n

Directory: %s

\n" % displaypath) - f.write("
\n\n
\n\n\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() - self.send_header("Content-type", "text/html; charset=%s" % encoding) - self.send_header("Content-Length", str(length)) + self.send_header('Content-type', 'text/html; charset=%s' % encoding) + self.send_header('Content-Length', str(length)) self.end_headers() return f def translate_path(self, path): - """Translate a /-separated PATH to the local filename syntax. - - Components that mean special things to the local file system - (e.g. drive or directory names) are ignored. (XXX They should - probably be diagnosed.) - """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] - path = posixpath.normpath(urllib.unquote(path)) + path = posixpath.normpath(urllib.parse.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() @@ -248,19 +200,6 @@ def translate_path(self, path): return path def guess_type(self, path, type): - """Guess the type of a file. - - Argument is a PATH (a filename). - - Return value is a string of the form type/subtype, - usable for a MIME Content-type header. - - The default implementation looks the file's extension - up in the table self.extensions_map, using application/octet-stream - as a default; however it would be permissible (if - slow) to look inside the data to make a better guess. - - """ base, ext = posixpath.splitext(path) if type == 'gzipped': @@ -284,30 +223,14 @@ def guess_type(self, path, type): '.h': 'text/plain' }) +parse_options() -def test(HandlerClass = SimpleHTTPRequestHandler, - ServerClass = BaseHTTPServer.HTTPServer): - """Run the HTTP request handler class. - - This runs an HTTP server on port 8000 (or the first command line - argument). - - """ - - parse_options() - - server_address = ('localhost', SERVER_PORT) - - SimpleHTTPRequestHandler.protocol_version = "HTTP/1.0" - httpd = BaseHTTPServer.HTTPServer(server_address, SimpleHTTPRequestHandler) - - sa = httpd.socket.getsockname() - print "Serving HTTP on", sa[0], "port", sa[1], "..." - url = 'http://localhost:' + str(sa[1]) - webbrowser.open(url) - httpd.serve_forever() - BaseHTTPServer.test(HandlerClass, ServerClass) +server_address = ('localhost', SERVER_PORT) +httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) -if __name__ == '__main__': - test() +sa = httpd.socket.getsockname() +print('Serving HTTP on', sa[0], 'port', sa[1], '...') +url = 'http://localhost:' + str(sa[1]) + '/build/' +webbrowser.open(url) +httpd.serve_forever() \ No newline at end of file diff --git a/README.md b/README.md index 85d2fb4..5951b39 100644 --- a/README.md +++ b/README.md @@ -105,8 +105,8 @@ in your local network. Point to this unit inside a file called ``custom.json``, ### Run as COMPILED localhost To test different versions of the compiled code we have added the ``GzipSimpleHTTPServer.py`` -script. Given that you have python already installed you can simply double click on this -file will start the server and automatically open ``localhost:8000`` and you will see +script. Given that you have [Python](https://www.python.org/downloads/) already installed you can simply double click on this +file and it will start the server and automatically open ``localhost:8000`` and you will see the entire project folder listed. Click your way through to the build you want to test. The compiled code will, if started in localhost mode, search for the ``src/custom.json`` file so make sure you have that one setup according to your needs. diff --git a/src/gui_easy.css b/src/gui_easy.css index f652c6f..8d91cbc 100644 --- a/src/gui_easy.css +++ b/src/gui_easy.css @@ -291,9 +291,10 @@ div.bottom-drawer::before { box-shadow: inset 0 30px 25px -20px rgba(var(--main-inverted-color), 1); } div.bottom-tab { + z-index: 10000; display: flex; background-color: var(--main-inverted-color-rgba); - padding: 2px 8px 6px; + padding: 2px 8px 0; width: auto; position: absolute; top: 4px; diff --git a/src/gui_easy_helper.js b/src/gui_easy_helper.js index 7d04c5e..c0f73c2 100644 --- a/src/gui_easy_helper.js +++ b/src/gui_easy_helper.js @@ -458,20 +458,48 @@ const helpEasy = { return json[path[0]][path[1]][path[2]][path[3]][path[4]][path[5]][path[6]][path[7]][path[8]][path[9]]; } }, - 'iniFileToObject': function(string) { - let object = {}; - let sections = string.match(/^\[[^\]\n]+](?:\n(?:[^[\n].*)?)*/gm); - for (let i=0; i < sections.length; i++) { - let sectionName = sections[i].split("\n")[0]; - sectionName = sectionName.slice(1, sectionName.length-1); - object[sectionName] = {}; - let key = sections[i].match(/^[^;\s][^;\n]*/gm); //we remove comments behind ";" character - for (let k=1; k < key.length; k++) { - let keyValue = key[k].split("="); - object[sectionName][keyValue[0]] = keyValue[1]; - } - } - return object; + 'iniFileToObject': function(string, pipe2array = false) { + let object = {}; + let sections = string.match(/^\[[^\]\r\n]+](?:[\r\n]([^[\r\n].*)?)*/gm); + if (sections === null) { + return object["error"] = "Cannot parse ini data!"; + } + for (let i=0; i < sections.length; i++) { + let sectionName = sections[i].split("\n")[0]; + sectionName = sectionName.replace(/[\[\]]/g, '').trim(); + object[sectionName] = {}; + let key = sections[i].match(/^((?!\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$).)+/gm); //we remove comments "//" syntax, single row + for (let k=1; k < key.length; k++) { + let keyValue = key[k].split("="); + if (keyValue.length === 1) { + continue; // since we don't have a "=" sign we treat this the same way we treat comments = remove them + } + if (keyValue.length > 2) { + keyValue[1] = keyValue.slice(1, keyValue.length).join('='); //join if = is used in the string value + } + if (keyValue[1] === "") { + object[sectionName][keyValue[0].trim()] = null; // make empty strings null + continue; + } + if ((keyValue[1].charAt(0) === "0" && keyValue[1].charAt(1) !== "." && keyValue[1].length > 1) || isNaN(Number(keyValue[1]))) { // leading zeros with no dot following are interpreted as string values + if (pipe2array && keyValue[1].trim().includes("|")) { + object[sectionName][keyValue[0].trim()] = keyValue[1].trim().split("|"); + } else { + object[sectionName][keyValue[0].trim()] = (function (string) { //parse booleans and nulls + switch(string){ + case "true": case "yes": return true; + case "false": case "no": return false; + case "null": return null; + default: return string; + } + })(keyValue[1].toLowerCase().trim()); + } + } else { + object[sectionName][keyValue[0].trim()] = Number(keyValue[1]); + } + } + } + return object; }, 'sortObjectArray': (propName) => (a, b) => a[propName] === b[propName] ? 0 : a[propName] < b[propName] ? -1 : 1 diff --git a/src/gui_easy_helper_esp_specific.js b/src/gui_easy_helper_esp_specific.js index be6913e..e0193b4 100644 --- a/src/gui_easy_helper_esp_specific.js +++ b/src/gui_easy_helper_esp_specific.js @@ -13,6 +13,7 @@ helpEasy.int32binaryBool = function (obj, int, names, base, emptyString = "_empt } }; +//should be async + await fetch helpEasy.getDataFromNode = function (array, index, endpoint, ttl_fallback) { array[index]["scheduler"].shift(); let timeStart = Date.now(); diff --git a/src/gui_easy_pitcher.js b/src/gui_easy_pitcher.js index 5ec5819..5bb01ff 100644 --- a/src/gui_easy_pitcher.js +++ b/src/gui_easy_pitcher.js @@ -20,7 +20,7 @@ guiEasy.pitcher = async function (processID, processType) { guiEasy.nodes.push(jsonData); //THIS ONE IS USED TO RUN THE GUI FROM LOCALHOST }) .catch(error => { - helpEasy.addToLogDOM('Error fetching (custom.json): ' + error, 0, "error"); + helpEasy.addToLogDOM('Error fetching (src/custom.json): ' + error, 0, "error"); helpEasy.addToLogDOM('You should create a "custom.json", please refer to the "custom-template.json".', 0, "warn"); helpEasy.addToLogDOM('With this file you can specify what unit you want to connect to during development...', 0, "info"); });