Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dash update #3 #26

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
163 changes: 43 additions & 120 deletions GzipSimpleHTTPServer.py
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -64,7 +50,6 @@ def parse_options():
sys.stderr.write("Usage: python GzipSimpleHTTPServer.py --encoding=<encoding_type>\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()
Expand All @@ -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)

Expand All @@ -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 == '':
Expand All @@ -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('<!DOCTYPE html>')
f.write("<html>\n<title>GUI Easy %s</title>\n" % displaypath)
f.write("<body>\n<h2>Directory: %s</h2>\n" % displaypath)
f.write("<hr>\n<ul>\n")
f.write('<html>\n<title>GUI Easy %s</title>\n' % displaypath)
f.write('<body>\n<h2>Directory: %s</h2>\n' % displaypath)
f.write('<hr>\n<ul>\n')
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
displayname = name + '/'
linkname = name + '/'
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<li><a href="%s">%s</a>\n'
% (urllib.quote(linkname), cgi.escape(displayname)))
f.write("</ul>\n<hr>\n</body>\n</html>\n")
% (urllib.parse.quote(linkname), html.escape(displayname)))
f.write('</ul>\n<hr>\n</body>\n</html>\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()
Expand All @@ -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':
Expand All @@ -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()
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion src/gui_easy.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
56 changes: 42 additions & 14 deletions src/gui_easy_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/gui_easy_helper_esp_specific.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/gui_easy_pitcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
Expand Down