增加高压空闲调节
@@ -0,0 +1,8 @@
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,377 @@
|
||||
|
||||
<h3>
|
||||
<p align="center">
|
||||
Also check out the new ESP32 MPY-Jama free IDE and the latest MicroWebSrv2 below:
|
||||
</p>
|
||||
</h3>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/jczic/ESP32-MPY-Jama"><img src="https://github.com/jczic/ESP32-MPY-Jama/raw/master/img/ESP32%20MPY-Jama%20NEW.png" alt="New microWebSrv2" width="350" valign="middle"></a>
|
||||
<a href="https://github.com/jczic/MicroWebSrv2"><img src="microWebSrv2.png" alt="New microWebSrv2" width="350" valign="middle"></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
<br />
|
||||
|
||||
### MicroWebSrv is a micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (principally used on ESP32 and [Pycom](http://www.pycom.io) modules. Now supports all variants of [Pyboard D-series](https://store.micropython.org/category/pyboard%20D-series) from the makers of Micropython)
|
||||
|
||||

|
||||
|
||||
Very easy to integrate and very light with 3 files only :
|
||||
- `"microWebSrv.py"` - The Web server
|
||||
- `"microWebSocket.py"` - The optional support of WebSockets
|
||||
- `"microWebTemplate.py"` - The optional templating language for **.pyhtml** rendered pages
|
||||
|
||||
Mini tuto in video by rdagger68 :
|
||||
- [https://www.youtube.com/watch?v=xscBwC1SrF4](https://www.youtube.com/watch?v=xscBwC1SrF4)
|
||||
|
||||
Simple but effective :
|
||||
- Use it to embed a cool Web site in yours modules
|
||||
- Handle GET, POST, ... requests to interract with user and configure options
|
||||
- Exchange in JSON format on HTTP methods to make an embedded fullREST API
|
||||
- Serve files on the fly to export any data to the user
|
||||
- Use routes and variable route handlers
|
||||
- Play with AjAX to interact speedly with a Web application
|
||||
- Make it a captive portal simply
|
||||
- Use WebSockets for fast and powerful data exchange
|
||||
- Make html/python files for rendering more efficient web pages
|
||||
|
||||
### Using *microWebSrv* main class :
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Constructor | `mws = MicroWebSrv(routeHandlers=None, port=80, bindIP='0.0.0.0', webPath="/flash/www")` |
|
||||
| Start Web server | `mws.Start(threaded=True)` |
|
||||
| Stop Web server | `mws.Stop()` |
|
||||
| Check if Web server is running | `mws.IsStarted()` |
|
||||
| Set URL location for not found page | `mws.SetNotFoundPageUrl(url=None)` |
|
||||
| Get mime type from file extention | `mws.GetMimeTypeFromFilename(filename)` |
|
||||
| Get handler function from route | `(routeHandler, routeArgs) = mws.GetRouteHandler(resUrl, method)` |
|
||||
| Callback function to enable and accept WebSockets | `mws.AcceptWebSocketCallback = _acptWS` `_acptWS(webSocket, httpClient) { }` |
|
||||
| Maximum length of memory allocated to receive WebSockets data (1024 by default) | `mws.MaxWebSocketRecvLen` |
|
||||
| New thread used for each WebSocket connection (True by default) | `mws.WebSocketThreaded` |
|
||||
| Escape string to HTML usage | `MicroWebSrv.HTMLEscape(s)` |
|
||||
|
||||
### Basic example :
|
||||
```python
|
||||
from microWebSrv import MicroWebSrv
|
||||
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
|
||||
mws.Start(threaded=True) # Starts server in a new thread
|
||||
```
|
||||
|
||||
### Using as captive portal :
|
||||
```python
|
||||
# To intercept all not found queries and redirect it,
|
||||
mws.SetNotFoundPageUrl("http://my-device.wifi")
|
||||
```
|
||||
- Can be used with [MicroDNSSrv](http://microdnssrv.hc2.fr) easily.
|
||||
|
||||
### Using route handlers example :
|
||||
```python
|
||||
|
||||
routeHandlers = [
|
||||
( "relative_url_route_1", "METHOD", handlerFunc_1 ),
|
||||
( "relative_url_route_2", "METHOD", handlerFunc_2 ),
|
||||
( ... )
|
||||
]
|
||||
```
|
||||
```python
|
||||
def handlerFunc_1(httpClient, httpResponse, routeArgs=None) :
|
||||
print("In HTTP handler 1")
|
||||
|
||||
def handlerFunc_2(httpClient, httpResponse, routeArgs=None) :
|
||||
print("In HTTP handler 2")
|
||||
```
|
||||
|
||||
### Using directly route handlers decorators example :
|
||||
```python
|
||||
@MicroWebSrv.route('/get-test')
|
||||
def handlerFuncGet(httpClient, httpResponse) :
|
||||
print("In GET-TEST HTTP")
|
||||
|
||||
@MicroWebSrv.route('/post-test', 'POST')
|
||||
def handlerFuncPost(httpClient, httpResponse) :
|
||||
print("In POST-TEST HTTP")
|
||||
```
|
||||
|
||||
### Using variable routes example :
|
||||
```python
|
||||
routeHandlers = [
|
||||
( "/edit/<testid>/<testpath>", "GET", handlerFuncEdit ),
|
||||
( ... )
|
||||
]
|
||||
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
|
||||
print("In EDIT HTTP variable route :")
|
||||
print(" - testid = %s" % routeArgs['testid'])
|
||||
print(" - testpath = %s" % routeArgs['testpath'])
|
||||
```
|
||||
|
||||
Or direclty with route handler decorator :
|
||||
|
||||
```python
|
||||
@MicroWebSrv.route('/edit/<testid>/<testpath>')
|
||||
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
|
||||
print("In EDIT HTTP variable route :")
|
||||
print(" - testid = %s" % routeArgs['testid'])
|
||||
print(" - testpath = %s" % routeArgs['testpath'])
|
||||
```
|
||||
|
||||
### Using *httpClient* class in a route handler function :
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Get MicroWebSrv class | `httpClient.GetServer()` |
|
||||
| Get client address as tuple | `httpClient.GetAddr()` |
|
||||
| Get client IP address | `httpClient.GetIPAddr()` |
|
||||
| Get client TCP port | `httpClient.GetPort()` |
|
||||
| Get client request method | `httpClient.GetRequestMethod()` |
|
||||
| Get client request total path | `httpClient.GetRequestTotalPath()` |
|
||||
| Get client request ressource path | `httpClient.GetRequestPath()` |
|
||||
| Get client request query string | `httpClient.GetRequestQueryString()` |
|
||||
| Get client request query parameters as list | `httpClient.GetRequestQueryParams()` |
|
||||
| Get client request headers as list | `httpClient.GetRequestHeaders()` |
|
||||
| Get client request content type | `httpClient.GetRequestContentType()` |
|
||||
| Get client request content length | `httpClient.GetRequestContentLength()` |
|
||||
| Get client request content | `httpClient.ReadRequestContent(size=None)` |
|
||||
| Get client request form data as list | `httpClient.ReadRequestPostedFormData()` |
|
||||
| Get client request as JSON object | `httpClient.ReadRequestContentAsJSON()` |
|
||||
|
||||
### Using *httpResponse* class in a route handler function :
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Write switching protocols response | `httpResponse.WriteSwitchProto(upgrade, headers=None)` |
|
||||
| Write generic response | `httpResponse.WriteResponse(code, headers, contentType, contentCharset, content)` |
|
||||
| Write PyHTML rendered response page | `httpResponse.WriteResponsePyHTMLFile(filepath, headers=None, vars=None)` |
|
||||
| Write file directly as response | `httpResponse.WriteResponseFile(filepath, contentType=None, headers=None)` |
|
||||
| Write attached file as response | `httpResponse.WriteResponseFileAttachment(filepath, attachmentName, headers=None)` |
|
||||
| Write OK response | `httpResponse.WriteResponseOk(headers=None, contentType=None, contentCharset=None, content=None)` |
|
||||
| Write JSON object as OK response | `httpResponse.WriteResponseJSONOk(obj=None, headers=None)` |
|
||||
| Write redirect response | `httpResponse.WriteResponseRedirect(location)` |
|
||||
| Write error response | `httpResponse.WriteResponseError(code)` |
|
||||
| Write JSON object as error response | `httpResponse.WriteResponseJSONError(code, obj=None)` |
|
||||
| Write bad request response | `httpResponse.WriteResponseBadRequest()` |
|
||||
| Write forbidden response | `httpResponse.WriteResponseForbidden()` |
|
||||
| Write not found response | `httpResponse.WriteResponseNotFound()` |
|
||||
| Write method not allowed response | `httpResponse.WriteResponseMethodNotAllowed()` |
|
||||
| Write internal server error response | `httpResponse.WriteResponseInternalServerError()` |
|
||||
| Write not implemented response | `httpResponse.WriteResponseNotImplemented()` |
|
||||
|
||||
### Using route handler function example :
|
||||
|
||||
```python
|
||||
def _httpHandlerTestPost(httpClient, httpResponse) :
|
||||
formData = httpClient.ReadRequestPostedFormData()
|
||||
firstname = formData["firstname"]
|
||||
lastname = formData["lastname"]
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST POST</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TEST POST</h1>
|
||||
Firstname = %s<br />
|
||||
Lastname = %s<br />
|
||||
</body>
|
||||
</html>
|
||||
""" % ( MicroWebSrv.HTMLEscape(firstname),
|
||||
MicroWebSrv.HTMLEscape(lastname) )
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
```
|
||||
|
||||
### Known mime types (content types) :
|
||||
|
||||
| File extension | Mime type |
|
||||
| - | - |
|
||||
| .txt | text/plain |
|
||||
| .htm | text/html |
|
||||
| .html | text/html |
|
||||
| .css | text/css |
|
||||
| .csv | text/csv |
|
||||
| .js | application/javascript |
|
||||
| .xml | application/xml |
|
||||
| .xhtml | application/xhtml+xml |
|
||||
| .json | application/json |
|
||||
| .zip | application/zip |
|
||||
| .pdf | application/pdf |
|
||||
| .ts | application/typescript |
|
||||
| .woff | font/woff |
|
||||
| .woff2 | font/woff2 |
|
||||
| .ttf | font/ttf |
|
||||
| .otf | font/otf |
|
||||
| .jpg | image/jpeg |
|
||||
| .jpeg | image/jpeg |
|
||||
| .png | image/png |
|
||||
| .gif | image/gif |
|
||||
| .svg | image/svg+xml |
|
||||
| .ico | image/x-icon |
|
||||
|
||||
### Default index pages order (for http://hostname/) :
|
||||
|
||||
| Filename |
|
||||
| - |
|
||||
| index.pyhtml |
|
||||
| index.html |
|
||||
| index.htm |
|
||||
| default.pyhtml |
|
||||
| default.html |
|
||||
| default.htm |
|
||||
|
||||
### Using optional module *microWebSocket* to connect WebSockets :
|
||||
|
||||
- File `"microWebSocket.py"` must be present to activate WebSockets support
|
||||
|
||||
### Enable and accept WebSockets :
|
||||
```python
|
||||
from microWebSrv import MicroWebSrv
|
||||
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
|
||||
mws.MaxWebSocketRecvLen = 256 # Default is set to 1024
|
||||
mws.WebSocketThreaded = False # WebSockets without new threads
|
||||
mws.AcceptWebSocketCallback = _acceptWebSocketCallback # Function to receive WebSockets
|
||||
mws.Start(threaded=True) # Starts server in a new thread
|
||||
```
|
||||
|
||||
| Name | Function |
|
||||
| - | - |
|
||||
| Callback function to receive text message | `ws.RecvTextCallback = func(webSocket, msg)` |
|
||||
| Callback function to receive binary data | `ws.RecvBinaryCallback = func(webSocket, data)` |
|
||||
| Callback function when connection was closed | `ws.ClosedCallback = func(webSocket)` |
|
||||
| Send a text message | `ws.SendText(msg)` |
|
||||
| Send a binary message | `ws.SendBinary(data)` |
|
||||
| Check connection state | `ws.IsClosed()` |
|
||||
| Close the connection | `ws.Close()` |
|
||||
|
||||
### Basic example of callback functions :
|
||||
```python
|
||||
def _acceptWebSocketCallback(webSocket, httpClient) :
|
||||
print("WS ACCEPT")
|
||||
webSocket.RecvTextCallback = _recvTextCallback
|
||||
webSocket.RecvBinaryCallback = _recvBinaryCallback
|
||||
webSocket.ClosedCallback = _closedCallback
|
||||
|
||||
def _recvTextCallback(webSocket, msg) :
|
||||
print("WS RECV TEXT : %s" % msg)
|
||||
webSocket.SendText("Reply for %s" % msg)
|
||||
|
||||
def _recvBinaryCallback(webSocket, data) :
|
||||
print("WS RECV DATA : %s" % data)
|
||||
|
||||
def _closedCallback(webSocket) :
|
||||
print("WS CLOSED")
|
||||
```
|
||||
|
||||
### Using optional module *microWebTemplate* for *.pyhtml* rendered pages :
|
||||
|
||||
- File `"microWebTemplate.py"` must be present to activate **.pyhtml** pages
|
||||
- Pages will be rendered in HTML with integrated MicroPython code
|
||||
|
||||
| Instruction | Schema |
|
||||
| - | - |
|
||||
| PY | `{{ py }}` *MicroPython code* `{{ end }}` |
|
||||
| IF | `{{ if` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
|
||||
| ELIF | `{{ elif` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
|
||||
| ELSE | `{{ else }}` *html bloc* `{{ end }}` |
|
||||
| FOR | `{{ for` *identifier* `in` *MicroPython iterator* `}}` *html bloc* `{{ end }}` |
|
||||
| INCLUDE | `{{ include` *pyhtml_filename* `}}` |
|
||||
| ? | `{{` *MicroPython expression* `}}` |
|
||||
|
||||
|
||||
### Using {{ py }} :
|
||||
|
||||
```python
|
||||
{{ py }}
|
||||
import machine
|
||||
from utime import sleep
|
||||
test = 123
|
||||
def testFunc(x) :
|
||||
return 2 * x
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Using {{ if ... }} :
|
||||
|
||||
```python
|
||||
{{ if testFunc(5) <= 3 }}
|
||||
<span>titi</span>
|
||||
{{ elif testFunc(10) >= 15 }}
|
||||
<span>tata</span>
|
||||
{{ else }}
|
||||
<span>I like the number {{ test }} !</span>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Using {{ for ... }} :
|
||||
|
||||
```python
|
||||
{{ for toto in range(testFunc(3)) }}
|
||||
<div>toto x 10 equal {{ toto * 10 }}</div>
|
||||
<hr />
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
### Using {{ include ... }} :
|
||||
|
||||
```python
|
||||
{{ include myTemplate.pyhtml }}
|
||||
```
|
||||
|
||||
### Example of a .pyhtml file :
|
||||
|
||||
```html
|
||||
<html>
|
||||
<head>
|
||||
<title>TEST PYHTML</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>BEGIN</h1>
|
||||
{{ py }}
|
||||
def _testFunction(x) :
|
||||
return "IN TEST FUNCTION %s" % x
|
||||
{{ end }}
|
||||
<div style="background-color: black; color: white;">
|
||||
{{ for toto in range(3) }}
|
||||
This is an HTML test...<br />
|
||||
TOTO = {{ toto + 1 }} !<br />
|
||||
{{ for toto2 in range(3) }}
|
||||
TOTO2 = {{ _testFunction(toto2) }}
|
||||
{{ end }}
|
||||
Ok good.<br />
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ _testFunction(100) }}<br />
|
||||
<br />
|
||||
{{ if 2+5 < 3 }}
|
||||
IN IF (1)
|
||||
{{ elif 10+15 != 25 }}
|
||||
IN ELIF (2)
|
||||
{{ elif 10+15 == 25 }}
|
||||
IN ELIF (3)
|
||||
{{ else }}
|
||||
IN ELSE (4)
|
||||
{{ end }}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
<a name="author"></a>
|
||||
## :wink: Author
|
||||
|
||||
**Jean-Christophe Bos** (:fr:)
|
||||
- GitHub: *[@jczic](https://github.com/jczic)*
|
||||
- Email: *<jczic.bos@gmail.com>*
|
||||
- Profil: *[LinkedIn](https://www.linkedin.com/in/jczic)*
|
||||
- Music: *[SoundCloud](https://soundcloud.com/jczic/sets/electro-pulse)*
|
||||
*[Spotify](https://open.spotify.com/album/5fUd57GcAIcdUn9NX3fviG)*
|
||||
*[YouTube](https://www.youtube.com/playlist?list=PL9CsGuMbcLaU02VKS7jtR6LaDNpq7MZEq)*
|
||||
|
||||
|
||||
### By JC`zic for [HC²](https://www.hc2.fr) ;')
|
||||
|
||||
*Keep it simple, stupid* :+1:
|
||||
@@ -0,0 +1,2 @@
|
||||
show_downloads: true
|
||||
theme: jekyll-theme-midnight
|
||||
|
After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,121 @@
|
||||
|
||||
from microWebSrv import MicroWebSrv
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@MicroWebSrv.route('/test')
|
||||
def _httpHandlerTestGet(httpClient, httpResponse) :
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST GET</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TEST GET</h1>
|
||||
Client IP address = %s
|
||||
<br />
|
||||
<form action="/test" method="post" accept-charset="ISO-8859-1">
|
||||
First name: <input type="text" name="firstname"><br />
|
||||
Last name: <input type="text" name="lastname"><br />
|
||||
<input type="submit" value="Submit">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
""" % httpClient.GetIPAddr()
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
|
||||
|
||||
@MicroWebSrv.route('/test', 'POST')
|
||||
def _httpHandlerTestPost(httpClient, httpResponse) :
|
||||
formData = httpClient.ReadRequestPostedFormData()
|
||||
firstname = formData["firstname"]
|
||||
lastname = formData["lastname"]
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST POST</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>TEST POST</h1>
|
||||
Firstname = %s<br />
|
||||
Lastname = %s<br />
|
||||
</body>
|
||||
</html>
|
||||
""" % ( MicroWebSrv.HTMLEscape(firstname),
|
||||
MicroWebSrv.HTMLEscape(lastname) )
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
|
||||
|
||||
@MicroWebSrv.route('/edit/<index>') # <IP>/edit/123 -> args['index']=123
|
||||
@MicroWebSrv.route('/edit/<index>/abc/<foo>') # <IP>/edit/123/abc/bar -> args['index']=123 args['foo']='bar'
|
||||
@MicroWebSrv.route('/edit') # <IP>/edit -> args={}
|
||||
def _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html lang=en>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TEST EDIT</title>
|
||||
</head>
|
||||
<body>
|
||||
"""
|
||||
content += "<h1>EDIT item with {} variable arguments</h1>"\
|
||||
.format(len(args))
|
||||
|
||||
if 'index' in args :
|
||||
content += "<p>index = {}</p>".format(args['index'])
|
||||
|
||||
if 'foo' in args :
|
||||
content += "<p>foo = {}</p>".format(args['foo'])
|
||||
|
||||
content += """
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
httpResponse.WriteResponseOk( headers = None,
|
||||
contentType = "text/html",
|
||||
contentCharset = "UTF-8",
|
||||
content = content )
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _acceptWebSocketCallback(webSocket, httpClient) :
|
||||
print("WS ACCEPT")
|
||||
webSocket.RecvTextCallback = _recvTextCallback
|
||||
webSocket.RecvBinaryCallback = _recvBinaryCallback
|
||||
webSocket.ClosedCallback = _closedCallback
|
||||
|
||||
def _recvTextCallback(webSocket, msg) :
|
||||
print("WS RECV TEXT : %s" % msg)
|
||||
webSocket.SendText("Reply for %s" % msg)
|
||||
|
||||
def _recvBinaryCallback(webSocket, data) :
|
||||
print("WS RECV DATA : %s" % data)
|
||||
|
||||
def _closedCallback(webSocket) :
|
||||
print("WS CLOSED")
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
#routeHandlers = [
|
||||
# ( "/test", "GET", _httpHandlerTestGet ),
|
||||
# ( "/test", "POST", _httpHandlerTestPost )
|
||||
#]
|
||||
|
||||
srv = MicroWebSrv(webPath='/web_root/web_admin/')
|
||||
srv.MaxWebSocketRecvLen = 256
|
||||
srv.WebSocketThreaded = False
|
||||
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
|
||||
srv.Start()
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
@@ -0,0 +1,284 @@
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from hashlib import sha1
|
||||
from binascii import b2a_base64
|
||||
from struct import pack
|
||||
from _thread import start_new_thread, allocate_lock
|
||||
import gc
|
||||
|
||||
class MicroWebSocket :
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constants )============================================================
|
||||
# ============================================================================
|
||||
|
||||
_handshakeSign = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
_opContFrame = 0x0
|
||||
_opTextFrame = 0x1
|
||||
_opBinFrame = 0x2
|
||||
_opCloseFrame = 0x8
|
||||
_opPingFrame = 0x9
|
||||
_opPongFrame = 0xA
|
||||
|
||||
_msgTypeText = 1
|
||||
_msgTypeBin = 2
|
||||
|
||||
# ============================================================================
|
||||
# ===( Utils )===============================================================
|
||||
# ============================================================================
|
||||
|
||||
@staticmethod
|
||||
def _tryAllocByteArray(size) :
|
||||
for x in range(10) :
|
||||
try :
|
||||
gc.collect()
|
||||
return bytearray(size)
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _tryStartThread(func, args=()) :
|
||||
for x in range(10) :
|
||||
try :
|
||||
gc.collect()
|
||||
start_new_thread(func, args)
|
||||
return True
|
||||
except :
|
||||
global _mws_thread_id
|
||||
try :
|
||||
_mws_thread_id += 1
|
||||
except :
|
||||
_mws_thread_id = 0
|
||||
try :
|
||||
start_new_thread('MWS_THREAD_%s' % _mws_thread_id, func, args)
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constructor )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
def __init__(self, socket, httpClient, httpResponse, maxRecvLen, threaded, acceptCallback) :
|
||||
self._socket = socket
|
||||
self._httpCli = httpClient
|
||||
self._closed = True
|
||||
self._lock = allocate_lock()
|
||||
self.RecvTextCallback = None
|
||||
self.RecvBinaryCallback = None
|
||||
self.ClosedCallback = None
|
||||
|
||||
if hasattr(socket, 'read'): # MicroPython
|
||||
self._socketfile = self._socket
|
||||
else: # CPython
|
||||
self._socketfile = self._socket.makefile('rwb')
|
||||
|
||||
if self._handshake(httpResponse) :
|
||||
self._ctrlBuf = MicroWebSocket._tryAllocByteArray(0x7D)
|
||||
self._msgBuf = MicroWebSocket._tryAllocByteArray(maxRecvLen)
|
||||
if self._ctrlBuf and self._msgBuf :
|
||||
self._msgType = None
|
||||
self._msgLen = 0
|
||||
if threaded :
|
||||
if MicroWebSocket._tryStartThread(self._wsProcess, (acceptCallback, )) :
|
||||
return
|
||||
else :
|
||||
self._wsProcess(acceptCallback)
|
||||
return
|
||||
print("MicroWebSocket : Out of memory on new WebSocket connection.")
|
||||
try :
|
||||
if self._socketfile is not self._socket:
|
||||
self._socketfile.close()
|
||||
self._socket.close()
|
||||
except :
|
||||
pass
|
||||
|
||||
# ============================================================================
|
||||
# ===( Functions )============================================================
|
||||
# ============================================================================
|
||||
|
||||
def _handshake(self, httpResponse) :
|
||||
try :
|
||||
key = self._httpCli.GetRequestHeaders().get('sec-websocket-key', None)
|
||||
if key :
|
||||
key += self._handshakeSign
|
||||
r = sha1(key.encode()).digest()
|
||||
r = b2a_base64(r).decode().strip()
|
||||
httpResponse.WriteSwitchProto("websocket", { "Sec-WebSocket-Accept" : r })
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _wsProcess(self, acceptCallback) :
|
||||
self._socket.settimeout(3600)
|
||||
self._closed = False
|
||||
try :
|
||||
acceptCallback(self, self._httpCli)
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on accept callback (%s)." % str(ex))
|
||||
while not self._closed :
|
||||
if not self._receiveFrame() :
|
||||
self.Close()
|
||||
if self.ClosedCallback :
|
||||
try :
|
||||
self.ClosedCallback(self)
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on closed callback (%s)." % str(ex))
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _receiveFrame(self) :
|
||||
try :
|
||||
b = self._socketfile.read(2)
|
||||
if not b or len(b) != 2 :
|
||||
return False
|
||||
|
||||
fin = b[0] & 0x80 > 0
|
||||
opcode = b[0] & 0x0F
|
||||
masked = b[1] & 0x80 > 0
|
||||
length = b[1] & 0x7F
|
||||
|
||||
if opcode == self._opContFrame and not self._msgType :
|
||||
return False
|
||||
elif opcode == self._opTextFrame :
|
||||
self._msgType = self._msgTypeText
|
||||
elif opcode == self._opBinFrame :
|
||||
self._msgType = self._msgTypeBin
|
||||
|
||||
if length == 0x7E :
|
||||
b = self._socketfile.read(2)
|
||||
if not b or len(b) != 2 :
|
||||
return False
|
||||
length = (b[0] << 8) + b[1]
|
||||
elif length == 0x7F :
|
||||
return False
|
||||
|
||||
mask = self._socketfile.read(4) if masked else None
|
||||
if masked and (not mask or len(mask) != 4) :
|
||||
return False
|
||||
|
||||
if opcode == self._opContFrame or \
|
||||
opcode == self._opTextFrame or \
|
||||
opcode == self._opBinFrame :
|
||||
|
||||
if length > 0 :
|
||||
buf = memoryview(self._msgBuf)[self._msgLen:]
|
||||
if length > len(buf) :
|
||||
return False
|
||||
x = self._socketfile.readinto(buf[0:length])
|
||||
if x != length :
|
||||
return False
|
||||
if masked :
|
||||
for i in range(length) :
|
||||
idx = self._msgLen + i
|
||||
self._msgBuf[idx] ^= mask[i%4]
|
||||
self._msgLen += length
|
||||
if fin :
|
||||
b = bytes(memoryview(self._msgBuf)[:self._msgLen])
|
||||
if self._msgType == self._msgTypeText :
|
||||
if self.RecvTextCallback :
|
||||
try :
|
||||
self.RecvTextCallback(self, b.decode())
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on recv text callback (%s)." % str(ex))
|
||||
else :
|
||||
if self.RecvBinaryCallback :
|
||||
try :
|
||||
self.RecvBinaryCallback(self, b)
|
||||
except Exception as ex :
|
||||
print("MicroWebSocket : Error on recv binary callback (%s)." % str(ex))
|
||||
self._msgType = None
|
||||
self._msgLen = 0
|
||||
else :
|
||||
return False
|
||||
|
||||
elif opcode == self._opPingFrame :
|
||||
|
||||
if length > len(self._ctrlBuf) :
|
||||
return False
|
||||
if length > 0 :
|
||||
x = self._socketfile.readinto(self._ctrlBuf[0:length])
|
||||
if x != length :
|
||||
return False
|
||||
pingData = memoryview(self._ctrlBuf)[:length]
|
||||
else :
|
||||
pingData = None
|
||||
self._sendFrame(self._opPongFrame, pingData)
|
||||
|
||||
elif opcode == self._opCloseFrame :
|
||||
self.Close()
|
||||
|
||||
except :
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _sendFrame(self, opcode, data=None, fin=True) :
|
||||
if not self._closed and opcode >= 0x00 and opcode <= 0x0F :
|
||||
dataLen = 0 if not data else len(data)
|
||||
if dataLen <= 0xFFFF :
|
||||
b1 = (0x80 | opcode) if fin else opcode
|
||||
b2 = 0x7E if dataLen >= 0x7E else dataLen
|
||||
self._lock.acquire()
|
||||
try :
|
||||
if self._socketfile.write(pack('>BB', b1, b2)) == 2 :
|
||||
if dataLen > 0 :
|
||||
if dataLen >= 0x7E :
|
||||
self._socketfile.write(pack('>H', dataLen))
|
||||
ret = self._socketfile.write(data) == dataLen
|
||||
else :
|
||||
ret = True
|
||||
if self._socketfile is not self._socket :
|
||||
self._socketfile.flush() # CPython needs flush to continue protocol
|
||||
self._lock.release()
|
||||
return ret
|
||||
except :
|
||||
pass
|
||||
self._lock.release()
|
||||
return False
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def SendText(self, msg) :
|
||||
return self._sendFrame(self._opTextFrame, msg.encode())
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def SendBinary(self, data) :
|
||||
return self._sendFrame(self._opBinFrame, data)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def IsClosed(self) :
|
||||
return self._closed
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Close(self) :
|
||||
if not self._closed :
|
||||
try :
|
||||
self._sendFrame(self._opCloseFrame)
|
||||
if self._socketfile is not self._socket:
|
||||
self._socketfile.close()
|
||||
self._socket.close()
|
||||
self._closed = True
|
||||
except :
|
||||
pass
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
@@ -0,0 +1,880 @@
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
|
||||
from json import loads, dumps
|
||||
from os import stat
|
||||
from _thread import start_new_thread
|
||||
import socket
|
||||
import gc
|
||||
import re
|
||||
|
||||
try :
|
||||
from microWebTemplate import MicroWebTemplate
|
||||
except :
|
||||
pass
|
||||
|
||||
try :
|
||||
from microWebSocket import MicroWebSocket
|
||||
except :
|
||||
pass
|
||||
|
||||
class MicroWebSrvRoute :
|
||||
def __init__(self, route, method, func, routeArgNames, routeRegex) :
|
||||
self.route = route
|
||||
self.method = method
|
||||
self.func = func
|
||||
self.routeArgNames = routeArgNames
|
||||
self.routeRegex = routeRegex
|
||||
|
||||
|
||||
class MicroWebSrv :
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constants )============================================================
|
||||
# ============================================================================
|
||||
|
||||
_indexPages = [
|
||||
"index.pyhtml",
|
||||
"index.html",
|
||||
"index.htm",
|
||||
"default.pyhtml",
|
||||
"default.html",
|
||||
"default.htm"
|
||||
]
|
||||
|
||||
_mimeTypes = {
|
||||
".txt" : "text/plain",
|
||||
".htm" : "text/html",
|
||||
".html" : "text/html",
|
||||
".css" : "text/css",
|
||||
".csv" : "text/csv",
|
||||
".js" : "application/javascript",
|
||||
".xml" : "application/xml",
|
||||
".xhtml" : "application/xhtml+xml",
|
||||
".json" : "application/json",
|
||||
".zip" : "application/zip",
|
||||
".pdf" : "application/pdf",
|
||||
".ts" : "application/typescript",
|
||||
".woff" : "font/woff",
|
||||
".woff2" : "font/woff2",
|
||||
".ttf" : "font/ttf",
|
||||
".otf" : "font/otf",
|
||||
".jpg" : "image/jpeg",
|
||||
".jpeg" : "image/jpeg",
|
||||
".png" : "image/png",
|
||||
".gif" : "image/gif",
|
||||
".svg" : "image/svg+xml",
|
||||
".ico" : "image/x-icon"
|
||||
}
|
||||
|
||||
_html_escape_chars = {
|
||||
"&" : "&",
|
||||
'"' : """,
|
||||
"'" : "'",
|
||||
">" : ">",
|
||||
"<" : "<"
|
||||
}
|
||||
|
||||
_pyhtmlPagesExt = '.pyhtml'
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class globals )=======================================================
|
||||
# ============================================================================
|
||||
|
||||
_docoratedRouteHandlers = []
|
||||
|
||||
# ============================================================================
|
||||
# ===( Utils )===============================================================
|
||||
# ============================================================================
|
||||
|
||||
@classmethod
|
||||
def route(cls, url, method='GET'):
|
||||
""" Adds a route handler function to the routing list """
|
||||
def route_decorator(func):
|
||||
item = (url, method, func)
|
||||
cls._docoratedRouteHandlers.append(item)
|
||||
return func
|
||||
return route_decorator
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def HTMLEscape(s) :
|
||||
return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _startThread(func, args=()) :
|
||||
try :
|
||||
start_new_thread(func, args)
|
||||
except :
|
||||
global _mwsrv_thread_id
|
||||
try :
|
||||
_mwsrv_thread_id += 1
|
||||
except :
|
||||
_mwsrv_thread_id = 0
|
||||
try :
|
||||
start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args)
|
||||
except :
|
||||
return False
|
||||
return True
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _unquote(s) :
|
||||
r = str(s).split('%')
|
||||
try :
|
||||
b = r[0].encode()
|
||||
for i in range(1, len(r)) :
|
||||
try :
|
||||
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
|
||||
except :
|
||||
b += b'%' + r[i].encode()
|
||||
return b.decode('UTF-8')
|
||||
except :
|
||||
return str(s)
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _unquote_plus(s) :
|
||||
return MicroWebSrv._unquote(s.replace('+', ' '))
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _fileExists(path) :
|
||||
try :
|
||||
stat(path)
|
||||
return True
|
||||
except :
|
||||
return False
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _isPyHTMLFile(filename) :
|
||||
return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt)
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constructor )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
def __init__( self,
|
||||
routeHandlers = [],
|
||||
port = 80,
|
||||
bindIP = '0.0.0.0',
|
||||
webPath = "/flash/www" ) :
|
||||
|
||||
self._srvAddr = (bindIP, port)
|
||||
self._webPath = webPath
|
||||
self._notFoundUrl = None
|
||||
self._started = False
|
||||
|
||||
self.MaxWebSocketRecvLen = 1024
|
||||
self.WebSocketThreaded = True
|
||||
self.AcceptWebSocketCallback = None
|
||||
self.LetCacheStaticContentLevel = 2
|
||||
|
||||
self._routeHandlers = []
|
||||
routeHandlers += self._docoratedRouteHandlers
|
||||
for route, method, func in routeHandlers :
|
||||
routeParts = route.split('/')
|
||||
# -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>']
|
||||
routeArgNames = []
|
||||
routeRegex = ''
|
||||
for s in routeParts :
|
||||
if s.startswith('<') and s.endswith('>') :
|
||||
routeArgNames.append(s[1:-1])
|
||||
routeRegex += '/(\\w*)'
|
||||
elif s :
|
||||
routeRegex += '/' + s
|
||||
routeRegex += '$'
|
||||
# -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
|
||||
routeRegex = re.compile(routeRegex)
|
||||
|
||||
self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex))
|
||||
|
||||
# ============================================================================
|
||||
# ===( Server Process )=======================================================
|
||||
# ============================================================================
|
||||
|
||||
def _serverProcess(self) :
|
||||
self._started = True
|
||||
while True :
|
||||
try :
|
||||
client, cliAddr = self._server.accept()
|
||||
except Exception as ex :
|
||||
if ex.args and ex.args[0] == 113 :
|
||||
break
|
||||
continue
|
||||
self._client(self, client, cliAddr)
|
||||
self._started = False
|
||||
|
||||
# ============================================================================
|
||||
# ===( Functions )============================================================
|
||||
# ============================================================================
|
||||
|
||||
def Start(self, threaded=False) :
|
||||
if not self._started :
|
||||
self._server = socket.socket()
|
||||
self._server.setsockopt( socket.SOL_SOCKET,
|
||||
socket.SO_REUSEADDR,
|
||||
1 )
|
||||
self._server.bind(self._srvAddr)
|
||||
self._server.listen(16)
|
||||
if threaded :
|
||||
MicroWebSrv._startThread(self._serverProcess)
|
||||
else :
|
||||
self._serverProcess()
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Stop(self) :
|
||||
if self._started :
|
||||
self._server.close()
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def IsStarted(self) :
|
||||
return self._started
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def SetNotFoundPageUrl(self, url=None) :
|
||||
self._notFoundUrl = url
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def GetMimeTypeFromFilename(self, filename) :
|
||||
filename = filename.lower()
|
||||
for ext in self._mimeTypes :
|
||||
if filename.endswith(ext) :
|
||||
return self._mimeTypes[ext]
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def GetRouteHandler(self, resUrl, method) :
|
||||
if self._routeHandlers :
|
||||
#resUrl = resUrl.upper()
|
||||
if resUrl.endswith('/') :
|
||||
resUrl = resUrl[:-1]
|
||||
method = method.upper()
|
||||
for rh in self._routeHandlers :
|
||||
if rh.method == method :
|
||||
m = rh.routeRegex.match(resUrl)
|
||||
if m : # found matching route?
|
||||
if rh.routeArgNames :
|
||||
routeArgs = {}
|
||||
for i, name in enumerate(rh.routeArgNames) :
|
||||
value = m.group(i+1)
|
||||
try :
|
||||
value = int(value)
|
||||
except :
|
||||
pass
|
||||
routeArgs[name] = value
|
||||
return (rh.func, routeArgs)
|
||||
else :
|
||||
return (rh.func, None)
|
||||
return (None, None)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _physPathFromURLPath(self, urlPath) :
|
||||
if urlPath == '/' :
|
||||
for idxPage in self._indexPages :
|
||||
physPath = self._webPath + '/' + idxPage
|
||||
if MicroWebSrv._fileExists(physPath) :
|
||||
return physPath
|
||||
else :
|
||||
physPath = self._webPath + urlPath.replace('../', '/')
|
||||
if MicroWebSrv._fileExists(physPath) :
|
||||
return physPath
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class Client )========================================================
|
||||
# ============================================================================
|
||||
|
||||
class _client :
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, microWebSrv, socket, addr) :
|
||||
socket.settimeout(2)
|
||||
self._microWebSrv = microWebSrv
|
||||
self._socket = socket
|
||||
self._addr = addr
|
||||
self._method = None
|
||||
self._path = None
|
||||
self._httpVer = None
|
||||
self._resPath = "/"
|
||||
self._queryString = ""
|
||||
self._queryParams = { }
|
||||
self._headers = { }
|
||||
self._contentType = None
|
||||
self._contentLength = 0
|
||||
|
||||
if hasattr(socket, 'readline'): # MicroPython
|
||||
self._socketfile = self._socket
|
||||
else: # CPython
|
||||
self._socketfile = self._socket.makefile('rwb')
|
||||
|
||||
self._processRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequest(self) :
|
||||
try :
|
||||
response = MicroWebSrv._response(self)
|
||||
if self._parseFirstLine(response) :
|
||||
if self._parseHeader(response) :
|
||||
upg = self._getConnUpgrade()
|
||||
if not upg :
|
||||
routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method)
|
||||
if routeHandler :
|
||||
try :
|
||||
if routeArgs is not None:
|
||||
routeHandler(self, response, routeArgs)
|
||||
else :
|
||||
routeHandler(self, response)
|
||||
except Exception as ex :
|
||||
print('MicroWebSrv handler exception:\r\n - In route %s %s\r\n - %s' % (self._method, self._resPath, ex))
|
||||
raise ex
|
||||
elif self._method.upper() == "GET" :
|
||||
filepath = self._microWebSrv._physPathFromURLPath(self._resPath)
|
||||
if filepath :
|
||||
if MicroWebSrv._isPyHTMLFile(filepath) :
|
||||
response.WriteResponsePyHTMLFile(filepath)
|
||||
else :
|
||||
contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath)
|
||||
if contentType :
|
||||
if self._microWebSrv.LetCacheStaticContentLevel > 0 :
|
||||
if self._microWebSrv.LetCacheStaticContentLevel > 1 and \
|
||||
'if-modified-since' in self._headers :
|
||||
response.WriteResponseNotModified()
|
||||
else:
|
||||
headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \
|
||||
'Cache-Control' : 'max-age=315360000' }
|
||||
response.WriteResponseFile(filepath, contentType, headers)
|
||||
else :
|
||||
response.WriteResponseFile(filepath, contentType)
|
||||
else :
|
||||
response.WriteResponseForbidden()
|
||||
else :
|
||||
response.WriteResponseNotFound()
|
||||
else :
|
||||
response.WriteResponseMethodNotAllowed()
|
||||
elif upg == 'websocket' and 'MicroWebSocket' in globals() \
|
||||
and self._microWebSrv.AcceptWebSocketCallback :
|
||||
MicroWebSocket( socket = self._socket,
|
||||
httpClient = self,
|
||||
httpResponse = response,
|
||||
maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen,
|
||||
threaded = self._microWebSrv.WebSocketThreaded,
|
||||
acceptCallback = self._microWebSrv.AcceptWebSocketCallback )
|
||||
return
|
||||
else :
|
||||
response.WriteResponseNotImplemented()
|
||||
else :
|
||||
response.WriteResponseBadRequest()
|
||||
except :
|
||||
response.WriteResponseInternalServerError()
|
||||
try :
|
||||
if self._socketfile is not self._socket:
|
||||
self._socketfile.close()
|
||||
self._socket.close()
|
||||
except :
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseFirstLine(self, response) :
|
||||
try :
|
||||
elements = self._socketfile.readline().decode().strip().split()
|
||||
if len(elements) == 3 :
|
||||
self._method = elements[0].upper()
|
||||
self._path = elements[1]
|
||||
self._httpVer = elements[2].upper()
|
||||
elements = self._path.split('?', 1)
|
||||
if len(elements) > 0 :
|
||||
self._resPath = MicroWebSrv._unquote_plus(elements[0])
|
||||
if len(elements) > 1 :
|
||||
self._queryString = elements[1]
|
||||
elements = self._queryString.split('&')
|
||||
for s in elements :
|
||||
param = s.split('=', 1)
|
||||
if len(param) > 0 :
|
||||
value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else ''
|
||||
self._queryParams[MicroWebSrv._unquote(param[0])] = value
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseHeader(self, response) :
|
||||
while True :
|
||||
elements = self._socketfile.readline().decode().strip().split(':', 1)
|
||||
if len(elements) == 2 :
|
||||
self._headers[elements[0].strip().lower()] = elements[1].strip()
|
||||
elif len(elements) == 1 and len(elements[0]) == 0 :
|
||||
if self._method == 'POST' or self._method == 'PUT' :
|
||||
self._contentType = self._headers.get("content-type", None)
|
||||
self._contentLength = int(self._headers.get("content-length", 0))
|
||||
return True
|
||||
else :
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _getConnUpgrade(self) :
|
||||
if 'upgrade' in self._headers.get('connection', '').lower() :
|
||||
return self._headers.get('upgrade', '').lower()
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetServer(self) :
|
||||
return self._microWebSrv
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetAddr(self) :
|
||||
return self._addr
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetIPAddr(self) :
|
||||
return self._addr[0]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetPort(self) :
|
||||
return self._addr[1]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestMethod(self) :
|
||||
return self._method
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestTotalPath(self) :
|
||||
return self._path
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestPath(self) :
|
||||
return self._resPath
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestQueryString(self) :
|
||||
return self._queryString
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestQueryParams(self) :
|
||||
return self._queryParams
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestHeaders(self) :
|
||||
return self._headers
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestContentType(self) :
|
||||
return self._contentType
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetRequestContentLength(self) :
|
||||
return self._contentLength
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReadRequestContent(self, size=None) :
|
||||
if size is None :
|
||||
size = self._contentLength
|
||||
if size > 0 :
|
||||
try :
|
||||
return self._socketfile.read(size)
|
||||
except :
|
||||
pass
|
||||
return b''
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReadRequestPostedFormData(self) :
|
||||
res = { }
|
||||
data = self.ReadRequestContent()
|
||||
if data :
|
||||
elements = data.decode().split('&')
|
||||
for s in elements :
|
||||
param = s.split('=', 1)
|
||||
if len(param) > 0 :
|
||||
value = MicroWebSrv._unquote_plus(param[1]) if len(param) > 1 else ''
|
||||
res[MicroWebSrv._unquote_plus(param[0])] = value
|
||||
return res
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReadRequestContentAsJSON(self) :
|
||||
data = self.ReadRequestContent()
|
||||
if data :
|
||||
try :
|
||||
return loads(data.decode())
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class Response )======================================================
|
||||
# ============================================================================
|
||||
|
||||
class _response :
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, client) :
|
||||
self._client = client
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _write(self, data, strEncoding='ISO-8859-1') :
|
||||
if data :
|
||||
if type(data) == str :
|
||||
data = data.encode(strEncoding)
|
||||
data = memoryview(data)
|
||||
while data :
|
||||
n = self._client._socketfile.write(data)
|
||||
if n is None :
|
||||
return False
|
||||
data = data[n:]
|
||||
return True
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeFirstLine(self, code) :
|
||||
reason = self._responseCodes.get(code, ('Unknown reason', ))[0]
|
||||
return self._write("HTTP/1.1 %s %s\r\n" % (code, reason))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeHeader(self, name, value) :
|
||||
return self._write("%s: %s\r\n" % (name, value))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeContentTypeHeader(self, contentType, charset=None) :
|
||||
if contentType :
|
||||
ct = contentType \
|
||||
+ (("; charset=%s" % charset) if charset else "")
|
||||
else :
|
||||
ct = "application/octet-stream"
|
||||
self._writeHeader("Content-Type", ct)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeServerHeader(self) :
|
||||
self._writeHeader("Server", "MicroWebSrv by JC`zic")
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeEndHeader(self) :
|
||||
return self._write("\r\n")
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) :
|
||||
self._writeFirstLine(code)
|
||||
if isinstance(headers, dict) :
|
||||
for header in headers :
|
||||
self._writeHeader(header, headers[header])
|
||||
if contentLength > 0 :
|
||||
self._writeContentTypeHeader(contentType, contentCharset)
|
||||
self._writeHeader("Content-Length", contentLength)
|
||||
self._writeServerHeader()
|
||||
self._writeHeader("Connection", "close")
|
||||
self._writeEndHeader()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteSwitchProto(self, upgrade, headers=None) :
|
||||
self._writeFirstLine(101)
|
||||
self._writeHeader("Connection", "Upgrade")
|
||||
self._writeHeader("Upgrade", upgrade)
|
||||
if isinstance(headers, dict) :
|
||||
for header in headers :
|
||||
self._writeHeader(header, headers[header])
|
||||
self._writeServerHeader()
|
||||
self._writeEndHeader()
|
||||
if self._client._socketfile is not self._client._socket :
|
||||
self._client._socketfile.flush() # CPython needs flush to continue protocol
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponse(self, code, headers, contentType, contentCharset, content) :
|
||||
try :
|
||||
if content :
|
||||
if type(content) == str :
|
||||
content = content.encode(contentCharset)
|
||||
contentLength = len(content)
|
||||
else :
|
||||
contentLength = 0
|
||||
self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength)
|
||||
if content :
|
||||
return self._write(content)
|
||||
return True
|
||||
except :
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) :
|
||||
if 'MicroWebTemplate' in globals() :
|
||||
with open(filepath, 'r') as file :
|
||||
code = file.read()
|
||||
mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath)
|
||||
try :
|
||||
tmplResult = mWebTmpl.Execute(None, vars)
|
||||
return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult)
|
||||
except Exception as ex :
|
||||
return self.WriteResponse( 500,
|
||||
None,
|
||||
"text/html",
|
||||
"UTF-8",
|
||||
self._execErrCtnTmpl % {
|
||||
'module' : 'PyHTML',
|
||||
'message' : str(ex)
|
||||
} )
|
||||
return self.WriteResponseNotImplemented()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseFile(self, filepath, contentType=None, headers=None) :
|
||||
try :
|
||||
size = stat(filepath)[6]
|
||||
if size > 0 :
|
||||
with open(filepath, 'rb') as file :
|
||||
self._writeBeforeContent(200, headers, contentType, None, size)
|
||||
try :
|
||||
buf = bytearray(1024)
|
||||
while size > 0 :
|
||||
x = file.readinto(buf)
|
||||
if x < len(buf) :
|
||||
buf = memoryview(buf)[:x]
|
||||
if not self._write(buf) :
|
||||
return False
|
||||
size -= x
|
||||
return True
|
||||
except :
|
||||
self.WriteResponseInternalServerError()
|
||||
return False
|
||||
except :
|
||||
pass
|
||||
self.WriteResponseNotFound()
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) :
|
||||
if not isinstance(headers, dict) :
|
||||
headers = { }
|
||||
headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName
|
||||
return self.WriteResponseFile(filepath, None, headers)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) :
|
||||
return self.WriteResponse(200, headers, contentType, contentCharset, content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseJSONOk(self, obj=None, headers=None) :
|
||||
return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseRedirect(self, location) :
|
||||
headers = { "Location" : location }
|
||||
return self.WriteResponse(302, headers, None, None, None)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseError(self, code) :
|
||||
responseCode = self._responseCodes.get(code, ('Unknown reason', ''))
|
||||
return self.WriteResponse( code,
|
||||
None,
|
||||
"text/html",
|
||||
"UTF-8",
|
||||
self._errCtnTmpl % {
|
||||
'code' : code,
|
||||
'reason' : responseCode[0],
|
||||
'message' : responseCode[1]
|
||||
} )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseJSONError(self, code, obj=None) :
|
||||
return self.WriteResponse( code,
|
||||
None,
|
||||
"application/json",
|
||||
"UTF-8",
|
||||
dumps(obj if obj else { }) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseNotModified(self) :
|
||||
return self.WriteResponseError(304)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseBadRequest(self) :
|
||||
return self.WriteResponseError(400)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseForbidden(self) :
|
||||
return self.WriteResponseError(403)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseNotFound(self) :
|
||||
if self._client._microWebSrv._notFoundUrl :
|
||||
self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl)
|
||||
else :
|
||||
return self.WriteResponseError(404)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseMethodNotAllowed(self) :
|
||||
return self.WriteResponseError(405)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseInternalServerError(self) :
|
||||
return self.WriteResponseError(500)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WriteResponseNotImplemented(self) :
|
||||
return self.WriteResponseError(501)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def FlashMessage(self, messageText, messageStyle='') :
|
||||
if 'MicroWebTemplate' in globals() :
|
||||
MicroWebTemplate.MESSAGE_TEXT = messageText
|
||||
MicroWebTemplate.MESSAGE_STYLE = messageStyle
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_errCtnTmpl = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>Error</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>%(code)d %(reason)s</h1>
|
||||
%(message)s
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_execErrCtnTmpl = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>Page execution error</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>%(module)s page execution error</h1>
|
||||
%(message)s
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_responseCodes = {
|
||||
100: ('Continue', 'Request received, please continue'),
|
||||
101: ('Switching Protocols',
|
||||
'Switching to new protocol; obey Upgrade header'),
|
||||
|
||||
200: ('OK', 'Request fulfilled, document follows'),
|
||||
201: ('Created', 'Document created, URL follows'),
|
||||
202: ('Accepted',
|
||||
'Request accepted, processing continues off-line'),
|
||||
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
|
||||
204: ('No Content', 'Request fulfilled, nothing follows'),
|
||||
205: ('Reset Content', 'Clear input form for further input.'),
|
||||
206: ('Partial Content', 'Partial content follows.'),
|
||||
|
||||
300: ('Multiple Choices',
|
||||
'Object has several resources -- see URI list'),
|
||||
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
|
||||
302: ('Found', 'Object moved temporarily -- see URI list'),
|
||||
303: ('See Other', 'Object moved -- see Method and URL list'),
|
||||
304: ('Not Modified',
|
||||
'Document has not changed since given time'),
|
||||
305: ('Use Proxy',
|
||||
'You must use proxy specified in Location to access this '
|
||||
'resource.'),
|
||||
307: ('Temporary Redirect',
|
||||
'Object moved temporarily -- see URI list'),
|
||||
|
||||
400: ('Bad Request',
|
||||
'Bad request syntax or unsupported method'),
|
||||
401: ('Unauthorized',
|
||||
'No permission -- see authorization schemes'),
|
||||
402: ('Payment Required',
|
||||
'No payment -- see charging schemes'),
|
||||
403: ('Forbidden',
|
||||
'Request forbidden -- authorization will not help'),
|
||||
404: ('Not Found', 'Nothing matches the given URI'),
|
||||
405: ('Method Not Allowed',
|
||||
'Specified method is invalid for this resource.'),
|
||||
406: ('Not Acceptable', 'URI not available in preferred format.'),
|
||||
407: ('Proxy Authentication Required', 'You must authenticate with '
|
||||
'this proxy before proceeding.'),
|
||||
408: ('Request Timeout', 'Request timed out; try again later.'),
|
||||
409: ('Conflict', 'Request conflict.'),
|
||||
410: ('Gone',
|
||||
'URI no longer exists and has been permanently removed.'),
|
||||
411: ('Length Required', 'Client must specify Content-Length.'),
|
||||
412: ('Precondition Failed', 'Precondition in headers is false.'),
|
||||
413: ('Request Entity Too Large', 'Entity is too large.'),
|
||||
414: ('Request-URI Too Long', 'URI is too long.'),
|
||||
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
|
||||
416: ('Requested Range Not Satisfiable',
|
||||
'Cannot satisfy request range.'),
|
||||
417: ('Expectation Failed',
|
||||
'Expect condition could not be satisfied.'),
|
||||
|
||||
500: ('Internal Server Error', 'Server got itself in trouble'),
|
||||
501: ('Not Implemented',
|
||||
'Server does not support this operation'),
|
||||
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
|
||||
503: ('Service Unavailable',
|
||||
'The server cannot process the request due to a high load'),
|
||||
504: ('Gateway Timeout',
|
||||
'The gateway server did not receive a timely response'),
|
||||
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
|
After Width: | Height: | Size: 43 KiB |
@@ -0,0 +1,336 @@
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
class MicroWebTemplate :
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constants )============================================================
|
||||
# ============================================================================
|
||||
|
||||
TOKEN_OPEN = '{{'
|
||||
TOKEN_CLOSE = '}}'
|
||||
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
|
||||
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
|
||||
|
||||
INSTRUCTION_PYTHON = 'py'
|
||||
INSTRUCTION_IF = 'if'
|
||||
INSTRUCTION_ELIF = 'elif'
|
||||
INSTRUCTION_ELSE = 'else'
|
||||
INSTRUCTION_FOR = 'for'
|
||||
INSTRUCTION_END = 'end'
|
||||
INSTRUCTION_INCLUDE = 'include'
|
||||
|
||||
MESSAGE_TEXT = ''
|
||||
MESSAGE_STYLE = ''
|
||||
|
||||
# ============================================================================
|
||||
# ===( Constructor )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
def __init__(self, code, escapeStrFunc=None, filepath='') :
|
||||
self._code = code
|
||||
self._escapeStrFunc = escapeStrFunc
|
||||
self._filepath = filepath
|
||||
self._pos = 0
|
||||
self._endPos = len(code)-1
|
||||
self._line = 1
|
||||
self._reIdentifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
|
||||
self._pyGlobalVars = { }
|
||||
self._pyLocalVars = { }
|
||||
self._rendered = ''
|
||||
self._instructions = {
|
||||
MicroWebTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
|
||||
MicroWebTemplate.INSTRUCTION_IF : self._processInstructionIF,
|
||||
MicroWebTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
|
||||
MicroWebTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
|
||||
MicroWebTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
|
||||
MicroWebTemplate.INSTRUCTION_END : self._processInstructionEND,
|
||||
MicroWebTemplate.INSTRUCTION_INCLUDE: self._processInstructionINCLUDE,
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# ===( Functions )============================================================
|
||||
# ============================================================================
|
||||
|
||||
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
|
||||
try :
|
||||
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
|
||||
return None
|
||||
except Exception as ex :
|
||||
return str(ex)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
|
||||
try :
|
||||
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
|
||||
return self._rendered
|
||||
except Exception as ex :
|
||||
raise Exception(str(ex))
|
||||
|
||||
# ============================================================================
|
||||
# ===( Utils )===============================================================
|
||||
# ============================================================================
|
||||
|
||||
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
|
||||
if pyGlobalVars:
|
||||
self._pyGlobalVars.update(pyGlobalVars)
|
||||
if pyLocalVars:
|
||||
self._pyLocalVars.update(pyLocalVars)
|
||||
self._pyLocalVars['MESSAGE_TEXT'] = MicroWebTemplate.MESSAGE_TEXT
|
||||
self._pyLocalVars['MESSAGE_STYLE'] = MicroWebTemplate.MESSAGE_STYLE
|
||||
self._rendered = ''
|
||||
newTokenToProcess = self._parseBloc(execute)
|
||||
if newTokenToProcess is not None :
|
||||
raise Exception( '"%s" instruction is not valid here (line %s)'
|
||||
% (newTokenToProcess, self._line) )
|
||||
MicroWebTemplate.MESSAGE_TEXT = ''
|
||||
MicroWebTemplate.MESSAGE_STYLE = ''
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _parseBloc(self, execute) :
|
||||
while self._pos <= self._endPos :
|
||||
c = self._code[self._pos]
|
||||
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
|
||||
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
|
||||
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
|
||||
tokenContent = ''
|
||||
x = self._pos
|
||||
while True :
|
||||
if x > self._endPos :
|
||||
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
|
||||
c = self._code[x]
|
||||
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
|
||||
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
|
||||
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
|
||||
break
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
tokenContent += c
|
||||
x += 1
|
||||
newTokenToProcess = self._processToken(tokenContent, execute)
|
||||
if newTokenToProcess is not None :
|
||||
return newTokenToProcess
|
||||
continue
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
if execute :
|
||||
self._rendered += c
|
||||
self._pos += 1
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processToken(self, tokenContent, execute) :
|
||||
tokenContent = tokenContent.strip()
|
||||
parts = tokenContent.split(' ', 1)
|
||||
instructName = parts[0].strip()
|
||||
instructBody = parts[1].strip() if len(parts) > 1 else None
|
||||
if len(instructName) == 0 :
|
||||
raise Exception( '"%s %s" : instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.TOKEN_OPEN, MicroWebTemplate.TOKEN_CLOSE, self._line) )
|
||||
newTokenToProcess = None
|
||||
if instructName in self._instructions :
|
||||
newTokenToProcess = self._instructions[instructName](instructBody, execute)
|
||||
elif execute :
|
||||
try :
|
||||
s = str( eval( tokenContent,
|
||||
self._pyGlobalVars,
|
||||
self._pyLocalVars ) )
|
||||
if (self._escapeStrFunc is not None) :
|
||||
self._rendered += self._escapeStrFunc(s)
|
||||
else :
|
||||
self._rendered += s
|
||||
except Exception as ex :
|
||||
raise Exception('%s (line %s)' % (str(ex), self._line))
|
||||
return newTokenToProcess
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionPYTHON(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise Exception( 'Instruction "%s" is invalid (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_PYTHON, self._line) )
|
||||
pyCode = ''
|
||||
while True :
|
||||
if self._pos > self._endPos :
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
c = self._code[self._pos]
|
||||
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
|
||||
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
|
||||
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
|
||||
tokenContent = ''
|
||||
x = self._pos
|
||||
while True :
|
||||
if x > self._endPos :
|
||||
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
|
||||
c = self._code[x]
|
||||
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
|
||||
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
|
||||
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
|
||||
break
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
tokenContent += c
|
||||
x += 1
|
||||
tokenContent = tokenContent.strip()
|
||||
if tokenContent == MicroWebTemplate.INSTRUCTION_END :
|
||||
break
|
||||
raise Exception( '"%s" is a bad instruction in a python bloc (line %s)'
|
||||
% (tokenContent, self._line) )
|
||||
elif c == '\n' :
|
||||
self._line += 1
|
||||
if execute :
|
||||
pyCode += c
|
||||
self._pos += 1
|
||||
if execute :
|
||||
lines = pyCode.split('\n')
|
||||
indent = ''
|
||||
for line in lines :
|
||||
if len(line.strip()) > 0 :
|
||||
for c in line :
|
||||
if c == ' ' or c == '\t' :
|
||||
indent += c
|
||||
else :
|
||||
break
|
||||
break
|
||||
pyCode = ''
|
||||
for line in lines :
|
||||
if line.find(indent) == 0 :
|
||||
line = line[len(indent):]
|
||||
pyCode += line + '\n'
|
||||
try :
|
||||
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
|
||||
except Exception as ex :
|
||||
raise Exception('%s (line %s)' % (str(ex), self._line))
|
||||
return None
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionIF(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
if execute :
|
||||
try :
|
||||
if (' ' not in instructionBody) and \
|
||||
('=' not in instructionBody) and \
|
||||
('<' not in instructionBody) and \
|
||||
('>' not in instructionBody) and \
|
||||
(instructionBody not in self._pyGlobalVars) and \
|
||||
(instructionBody not in self._pyLocalVars):
|
||||
result = False
|
||||
else:
|
||||
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
|
||||
except Exception as ex :
|
||||
raise Exception('%s (line %s)' % (str(ex), self._line))
|
||||
else :
|
||||
result = False
|
||||
newTokenToProcess = self._parseBloc(execute and result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELSE :
|
||||
newTokenToProcess = self._parseBloc(execute and not result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise Exception( '"%s" instruction waited (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELIF :
|
||||
self._processInstructionIF(self._elifInstructionBody, execute and not result)
|
||||
return None
|
||||
raise Exception( '"%s" instruction waited (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_IF, self._line) )
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELIF(self, instructionBody, execute) :
|
||||
if instructionBody is None :
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_ELIF, self._line) )
|
||||
self._elifInstructionBody = instructionBody
|
||||
return MicroWebTemplate.INSTRUCTION_ELIF
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELSE(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise Exception( 'Instruction "%s" is invalid (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_ELSE, self._line) )
|
||||
return MicroWebTemplate.INSTRUCTION_ELSE
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionFOR(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
parts = instructionBody.split(' ', 1)
|
||||
identifier = parts[0].strip()
|
||||
if self._reIdentifier.match(identifier) is not None and len(parts) > 1 :
|
||||
parts = parts[1].strip().split(' ', 1)
|
||||
if parts[0] == 'in' and len(parts) > 1 :
|
||||
expression = parts[1].strip()
|
||||
newTokenToProcess = None
|
||||
beforePos = self._pos
|
||||
if execute :
|
||||
try :
|
||||
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
|
||||
except :
|
||||
raise Exception('%s (line %s)' % (str(expression), self._line))
|
||||
if execute and len(result) > 0 :
|
||||
for x in result :
|
||||
self._pyLocalVars[identifier] = x
|
||||
self._pos = beforePos
|
||||
newTokenToProcess = self._parseBloc(True)
|
||||
if newTokenToProcess != MicroWebTemplate.INSTRUCTION_END :
|
||||
break
|
||||
else :
|
||||
newTokenToProcess = self._parseBloc(False)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise Exception( '"%s" instruction waited (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s" instruction is missing (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
raise Exception( '"%s %s" is an invalid syntax'
|
||||
% (MicroWebTemplate.INSTRUCTION_FOR, instructionBody) )
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_FOR, self._line) )
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionEND(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise Exception( 'Instruction "%s" is invalid (line %s)'
|
||||
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
|
||||
return MicroWebTemplate.INSTRUCTION_END
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionINCLUDE(self, instructionBody, execute) :
|
||||
if not instructionBody :
|
||||
raise Exception( '"%s" alone is an incomplete syntax (line %s)' % (MicroWebTemplate.INSTRUCTION_INCLUDE, self._line) )
|
||||
filename = instructionBody.replace('"','').replace("'",'').strip()
|
||||
idx = self._filepath.rindex('/')
|
||||
if idx >= 0 :
|
||||
filename = self._filepath[:idx+1] + filename
|
||||
with open(filename, 'r') as file :
|
||||
includeCode = file.read()
|
||||
|
||||
self._code = self._code[:self._pos] + includeCode + self._code[self._pos:]
|
||||
self._endPos += len(includeCode)
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
After Width: | Height: | Size: 7.7 KiB |
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang=fr>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Page de test MicroWebSrv</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Page de test MicroWebSrv</h1>
|
||||
<h2>Hello !</h2>
|
||||
<p>
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget ligula quis libero mollis dapibus. Suspendisse potenti. Nullam facilisis neque et sem. Proin placerat adipiscing urna. Aenean sollicitudin. Mauris lorem erat, fringilla quis, sagittis a, varius sed, nunc. Pellentesque ligula. Nullam egestas eleifend turpis. Vivamus ac sapien. Sed venenatis, ligula ut scelerisque vehicula, erat tellus euismod ipsum, eget faucibus tortor arcu et lectus. Vivamus vel purus. Fusce dignissim tortor quis diam elementum fermentum. Mauris eleifend lorem vel arcu. Vivamus tempus faucibus lectus. Curabitur volutpat ornare mi. Curabitur ac libero. Sed eu elit ac metus egestas iaculis.
|
||||
</p>
|
||||
<br />
|
||||
<hr />
|
||||
<br />
|
||||
<div style="text-align: center">
|
||||
<img src="pdf.png" />
|
||||
<p>
|
||||
Afficher « <a href="test.pdf">un fichier PDF</a> »
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 4.4 KiB |
@@ -0,0 +1,36 @@
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
body {
|
||||
background-color: white;
|
||||
font-family: Verdana, sans-serif;
|
||||
font-size: 100%;
|
||||
}
|
||||
h1 {
|
||||
font-size: 200%;
|
||||
color: navy;
|
||||
text-align: center;
|
||||
}
|
||||
h2 {
|
||||
font-size: 150%;
|
||||
color: red;
|
||||
padding-left: 15px;
|
||||
}
|
||||
p,ul,li,td {
|
||||
color: black;
|
||||
}
|
||||
a:link {
|
||||
color: green;
|
||||
text-decoration: underline;
|
||||
}
|
||||
a:visited {
|
||||
color: gray;
|
||||
}
|
||||
a:hover {
|
||||
color: red;
|
||||
text-decoration: none;
|
||||
}
|
||||
a:active, a:focus {
|
||||
color: red;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>TEST</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>BEGIN</h1>
|
||||
{{ py }}
|
||||
def _testFunction(x) :
|
||||
return "IN TEST FUNCTION %s" % x
|
||||
{{ end }}
|
||||
<div style="background-color: black; color: white;">
|
||||
{{ for toto in range(3) }}
|
||||
This is an HTML test...<br />
|
||||
TOTO = {{ toto + 1 }} !<br />
|
||||
{{ for toto2 in range(3) }}
|
||||
TOTO2 = {{ _testFunction(toto2) }}
|
||||
{{ end }}
|
||||
Ok good.<br />
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ _testFunction(100) }}<br />
|
||||
<br />
|
||||
{{ if 2+5 < 3 }}
|
||||
IN IF (1)
|
||||
{{ elif 10+15 != 25 }}
|
||||
IN ELIF (2)
|
||||
{{ elif 10+15 == 25 }}
|
||||
IN ELIF (3)
|
||||
{{ else }}
|
||||
IN ELSE (4)
|
||||
{{ end }}
|
||||
<h1>JC :')</h1>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,78 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MicroWebSocket Test</title>
|
||||
</head>
|
||||
|
||||
<script language="javascript">
|
||||
|
||||
var output;
|
||||
|
||||
function init()
|
||||
{
|
||||
output = document.getElementById("output");
|
||||
testWebSocket();
|
||||
}
|
||||
|
||||
function testWebSocket()
|
||||
{
|
||||
var wsUri = "ws://" + window.location.hostname;
|
||||
writeToScreen("Connection to " + wsUri + "...")
|
||||
websocket = new WebSocket(wsUri);
|
||||
websocket.onopen = function(evt) { onOpen (evt) };
|
||||
websocket.onclose = function(evt) { onClose (evt) };
|
||||
websocket.onmessage = function(evt) { onMessage (evt) };
|
||||
websocket.onerror = function(evt) { onError (evt) };
|
||||
}
|
||||
|
||||
function onOpen(evt)
|
||||
{
|
||||
writeToScreen("<strong>-- CONNECTED --</strong>");
|
||||
SendMsg("Hello world :)");
|
||||
SendMsg("This is a WebSocket test");
|
||||
SendMsg("(with a text frame encoded in UTF-8)");
|
||||
setTimeout( function() { websocket.close() }, 500 )
|
||||
}
|
||||
|
||||
function onClose(evt)
|
||||
{
|
||||
writeToScreen("<strong>-- DISCONNECTED --</strong>");
|
||||
}
|
||||
|
||||
function onMessage(evt)
|
||||
{
|
||||
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
|
||||
}
|
||||
|
||||
function onError(evt)
|
||||
{
|
||||
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
|
||||
}
|
||||
|
||||
function SendMsg(msg)
|
||||
{
|
||||
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
|
||||
websocket.send(msg);
|
||||
}
|
||||
|
||||
function writeToScreen(s)
|
||||
{
|
||||
var pre = document.createElement("p");
|
||||
pre.style.wordWrap = "break-word";
|
||||
pre.innerHTML = s;
|
||||
output.appendChild(pre);
|
||||
}
|
||||
|
||||
window.addEventListener("load", init, false);
|
||||
|
||||
</script>
|
||||
|
||||
<body>
|
||||
<h2>MicroWebSocket Test :</h2>
|
||||
<div id="output"></div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,6 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info
|
||||
/dist
|
||||
/.venv*
|
||||
@@ -0,0 +1,8 @@
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (https://www.hc2.fr)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,18 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2024 Jean-Christophe Bos (jczic.bos@gmail.com)
|
||||
"""
|
||||
|
||||
print()
|
||||
print(' -------------------------')
|
||||
print(' - Python MicroWebSrv2 -')
|
||||
print(' - version 2.1.0 -')
|
||||
print(' - by JC`zic -')
|
||||
print(' -------------------------')
|
||||
print()
|
||||
|
||||
from .libs.XAsyncSockets import *
|
||||
from .libs.urlUtils import *
|
||||
from .webRoute import *
|
||||
from .microWebSrv2 import *
|
||||
@@ -0,0 +1,416 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from . import *
|
||||
from .httpResponse import HttpResponse
|
||||
from binascii import a2b_base64
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# ===( HttpRequest )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
class HttpRequest :
|
||||
|
||||
MAX_RECV_HEADER_LINES = 100
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, microWebSrv2, xasCli) :
|
||||
self._mws2 = microWebSrv2
|
||||
self._xasCli = xasCli
|
||||
self._waitForRecvRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _recvLine(self, onRecv) :
|
||||
self._xasCli.AsyncRecvLine(onLineRecv=onRecv, timeoutSec=self._mws2._timeoutSec)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _waitForRecvRequest(self) :
|
||||
self._httpVer = ''
|
||||
self._method = ''
|
||||
self._path = ''
|
||||
self._headers = { }
|
||||
self._content = None
|
||||
self._response = HttpResponse(self._mws2, self)
|
||||
self._recvLine(self._onFirstLineRecv)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onFirstLineRecv(self, xasCli, line, arg) :
|
||||
try :
|
||||
elements = line.strip().split()
|
||||
if len(elements) == 3 :
|
||||
self._httpVer = elements[2].upper()
|
||||
self._method = elements[0].upper()
|
||||
elements = elements[1].split('?', 1)
|
||||
self._path = UrlUtils.UnquotePlus(elements[0])
|
||||
self._queryString = (elements[1] if len(elements) > 1 else '')
|
||||
self._queryParams = { }
|
||||
if self._queryString :
|
||||
elements = self._queryString.split('&')
|
||||
for s in elements :
|
||||
p = s.split('=', 1)
|
||||
if len(p) > 0 :
|
||||
v = (UrlUtils.Unquote(p[1]) if len(p) > 1 else '')
|
||||
self._queryParams[UrlUtils.Unquote(p[0])] = v
|
||||
self._recvLine(self._onHeaderLineRecv)
|
||||
else :
|
||||
self._response.ReturnBadRequest()
|
||||
except :
|
||||
self._response.ReturnBadRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onHeaderLineRecv(self, xasCli, line, arg) :
|
||||
try :
|
||||
elements = line.strip().split(':', 1)
|
||||
if len(elements) == 2 :
|
||||
if len(self._headers) < HttpRequest.MAX_RECV_HEADER_LINES :
|
||||
self._headers[elements[0].strip().lower()] = elements[1].strip()
|
||||
self._recvLine(self._onHeaderLineRecv)
|
||||
else :
|
||||
self._response.ReturnEntityTooLarge()
|
||||
elif len(elements) == 1 and len(elements[0]) == 0 :
|
||||
self._processRequest()
|
||||
else :
|
||||
self._response.ReturnBadRequest()
|
||||
except :
|
||||
self._response.ReturnBadRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequest(self) :
|
||||
if not self._processRequestModules() :
|
||||
if not self.IsUpgrade :
|
||||
if not self._processRequestRoutes() :
|
||||
if self._method in ('GET', 'HEAD') :
|
||||
filename = self._mws2.ResolvePhysicalPath(self._path)
|
||||
if filename :
|
||||
ct = self._mws2.GetMimeTypeFromFilename(filename)
|
||||
if ct :
|
||||
self._response.AllowCaching = True
|
||||
self._response.ContentType = ct
|
||||
self._response.ReturnFile(filename)
|
||||
else :
|
||||
self._response.ReturnForbidden()
|
||||
else :
|
||||
self._response.ReturnNotFound()
|
||||
elif self._method == 'OPTIONS' :
|
||||
if self._mws2.CORSAllowAll :
|
||||
self._response.SetHeader( 'Access-Control-Allow-Methods', '*' )
|
||||
self._response.SetHeader( 'Access-Control-Allow-Headers', '*' )
|
||||
self._response.SetHeader( 'Access-Control-Allow-Credentials', 'true' )
|
||||
self._response.SetHeader( 'Access-Control-Max-Age', '86400' )
|
||||
self._response.ReturnOk()
|
||||
else :
|
||||
self._response.ReturnMethodNotAllowed()
|
||||
else :
|
||||
self._response.ReturnNotImplemented()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequestModules(self) :
|
||||
for modName, modInstance in self._mws2._modules.items() :
|
||||
try :
|
||||
modInstance.OnRequest(self._mws2, self)
|
||||
if self._response.HeadersSent :
|
||||
return True
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception in request handler of module "%s" (%s).'
|
||||
% (modName, ex),
|
||||
self._mws2.ERROR )
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processRequestRoutes(self) :
|
||||
self._routeResult = ResolveRoute(self._method, self._path)
|
||||
if self._routeResult :
|
||||
cntLen = self.ContentLength
|
||||
if not cntLen :
|
||||
self._routeRequest()
|
||||
elif self._method != 'GET' and self._method != 'HEAD' :
|
||||
if cntLen <= self._mws2._maxContentLen :
|
||||
def onContentRecv(xasCli, content, arg) :
|
||||
self._content = content
|
||||
self._routeRequest()
|
||||
self._content = None
|
||||
try :
|
||||
self._xasCli.AsyncRecvData( size = cntLen,
|
||||
onDataRecv = onContentRecv,
|
||||
timeoutSec = self._mws2._timeoutSec )
|
||||
except :
|
||||
self._mws2.Log( 'Not enough memory to read a content of %s bytes.' % cntLen,
|
||||
self._mws2.ERROR )
|
||||
self._response.ReturnServiceUnavailable()
|
||||
else :
|
||||
self._response.ReturnEntityTooLarge()
|
||||
else :
|
||||
self._response.ReturnBadRequest()
|
||||
return True
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _routeRequest(self) :
|
||||
try :
|
||||
currentResp = self._response
|
||||
if self._routeResult.Args :
|
||||
self._routeResult.Handler(self._mws2, self, self._routeResult.Args)
|
||||
else :
|
||||
self._routeResult.Handler(self._mws2, self)
|
||||
if not currentResp.HeadersSent :
|
||||
self._mws2.Log( 'No response was sent from route %s.'
|
||||
% self._routeResult,
|
||||
self._mws2.WARNING )
|
||||
currentResp.ReturnNotImplemented()
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from route %s: %s'
|
||||
% (self._routeResult, ex),
|
||||
self._mws2.ERROR )
|
||||
currentResp.ReturnInternalServerError()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetPostedURLEncodedForm(self) :
|
||||
res = { }
|
||||
if self.ContentType.lower() == 'application/x-www-form-urlencoded' :
|
||||
try :
|
||||
elements = bytes(self._content).decode('UTF-8').split('&')
|
||||
for s in elements :
|
||||
p = s.split('=', 1)
|
||||
if len(p) > 0 :
|
||||
v = (UrlUtils.UnquotePlus(p[1]) if len(p) > 1 else '')
|
||||
res[UrlUtils.UnquotePlus(p[0])] = v
|
||||
except :
|
||||
pass
|
||||
return res
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetPostedJSONObject(self) :
|
||||
if self.ContentType.lower() == 'application/json' :
|
||||
try :
|
||||
s = bytes(self._content).decode('UTF-8')
|
||||
return json.loads(s)
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetHeader(self, name) :
|
||||
if not isinstance(name, str) or len(name) == 0 :
|
||||
raise ValueError('"name" must be a not empty string.')
|
||||
return self._headers.get(name.lower(), '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def CheckBasicAuth(self, username, password) :
|
||||
if not isinstance(username, str) :
|
||||
raise ValueError('"username" must be a string.')
|
||||
if not isinstance(password, str) :
|
||||
raise ValueError('"password" must be a string.')
|
||||
auth = self.Authorization
|
||||
if auth :
|
||||
try :
|
||||
auth = auth.split()
|
||||
if len(auth) == 2 and auth[0].lower() == 'basic' :
|
||||
auth = a2b_base64(auth[1].encode()).decode()
|
||||
auth = auth.split(':')
|
||||
return ( auth[0].lower() == username.lower() and \
|
||||
auth[1] == password )
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def CheckBearerAuth(self, token) :
|
||||
if not isinstance(token, str) :
|
||||
raise ValueError('"token" must be a string.')
|
||||
auth = self.Authorization
|
||||
if auth :
|
||||
try :
|
||||
auth = auth.split()
|
||||
return ( len(auth) == 2 and \
|
||||
auth[0].lower() == 'bearer' and \
|
||||
auth[1] == token )
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def UserAddress(self) :
|
||||
return self._xasCli.CliAddr
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsSSL(self) :
|
||||
return self._xasCli.IsSSL
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def HttpVer(self) :
|
||||
return self._httpVer
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Method(self) :
|
||||
return self._method
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Path(self) :
|
||||
return self._path
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryString(self) :
|
||||
return self._queryString
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryParams(self) :
|
||||
return self._queryParams
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Host(self) :
|
||||
return self._headers.get('host', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Accept(self) :
|
||||
s = self._headers.get('accept', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(',')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AcceptEncodings(self) :
|
||||
s = self._headers.get('accept-encoding', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(',')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AcceptLanguages(self) :
|
||||
s = self._headers.get('accept-language', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(',')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Cookies(self) :
|
||||
s = self._headers.get('cookie', None)
|
||||
if s :
|
||||
return [x.strip() for x in s.split(';')]
|
||||
return [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def CacheControl(self) :
|
||||
return self._headers.get('cache-control', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Referer(self) :
|
||||
return self._headers.get('referer', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentType(self) :
|
||||
return self._headers.get('content-type', '').split(';', 1)[0].strip()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentLength(self) :
|
||||
try :
|
||||
return int(self._headers.get('content-length', 0))
|
||||
except :
|
||||
return 0
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def UserAgent(self) :
|
||||
return self._headers.get('user-agent', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Authorization(self) :
|
||||
return self._headers.get('authorization', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Origin(self) :
|
||||
return self._headers.get('origin', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsKeepAlive(self) :
|
||||
return ('keep-alive' in self._headers.get('connection', '').lower())
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsUpgrade(self) :
|
||||
return ('upgrade' in self._headers.get('connection', '').lower())
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Upgrade(self) :
|
||||
return self._headers.get('upgrade', '')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Content(self) :
|
||||
return self._content
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Response(self) :
|
||||
return self._response
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def XAsyncTCPClient(self) :
|
||||
return self._xasCli
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,550 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from os import stat
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# ===( HttpResponse )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
class HttpResponse :
|
||||
|
||||
_RESPONSE_CODES = {
|
||||
100: ( 'Continue',
|
||||
'Request received, please continue.' ),
|
||||
101: ( 'Switching Protocols',
|
||||
'Switching to new protocol; obey Upgrade header.' ),
|
||||
200: ( 'OK',
|
||||
'Request fulfilled, document follows.' ),
|
||||
201: ( 'Created',
|
||||
'Document created, URL follows' ),
|
||||
202: ( 'Accepted',
|
||||
'Request accepted, processing continues off-line.' ),
|
||||
203: ( 'Non-Authoritative Information',
|
||||
'Request fulfilled from cache' ),
|
||||
204: ( 'No Content',
|
||||
'Request fulfilled, nothing follows.' ),
|
||||
205: ( 'Reset Content',
|
||||
'Clear input form for further input.' ),
|
||||
206: ( 'Partial Content',
|
||||
'Partial content follows.' ),
|
||||
300: ( 'Multiple Choices',
|
||||
'Object has several resources -- see URI list.' ),
|
||||
301: ( 'Moved Permanently',
|
||||
'Object moved permanently -- see URI list.' ),
|
||||
302: ( 'Found',
|
||||
'Object moved temporarily -- see URI list.' ),
|
||||
303: ( 'See Other',
|
||||
'Object moved -- see Method and URL list.' ),
|
||||
304: ( 'Not Modified',
|
||||
'Document has not changed since given time.' ),
|
||||
305: ( 'Use Proxy',
|
||||
'You must use proxy specified in Location to access this resource.' ),
|
||||
307: ( 'Temporary Redirect',
|
||||
'Object moved temporarily -- see URI list.' ),
|
||||
400: ( 'Bad Request',
|
||||
'Bad request syntax or unsupported method.' ),
|
||||
401: ( 'Unauthorized',
|
||||
'No permission -- see authorization schemes.' ),
|
||||
402: ( 'Payment Required',
|
||||
'No payment -- see charging schemes.' ),
|
||||
403: ( 'Forbidden',
|
||||
'Request forbidden -- authorization will not help.' ),
|
||||
404: ( 'Not Found',
|
||||
'Nothing matches the given URI.' ),
|
||||
405: ( 'Method Not Allowed',
|
||||
'Specified method is invalid for this resource.' ),
|
||||
406: ( 'Not Acceptable',
|
||||
'URI not available in preferred format.' ),
|
||||
407: ( 'Proxy Authentication Required',
|
||||
'You must authenticate with this proxy before proceeding.' ),
|
||||
408: ( 'Request Timeout',
|
||||
'Request timed out; try again later.' ),
|
||||
409: ( 'Conflict',
|
||||
'Request conflict.' ),
|
||||
410: ( 'Gone',
|
||||
'URI no longer exists and has been permanently removed.' ),
|
||||
411: ( 'Length Required',
|
||||
'Client must specify Content-Length.' ),
|
||||
412: ( 'Precondition Failed',
|
||||
'Precondition in headers is false.' ),
|
||||
413: ( 'Request Entity Too Large',
|
||||
'Entity is too large.' ),
|
||||
414: ( 'Request-URI Too Long',
|
||||
'URI is too long.' ),
|
||||
415: ( 'Unsupported Media Type',
|
||||
'Entity body in unsupported format.' ),
|
||||
416: ( 'Requested Range Not Satisfiable',
|
||||
'Cannot satisfy request range.' ),
|
||||
417: ( 'Expectation Failed',
|
||||
'Expect condition could not be satisfied.' ),
|
||||
500: ( 'Internal Server Error',
|
||||
'Server got itself in trouble.' ),
|
||||
501: ( 'Not Implemented',
|
||||
'Server does not support this operation.' ),
|
||||
502: ( 'Bad Gateway',
|
||||
'Invalid responses from another server/proxy.' ),
|
||||
503: ( 'Service Unavailable',
|
||||
'The server cannot process the request due to a high load.' ),
|
||||
504: ( 'Gateway Timeout',
|
||||
'The gateway server did not receive a timely response.' ),
|
||||
505: ( 'HTTP Version Not Supported',
|
||||
'Cannot fulfill request.' )
|
||||
}
|
||||
|
||||
_CODE_CONTENT_TMPL = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>MicroWebSrv2</title>
|
||||
</head>
|
||||
<body style="font-family: Verdana; background-color: Black; color: White;">
|
||||
<h2>MicroWebSrv2 - [%(code)d] %(reason)s</h2>
|
||||
%(message)s
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, microWebSrv2, request) :
|
||||
self._mws2 = microWebSrv2
|
||||
self._request = request
|
||||
self._xasCli = request.XAsyncTCPClient
|
||||
self._headers = { }
|
||||
self._allowCaching = False
|
||||
self._acAllowOrigin = None
|
||||
self._contentType = None
|
||||
self._contentCharset = None
|
||||
self._contentLength = 0
|
||||
self._stream = None
|
||||
self._sendingBuf = None
|
||||
self._hdrSent = False
|
||||
self._onSent = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetHeader(self, name, value) :
|
||||
if not isinstance(name, str) or len(name) == 0 :
|
||||
raise ValueError('"name" must be a not empty string.')
|
||||
if value is None :
|
||||
raise ValueError('"value" cannot be None.')
|
||||
self._headers[name] = str(value)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onDataSent(self, xasCli, arg) :
|
||||
if self._stream :
|
||||
try :
|
||||
n = self._stream.readinto(self._sendingBuf)
|
||||
if n < len(self._sendingBuf) :
|
||||
self._stream.close()
|
||||
self._stream = None
|
||||
self._sendingBuf = self._sendingBuf[:n]
|
||||
except :
|
||||
self._xasCli.Close()
|
||||
self._mws2.Log( 'Stream cannot be read for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.ERROR )
|
||||
return
|
||||
if self._sendingBuf :
|
||||
if self._contentLength :
|
||||
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
|
||||
onDataSent = self._onDataSent )
|
||||
if not self._stream :
|
||||
self._sendingBuf = None
|
||||
else :
|
||||
def onChunkHdrSent(xasCli, arg) :
|
||||
def onChunkDataSent(xasCli, arg) :
|
||||
def onLastChunkSent(xasCli, arg) :
|
||||
self._xasCli.AsyncSendData(b'0\r\n\r\n', onDataSent=self._onDataSent)
|
||||
if self._stream :
|
||||
onDataSent = self._onDataSent
|
||||
else :
|
||||
self._sendingBuf = None
|
||||
onDataSent = onLastChunkSent
|
||||
self._xasCli.AsyncSendData(b'\r\n', onDataSent=onDataSent)
|
||||
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
|
||||
onDataSent = onChunkDataSent )
|
||||
data = ('%x\r\n' % len(self._sendingBuf)).encode()
|
||||
self._xasCli.AsyncSendData(data, onDataSent=onChunkHdrSent)
|
||||
else :
|
||||
self._xasCli.OnClosed = None
|
||||
if self._keepAlive :
|
||||
self._request._waitForRecvRequest()
|
||||
else :
|
||||
self._xasCli.Close()
|
||||
if self._onSent :
|
||||
try :
|
||||
self._onSent(self._mws2, self)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "Response.OnSent" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onClosed(self, xasCli, closedReason) :
|
||||
if self._stream :
|
||||
try :
|
||||
self._stream.close()
|
||||
except :
|
||||
pass
|
||||
self._stream = None
|
||||
self._sendingBuf = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _makeBaseResponseHdr(self, code) :
|
||||
reason = self._RESPONSE_CODES.get(code, ('Unknown reason', ))[0]
|
||||
self._mws2.Log( 'From %s:%s %s%s %s >> [%s] %s'
|
||||
% ( self._xasCli.CliAddr[0],
|
||||
self._xasCli.CliAddr[1],
|
||||
('SSL-' if self.IsSSL else ''),
|
||||
self._request._method,
|
||||
self._request._path,
|
||||
code,
|
||||
reason ),
|
||||
self._mws2.DEBUG )
|
||||
if self._mws2.AllowAllOrigins :
|
||||
self._acAllowOrigin = self._request.Origin
|
||||
if self._acAllowOrigin :
|
||||
self.SetHeader('Access-Control-Allow-Origin', self._acAllowOrigin)
|
||||
self.SetHeader('Server', 'MicroWebSrv2 by JC`zic')
|
||||
hdr = ''
|
||||
for n in self._headers :
|
||||
hdr += '%s: %s\r\n' % (n, self._headers[n])
|
||||
resp = 'HTTP/1.1 %s %s\r\n%s\r\n' % (code, reason, hdr)
|
||||
return resp.encode('ISO-8859-1')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _makeResponseHdr(self, code) :
|
||||
if code >= 200 and code < 300 :
|
||||
self._keepAlive = self._request.IsKeepAlive
|
||||
else :
|
||||
self._keepAlive = False
|
||||
if self._keepAlive :
|
||||
self.SetHeader('Connection', 'Keep-Alive')
|
||||
self.SetHeader('Keep-Alive', 'timeout=%s' % self._mws2._timeoutSec)
|
||||
else :
|
||||
self.SetHeader('Connection', 'Close')
|
||||
if self._allowCaching :
|
||||
self.SetHeader('Cache-Control', 'public, max-age=31536000')
|
||||
else :
|
||||
self.SetHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
|
||||
if self._contentType :
|
||||
ct = self._contentType
|
||||
if self._contentCharset :
|
||||
ct += '; charset=%s' % self._contentCharset
|
||||
self.SetHeader('Content-Type', ct)
|
||||
if self._contentLength :
|
||||
self.SetHeader('Content-Length', self._contentLength)
|
||||
return self._makeBaseResponseHdr(code)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SwitchingProtocols(self, upgrade) :
|
||||
if not isinstance(upgrade, str) or len(upgrade) == 0 :
|
||||
raise ValueError('"upgrade" must be a not empty string.')
|
||||
if self._hdrSent :
|
||||
self._mws2.Log( 'Response headers already sent for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.WARNING )
|
||||
return
|
||||
self.SetHeader('Connection', 'Upgrade')
|
||||
self.SetHeader('Upgrade', upgrade)
|
||||
data = self._makeBaseResponseHdr(101)
|
||||
self._xasCli.AsyncSendData(data)
|
||||
self._hdrSent = True
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnStream(self, code, stream) :
|
||||
if not isinstance(code, int) or code <= 0 :
|
||||
raise ValueError('"code" must be a positive integer.')
|
||||
if not hasattr(stream, 'readinto') or not hasattr(stream, 'close') :
|
||||
raise ValueError('"stream" must be a readable buffer protocol object.')
|
||||
if self._hdrSent :
|
||||
self._mws2.Log( 'Response headers already sent for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.WARNING )
|
||||
try :
|
||||
stream.close()
|
||||
except :
|
||||
pass
|
||||
return
|
||||
if self._request._method != 'HEAD' :
|
||||
self._stream = stream
|
||||
self._sendingBuf = memoryview(self._xasCli.SendingBuffer)
|
||||
self._xasCli.OnClosed = self._onClosed
|
||||
else :
|
||||
try :
|
||||
stream.close()
|
||||
except :
|
||||
pass
|
||||
if not self._contentType :
|
||||
self._contentType = 'application/octet-stream'
|
||||
if not self._contentLength :
|
||||
self.SetHeader('Transfer-Encoding', 'chunked')
|
||||
data = self._makeResponseHdr(code)
|
||||
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
|
||||
self._hdrSent = True
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Return(self, code, content=None) :
|
||||
if not isinstance(code, int) or code <= 0 :
|
||||
raise ValueError('"code" must be a positive integer.')
|
||||
if self._hdrSent :
|
||||
self._mws2.Log( 'Response headers already sent for request "%s".'
|
||||
% self._request._path,
|
||||
self._mws2.WARNING )
|
||||
return
|
||||
if not content :
|
||||
respCode = self._RESPONSE_CODES.get(code, ('Unknown reason', ''))
|
||||
self._contentType = 'text/html'
|
||||
content = self._CODE_CONTENT_TMPL % { 'code' : code,
|
||||
'reason' : respCode[0],
|
||||
'message' : respCode[1] }
|
||||
if isinstance(content, str) :
|
||||
content = content.encode('UTF-8')
|
||||
if not self._contentType :
|
||||
self._contentType = 'text/html'
|
||||
self._contentCharset = 'UTF-8'
|
||||
elif not self._contentType :
|
||||
self._contentType = 'application/octet-stream'
|
||||
self._contentLength = len(content)
|
||||
data = self._makeResponseHdr(code)
|
||||
if self._request._method != 'HEAD' :
|
||||
data += bytes(content)
|
||||
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
|
||||
self._hdrSent = True
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnJSON(self, code, obj) :
|
||||
if not isinstance(code, int) or code <= 0 :
|
||||
raise ValueError('"code" must be a positive integer.')
|
||||
self._contentType = 'application/json'
|
||||
try :
|
||||
content = json.dumps(obj)
|
||||
except :
|
||||
raise ValueError('"obj" cannot be converted into JSON format.')
|
||||
self.Return(code, content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnOk(self, content=None) :
|
||||
self.Return(200, content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnOkJSON(self, obj) :
|
||||
self.ReturnJSON(200, obj)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnFile(self, filename, attachmentName=None) :
|
||||
if not isinstance(filename, str) or len(filename) == 0 :
|
||||
raise ValueError('"filename" must be a not empty string.')
|
||||
if attachmentName is not None and not isinstance(attachmentName, str) :
|
||||
raise ValueError('"attachmentName" must be a string or None.')
|
||||
try :
|
||||
size = stat(filename)[6]
|
||||
except :
|
||||
self.ReturnNotFound()
|
||||
return
|
||||
try :
|
||||
file = open(filename, 'rb')
|
||||
except :
|
||||
self.ReturnForbidden()
|
||||
return
|
||||
if attachmentName :
|
||||
cd = 'attachment; filename="%s"' % attachmentName.replace('"', "'")
|
||||
self.SetHeader('Content-Disposition', cd)
|
||||
if not self._contentType :
|
||||
self._contentType = self._mws2.GetMimeTypeFromFilename(filename)
|
||||
self._contentLength = size
|
||||
self.ReturnStream(200, file)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnNotModified(self) :
|
||||
self.Return(304)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnRedirect(self, location) :
|
||||
if not isinstance(location, str) or len(location) == 0 :
|
||||
raise ValueError('"location" must be a not empty string.')
|
||||
self.SetHeader('Location', location)
|
||||
self.Return(307)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnBadRequest(self) :
|
||||
self.Return(400)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnUnauthorized(self, typeName, realm=None) :
|
||||
if not isinstance(typeName, str) or len(typeName) == 0 :
|
||||
raise ValueError('"typeName" must be a not empty string.')
|
||||
if realm is not None and not isinstance(realm, str) :
|
||||
raise ValueError('"realm" must be a string or None.')
|
||||
wwwAuth = typeName
|
||||
if realm :
|
||||
wwwAuth += (' realm="%s"' % realm.replace('"', "'")) if realm else ''
|
||||
self.SetHeader('WWW-Authenticate', wwwAuth)
|
||||
self.Return(401)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnForbidden(self) :
|
||||
self.Return(403)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnNotFound(self) :
|
||||
if self._mws2._notFoundURL :
|
||||
self.ReturnRedirect(self._mws2._notFoundURL)
|
||||
else :
|
||||
self.Return(404)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnMethodNotAllowed(self) :
|
||||
self.Return(405)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnEntityTooLarge(self) :
|
||||
self.Return(413)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnInternalServerError(self) :
|
||||
self.Return(500)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnNotImplemented(self) :
|
||||
self.Return(501)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnServiceUnavailable(self) :
|
||||
self.Return(503)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnBasicAuthRequired(self) :
|
||||
self.ReturnUnauthorized('Basic')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnBearerAuthRequired(self) :
|
||||
self.ReturnUnauthorized('Bearer')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Request(self) :
|
||||
return self._request
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def UserAddress(self) :
|
||||
return self._xasCli.CliAddr
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsSSL(self) :
|
||||
return self._xasCli.IsSSL
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AllowCaching(self) :
|
||||
return self._allowCaching
|
||||
|
||||
@AllowCaching.setter
|
||||
def AllowCaching(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"AllowCaching" must be a boolean.')
|
||||
self._allowCaching = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AccessControlAllowOrigin(self) :
|
||||
return self._acAllowOrigin
|
||||
|
||||
@AccessControlAllowOrigin.setter
|
||||
def AccessControlAllowOrigin(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"AccessControlAllowOrigin" must be a string or None.')
|
||||
self._acAllowOrigin = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentType(self) :
|
||||
return self._contentType
|
||||
|
||||
@ContentType.setter
|
||||
def ContentType(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"ContentType" must be a string or None.')
|
||||
self._contentType = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentCharset(self) :
|
||||
return self._contentCharset
|
||||
|
||||
@ContentCharset.setter
|
||||
def ContentCharset(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"ContentCharset" must be a string or None.')
|
||||
self._contentCharset = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ContentLength(self) :
|
||||
return self._contentLength
|
||||
|
||||
@ContentLength.setter
|
||||
def ContentLength(self, value) :
|
||||
if not isinstance(value, int) or value < 0 :
|
||||
raise ValueError('"ContentLength" must be a positive integer or zero.')
|
||||
self._contentLength = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def HeadersSent(self) :
|
||||
return self._hdrSent
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnSent(self) :
|
||||
return self._onSent
|
||||
|
||||
@OnSent.setter
|
||||
def OnSent(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnSent" must be a function.')
|
||||
self._onSent = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,218 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
class UrlUtils :
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def Quote(s, safe='/') :
|
||||
r = ''
|
||||
for c in str(s) :
|
||||
if (c >= 'a' and c <= 'z') or \
|
||||
(c >= '0' and c <= '9') or \
|
||||
(c >= 'A' and c <= 'Z') or \
|
||||
(c in '.-_') or (c in safe) :
|
||||
r += c
|
||||
else :
|
||||
for b in c.encode('UTF-8') :
|
||||
r += '%%%02X' % b
|
||||
return r
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def UrlEncode(s) :
|
||||
return UrlUtils.Quote(s, ';/?:@&=+$,')
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def Unquote(s) :
|
||||
r = str(s).split('%')
|
||||
try :
|
||||
b = r[0].encode()
|
||||
for i in range(1, len(r)) :
|
||||
try :
|
||||
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
|
||||
except :
|
||||
b += b'%' + r[i].encode()
|
||||
return b.decode('UTF-8')
|
||||
except :
|
||||
return str(s)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def UnquotePlus(s) :
|
||||
return UrlUtils.Unquote(str(s).replace('+', ' '))
|
||||
|
||||
# ============================================================================
|
||||
# ===( Class Url )============================================================
|
||||
# ============================================================================
|
||||
|
||||
class Url :
|
||||
|
||||
def __init__(self, url='') :
|
||||
self.URL = url
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __repr__(self) :
|
||||
return self.URL if self.URL is not None else ''
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def IsHttps(self) :
|
||||
return (self._proto == 'https')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def URL(self) :
|
||||
host = self.Host
|
||||
if host != '' :
|
||||
proto = self.Proto
|
||||
port = self.Port
|
||||
if ( proto == 'http' and port == 80 ) or \
|
||||
( proto == 'https' and port == 443 ) :
|
||||
port = ''
|
||||
else :
|
||||
port = ':' + str(port)
|
||||
url = proto + '://' + host + port + self.Path
|
||||
url = UrlUtils.UrlEncode(url)
|
||||
qs = self.QueryString
|
||||
if qs != '' :
|
||||
return url + '?' + qs
|
||||
return url
|
||||
return None
|
||||
|
||||
@URL.setter
|
||||
def URL(self, value) :
|
||||
try :
|
||||
s = str(value)
|
||||
if '://' in s :
|
||||
proto, s = s.split('://', 1)
|
||||
else :
|
||||
proto = 'http'
|
||||
except :
|
||||
raise ValueError('URL error (%s)' % value)
|
||||
self.Proto = proto
|
||||
if '/' in s :
|
||||
host, path = s.split('/', 1)
|
||||
elif '?' in s :
|
||||
host, path = s.split('?', 1)
|
||||
path = '?' + path
|
||||
else :
|
||||
host = s
|
||||
path = ''
|
||||
if ':' in host :
|
||||
try :
|
||||
host, port = host.split(':')
|
||||
self.Port = port
|
||||
except :
|
||||
raise ValueError('URL host:port error (%s)' % host)
|
||||
self.Host = host
|
||||
self._queryParams = { }
|
||||
self.Path = path
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Proto(self) :
|
||||
return self._proto
|
||||
|
||||
@Proto.setter
|
||||
def Proto(self, value) :
|
||||
value = str(value).lower()
|
||||
if value == 'http' :
|
||||
self._port = 80
|
||||
elif value == 'https' :
|
||||
self._port = 443
|
||||
else :
|
||||
raise ValueError('Unsupported URL protocol (%s)' % value)
|
||||
self._proto = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Host(self) :
|
||||
return self._host
|
||||
|
||||
@Host.setter
|
||||
def Host(self, value) :
|
||||
self._host = UrlUtils.UnquotePlus(value)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Port(self) :
|
||||
return self._port
|
||||
|
||||
@Port.setter
|
||||
def Port(self, value) :
|
||||
try :
|
||||
p = int(value)
|
||||
except :
|
||||
raise ValueError('Port must be an integer value')
|
||||
if p <= 0 or p >= 65536 :
|
||||
raise ValueError('Port must be greater than 0 and less than 65536')
|
||||
self._port = p
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Path(self) :
|
||||
return self._path
|
||||
|
||||
@Path.setter
|
||||
def Path(self, value) :
|
||||
x = value.split('?', 1)
|
||||
if len(x[0]) > 0 :
|
||||
if x[0][0] != '/' :
|
||||
x[0] = '/' + x[0]
|
||||
self._path = UrlUtils.UnquotePlus(x[0])
|
||||
else :
|
||||
self._path = '/'
|
||||
if len(x) == 2 :
|
||||
self.QueryString = x[1]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryString(self) :
|
||||
r = ''
|
||||
for param in self._queryParams :
|
||||
if param != '' :
|
||||
if r != '' :
|
||||
r += '&'
|
||||
r += UrlUtils.Quote(param) + '=' + UrlUtils.Quote(self._queryParams[param])
|
||||
return r
|
||||
|
||||
@QueryString.setter
|
||||
def QueryString(self, value) :
|
||||
self._queryParams = { }
|
||||
for x in value.split('&') :
|
||||
param = x.split('=', 1)
|
||||
if param[0] != '' :
|
||||
value = UrlUtils.Unquote(param[1]) if len(param) > 1 else ''
|
||||
self._queryParams[UrlUtils.Unquote(param[0])] = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def QueryParams(self) :
|
||||
return self._queryParams
|
||||
|
||||
@QueryParams.setter
|
||||
def QueryParams(self, value) :
|
||||
if not isinstance(value, dict) :
|
||||
raise ValueError('QueryParams must be a dict')
|
||||
self._queryParams = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,544 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from . import *
|
||||
from .httpRequest import HttpRequest
|
||||
from os import stat
|
||||
from sys import implementation
|
||||
from _thread import stack_size
|
||||
|
||||
# ============================================================================
|
||||
# ===( MicroWebSrv2 )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
class MicroWebSrv2Exception(Exception) :
|
||||
pass
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
class MicroWebSrv2 :
|
||||
|
||||
_DEFAULT_PAGES = [
|
||||
"index.html",
|
||||
"index.htm",
|
||||
"default.html",
|
||||
"default.htm"
|
||||
]
|
||||
|
||||
_MIME_TYPES = {
|
||||
".txt" : "text/plain",
|
||||
".htm" : "text/html",
|
||||
".html" : "text/html",
|
||||
".css" : "text/css",
|
||||
".csv" : "text/csv",
|
||||
".js" : "application/javascript",
|
||||
".xml" : "application/xml",
|
||||
".xhtml" : "application/xhtml+xml",
|
||||
".json" : "application/json",
|
||||
".zip" : "application/zip",
|
||||
".pdf" : "application/pdf",
|
||||
".ts" : "application/typescript",
|
||||
".woff" : "font/woff",
|
||||
".woff2" : "font/woff2",
|
||||
".ttf" : "font/ttf",
|
||||
".otf" : "font/otf",
|
||||
".jpg" : "image/jpeg",
|
||||
".jpeg" : "image/jpeg",
|
||||
".png" : "image/png",
|
||||
".gif" : "image/gif",
|
||||
".svg" : "image/svg+xml",
|
||||
".ico" : "image/x-icon"
|
||||
}
|
||||
|
||||
_HTML_ESCAPE_CHARS = {
|
||||
"&" : "&",
|
||||
'"' : """,
|
||||
"'" : "'",
|
||||
">" : ">",
|
||||
"<" : "<"
|
||||
}
|
||||
|
||||
_STAT_MODE_DIR = 1 << 14
|
||||
|
||||
DEBUG = 0x00
|
||||
INFO = 0x01
|
||||
WARNING = 0x02
|
||||
ERROR = 0x03
|
||||
MSG_TYPE_STR = {
|
||||
DEBUG : 'DEBUG',
|
||||
INFO : 'INFO',
|
||||
WARNING : 'WARNING',
|
||||
ERROR : 'ERROR'
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
_modules = { }
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self) :
|
||||
self._backlog = None
|
||||
self._slotsCount = None
|
||||
self._slotsSize = None
|
||||
self._keepAlloc = None
|
||||
self._maxContentLen = None
|
||||
self._bindAddr = ('0.0.0.0', 80)
|
||||
self._sslContext = None
|
||||
self._rootPath = 'www'
|
||||
self._timeoutSec = 2
|
||||
self._notFoundURL = None
|
||||
self._allowAllOrigins = False
|
||||
self._corsAllowAll = False
|
||||
self._onLogging = None
|
||||
self._xasSrv = None
|
||||
self._xasPool = None
|
||||
self.SetNormalConfig()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _physPathExists(physPath) :
|
||||
try :
|
||||
stat(physPath)
|
||||
return True
|
||||
except :
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _physPathIsDir(physPath) :
|
||||
return (stat(physPath)[0] & MicroWebSrv2._STAT_MODE_DIR != 0)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def LoadModule(modName) :
|
||||
if not isinstance(modName, str) or len(modName) == 0 :
|
||||
raise ValueError('"modName" must be a not empty string.')
|
||||
if modName in MicroWebSrv2._modules :
|
||||
raise MicroWebSrv2Exception('Module "%s" is already loaded.' % modName)
|
||||
try :
|
||||
modPath = MicroWebSrv2.__module__.split('microWebSrv2')[0] \
|
||||
+ ('mods.%s' % modName)
|
||||
print('loadmod',modPath)
|
||||
module = getattr(__import__(modPath).mods, modName)
|
||||
modClass = getattr(module, modName)
|
||||
if type(modClass) is not type :
|
||||
raise Exception
|
||||
modInstance = modClass()
|
||||
MicroWebSrv2._modules[modName] = modInstance
|
||||
return modInstance
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Cannot load module "%s".' % modName)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def HTMLEscape(s) :
|
||||
if not isinstance(s, str) :
|
||||
raise ValueError('"s" must be a string.')
|
||||
return ''.join(MicroWebSrv2._HTML_ESCAPE_CHARS.get(c, c) for c in s)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def AddDefaultPage(filename) :
|
||||
if not isinstance(filename, str) or len(filename) == 0 :
|
||||
raise ValueError('"filename" must be a not empty string.')
|
||||
MicroWebSrv2._DEFAULT_PAGES.append(filename)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def AddMimeType(ext, mimeType) :
|
||||
if not isinstance(ext, str) or len(ext) == 0 :
|
||||
raise ValueError('"ext" must be a not empty string.')
|
||||
if not isinstance(mimeType, str) or len(mimeType) == 0 :
|
||||
raise ValueError('"mimeType" must be a not empty string.')
|
||||
MicroWebSrv2._MIME_TYPES[ext.lower()] = mimeType.lower()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def GetMimeTypeFromFilename(filename) :
|
||||
filename = filename.lower()
|
||||
for ext in MicroWebSrv2._MIME_TYPES :
|
||||
if filename.endswith(ext) :
|
||||
return MicroWebSrv2._MIME_TYPES[ext]
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def StartInPool(self, asyncSocketsPool) :
|
||||
if not isinstance(asyncSocketsPool, XAsyncSocketsPool) :
|
||||
raise ValueError('"asyncSocketsPool" must be a XAsyncSocketsPool class.')
|
||||
if self._xasSrv :
|
||||
raise MicroWebSrv2Exception('Server is already running.')
|
||||
try :
|
||||
xBufSlots = XBufferSlots( slotsCount = self._slotsCount,
|
||||
slotsSize = self._slotsSize,
|
||||
keepAlloc = self._keepAlloc )
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Not enough memory to allocate slots.')
|
||||
try :
|
||||
self._xasSrv = XAsyncTCPServer.Create( asyncSocketsPool = asyncSocketsPool,
|
||||
srvAddr = self._bindAddr,
|
||||
srvBacklog = self._backlog,
|
||||
bufSlots = xBufSlots )
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Cannot bind server on %s:%s.' % self._bindAddr)
|
||||
self._xasSrv.OnClientAccepted = self._onSrvClientAccepted
|
||||
self._xasSrv.OnClosed = self._onSrvClosed
|
||||
self.Log('Server listening on %s:%s.' % self._bindAddr, MicroWebSrv2.INFO)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def StartManaged(self, parllProcCount=1, procStackSize=0) :
|
||||
if not isinstance(parllProcCount, int) or parllProcCount < 0 :
|
||||
raise ValueError('"parllProcCount" must be a positive integer or zero.')
|
||||
if not isinstance(procStackSize, int) or procStackSize < 0 :
|
||||
raise ValueError('"procStackSize" must be a positive integer or zero.')
|
||||
if self._xasSrv :
|
||||
raise MicroWebSrv2Exception('Server is already running.')
|
||||
if procStackSize == 0 and implementation.name == 'micropython' :
|
||||
procStackSize = 8*1024
|
||||
try :
|
||||
saveStackSize = stack_size(procStackSize)
|
||||
except Exception as ex :
|
||||
raise ValueError('"procStackSize" of %s is not correct (%s).' % (procStackSize, ex))
|
||||
self._xasPool = XAsyncSocketsPool()
|
||||
try :
|
||||
self.StartInPool(self._xasPool)
|
||||
try :
|
||||
self.Log('Starts the managed pool to wait for I/O events.', MicroWebSrv2.INFO)
|
||||
self._xasPool.AsyncWaitEvents(threadsCount=parllProcCount)
|
||||
except :
|
||||
raise MicroWebSrv2Exception('Not enough memory to start %s parallel processes.' % parllProcCount)
|
||||
except Exception as ex :
|
||||
self.Stop()
|
||||
raise ex
|
||||
finally :
|
||||
try :
|
||||
stack_size(saveStackSize)
|
||||
except :
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Stop(self) :
|
||||
if self._xasSrv :
|
||||
self._xasSrv.Close()
|
||||
self._xasSrv = None
|
||||
if self._xasPool :
|
||||
self.Log('Stops the managed pool.', MicroWebSrv2.INFO)
|
||||
self._xasPool.StopWaitEvents()
|
||||
self._xasPool = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Log(self, msg, msgType) :
|
||||
if self._onLogging :
|
||||
try :
|
||||
self._onLogging(self, str(msg), msgType)
|
||||
return
|
||||
except Exception as ex :
|
||||
msgType = MicroWebSrv2.ERROR
|
||||
msg = 'Exception raised from "OnLoggin" handler: %s' % ex
|
||||
t = MicroWebSrv2.MSG_TYPE_STR.get(msgType, None)
|
||||
if t :
|
||||
print('MWS2-%s> %s' % (t, msg))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ResolvePhysicalPath(self, urlPath) :
|
||||
if not isinstance(urlPath, str) or len(urlPath) == 0 :
|
||||
raise ValueError('"urlPath" must be a not empty string.')
|
||||
try :
|
||||
physPath = self._rootPath + urlPath.replace('..', '/')
|
||||
if physPath.endswith('/') :
|
||||
physPath = physPath[:-1]
|
||||
if MicroWebSrv2._physPathIsDir(physPath) :
|
||||
for filename in MicroWebSrv2._DEFAULT_PAGES :
|
||||
p = physPath + '/' + filename
|
||||
if MicroWebSrv2._physPathExists(p) :
|
||||
return p
|
||||
return physPath
|
||||
except :
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onSrvClientAccepted(self, xAsyncTCPServer, xAsyncTCPClient) :
|
||||
if self._sslContext :
|
||||
try :
|
||||
xAsyncTCPClient.StartSSLContext( sslContext = self._sslContext,
|
||||
serverSide = True )
|
||||
except :
|
||||
self.Log( 'SSL connection failed from %s:%s.'
|
||||
% xAsyncTCPClient.CliAddr,
|
||||
MicroWebSrv2.DEBUG )
|
||||
xAsyncTCPClient.Close()
|
||||
return
|
||||
HttpRequest(self, xAsyncTCPClient)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onSrvClosed(self, xAsyncTCPServer, closedReason) :
|
||||
self.Log('Server %s:%s closed.' % self._bindAddr, MicroWebSrv2.INFO)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _validateChangeConf(self, name='Configuration') :
|
||||
if self._xasSrv :
|
||||
raise MicroWebSrv2Exception('%s cannot be changed while the server is running.' % name)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def EnableSSL(self, certFile, keyFile, caFile=None) :
|
||||
import ssl
|
||||
if not hasattr(ssl, 'SSLContext') :
|
||||
raise MicroWebSrv2Exception('Unable to use SSL (implementation not supported).')
|
||||
if not isinstance(certFile, str) or len(certFile) == 0 :
|
||||
raise ValueError('"certFile" must be a not empty string.')
|
||||
if not isinstance(keyFile, str) or len(keyFile) == 0 :
|
||||
raise ValueError('"keyFile" must be a not empty string.')
|
||||
if caFile is not None and not isinstance(caFile, str) :
|
||||
raise ValueError('"caFile" must be a string or None.')
|
||||
self._validateChangeConf()
|
||||
try :
|
||||
ctx = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH,
|
||||
cafile = caFile )
|
||||
except :
|
||||
raise ValueError('"caFile" must indicate a valid PEM file.')
|
||||
try :
|
||||
ctx.load_cert_chain(certfile=certFile, keyfile=keyFile)
|
||||
except :
|
||||
raise ValueError('"certFile" and "keyFile" must indicate the valid certificate and key files.')
|
||||
self._sslContext = ctx
|
||||
if self._bindAddr[1] == 80 :
|
||||
self._bindAddr = (self._bindAddr[0], 443)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def DisableSSL(self) :
|
||||
self._validateChangeConf()
|
||||
self._sslContext = None
|
||||
if self._bindAddr[1] == 443 :
|
||||
self._bindAddr = (self._bindAddr[0], 80)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetEmbeddedConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 8
|
||||
self._slotsCount = 16
|
||||
self._slotsSize = 1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 16*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetLightConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 64
|
||||
self._slotsCount = 128
|
||||
self._slotsSize = 1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 512*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetNormalConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 256
|
||||
self._slotsCount = 512
|
||||
self._slotsSize = 4*1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 2*1024*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetLargeConfig(self) :
|
||||
self._validateChangeConf()
|
||||
self._backlog = 512
|
||||
self._slotsCount = 2048
|
||||
self._slotsSize = 16*1024
|
||||
self._keepAlloc = True
|
||||
self._maxContentLen = 8*1024*1024
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsRunning(self) :
|
||||
return ( self._xasPool is not None and \
|
||||
self._xasPool.WaitEventsProcessing and \
|
||||
self._xasSrv is not None )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ConnQueueCapacity(self) :
|
||||
return self._backlog
|
||||
|
||||
@ConnQueueCapacity.setter
|
||||
def ConnQueueCapacity(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"ConnQueueCapacity" must be a positive integer.')
|
||||
self._validateChangeConf('"ConnQueueCapacity"')
|
||||
self._backlog = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def BufferSlotsCount(self) :
|
||||
return self._slotsCount
|
||||
|
||||
@BufferSlotsCount.setter
|
||||
def BufferSlotsCount(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"BufferSlotsCount" must be a positive integer.')
|
||||
self._validateChangeConf('"BufferSlotsCount"')
|
||||
self._slotsCount = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def BufferSlotSize(self) :
|
||||
return self._slotsSize
|
||||
|
||||
@BufferSlotSize.setter
|
||||
def BufferSlotSize(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"BufferSlotSize" must be a positive integer.')
|
||||
self._validateChangeConf('"BufferSlotSize"')
|
||||
self._slotsSize = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def KeepAllocBufferSlots(self) :
|
||||
return self._keepAlloc
|
||||
|
||||
@KeepAllocBufferSlots.setter
|
||||
def KeepAllocBufferSlots(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"KeepAllocBufferSlots" must be a boolean.')
|
||||
self._validateChangeConf('"KeepAllocBufferSlots"')
|
||||
self._keepAlloc = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def MaxRequestContentLength(self) :
|
||||
return self._maxContentLen
|
||||
|
||||
@MaxRequestContentLength.setter
|
||||
def MaxRequestContentLength(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"MaxRequestContentLength" must be a positive integer.')
|
||||
self._maxContentLen = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def BindAddress(self) :
|
||||
return self._bindAddr
|
||||
|
||||
@BindAddress.setter
|
||||
def BindAddress(self, value) :
|
||||
if not value or len(value) != 2 or \
|
||||
not isinstance(value[0], str) or \
|
||||
not isinstance(value[1], int) :
|
||||
raise ValueError('"BindAddress" must be a tuple of (ipAddr, tcpPort).')
|
||||
if value[1] < 1 or value[1] > 65535 :
|
||||
raise ValueError('"BindAddress" has an incorrect port number.')
|
||||
self._validateChangeConf('"BindAddress"')
|
||||
self._bindAddr = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsSSLEnabled(self) :
|
||||
return (self._sslContext is not None)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def RootPath(self) :
|
||||
return self._rootPath
|
||||
|
||||
@RootPath.setter
|
||||
def RootPath(self, value) :
|
||||
if not isinstance(value, str) or len(value) == 0 :
|
||||
raise ValueError('"RootPath" must be a not empty string.')
|
||||
self._validateChangeConf('"RootPath"')
|
||||
self._rootPath = (value[:-1] if value.endswith('/') else value)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def RequestsTimeoutSec(self) :
|
||||
return self._timeoutSec
|
||||
|
||||
@RequestsTimeoutSec.setter
|
||||
def RequestsTimeoutSec(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"RequestsTimeoutSec" must be a positive integer.')
|
||||
self._timeoutSec = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def NotFoundURL(self) :
|
||||
return self._notFoundURL
|
||||
|
||||
@NotFoundURL.setter
|
||||
def NotFoundURL(self, value) :
|
||||
if value is not None and not isinstance(value, str) :
|
||||
raise ValueError('"NotFoundURL" must be a string or None.')
|
||||
self._notFoundURL = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def AllowAllOrigins(self) :
|
||||
return self._allowAllOrigins
|
||||
|
||||
@AllowAllOrigins.setter
|
||||
def AllowAllOrigins(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"AllowAllOrigins" must be a boolean.')
|
||||
self._allowAllOrigins = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def CORSAllowAll(self) :
|
||||
return self._corsAllowAll
|
||||
|
||||
@CORSAllowAll.setter
|
||||
def CORSAllowAll(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"CORSAllowAll" must be a boolean.')
|
||||
self._corsAllowAll = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnLogging(self) :
|
||||
return self._onLogging
|
||||
|
||||
@OnLogging.setter
|
||||
def OnLogging(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnLogging" must be a function.')
|
||||
self._onLogging = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,394 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from os import stat
|
||||
import re
|
||||
|
||||
# ============================================================================
|
||||
# ===( MicroWebSrv2 : PyhtmlTemplate Module )=================================
|
||||
# ============================================================================
|
||||
|
||||
class PyhtmlTemplate :
|
||||
|
||||
_CODE_CONTENT_DEBUG = """\
|
||||
<html>
|
||||
<head>
|
||||
<title>MicroWebSrv2</title>
|
||||
</head>
|
||||
<body style="font-family: Verdana; background-color: Black; color: White;">
|
||||
<h2>MicroWebSrv2 - [500] Internal Server Error</h2>
|
||||
<div style="margin: 20px;">
|
||||
<h3>PyhtmlTemplate Module Debug</h3>
|
||||
<div style="padding: 15px; background-color: Crimson;">
|
||||
Exception in %(path)s<br />
|
||||
%(message)s
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self) :
|
||||
self._showDebug = False
|
||||
self._pyGlobalVars = { }
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnRequest(self, microWebSrv2, request) :
|
||||
if (request.Method == 'GET' or request.Method == 'HEAD') and \
|
||||
request.Path.lower().endswith('.pyhtml') :
|
||||
filepath = microWebSrv2.ResolvePhysicalPath(request.Path)
|
||||
self.ReturnTemplate(microWebSrv2, request, filepath)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def ReturnTemplate(self, microWebSrv2, request, filepath):
|
||||
if not filepath:
|
||||
request.Response.ReturnNotFound()
|
||||
return
|
||||
|
||||
try :
|
||||
with open(filepath, 'r') as file :
|
||||
code = file.read()
|
||||
except :
|
||||
request.Response.ReturnForbidden()
|
||||
return
|
||||
|
||||
try :
|
||||
self._pyGlobalVars['Request'] = request
|
||||
codeTemplate = CodeTemplate(code, microWebSrv2.HTMLEscape)
|
||||
content = codeTemplate.Execute(self._pyGlobalVars, None)
|
||||
request.Response.ReturnOk(content)
|
||||
|
||||
except Exception as ex :
|
||||
microWebSrv2.Log( 'Exception raised from pyhtml template file "%s": %s' % (filepath, ex),
|
||||
microWebSrv2.ERROR )
|
||||
if self._showDebug :
|
||||
request.Response.Return( 500,
|
||||
PyhtmlTemplate._CODE_CONTENT_DEBUG
|
||||
% { 'path' : filepath,
|
||||
'message' : ex } )
|
||||
else :
|
||||
request.Response.ReturnInternalServerError()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SetGlobalVar(self, globalVarName, globalVar) :
|
||||
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
|
||||
raise ValueError('"globalVarName" must be a not empty string.')
|
||||
self._pyGlobalVars[globalVarName] = globalVar
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def GetGlobalVar(self, globalVarName) :
|
||||
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
|
||||
raise ValueError('"globalVarName" must be a not empty string.')
|
||||
try :
|
||||
return self._pyGlobalVars[globalVarName]
|
||||
except :
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def ShowDebug(self) :
|
||||
return self._showDebug
|
||||
|
||||
@ShowDebug.setter
|
||||
def ShowDebug(self, value) :
|
||||
if not isinstance(value, bool) :
|
||||
raise ValueError('"ShowDebug" must be a boolean.')
|
||||
self._showDebug = value
|
||||
|
||||
# ============================================================================
|
||||
# ===( CodeTemplate )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
class CodeTemplateException(Exception) :
|
||||
pass
|
||||
|
||||
class CodeTemplate :
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
TOKEN_OPEN = '{{'
|
||||
TOKEN_CLOSE = '}}'
|
||||
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
|
||||
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
|
||||
|
||||
INSTRUCTION_PYTHON = 'py'
|
||||
INSTRUCTION_IF = 'if'
|
||||
INSTRUCTION_ELIF = 'elif'
|
||||
INSTRUCTION_ELSE = 'else'
|
||||
INSTRUCTION_FOR = 'for'
|
||||
INSTRUCTION_END = 'end'
|
||||
|
||||
RE_IDENTIFIER = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, code, escapeStrFunc=None) :
|
||||
self._code = code
|
||||
self._escapeStrFunc = escapeStrFunc
|
||||
self._pos = 0
|
||||
self._endPos = len(code)-1
|
||||
self._line = 1
|
||||
self._pyGlobalVars = { }
|
||||
self._pyLocalVars = { }
|
||||
self._rendered = ''
|
||||
self._instructions = {
|
||||
CodeTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
|
||||
CodeTemplate.INSTRUCTION_IF : self._processInstructionIF,
|
||||
CodeTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
|
||||
CodeTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
|
||||
CodeTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
|
||||
CodeTemplate.INSTRUCTION_END : self._processInstructionEND
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
|
||||
try :
|
||||
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
|
||||
return None
|
||||
except Exception as ex :
|
||||
return str(ex)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
|
||||
try :
|
||||
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
|
||||
return self._rendered
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException(str(ex))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
|
||||
self._pos = 0
|
||||
self._line = 1
|
||||
self._pyGlobalVars = (pyGlobalVars if isinstance(pyGlobalVars, dict) else { })
|
||||
self._pyLocalVars = (pyLocalVars if isinstance(pyLocalVars, dict) else { })
|
||||
self._rendered = ''
|
||||
self._pyGlobalVars['print'] = self._renderingPrint
|
||||
newTokenToProcess = self._parseBloc(execute)
|
||||
if newTokenToProcess is not None :
|
||||
raise CodeTemplateException( '"%s" instruction is not valid here (line %s)'
|
||||
% (newTokenToProcess, self._line) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _parseBloc(self, execute) :
|
||||
while True :
|
||||
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
|
||||
end = (idx < 0)
|
||||
if end :
|
||||
idx = self._endPos+1
|
||||
code = self._code[self._pos:idx]
|
||||
self._line += code.count('\n')
|
||||
if execute :
|
||||
self._rendered += code
|
||||
if end :
|
||||
self._pos = idx
|
||||
return None
|
||||
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
|
||||
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
|
||||
if idx < 0 :
|
||||
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
|
||||
tokenContent = self._code[self._pos:idx].strip()
|
||||
self._line += tokenContent.count('\n')
|
||||
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
|
||||
newTokenToProcess = self._processToken(tokenContent, execute)
|
||||
if newTokenToProcess is not None :
|
||||
return newTokenToProcess
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _renderingPrint(self, s) :
|
||||
self._rendered += str(s)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processToken(self, tokenContent, execute) :
|
||||
parts = tokenContent.split(' ', 1)
|
||||
instructName = parts[0].strip()
|
||||
instructBody = parts[1].strip() if len(parts) > 1 else None
|
||||
if len(instructName) == 0 :
|
||||
raise CodeTemplateException( '"%s %s" : instruction is missing (line %s)'
|
||||
% (CodeTemplate.TOKEN_OPEN, CodeTemplate.TOKEN_CLOSE, self._line) )
|
||||
newTokenToProcess = None
|
||||
if instructName in self._instructions :
|
||||
newTokenToProcess = self._instructions[instructName](instructBody, execute)
|
||||
elif execute :
|
||||
try :
|
||||
ret = eval( tokenContent,
|
||||
self._pyGlobalVars,
|
||||
self._pyLocalVars )
|
||||
if ret is not None :
|
||||
if (self._escapeStrFunc is not None) :
|
||||
self._rendered += self._escapeStrFunc(str(ret))
|
||||
else :
|
||||
self._rendered += str(ret)
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
|
||||
return newTokenToProcess
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionPYTHON(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_PYTHON, self._line) )
|
||||
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
|
||||
if idx < 0 :
|
||||
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_OPEN)
|
||||
pyCode = self._code[self._pos:idx]
|
||||
self._line += pyCode.count('\n')
|
||||
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
|
||||
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
|
||||
if idx < 0 :
|
||||
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
|
||||
tokenContent = self._code[self._pos:idx].strip()
|
||||
self._line += tokenContent.count('\n')
|
||||
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
|
||||
if tokenContent != CodeTemplate.INSTRUCTION_END :
|
||||
raise CodeTemplateException( '"%s" is a bad instruction in a python bloc (line %s)'
|
||||
% (tokenContent, self._line) )
|
||||
if execute :
|
||||
lines = pyCode.split('\n')
|
||||
indent = ''
|
||||
for line in lines :
|
||||
if len(line.strip()) > 0 :
|
||||
for c in line :
|
||||
if c == ' ' or c == '\t' :
|
||||
indent += c
|
||||
else :
|
||||
break
|
||||
break
|
||||
indentLen = len(indent)
|
||||
for i in range(len(lines)) :
|
||||
if lines[i].startswith(indent) :
|
||||
lines[i] = lines[i][indentLen:] + '\n'
|
||||
else :
|
||||
lines[i] += '\n'
|
||||
pyCode = ''.join(lines)
|
||||
try :
|
||||
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionIF(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
if execute :
|
||||
try :
|
||||
if (' ' not in instructionBody) and \
|
||||
('=' not in instructionBody) and \
|
||||
('<' not in instructionBody) and \
|
||||
('>' not in instructionBody) and \
|
||||
(instructionBody not in self._pyGlobalVars) and \
|
||||
(instructionBody not in self._pyLocalVars):
|
||||
result = False
|
||||
else:
|
||||
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
|
||||
except Exception as ex :
|
||||
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
|
||||
else :
|
||||
result = False
|
||||
newTokenToProcess = self._parseBloc(execute and result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELSE :
|
||||
newTokenToProcess = self._parseBloc(execute and not result)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise CodeTemplateException( '"%s" instruction waited (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELIF :
|
||||
self._processInstructionIF(self._elifInstructionBody, execute and not result)
|
||||
return None
|
||||
raise CodeTemplateException( '"%s" instruction waited (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_IF, self._line) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELIF(self, instructionBody, execute) :
|
||||
if instructionBody is None :
|
||||
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_ELIF, self._line) )
|
||||
self._elifInstructionBody = instructionBody
|
||||
return CodeTemplate.INSTRUCTION_ELIF
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionELSE(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_ELSE, self._line) )
|
||||
return CodeTemplate.INSTRUCTION_ELSE
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionFOR(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
parts = instructionBody.split(' ', 1)
|
||||
identifier = parts[0].strip()
|
||||
if CodeTemplate.RE_IDENTIFIER.match(identifier) is not None and len(parts) > 1 :
|
||||
parts = parts[1].strip().split(' ', 1)
|
||||
if parts[0] == 'in' and len(parts) > 1 :
|
||||
expression = parts[1].strip()
|
||||
newTokenToProcess = None
|
||||
beforePos = self._pos
|
||||
if execute :
|
||||
try :
|
||||
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
|
||||
except :
|
||||
raise CodeTemplateException('%s (line %s)' % (str(expression), self._line))
|
||||
if execute and len(result) > 0 :
|
||||
for x in result :
|
||||
self._pyLocalVars[identifier] = x
|
||||
self._pos = beforePos
|
||||
newTokenToProcess = self._parseBloc(True)
|
||||
if newTokenToProcess != CodeTemplate.INSTRUCTION_END :
|
||||
break
|
||||
else :
|
||||
newTokenToProcess = self._parseBloc(False)
|
||||
if newTokenToProcess is not None :
|
||||
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
|
||||
return None
|
||||
raise CodeTemplateException( '"%s" instruction waited (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
raise CodeTemplateException( '"%s %s" is an invalid syntax'
|
||||
% (CodeTemplate.INSTRUCTION_FOR, instructionBody) )
|
||||
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_FOR, self._line) )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _processInstructionEND(self, instructionBody, execute) :
|
||||
if instructionBody is not None :
|
||||
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
|
||||
% (CodeTemplate.INSTRUCTION_END, self._line) )
|
||||
return CodeTemplate.INSTRUCTION_END
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,477 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
from hashlib import sha1
|
||||
from binascii import b2a_base64
|
||||
from struct import pack
|
||||
|
||||
# ============================================================================
|
||||
# ===( MicroWebSrv2 : WebSockets Module )=====================================
|
||||
# ============================================================================
|
||||
|
||||
class WebSockets :
|
||||
|
||||
_PROTOCOL_VERSION = 13
|
||||
_HANDSHAKE_SIGN = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self) :
|
||||
self._onWebSocketProtocol = None
|
||||
self._onWebSocketAccepted = None
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnRequest(self, microWebSrv2, request) :
|
||||
if request.IsUpgrade and request.Upgrade.lower() == 'websocket' :
|
||||
ver = request.GetHeader('Sec-Websocket-Version')
|
||||
if ver == str(WebSockets._PROTOCOL_VERSION) :
|
||||
response = request.Response
|
||||
key = request.GetHeader('Sec-Websocket-Key')
|
||||
if key :
|
||||
try :
|
||||
key += WebSockets._HANDSHAKE_SIGN
|
||||
sec = sha1(key.encode()).digest()
|
||||
sec = b2a_base64(sec).decode().strip()
|
||||
protocols = request.GetHeader('Sec-WebSocket-Protocol')
|
||||
response.SetHeader('Sec-WebSocket-Accept', sec)
|
||||
if protocols and self._onWebSocketProtocol :
|
||||
protocols = [x.strip() for x in protocols.split(',')]
|
||||
try :
|
||||
proto = self._onWebSocketProtocol(microWebSrv2, protocols)
|
||||
except Exception as ex :
|
||||
microWebSrv2.Log( 'Exception raised from "WebSockets.OnWebSocketProtocol" handler: %s' % ex,
|
||||
microWebSrv2.ERROR )
|
||||
raise ex
|
||||
if proto in protocols :
|
||||
response.SetHeader('Sec-WebSocket-Protocol', proto)
|
||||
response.SwitchingProtocols('websocket')
|
||||
WebSocket(self, microWebSrv2, request)
|
||||
except :
|
||||
response.ReturnInternalServerError()
|
||||
else :
|
||||
response.ReturnBadRequest()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnWebSocketProtocol(self) :
|
||||
return self._onWebSocketProtocol
|
||||
|
||||
@OnWebSocketProtocol.setter
|
||||
def OnWebSocketProtocol(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnWebSocketProtocol" must be a function.')
|
||||
self._onWebSocketProtocol = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnWebSocketAccepted(self) :
|
||||
return self._onWebSocketAccepted
|
||||
|
||||
@OnWebSocketAccepted.setter
|
||||
def OnWebSocketAccepted(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnWebSocketAccepted" must be a function.')
|
||||
self._onWebSocketAccepted = value
|
||||
|
||||
# ============================================================================
|
||||
# ===( WebSocket )============================================================
|
||||
# ============================================================================
|
||||
|
||||
class WebSocket :
|
||||
|
||||
_OP_FRAME_CONT = 0x00
|
||||
_OP_FRAME_TEXT = 0x01
|
||||
_OP_FRAME_BIN = 0x02
|
||||
_OP_FRAME_CLOSE = 0x08
|
||||
_OP_FRAME_PING = 0x09
|
||||
_OP_FRAME_PONG = 0x0A
|
||||
|
||||
_MSG_TYPE_TEXT = 0x01
|
||||
_MSG_TYPE_BIN = 0x02
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def __init__(self, wsMod, mws2, request) :
|
||||
|
||||
self._mws2 = mws2
|
||||
self._request = request
|
||||
self._xasCli = request.XAsyncTCPClient
|
||||
self._currentMsgType = None
|
||||
self._currentMsgData = None
|
||||
self._isClosed = False
|
||||
self._waitFrameTimeoutSec = 300
|
||||
self._maxRecvMsgLen = mws2.MaxRequestContentLength
|
||||
self._onTextMsg = None
|
||||
self._onBinMsg = None
|
||||
self._onClosed = None
|
||||
|
||||
onWSAccepted = wsMod.OnWebSocketAccepted
|
||||
|
||||
self._mws2.Log( '%sWebSocket %s from %s:%s.'
|
||||
% ( ('SSL-' if request.IsSSL else ''),
|
||||
'accepted' if onWSAccepted else 'denied',
|
||||
self._xasCli.CliAddr[0],
|
||||
self._xasCli.CliAddr[1] ),
|
||||
self._mws2.INFO )
|
||||
|
||||
if not onWSAccepted :
|
||||
self._close(1001, 'Going away...')
|
||||
return
|
||||
|
||||
self._xasCli.OnClosed = self._onXAsCliClosed
|
||||
|
||||
try :
|
||||
onWSAccepted(self._mws2, self)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSockets.OnWebSocketAccepted" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
self._close(1011, 'Unexpected error')
|
||||
return
|
||||
|
||||
self._waitFrame()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _recvData(self, onRecv, size=None) :
|
||||
self._xasCli.AsyncRecvData( size = size,
|
||||
onDataRecv = onRecv,
|
||||
timeoutSec = self._mws2.RequestsTimeoutSec )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _onXAsCliClosed(self, xasCli, closedReason) :
|
||||
self._isClosed = True
|
||||
if self._onClosed :
|
||||
try :
|
||||
self._onClosed(self)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSocket.OnClosed" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _waitFrame(self) :
|
||||
|
||||
def onHdrStartingRecv(xasCli, data, arg) :
|
||||
|
||||
fin = data[0] & 0x80 > 0
|
||||
opcode = data[0] & 0x0F
|
||||
masked = data[1] & 0x80 > 0
|
||||
length = data[1] & 0x7F
|
||||
|
||||
# Control frame ?
|
||||
isCtrlFrame = ( opcode != WebSocket._OP_FRAME_TEXT and \
|
||||
opcode != WebSocket._OP_FRAME_BIN and \
|
||||
opcode != WebSocket._OP_FRAME_CONT )
|
||||
|
||||
if ( isCtrlFrame and not fin ) \
|
||||
or \
|
||||
( opcode == WebSocket._OP_FRAME_CONT and \
|
||||
not self._currentMsgType ) \
|
||||
or \
|
||||
( self._currentMsgType and \
|
||||
( opcode == WebSocket._OP_FRAME_TEXT or \
|
||||
opcode == WebSocket._OP_FRAME_BIN ) ) :
|
||||
# Bad frame in the context,
|
||||
self._close(1002, 'Protocol error (bad frame in the context)')
|
||||
return
|
||||
|
||||
def endOfHeader(dataLen, maskingKey) :
|
||||
|
||||
def onPayloadDataRecv(xasCli, data, arg) :
|
||||
|
||||
if maskingKey :
|
||||
for i in range(dataLen) :
|
||||
data[i] ^= maskingKey[i%4]
|
||||
|
||||
if self._currentMsgData :
|
||||
try :
|
||||
self._currentMsgData += data
|
||||
except :
|
||||
# Frame is too large for memory allocation,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
return
|
||||
else :
|
||||
self._currentMsgData = data
|
||||
|
||||
if fin :
|
||||
# Frame is fully received,
|
||||
if self._currentMsgType == WebSocket._MSG_TYPE_TEXT :
|
||||
# Text frame,
|
||||
if self._onTextMsg :
|
||||
try :
|
||||
msg = bytes(self._currentMsgData).decode('UTF-8')
|
||||
try :
|
||||
self._onTextMsg(self, msg)
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSocket.OnTextMessage" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
self._close(1011, 'Unexpected error while processing text message')
|
||||
return
|
||||
except :
|
||||
self._mws2.Log( 'Error during UTF-8 decoding of websocket text message.',
|
||||
self._mws2.WARNING )
|
||||
self._close(1007, 'Error to decode UTF-8 text message')
|
||||
return
|
||||
else :
|
||||
self._close(1003, 'Text messages are not implemented')
|
||||
return
|
||||
elif self._currentMsgType == WebSocket._MSG_TYPE_BIN :
|
||||
# Binary frame,
|
||||
if self._onBinMsg :
|
||||
try :
|
||||
self._onBinMsg(self, bytes(self._currentMsgData))
|
||||
except Exception as ex :
|
||||
self._mws2.Log( 'Exception raised from "WebSocket.OnBinaryMessage" handler: %s' % ex,
|
||||
self._mws2.ERROR )
|
||||
self._close(1011, 'Unexpected error while processing binary message')
|
||||
return
|
||||
else :
|
||||
self._close(1003, 'Binary messages are not implemented')
|
||||
return
|
||||
|
||||
self._currentMsgType = None
|
||||
self._currentMsgData = None
|
||||
|
||||
self._waitFrame()
|
||||
|
||||
# - End of onPayloadDataRecv -
|
||||
|
||||
if not isCtrlFrame :
|
||||
# Message frame or continuation frame,
|
||||
if self._maxRecvMsgLen :
|
||||
l = dataLen
|
||||
if self._currentMsgData :
|
||||
l += len(self._currentMsgData)
|
||||
if l > self._maxRecvMsgLen :
|
||||
# Message length exceeds the defined limit,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
return
|
||||
if opcode == WebSocket._OP_FRAME_TEXT :
|
||||
self._currentMsgType = WebSocket._MSG_TYPE_TEXT
|
||||
elif opcode == WebSocket._OP_FRAME_BIN :
|
||||
self._currentMsgType = WebSocket._MSG_TYPE_BIN
|
||||
try :
|
||||
self._recvData(onPayloadDataRecv, dataLen)
|
||||
except :
|
||||
# Frame is too large for memory allocation,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
elif opcode == WebSocket._OP_FRAME_PING :
|
||||
# Ping control frame,
|
||||
if dataLen > 0 :
|
||||
def onPingDataRecv(xasCli, data, arg) :
|
||||
data = bytearray(data)
|
||||
self._sendFrame(WebSocket._OP_FRAME_PONG, data)
|
||||
self._waitFrame()
|
||||
self._recvData(onPingDataRecv, dataLen)
|
||||
else :
|
||||
self._sendFrame(WebSocket._OP_FRAME_PONG)
|
||||
self._waitFrame()
|
||||
elif opcode == WebSocket._OP_FRAME_PONG :
|
||||
# Pong control frame,
|
||||
if dataLen > 0 :
|
||||
def onPongDataRecv(xasCli, data, arg) :
|
||||
self._waitFrame()
|
||||
self._recvData(onPongDataRecv, dataLen)
|
||||
else :
|
||||
self._waitFrame()
|
||||
elif opcode == WebSocket._OP_FRAME_CLOSE :
|
||||
# Close control frame,')
|
||||
if dataLen > 0 :
|
||||
def onCloseDataRecv(xasCli, data, arg) :
|
||||
self._close()
|
||||
self._recvData(onCloseDataRecv, dataLen)
|
||||
else :
|
||||
self._close()
|
||||
else :
|
||||
# Unknown frame type,
|
||||
self._close(1002, 'Protocol error (bad opcode)')
|
||||
|
||||
# - End of endOfHeader -
|
||||
|
||||
def getMaskingKey(dataLen) :
|
||||
|
||||
if masked :
|
||||
# Frame is masked by the next 4 bytes key,
|
||||
def onMaskingKeyRecv(xasCli, data, arg) :
|
||||
endOfHeader(dataLen=dataLen, maskingKey=bytes(data))
|
||||
self._recvData(onMaskingKeyRecv, 4)
|
||||
else :
|
||||
# Frame is not masked,
|
||||
endOfHeader(dataLen=dataLen, maskingKey=None)
|
||||
|
||||
# - End of getMaskingKey -
|
||||
|
||||
if length == 0 and not isCtrlFrame :
|
||||
# Bad frame for a no control frame without payload data,
|
||||
self._close(1002, 'Protocol error (payload data required)')
|
||||
elif length <= 0x7D :
|
||||
# Frame length <= 0x7D,
|
||||
getMaskingKey(dataLen=length)
|
||||
elif isCtrlFrame :
|
||||
# Bad frame for length of control frame > 0x7D,
|
||||
self._close(1002, 'Protocol error (bad control frame length)')
|
||||
elif length == 0x7E :
|
||||
# Frame length is encoded on next 16 bits,
|
||||
def onLenExt1Recv(xasCli, data, arg) :
|
||||
length = (data[0] << 8) + data[1]
|
||||
if length < 0x7E :
|
||||
# Bad frame for 16 bits length < 0x7E,
|
||||
self._close(1002, 'Protocol error (bad length encoding)')
|
||||
else :
|
||||
getMaskingKey(dataLen=length)
|
||||
self._recvData(onLenExt1Recv, 2)
|
||||
else :
|
||||
# Frame length is encoded on next 64 bits.
|
||||
# It's too large and not implemented,
|
||||
self._close(1009, 'Frame is too large to be processed')
|
||||
|
||||
# - End of onHdrStartingRecv -
|
||||
|
||||
self._xasCli.AsyncRecvData( size = 2,
|
||||
onDataRecv = onHdrStartingRecv,
|
||||
timeoutSec = self._waitFrameTimeoutSec )
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _sendFrame(self, opcode, data=None, fin=True) :
|
||||
try :
|
||||
if opcode >= 0x00 and opcode <= 0x0F :
|
||||
length = len(data) if data else 0
|
||||
if length <= 0xFFFF :
|
||||
data = bytes([ (opcode | 0x80) if fin else opcode ] ) \
|
||||
+ bytes([ length if length <= 0x7D else 0x7E ] ) \
|
||||
+ (pack('>H', length) if length >= 0x7E else b'') \
|
||||
+ (bytes(data) if data else b'')
|
||||
return self._xasCli.AsyncSendData(data)
|
||||
except :
|
||||
pass
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def _close(self, statusCode=None, reason=None, waitCloseFrame=False) :
|
||||
if not self._isClosed :
|
||||
if statusCode :
|
||||
data = pack('>H', statusCode)
|
||||
if reason :
|
||||
data += reason.encode('UTF-8')
|
||||
else :
|
||||
data = None
|
||||
self._sendFrame(WebSocket._OP_FRAME_CLOSE, data)
|
||||
self._isClosed = True
|
||||
if waitCloseFrame :
|
||||
return
|
||||
self._xasCli.Close()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SendTextMessage(self, msg) :
|
||||
if not isinstance(msg, str) or len(msg) == 0 :
|
||||
raise ValueError('"msg" must be a not empty string.')
|
||||
if not self._isClosed :
|
||||
try :
|
||||
msg = msg.encode('UTF-8')
|
||||
except :
|
||||
return False
|
||||
return self._sendFrame(WebSocket._OP_FRAME_TEXT, msg)
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def SendBinaryMessage(self, msg) :
|
||||
try :
|
||||
bytes([msg[0]])
|
||||
except :
|
||||
raise ValueError('"msg" must be a not empty bytes object.')
|
||||
if not self._isClosed :
|
||||
return self._sendFrame(WebSocket._OP_FRAME_BIN, msg)
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def Close(self) :
|
||||
if not self._isClosed :
|
||||
self._close(1000, 'Normal closure', waitCloseFrame=True)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def Request(self) :
|
||||
return self._request
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def IsClosed(self) :
|
||||
return self._isClosed
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def WaitFrameTimeoutSec(self) :
|
||||
return self._waitFrameTimeoutSec
|
||||
|
||||
@WaitFrameTimeoutSec.setter
|
||||
def WaitFrameTimeoutSec(self, value) :
|
||||
if not isinstance(value, int) or value <= 0 :
|
||||
raise ValueError('"WaitFrameTimeoutSec" must be a positive integer.')
|
||||
self._waitFrameTimeoutSec = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def MaxRecvMessageLength(self) :
|
||||
return self._maxRecvMsgLen
|
||||
|
||||
@MaxRecvMessageLength.setter
|
||||
def MaxRecvMessageLength(self, value) :
|
||||
if value is not None and (not isinstance(value, int) or value < 125) :
|
||||
raise ValueError('"MaxRecvMessageLength" must be an integer >= 125 or None.')
|
||||
self._maxRecvMsgLen = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnTextMessage(self) :
|
||||
return self._onTextMsg
|
||||
|
||||
@OnTextMessage.setter
|
||||
def OnTextMessage(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnTextMessage" must be a function.')
|
||||
self._onTextMsg = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnBinaryMessage(self) :
|
||||
return self._onBinMsg
|
||||
|
||||
@OnBinaryMessage.setter
|
||||
def OnBinaryMessage(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnBinaryMessage" must be a function.')
|
||||
self._onBinMsg = value
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def OnClosed(self) :
|
||||
return self._onClosed
|
||||
|
||||
@OnClosed.setter
|
||||
def OnClosed(self, value) :
|
||||
if type(value) is not type(lambda x:x) :
|
||||
raise ValueError('"OnClosed" must be a function.')
|
||||
self._onClosed = value
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,184 @@
|
||||
|
||||
"""
|
||||
The MIT License (MIT)
|
||||
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# ============================================================================
|
||||
# ===( @WebRoute decorator )==================================================
|
||||
# ============================================================================
|
||||
|
||||
def WebRoute(method=None, routePath=None, name=None) :
|
||||
|
||||
if type(method) is type(lambda x:x) and not routePath :
|
||||
raise ValueError('[@WebRoute] arguments are required for this decorator.')
|
||||
|
||||
def decorated(handler) :
|
||||
RegisterRoute(handler, method, routePath, name)
|
||||
s = (' (%s)' % name) if name else ''
|
||||
print(' + [@WebRoute] %s %s' % (method, routePath) + s)
|
||||
return handler
|
||||
|
||||
return decorated
|
||||
|
||||
# ============================================================================
|
||||
# ===( RegisterResult )=======================================================
|
||||
# ============================================================================
|
||||
|
||||
def RegisterRoute(handler, method, routePath, name=None) :
|
||||
if type(handler) is not type(lambda x:x) :
|
||||
raise ValueError('"handler" must be a function.')
|
||||
if not isinstance(method, str) or len(method) == 0 :
|
||||
raise ValueError('"method" requires a not empty string.')
|
||||
if not isinstance(routePath, str) or len(routePath) == 0 :
|
||||
raise ValueError('"routePath" requires a not empty string.')
|
||||
if routePath[0] != '/' :
|
||||
raise ValueError('"routePath" must start with a "/".')
|
||||
if name is not None and not isinstance(name, str) :
|
||||
raise ValueError('"name" must be a string or None.')
|
||||
method = method.upper()
|
||||
if len(routePath) > 1 and routePath.endswith('/') :
|
||||
routePath = routePath[:-1]
|
||||
# Route -> '/users/<uID>/addresses/<addrID>/test/<anotherID>'
|
||||
# Regex -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
|
||||
# Args -> ['uID', 'addrID', 'anotherID']
|
||||
argNames = [ ]
|
||||
regex = ''
|
||||
try :
|
||||
for i, part in enumerate(routePath.lower().split('/')) :
|
||||
if i > 0 :
|
||||
if part.startswith('<') and part.endswith('>') :
|
||||
argName = part[1:-1]
|
||||
if not argName :
|
||||
raise Exception
|
||||
argNames.append(argName)
|
||||
regex += '/([\\w.]*)'
|
||||
else :
|
||||
regex += '/' + part
|
||||
regex = re.compile(regex + '$')
|
||||
except :
|
||||
raise ValueError('Bad route path: "%s".' % routePath)
|
||||
for regRoute in _registeredRoutes :
|
||||
if regRoute.Method == method and regRoute.Regex == regex :
|
||||
raise ValueError('Duplicated route: "%s".' % routePath)
|
||||
regRoute = _registeredRoute(handler, method, routePath, name, regex, argNames)
|
||||
_registeredRoutes.append(regRoute)
|
||||
|
||||
# ============================================================================
|
||||
# ===( ResolveRoute )=========================================================
|
||||
# ============================================================================
|
||||
|
||||
def ResolveRoute(method, path) :
|
||||
try :
|
||||
path = path.lower()
|
||||
if len(path) > 1 and path.endswith('/') :
|
||||
path = path[:-1]
|
||||
for regRoute in _registeredRoutes :
|
||||
if regRoute.Method == method :
|
||||
reMatch = regRoute.Regex.match(path)
|
||||
if reMatch :
|
||||
if not regRoute.ArgNames :
|
||||
return RouteResult(regRoute)
|
||||
args = { }
|
||||
for i, argName in enumerate(regRoute.ArgNames) :
|
||||
argValue = reMatch.group(i+1)
|
||||
try :
|
||||
argValue = int(argValue)
|
||||
except :
|
||||
pass
|
||||
args[argName] = argValue
|
||||
return RouteResult(regRoute, args)
|
||||
except :
|
||||
pass
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# ===( PathFromRoute )========================================================
|
||||
# ============================================================================
|
||||
|
||||
def PathFromRoute(routeName, routeArgs={ }) :
|
||||
if not isinstance(routeName, str) or len(routeName) == 0 :
|
||||
raise ValueError('"routeName" requires a not empty string.')
|
||||
if not isinstance(routeArgs, dict) :
|
||||
raise ValueError('"routeArgs" must be a dict.')
|
||||
for regRoute in _registeredRoutes :
|
||||
if regRoute.Name == routeName :
|
||||
path = regRoute.RoutePath
|
||||
for argName in regRoute.ArgNames :
|
||||
arg = routeArgs.get(argName, None)
|
||||
if arg is None :
|
||||
raise ValueError('"routeArgs" does not contains "%s" for route %s.' % (argName, routeName))
|
||||
path = path.replace('<%s>' % argName, str(arg))
|
||||
return path
|
||||
raise ValueError('"routeName" is not a registered route (%s).' % routeName)
|
||||
|
||||
# ============================================================================
|
||||
# ===( RouteResult )==========================================================
|
||||
# ============================================================================
|
||||
|
||||
class RouteResult :
|
||||
|
||||
def __init__(self, regRoute, args=None) :
|
||||
self._regRoute = regRoute
|
||||
self._args = args
|
||||
|
||||
def __repr__(self) :
|
||||
if self._regRoute.Name :
|
||||
return self._regRoute.Name
|
||||
return '%s %s' % (self._regRoute.Method, self._regRoute.RoutePath)
|
||||
|
||||
@property
|
||||
def Handler(self) :
|
||||
return self._regRoute.Handler
|
||||
|
||||
@property
|
||||
def Method(self) :
|
||||
return self._regRoute.Method
|
||||
|
||||
@property
|
||||
def RoutePath(self) :
|
||||
return self._regRoute.RoutePath
|
||||
|
||||
@property
|
||||
def Name(self) :
|
||||
return self._regRoute.Name
|
||||
|
||||
@property
|
||||
def Args(self) :
|
||||
return self._args
|
||||
|
||||
# ============================================================================
|
||||
# ===( Methods )==============================================================
|
||||
# ============================================================================
|
||||
|
||||
GET = 'GET'
|
||||
HEAD = 'HEAD'
|
||||
POST = 'POST'
|
||||
PUT = 'PUT'
|
||||
DELETE = 'DELETE'
|
||||
OPTIONS = 'OPTIONS'
|
||||
PATCH = 'PATCH'
|
||||
|
||||
# ============================================================================
|
||||
# ===( Private registered routes )===========================================
|
||||
# ============================================================================
|
||||
|
||||
_registeredRoutes = [ ]
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
class _registeredRoute :
|
||||
|
||||
def __init__(self, handler, method, routePath, name, regex, argNames) :
|
||||
self.Handler = handler
|
||||
self.Method = method
|
||||
self.RoutePath = routePath
|
||||
self.Name = name
|
||||
self.Regex = regex
|
||||
self.ArgNames = argNames
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDODCCAiACCQCr018O4/g/kzANBgkqhkiG9w0BAQUFADBdMQswCQYDVQQGEwJG
|
||||
UjEOMAwGA1UEBwwFUEFSSVMxDDAKBgNVBAoMA0hDMjERMA8GA1UEAwwIKi5oYzIu
|
||||
ZnIxHTAbBgkqhkiG9w0BCQEWDmNvbnRhY3RAaGMyLmZyMCAXDTE4MTIxNjEyMTI0
|
||||
NFoYDzIyOTIwOTI5MTIxMjQ0WjBdMQswCQYDVQQGEwJGUjEOMAwGA1UEBwwFUEFS
|
||||
SVMxDDAKBgNVBAoMA0hDMjERMA8GA1UEAwwIKi5oYzIuZnIxHTAbBgkqhkiG9w0B
|
||||
CQEWDmNvbnRhY3RAaGMyLmZyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
|
||||
AQEAvj1L4FLuOLypHqERQKkYcGJyIwt0vm/lbl6+hDF0nt3GVmYijorLuUn1tTE2
|
||||
93cXrixbZ9Bd65c8hsmEvVZbvjG2UmhXxGxk7NserbF4fAyZ+w7k+L0YOO1s5A53
|
||||
TcqWOLUd7E8J36j+SVx90T3VMnrl655K+ZqWM0IQnmLweddp+y1rZ0gAUhR/wmUB
|
||||
gWlfCCyhRl9ktAD0q0e6sVq7x/fwYTpG5ENCGPD3ZVlsgMWZMcj8liFbY7YNsVxD
|
||||
O1+eH6A20X7FwOSpX9AxVoYnDfB0Dlh0/7FaYIZ0ZhDDyvied43WW2DTEkKsdC48
|
||||
8Yr7GBb1Fw/Go3oYkaMChQN/FQIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQBW/KlS
|
||||
gTScaWf1RcpjHvvdBYfBwSlYZg5sxVbV2cPmC+M52EPbzIT5qM6TnTwnJgywj+zx
|
||||
NzxVvDwDIfLNO8NmKvsVjvzaMgjPoeknoZ33jULfLF8cgwrFzE+XmXUDii9dugQm
|
||||
GipA0JcWHGnR93pYJoZuXH7ACneNR3MNYIkHJ2M+PkkVppdx8ilOwgTI4pCLGAhm
|
||||
fwc/Bmkz6HEwju6vRzwdae9Z0xL7wKmZxO2IujbZpgQvwhf0ZvJzpXlmK2dxcBL/
|
||||
YrwgvneacuXWM3SXPTIlCNgYHzi0Mi+ElUqnfAjI1MtMOpW+jKpZxHRkJqfwFalp
|
||||
fLavWdBgXaJKb3Tx
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEAvj1L4FLuOLypHqERQKkYcGJyIwt0vm/lbl6+hDF0nt3GVmYi
|
||||
jorLuUn1tTE293cXrixbZ9Bd65c8hsmEvVZbvjG2UmhXxGxk7NserbF4fAyZ+w7k
|
||||
+L0YOO1s5A53TcqWOLUd7E8J36j+SVx90T3VMnrl655K+ZqWM0IQnmLweddp+y1r
|
||||
Z0gAUhR/wmUBgWlfCCyhRl9ktAD0q0e6sVq7x/fwYTpG5ENCGPD3ZVlsgMWZMcj8
|
||||
liFbY7YNsVxDO1+eH6A20X7FwOSpX9AxVoYnDfB0Dlh0/7FaYIZ0ZhDDyvied43W
|
||||
W2DTEkKsdC488Yr7GBb1Fw/Go3oYkaMChQN/FQIDAQABAoIBAFZYmAHfYkTaTKCc
|
||||
VqpUlcUcydViM8DkJOytkCeMEvSwkH9SqEiucr1M9nshNWOo6FSjyXEbQCXYZR6A
|
||||
hQEzGzz+b1SEC6IZ2M0wv4Hy1U7ooVM0dXT4zu+3w/7XGgty8jAW9Nf3H/ImUBSY
|
||||
KHs6Z3QcGBOTq1ATfC0TxVs+aQvDk/ceLuEbjDZAyhkqJTcUJaUrai91dwe1ChQj
|
||||
uBZCRa87Z7gdFBItY+g8RBtdOoT9KZNDZ4OqHXpzzg0la1GMbLKNA82dqUx3mexr
|
||||
HHlxV+cDt7gFT80Usj9Knk0tQnoiLkxFBblcHId9b93bSKdzFiVAUxkCkbI8xcUX
|
||||
JVf9a1kCgYEA4NsV5sFye2O+7Idwm1eUu4e/lXBrnwpNmDVy3rYlweQGNSyMrU+A
|
||||
wcBS7bAghq4QdFbZMEqNVxyFJFa7W1Xvy3HqCpsEUnDO6n9wCN8aCUGMU2YFP9Y/
|
||||
OoIrTye2ZO36C5pwZiOmT8KZ3Z45f1CxKrgVRDVnfwcCd7xLpPL4BKcCgYEA2JbJ
|
||||
i8eismhpx4oGvoV1LCgiazgm5+w1b+ZvzaknAAocqwNXLMVNqbGNY/136dCB1DYj
|
||||
A/Nvyr/WxBBTwYEXOoefgD0BpV2JjBmHckBTtwC8v3Ybi1dLm+JOtFT9uB1hXn/u
|
||||
08VahTU9GSo8OCyeJF5eDLcg3Rx0ZGtFRYPWieMCgYAN0CemR1f7EIOYEDHwuQ6f
|
||||
/pTcX02dNYrSwOXPnKzxHkrrVVNHCk1EmcX+aAV3gJXuL6+j8dCA+3WKZ/GWiM70
|
||||
VokkIaXAUsHDUhTV1q7IxsgSD4BfDZBQzdJPSIdB6ASmVdR10dbTq4a8QI4TridU
|
||||
En7r88Pp38pdBKo49dwanQKBgHnF9ZVIbfoe6HJO8VHHGUT1X7ymuoEk9jpu9idM
|
||||
VmgYR1wDKc07NVoWQKeaSARGvegBdBhxk0YMLATaJS0jllrLC+t+4WEHQSFq7RNY
|
||||
hXjbykNfdUcXkqQXTibnrisJIciO50lbqXRBpZNzgp4Wv+c0w24kvC51JB+djDn0
|
||||
UPf/AoGBAKZoSsbLjSIrxXDkASEGohLgId7AqJBndzCVzWV2+YQrgJCMMorBFVqC
|
||||
7myB69IDooBFhR7D0Is3uIUzyk62zeRSQPTgQYjUq1LYtvB+sLA3Dqs8cWdFWpAc
|
||||
a8lnxGKUNRpO18WIuNbFSibK6jyPqA1iRn/9KhZwRmygNzMh/f9P
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
microwebsrv2.hc2.fr
|
||||
@@ -0,0 +1 @@
|
||||
theme: jekyll-theme-hacker
|
||||
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 232 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 131 KiB |
@@ -0,0 +1,189 @@
|
||||
|
||||
import sys
|
||||
sys.path.append('/web_root/microWebServer2/')
|
||||
from MicroWebSrv2.microWebSrv2 import *
|
||||
from time import sleep
|
||||
from _thread import allocate_lock
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
@WebRoute(GET, '/test-redir')
|
||||
def RequestTestRedirect(microWebSrv2, request) :
|
||||
request.Response.ReturnRedirect('/test.pdf')
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
@WebRoute(GET, '/test-post', name='TestPost1/2')
|
||||
def RequestTestPost(microWebSrv2, request) :
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>POST 1/2</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>MicroWebSrv2 - POST 1/2</h2>
|
||||
User address: %s<br />
|
||||
<form action="/test-post" method="post">
|
||||
First name: <input type="text" name="firstname"><br />
|
||||
Last name: <input type="text" name="lastname"><br />
|
||||
<input type="submit" value="OK">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
""" % request.UserAddress[0]
|
||||
request.Response.ReturnOk(content)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
@WebRoute(POST, '/test-post', name='TestPost2/2')
|
||||
def RequestTestPost(microWebSrv2, request) :
|
||||
data = request.GetPostedURLEncodedForm()
|
||||
try :
|
||||
firstname = data['firstname']
|
||||
lastname = data['lastname']
|
||||
except :
|
||||
request.Response.ReturnBadRequest()
|
||||
return
|
||||
content = """\
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>POST 2/2</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>MicroWebSrv2 - POST 2/2</h2>
|
||||
Hello %s %s :)<br />
|
||||
</body>
|
||||
</html>
|
||||
""" % ( MicroWebSrv2.HTMLEscape(firstname),
|
||||
MicroWebSrv2.HTMLEscape(lastname) )
|
||||
request.Response.ReturnOk(content)
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
def OnWebSocketAccepted(microWebSrv2, webSocket) :
|
||||
print('Example WebSocket accepted:')
|
||||
print(' - User : %s:%s' % webSocket.Request.UserAddress)
|
||||
print(' - Path : %s' % webSocket.Request.Path)
|
||||
print(' - Origin : %s' % webSocket.Request.Origin)
|
||||
if webSocket.Request.Path.lower() == '/wschat' :
|
||||
WSJoinChat(webSocket)
|
||||
else :
|
||||
webSocket.OnTextMessage = OnWebSocketTextMsg
|
||||
webSocket.OnBinaryMessage = OnWebSocketBinaryMsg
|
||||
webSocket.OnClosed = OnWebSocketClosed
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
def OnWebSocketTextMsg(webSocket, msg) :
|
||||
print('WebSocket text message: %s' % msg)
|
||||
webSocket.SendTextMessage('Received "%s"' % msg)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnWebSocketBinaryMsg(webSocket, msg) :
|
||||
print('WebSocket binary message: %s' % msg)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnWebSocketClosed(webSocket) :
|
||||
print('WebSocket %s:%s closed' % webSocket.Request.UserAddress)
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
global _chatWebSockets
|
||||
_chatWebSockets = [ ]
|
||||
|
||||
global _chatLock
|
||||
_chatLock = allocate_lock()
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def WSJoinChat(webSocket) :
|
||||
webSocket.OnTextMessage = OnWSChatTextMsg
|
||||
webSocket.OnClosed = OnWSChatClosed
|
||||
addr = webSocket.Request.UserAddress
|
||||
with _chatLock :
|
||||
for ws in _chatWebSockets :
|
||||
ws.SendTextMessage('<%s:%s HAS JOINED THE CHAT>' % addr)
|
||||
_chatWebSockets.append(webSocket)
|
||||
webSocket.SendTextMessage('<WELCOME %s:%s>' % addr)
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnWSChatTextMsg(webSocket, msg) :
|
||||
addr = webSocket.Request.UserAddress
|
||||
with _chatLock :
|
||||
for ws in _chatWebSockets :
|
||||
ws.SendTextMessage('<%s:%s> %s' % (addr[0], addr[1], msg))
|
||||
|
||||
# ------------------------------------------------------------------------
|
||||
|
||||
def OnWSChatClosed(webSocket) :
|
||||
addr = webSocket.Request.UserAddress
|
||||
with _chatLock :
|
||||
if webSocket in _chatWebSockets :
|
||||
_chatWebSockets.remove(webSocket)
|
||||
for ws in _chatWebSockets :
|
||||
ws.SendTextMessage('<%s:%s HAS LEFT THE CHAT>' % addr)
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
|
||||
print()
|
||||
|
||||
# Loads the PyhtmlTemplate module globally and configure it,
|
||||
pyhtmlMod = MicroWebSrv2.LoadModule('PyhtmlTemplate')
|
||||
pyhtmlMod.ShowDebug = True
|
||||
pyhtmlMod.SetGlobalVar('TestVar', 12345)
|
||||
|
||||
# Loads the WebSockets module globally and configure it,
|
||||
wsMod = MicroWebSrv2.LoadModule('WebSockets')
|
||||
wsMod.OnWebSocketAccepted = OnWebSocketAccepted
|
||||
|
||||
# Instanciates the MicroWebSrv2 class,
|
||||
mws2 = MicroWebSrv2()
|
||||
mws2.BindAddress = ('0.0.0.0', 8080) # Binds to all interfaces on port 8080.
|
||||
|
||||
# SSL is not correctly supported on MicroPython.
|
||||
# But you can uncomment the following for standard Python.
|
||||
# mws2.EnableSSL( certFile = 'SSL-Cert/openhc2.crt',
|
||||
# keyFile = 'SSL-Cert/openhc2.key' )
|
||||
|
||||
# For embedded MicroPython, use a very light configuration,
|
||||
mws2.SetEmbeddedConfig()
|
||||
|
||||
# All pages not found will be redirected to the home '/',
|
||||
mws2.NotFoundURL = '/'
|
||||
|
||||
# Starts the server as easily as possible in managed mode,
|
||||
mws2.StartManaged()
|
||||
|
||||
# Main program loop until keyboard interrupt,
|
||||
try :
|
||||
while mws2.IsRunning :
|
||||
sleep(1)
|
||||
except KeyboardInterrupt :
|
||||
pass
|
||||
|
||||
# End,
|
||||
print()
|
||||
mws2.Stop()
|
||||
print('Bye')
|
||||
print()
|
||||
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
# ============================================================================
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
README = open(os.path.join(here, 'README.md'), encoding='utf-8').read()
|
||||
|
||||
setup(
|
||||
name='MicroWebSrv2',
|
||||
version='2.0.6',
|
||||
description='Embedded webserver for MicroPython and CPython',
|
||||
long_description=README,
|
||||
author='Jean-Christophe Bos',
|
||||
author_email='jczic.bos@gmail.com',
|
||||
url='https://github.com/jczic/MicroWebSrv2',
|
||||
download_url='https://github.com/jczic/MicroWebSrv2/archive/master.zip',
|
||||
packages=find_packages(),
|
||||
classifiers=[
|
||||
'Environment :: Web Environment',
|
||||
'Topic :: Internet :: WWW/HTTP',
|
||||
'Topic :: Software Development :: Libraries',
|
||||
'Topic :: Software Development :: Embedded Systems',
|
||||
'Programming Language :: Python',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Programming Language :: Python :: Implementation :: CPython',
|
||||
'Programming Language :: Python :: Implementation :: MicroPython',
|
||||
'License :: OSI Approved :: MIT License',
|
||||
'Development Status :: 5 - Production/Stable',
|
||||
],
|
||||
)
|
||||
|
After Width: | Height: | Size: 7.7 KiB |
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang=fr>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>MicroWebSrv2</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
|
||||
<body style="padding: 0 70px;">
|
||||
<h1>< MicroWebSrv2 /></h1>
|
||||
<h2>About</h2>
|
||||
<p>
|
||||
This project follows the embedded <a href="https://github.com/jczic/MicroWebSrv">MicroWebSrv</a>,
|
||||
which is mainly used on microcontrollers such as Pycom, ESP32 and STM32 on Pyboards.<br />
|
||||
<br />
|
||||
In a need for scalability and to meet the IoT universe, <b>microWebSrv2</b> was developed as a new project
|
||||
and has been completely redesigned to be much more robust and efficient that its predecessor.<br />
|
||||
<br />
|
||||
Internal mechanisms works <b>directly at I/O level</b>, are fully asynchronous from end to end, and manages the memory in a highly optimized way.
|
||||
Also, architecture makes its integration very easy and the source code, <b>MIT licensed</b>, remains really small.<br />
|
||||
<br />
|
||||
</p>
|
||||
<ul>
|
||||
<li><a href="test-redir">Test a redirection</a></li>
|
||||
<li><a href="test-post">Test a POST form</a></li>
|
||||
<li><a href="wstest.html">Test the WebSockets page</a></li>
|
||||
<li><a href="wschat.html">Test the multi-users chat page</a></li>
|
||||
<li><a href="test.pyhtml">Test a pyhtml template page</a></li>
|
||||
</ul>
|
||||
<br />
|
||||
<hr />
|
||||
<br />
|
||||
<div style="text-align: center">
|
||||
<img src="pdf.png" />
|
||||
<p>
|
||||
View a « <a href="test.pdf">PDF file</a> »
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 4.4 KiB |
@@ -0,0 +1,44 @@
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
body {
|
||||
margin: 30px;
|
||||
background-color: white;
|
||||
font-family: "Trebuchet MS", Verdana, sans-serif;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
h1 {
|
||||
color: #D35F8D;
|
||||
text-align: center;
|
||||
}
|
||||
h2 {
|
||||
color: #5FA3D3;
|
||||
padding-left: 15px;
|
||||
}
|
||||
p, ul, li, td {
|
||||
color: black;
|
||||
}
|
||||
a:link {
|
||||
color: green;
|
||||
text-decoration: underline;
|
||||
}
|
||||
a:visited {
|
||||
color: gray;
|
||||
}
|
||||
a:hover {
|
||||
color: red;
|
||||
text-decoration: none;
|
||||
}
|
||||
a:active, a:focus {
|
||||
color: red;
|
||||
}
|
||||
.sep {
|
||||
margin: 15px 0;
|
||||
height: 3px;
|
||||
background-color: #5FA3D3;
|
||||
}
|
||||
.label {
|
||||
color: #D35F8D;
|
||||
font-weight: bold;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MicroWebSrv2 - PyhtmlTemplate Module</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
{{ py }}
|
||||
|
||||
import sys
|
||||
|
||||
global Toto
|
||||
try :
|
||||
Toto += 1
|
||||
except :
|
||||
Toto = 1
|
||||
|
||||
{{ end }}
|
||||
|
||||
<h1>MicroWebSrv2 - PyhtmlTemplate Module</h1>
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Platform: {{ sys.platform }} <br />
|
||||
Version: {{ sys.version }} <br />
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Global var "TestVar" : <span class="label">{{ TestVar }}</span><br />
|
||||
* Set from the main program.
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Global var "Toto" : <span class="label">{{ Toto }}</span><br />
|
||||
* Refresh this page to see this variable changing.
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
{{ py }}
|
||||
print('Unescaped HTML: <strong><u>Okay</u></strong>')
|
||||
{{ end }}
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Your address:<br />
|
||||
<ul>
|
||||
<li> IP = {{ Request.UserAddress[0] }} </li>
|
||||
<li> Port = {{ Request.UserAddress[1] }} </li>
|
||||
</ul>
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
{{ if 'CHROME' in Request.UserAgent.upper() }}
|
||||
You are on <span class="label">Chrome</span> browser.
|
||||
{{ elif 'FIREFOX' in Request.UserAgent.upper() }}
|
||||
You are on <span class="label">Firefox</span> browser.
|
||||
{{ else }}
|
||||
You are not on Chrome or Firefox browser.
|
||||
{{ end }}
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
You are in SSL: {{ Request.IsSSL }}<br />
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Your host: {{ Request.Host }}<br />
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Requested path: {{ Request.Path }}<br />
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Your query params:
|
||||
{{ if not Request.QueryParams }}
|
||||
<a href="?question=How are you?&answer=I'm fine!">
|
||||
Test query string on this page.
|
||||
</a>
|
||||
{{ else }}
|
||||
<ul>
|
||||
{{ for param in Request.QueryParams }}
|
||||
<li>Param "{{ param }}" = "{{ Request.QueryParams[param] }}"</li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
{{ end }}
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Accepted content types:
|
||||
<ul>
|
||||
{{ for accept in Request.Accept }}
|
||||
<li>{{ accept }}</li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Accepted encodings:
|
||||
<ul>
|
||||
{{ for encoding in Request.AcceptEncodings }}
|
||||
<li>{{ encoding }}</li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Accepted languages:
|
||||
<ul>
|
||||
{{ for language in Request.AcceptLanguages }}
|
||||
<li>{{ language }}</li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Your request is keep-alive: {{ Request.IsKeepAlive }}<br />
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
Your user agent:<br />
|
||||
{{ Request.UserAgent }}
|
||||
|
||||
<div class="sep"></div>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,124 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MicroWebSrv2 - WS Chat</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
|
||||
<style>
|
||||
.chat-zone {
|
||||
height : 350px;
|
||||
padding: 10px;
|
||||
background-color: #304050;
|
||||
font: 15px monospace;
|
||||
color: white;
|
||||
overflow: scroll;
|
||||
}
|
||||
#input-chat {
|
||||
height: 40px;
|
||||
border: 0px;
|
||||
padding: 0px 10px;
|
||||
outline: none;
|
||||
border-top: 1px solid white;
|
||||
background-color: #304050;
|
||||
font: 15px monospace;
|
||||
letter-spacing: 2px;
|
||||
color: white;
|
||||
}
|
||||
input {
|
||||
box-sizing: border-box;
|
||||
-webkit-box-sizing: border-box;
|
||||
-moz-box-sizing: border-box;
|
||||
width: 100%;
|
||||
margin-top: 3px;
|
||||
border: 2px solid #5FA3D3;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script language="javascript">
|
||||
|
||||
function init()
|
||||
{
|
||||
var scheme
|
||||
if (window.location.protocol == 'https:')
|
||||
scheme = 'wss:';
|
||||
else
|
||||
scheme = 'ws:';
|
||||
var wsUri = scheme + '//' + window.location.hostname + '/wschat';
|
||||
writeLineToChat("Connection to " + wsUri + "...")
|
||||
websocket = new WebSocket(wsUri);
|
||||
websocket.onopen = function(evt) { onOpen (evt) };
|
||||
websocket.onclose = function(evt) { onClose (evt) };
|
||||
websocket.onmessage = function(evt) { onMessage (evt) };
|
||||
websocket.onerror = function(evt) { onError (evt) };
|
||||
getElmById("input-chat").addEventListener("keyup", onChatLine);
|
||||
getElmById("input-chat").focus()
|
||||
}
|
||||
|
||||
function getElmById(id) {
|
||||
return document.getElementById(id);
|
||||
}
|
||||
|
||||
function writeLineToChat(line)
|
||||
{
|
||||
var elm = getElmById('chat');
|
||||
if (elm)
|
||||
{
|
||||
var lineElm = document.createElement('div');
|
||||
if (line) {
|
||||
var time = new Date().toLocaleTimeString();
|
||||
lineElm.innerText = "[" + time + "] " + line;
|
||||
}
|
||||
else
|
||||
lineElm.innerHTML = ' ';
|
||||
elm.appendChild(lineElm);
|
||||
elm.scrollTop = elm.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
function onOpen(evt)
|
||||
{
|
||||
writeLineToChat("[CONNECTED]")
|
||||
}
|
||||
|
||||
function onClose(evt)
|
||||
{
|
||||
writeLineToChat("[CONNECTION CLOSED]")
|
||||
}
|
||||
|
||||
function onMessage(evt)
|
||||
{
|
||||
writeLineToChat(evt.data)
|
||||
}
|
||||
|
||||
function onError(evt)
|
||||
{
|
||||
writeLineToChat("[CONNECTION ERROR]")
|
||||
}
|
||||
|
||||
function onChatLine(e) {
|
||||
key = (e.key || e.keyCode);
|
||||
if (key === 13 || key.toUpperCase() === "ENTER") {
|
||||
input = getElmById("input-chat");
|
||||
line = input.value.trim();
|
||||
input.value = "";
|
||||
if (line.length > 0)
|
||||
websocket.send(line);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("load", init, false);
|
||||
|
||||
</script>
|
||||
|
||||
<body>
|
||||
<h1>MicroWebSrv2 - WS Chat</h1>
|
||||
<div id="chat" class="chat-zone">
|
||||
</div>
|
||||
<input id="input-chat" type="text" />
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,92 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MicroWebSrv2 - WebSockets Module</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
|
||||
<script language="javascript">
|
||||
|
||||
var output;
|
||||
|
||||
function init()
|
||||
{
|
||||
output = document.getElementById("output");
|
||||
testWebSocket();
|
||||
}
|
||||
|
||||
function testWebSocket()
|
||||
{
|
||||
var scheme, defaultPort
|
||||
if (window.location.protocol == 'https:')
|
||||
{
|
||||
scheme = 'wss:';
|
||||
defaultPort = 443;
|
||||
}
|
||||
else
|
||||
{
|
||||
scheme = 'ws:';
|
||||
defaultPort = 80;
|
||||
}
|
||||
var wsUri = scheme + '//' + window.location.hostname;
|
||||
if (window.location.port !== defaultPort)
|
||||
wsUri += ':' + window.location.port;
|
||||
writeToScreen("Connecting to " + wsUri + "...")
|
||||
websocket = new WebSocket(wsUri);
|
||||
websocket.onopen = function(evt) { onOpen (evt) };
|
||||
websocket.onclose = function(evt) { onClose (evt) };
|
||||
websocket.onmessage = function(evt) { onMessage (evt) };
|
||||
websocket.onerror = function(evt) { onError (evt) };
|
||||
}
|
||||
|
||||
function onOpen(evt)
|
||||
{
|
||||
writeToScreen("<strong>-- CONNECTED --</strong>");
|
||||
SendMsg("Hello world :)");
|
||||
SendMsg("This is a WebSocket test");
|
||||
SendMsg("(with a text frame encoded in UTF-8)");
|
||||
setTimeout( function() { websocket.close() }, 3000 )
|
||||
}
|
||||
|
||||
function onClose(evt)
|
||||
{
|
||||
writeToScreen("<strong>-- DISCONNECTED --</strong>");
|
||||
}
|
||||
|
||||
function onMessage(evt)
|
||||
{
|
||||
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
|
||||
}
|
||||
|
||||
function onError(evt)
|
||||
{
|
||||
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
|
||||
}
|
||||
|
||||
function SendMsg(msg)
|
||||
{
|
||||
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
|
||||
websocket.send(msg);
|
||||
}
|
||||
|
||||
function writeToScreen(s)
|
||||
{
|
||||
var pre = document.createElement("p");
|
||||
pre.style.wordWrap = "break-word";
|
||||
pre.innerHTML = s;
|
||||
output.appendChild(pre);
|
||||
}
|
||||
|
||||
window.addEventListener("load", init, false);
|
||||
|
||||
</script>
|
||||
|
||||
<body>
|
||||
<h1>MicroWebSrv2 - WebSockets Module</h1>
|
||||
<div id="output"></div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 5.4 KiB |
@@ -0,0 +1 @@
|
||||
.cm-s-monokai.CodeMirror{background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483e}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle{color:#d0d0d0}.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom{color:#ae81ff}.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-comment.cm-attribute{color:#97b757}.cm-s-monokai span.cm-comment.cm-def{color:#bc9262}.cm-s-monokai span.cm-comment.cm-tag{color:#bc6283}.cm-s-monokai span.cm-comment.cm-type{color:#5998a6}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-type,.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header{color:#ae81ff}.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
|
||||
@@ -0,0 +1,85 @@
|
||||
.card {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.form-control {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
#feedbackVoltage,
|
||||
#feedbackCurrent,
|
||||
#filamentVoltage,
|
||||
#filamentCurrent {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.navbar {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.nav-link i {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
/* 编辑器相关样式 */
|
||||
.CodeMirror {
|
||||
height: calc(100vh - 200px);
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#fileTree {
|
||||
height: calc(100vh - 200px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-icon {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon {
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon-custom {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
/* 文件类型图标颜色 */
|
||||
.bi-filetype-py {
|
||||
color: #306998;
|
||||
}
|
||||
|
||||
.bi-filetype-json {
|
||||
color: #f7df1e;
|
||||
}
|
||||
|
||||
.bi-filetype-sh {
|
||||
color: #4eaa25;
|
||||
}
|
||||
|
||||
.bi-folder {
|
||||
color: #ffc107;
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>高压电源管理系统1</title>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="css/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="css/style.min.css" rel="stylesheet">
|
||||
<link href="css/codemirror.min.css" rel="stylesheet">
|
||||
<link href="css/monokai.min.css" rel="stylesheet">
|
||||
|
||||
<link href="css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- 导航栏 -->
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="/">高压电源管理系统</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid mt-4">
|
||||
<!-- Toast提示组件 -->
|
||||
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong class="me-auto">系统提示</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="toast-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 选项卡 -->
|
||||
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||
脚本编辑器</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="var-tab" data-bs-toggle="tab" data-bs-target="#var" type="button"
|
||||
role="tab" aria-controls="var" aria-selected="false"><i class="bi bi-gear"></i>
|
||||
变量设置</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content" id="mainTabContent">
|
||||
<!-- 控制面板 -->
|
||||
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设备控制</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="reboot">重启设备</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_start">启动程序</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_stop">停止程序</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_restart">重启程序</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-danger" id="hvEnable">开启高压</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-success" id="hvDisable">关闭高压</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-danger" id="rayEnable">开启射线</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-success" id="rayDisable">关闭射线</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设定参数</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label for="setVoltage" class="form-label">设定电压 (kV)</label>
|
||||
<input type="number" class="form-control" id="setVoltage" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="setCurrent" class="form-label">设定电流 (mA)</label>
|
||||
<input type="number" class="form-control" id="setCurrent" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="filaPreheatCurrent" class="form-label">灯丝预热电流 (A)</label>
|
||||
<input type="number" class="form-control" id="filaPreheatCurrent" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="filaLimitCurrent" class="form-label">灯丝限制电流 (A)</label>
|
||||
<input type="number" class="form-control" id="filaLimitCurrent" value="0">
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-primary" id="getParams">读取参数</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-primary" id="setParams">设置参数</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">实时状态</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">电源状态</label>
|
||||
<div class="form-control" id="vinState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">高压状态</label>
|
||||
<div class="form-control" id="hvState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">射线状态</label>
|
||||
<div class="form-control" id="rayState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">反馈电压 (kV)</label>
|
||||
<div class="form-control" id="feedbackVoltage">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">反馈电流 (mA)</label>
|
||||
<div class="form-control" id="feedbackCurrent">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">灯丝电压 (V)</label>
|
||||
<div class="form-control" id="filamentVoltage">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">灯丝电流 (A)</label>
|
||||
<div class="form-control" id="filamentCurrent">--</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 脚本编辑器 -->
|
||||
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>文件目录</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="fileTree"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span id="currentFile">未选择文件</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||
<i class="bi bi-save"></i> 保存
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<textarea id="editor"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 变量设置 -->
|
||||
<div class="tab-pane fade" id="var" role="tabpanel" aria-labelledby="var-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>变量配置</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-primary" id="getVar">
|
||||
<i class="bi bi-download"></i> 读取变量
|
||||
</button>
|
||||
<button class="btn btn-sm btn-success" id="setVar">
|
||||
<i class="bi bi-upload"></i> 保存变量
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label for="varEditor" class="form-label">变量配置 (JSON格式)</label>
|
||||
<textarea class="form-control" id="varEditor" rows="20" placeholder="变量配置将以JSON格式显示在这里..."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/jquery.min.js"></script>
|
||||
<script src="js/bootstrap.bundle.min.js"></script>
|
||||
<script src="js/jstree.min.js"></script>
|
||||
<script src="js/codemirror.min.js"></script>
|
||||
<script src="js/python.min.js"></script>
|
||||
<script src="js/javascript.min.js"></script>
|
||||
<script src="js/shell.min.js"></script>
|
||||
<script src="js/htmlmixed.min.js"></script>
|
||||
<script src="js/xml.min.js"></script>
|
||||
<script src="js/css.min.js"></script>
|
||||
<script src="js/base64.min.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Minified by jsDelivr using Terser v5.15.1.
|
||||
* Original file: /npm/js-base64@3.7.5/base64.js
|
||||
*
|
||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||
*/
|
||||
!function(t,n){var r,e;"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(r=t.Base64,(e=n()).noConflict=function(){return t.Base64=r,e},t.Meteor&&(Base64=e),t.Base64=e)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,(function(){"use strict";var t,n="3.7.5",r="function"==typeof atob,e="function"==typeof btoa,o="function"==typeof Buffer,u="function"==typeof TextDecoder?new TextDecoder:void 0,i="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),c=(t={},f.forEach((function(n,r){return t[n]=r})),t),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,d=String.fromCharCode.bind(String),s="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){return new Uint8Array(Array.prototype.slice.call(t,0))},l=function(t){return t.replace(/=/g,"").replace(/[+\/]/g,(function(t){return"+"==t?"-":"_"}))},h=function(t){return t.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(t){for(var n,r,e,o,u="",i=t.length%3,c=0;c<t.length;){if((r=t.charCodeAt(c++))>255||(e=t.charCodeAt(c++))>255||(o=t.charCodeAt(c++))>255)throw new TypeError("invalid character found");u+=f[(n=r<<16|e<<8|o)>>18&63]+f[n>>12&63]+f[n>>6&63]+f[63&n]}return i?u.slice(0,i-3)+"===".substring(i):u},y=e?function(t){return btoa(t)}:o?function(t){return Buffer.from(t,"binary").toString("base64")}:p,A=o?function(t){return Buffer.from(t).toString("base64")}:function(t){for(var n=[],r=0,e=t.length;r<e;r+=4096)n.push(d.apply(null,t.subarray(r,r+4096)));return y(n.join(""))},b=function(t,n){return void 0===n&&(n=!1),n?l(A(t)):A(t)},g=function(t){if(t.length<2)return(n=t.charCodeAt(0))<128?t:n<2048?d(192|n>>>6)+d(128|63&n):d(224|n>>>12&15)+d(128|n>>>6&63)+d(128|63&n);var n=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return d(240|n>>>18&7)+d(128|n>>>12&63)+d(128|n>>>6&63)+d(128|63&n)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,x=function(t){return t.replace(B,g)},C=o?function(t){return Buffer.from(t,"utf8").toString("base64")}:i?function(t){return A(i.encode(t))}:function(t){return y(x(t))},m=function(t,n){return void 0===n&&(n=!1),n?l(C(t)):C(t)},v=function(t){return m(t,!0)},U=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,F=function(t){switch(t.length){case 4:var n=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return d(55296+(n>>>10))+d(56320+(1023&n));case 3:return d((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return d((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},w=function(t){return t.replace(U,F)},S=function(t){if(t=t.replace(/\s+/g,""),!a.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(3&t.length));for(var n,r,e,o="",u=0;u<t.length;)n=c[t.charAt(u++)]<<18|c[t.charAt(u++)]<<12|(r=c[t.charAt(u++)])<<6|(e=c[t.charAt(u++)]),o+=64===r?d(n>>16&255):64===e?d(n>>16&255,n>>8&255):d(n>>16&255,n>>8&255,255&n);return o},E=r?function(t){return atob(h(t))}:o?function(t){return Buffer.from(t,"base64").toString("binary")}:S,D=o?function(t){return s(Buffer.from(t,"base64"))}:function(t){return s(E(t).split("").map((function(t){return t.charCodeAt(0)})))},R=function(t){return D(T(t))},z=o?function(t){return Buffer.from(t,"base64").toString("utf8")}:u?function(t){return u.decode(D(t))}:function(t){return w(E(t))},T=function(t){return h(t.replace(/[-_]/g,(function(t){return"-"==t?"+":"/"})))},Z=function(t){return z(T(t))},j=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}},I=function(){var t=function(t,n){return Object.defineProperty(String.prototype,t,j(n))};t("fromBase64",(function(){return Z(this)})),t("toBase64",(function(t){return m(this,t)})),t("toBase64URI",(function(){return m(this,!0)})),t("toBase64URL",(function(){return m(this,!0)})),t("toUint8Array",(function(){return R(this)}))},O=function(){var t=function(t,n){return Object.defineProperty(Uint8Array.prototype,t,j(n))};t("toBase64",(function(t){return b(this,t)})),t("toBase64URI",(function(){return b(this,!0)})),t("toBase64URL",(function(){return b(this,!0)}))},P={version:n,VERSION:"3.7.5",atob:E,atobPolyfill:S,btoa:y,btoaPolyfill:p,fromBase64:Z,toBase64:m,encode:m,encodeURI:v,encodeURL:v,utob:x,btou:w,decode:Z,isValid:function(t){if("string"!=typeof t)return!1;var n=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(n)||!/[^\s0-9a-zA-Z\-_]/.test(n)},fromUint8Array:b,toUint8Array:R,extendString:I,extendUint8Array:O,extendBuiltins:function(){I(),O()},Base64:{}};return Object.keys(P).forEach((function(t){return P.Base64[t]=P[t]})),P}));
|
||||
//# sourceMappingURL=/sm/555281732ed54ee1693a772f485329378d8ea5052ffa4370e9c2e9947eb42d22.map
|
||||
@@ -0,0 +1 @@
|
||||
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],t):t(CodeMirror)}(function(m){"use strict";var l={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var a={};function d(t,e){e=t.match(a[e=e]||(a[e]=new RegExp("\\s+"+e+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return e?/^\s*(.*?)\s*$/.exec(e[2])[1]:""}function g(t,e){return new RegExp((e?"^":"")+"</\\s*"+t+"\\s*>","i")}function o(t,e){for(var a in t)for(var n=e[a]||(e[a]=[]),l=t[a],o=l.length-1;0<=o;o--)n.unshift(l[o])}m.defineMode("htmlmixed",function(i,t){var c=m.getMode(i,{name:"xml",htmlMode:!0,multilineTagIndentFactor:t.multilineTagIndentFactor,multilineTagIndentPastTag:t.multilineTagIndentPastTag,allowMissingTagName:t.allowMissingTagName}),s={},e=t&&t.tags,a=t&&t.scriptTypes;if(o(l,s),e&&o(e,s),a)for(var n=a.length-1;0<=n;n--)s.script.unshift(["type",a[n].matches,a[n].mode]);function u(t,e){var a,o,r,n=c.token(t,e.htmlState),l=/\btag\b/.test(n);return l&&!/[<>\s\/]/.test(t.current())&&(a=e.htmlState.tagName&&e.htmlState.tagName.toLowerCase())&&s.hasOwnProperty(a)?e.inTag=a+" ":e.inTag&&l&&/>$/.test(t.current())?(a=/^([\S]+) (.*)/.exec(e.inTag),e.inTag=null,l=">"==t.current()&&function(t,e){for(var a=0;a<t.length;a++){var n=t[a];if(!n[0]||n[1].test(d(e,n[0])))return n[2]}}(s[a[1]],a[2]),l=m.getMode(i,l),o=g(a[1],!0),r=g(a[1],!1),e.token=function(t,e){return t.match(o,!1)?(e.token=u,e.localState=e.localMode=null):(a=t,n=r,l=e.localMode.token(t,e.localState),t=a.current(),-1<(e=t.search(n))?a.backUp(t.length-e):t.match(/<\/?$/)&&(a.backUp(t.length),a.match(n,!1)||a.match(t)),l);var a,n,l},e.localMode=l,e.localState=m.startState(l,c.indent(e.htmlState,"",""))):e.inTag&&(e.inTag+=t.current(),t.eol()&&(e.inTag+=" ")),n}return{startState:function(){return{token:u,inTag:null,localMode:null,localState:null,htmlState:m.startState(c)}},copyState:function(t){var e;return t.localState&&(e=m.copyState(t.localMode,t.localState)),{token:t.token,inTag:t.inTag,localMode:t.localMode,localState:e,htmlState:m.copyState(c,t.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(t,e,a){return!t.localMode||/^\s*<\//.test(e)?c.indent(t.htmlState,e,a):t.localMode.indent?t.localMode.indent(t.localState,e,a):m.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||c}}}},"xml","javascript","css"),m.defineMIME("text/html","htmlmixed")});
|
||||
@@ -0,0 +1,505 @@
|
||||
$(document).ready(function() {
|
||||
const topic_control = '/dev/control/hsv';
|
||||
const topic_status = '/dev/status/hsv';
|
||||
const topic_response = '/dev/response/hsv';
|
||||
|
||||
// ================== 控制面板相关 ==================
|
||||
// WebSocket客户端配置
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsHost = location.hostname + (location.port ? ':' + location.port : '');
|
||||
const wsuri = wsProtocol + '//' + wsHost + '/ws';
|
||||
console.log('WebSocket URI:', wsuri);
|
||||
// 创建WebSocket连接
|
||||
let ws;
|
||||
let reconnectTimer;
|
||||
|
||||
function connectWebSocket() {
|
||||
ws = new WebSocket(wsuri);
|
||||
|
||||
ws.onopen = function() {
|
||||
showToast('已连接到WebSocket服务器');
|
||||
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_status }));
|
||||
// 清除重连定时器
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
let data;
|
||||
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
return;
|
||||
}
|
||||
const topic = data.topic;
|
||||
const message = data.message;
|
||||
|
||||
if (topic && message) {
|
||||
if (topic.startsWith(topic_status)) {
|
||||
try {
|
||||
const value = typeof message === 'string' ? JSON.parse(message) : message;
|
||||
var iin = parseFloat(value.value.Iin);
|
||||
if (iin > 65) {
|
||||
iin = 0;
|
||||
}
|
||||
var vinState = parseFloat(value.value.Vin).toFixed(1) + 'V ' + parseFloat(iin).toFixed(2) + 'A';
|
||||
$('#vinState').text(vinState)
|
||||
$('#hvState').text(value.value.hv == 'on' ? '高压已打开' : '高压已关闭');
|
||||
$('#rayState').text(value.value.xray == 'on' ? '射线已打开' : '射线已关闭');
|
||||
$('#feedbackVoltage').text(parseFloat(value.value.kV).toFixed(2));
|
||||
$('#feedbackCurrent').text(parseFloat(value.value.mA).toFixed(2));
|
||||
$('#filamentVoltage').text(parseFloat(value.value.fV).toFixed(3));
|
||||
$('#filamentCurrent').text(parseFloat(value.value.fI).toFixed(3));
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
}
|
||||
} else if (topic.startsWith(topic_response)) {
|
||||
try {
|
||||
const value = typeof message === 'string' ? JSON.parse(message) : message;
|
||||
if (value.command == 'get_params') {
|
||||
$('#setVoltage').val(parseFloat(value.value.kV).toFixed(2));
|
||||
$('#setCurrent').val(parseFloat(value.value.mA).toFixed(2));
|
||||
$('#filaPreheatCurrent').val(parseFloat(value.value.filament.preheat / 1000).toFixed(2));
|
||||
$('#filaLimitCurrent').val(parseFloat(value.value.filament.limit / 1000).toFixed(2));
|
||||
showToast('参数已更新');
|
||||
} else if (value.command == 'get_var') {
|
||||
// 处理变量配置响应
|
||||
if (varEditor) {
|
||||
try {
|
||||
const varData = JSON.stringify(value.value, null, 2);
|
||||
varEditor.value = varData;
|
||||
showToast('变量配置已加载');
|
||||
} catch (e) {
|
||||
showToast('解析变量配置失败:' + e.message);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
showToast('请求已发送');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = function() {
|
||||
showToast('WebSocket连接错误');
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
showToast('WebSocket连接已关闭,正在尝试重连...');
|
||||
// 仅在没有活跃定时器时创建新的重连定时器
|
||||
if (!reconnectTimer) {
|
||||
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||
}
|
||||
};
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
// 初始连接
|
||||
connectWebSocket();
|
||||
|
||||
// 定期检查连接状态(每10秒)
|
||||
setInterval(function() {
|
||||
if (!ws || ws.readyState === WebSocket.CLOSED) {
|
||||
showToast('定期检查发现连接已关闭,尝试重连...');
|
||||
if (!reconnectTimer) {
|
||||
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||
}
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
// 替换 client.publish 为 ws.send
|
||||
function wsPublish(topic, msg) {
|
||||
ws.send(JSON.stringify({
|
||||
action: 'publish',
|
||||
topic: topic,
|
||||
message: msg
|
||||
}));
|
||||
}
|
||||
// Toast初始化
|
||||
const toastEl = document.getElementById('toast');
|
||||
const toast = new bootstrap.Toast(toastEl, {
|
||||
autohide: true,
|
||||
delay: 3000
|
||||
});
|
||||
function showToast(message) {
|
||||
$('.toast-body').text(message);
|
||||
toast.show();
|
||||
}
|
||||
|
||||
$('#setParams').click(function() {
|
||||
const setVoltage = parseFloat($('#setVoltage').val());
|
||||
const setCurrent = parseFloat($('#setCurrent').val());
|
||||
const filaPreheatCurrent = parseFloat($('#filaPreheatCurrent').val()) * 1000;
|
||||
const filaLimitCurrent = parseFloat($('#filaLimitCurrent').val()) * 1000;
|
||||
var msg = {
|
||||
device_id: '2',
|
||||
device_code: '2#HVS',
|
||||
command: 'set_params',
|
||||
value: {
|
||||
kV: setVoltage,
|
||||
mA: setCurrent,
|
||||
filament : {
|
||||
preheat: filaPreheatCurrent,
|
||||
limit: filaLimitCurrent
|
||||
}
|
||||
}
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
$('#getParams').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '2#HVS',
|
||||
command: 'get_params'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#hvEnable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'hv_control',
|
||||
value: 'on'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#hvDisable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'hv_control',
|
||||
value: 'off'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
$('#rayEnable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'ray_control',
|
||||
value: 'on'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#rayDisable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'ray_control',
|
||||
value: 'off'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
|
||||
$('#reboot').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/device/reboot',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#hv_service_start').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/hv_service/start',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
$('#hv_service_stop').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/hv_service/stop',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$(window).on('beforeunload', function() {
|
||||
ws.close();
|
||||
});
|
||||
|
||||
// ================== 脚本编辑器相关 ==================
|
||||
let scriptTabInited = false;
|
||||
let editor = null;
|
||||
|
||||
// ================== 变量设置相关 ==================
|
||||
let varTabInited = false;
|
||||
let varEditor = null;
|
||||
|
||||
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
|
||||
console.log('tab shown', e);
|
||||
const target = $(e.target).attr('data-bs-target');
|
||||
if (target === '#script' && !scriptTabInited) {
|
||||
// 初始化CodeMirror
|
||||
editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
|
||||
mode: 'text/x-python',
|
||||
theme: 'monokai',
|
||||
lineNumbers: true,
|
||||
indentUnit: 4,
|
||||
lineWrapping: true,
|
||||
matchBrackets: true,
|
||||
autoCloseBrackets: true
|
||||
});
|
||||
|
||||
editor.setValue("请选择一个文件");
|
||||
|
||||
// 初始化文件树
|
||||
$('#fileTree').jstree({
|
||||
'core': {
|
||||
'data': {
|
||||
'url': function(node) {
|
||||
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||
return url;
|
||||
},
|
||||
'data': function(node) {
|
||||
return { 'id': node.id };
|
||||
},
|
||||
'dataFilter': function(data) {
|
||||
var json = {};
|
||||
try {
|
||||
json = JSON.parse(data);
|
||||
} catch (e) {
|
||||
return "[]";
|
||||
}
|
||||
if (json.success && Array.isArray(json.data)) {
|
||||
return JSON.stringify(json.data);
|
||||
}
|
||||
return "[]";
|
||||
},
|
||||
'error': function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件列表失败:' + textStatus);
|
||||
}
|
||||
},
|
||||
'themes': {
|
||||
'name': 'default',
|
||||
'responsive': true
|
||||
},
|
||||
'check_callback': true,
|
||||
'multiple': false
|
||||
},
|
||||
'types': {
|
||||
'default': {
|
||||
'icon': 'bi bi-file-text'
|
||||
},
|
||||
'folder': {
|
||||
'icon': 'bi bi-folder'
|
||||
},
|
||||
'python': {
|
||||
'icon': 'bi bi-filetype-py'
|
||||
},
|
||||
'json': {
|
||||
'icon': 'bi bi-filetype-json'
|
||||
},
|
||||
'shell': {
|
||||
'icon': 'bi bi-filetype-sh'
|
||||
}
|
||||
},
|
||||
'plugins': ['types']
|
||||
}).on('ready.jstree', function() {
|
||||
// 文件树初始化完成
|
||||
});
|
||||
|
||||
// 文件树节点点击事件
|
||||
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||
const node = data.node;
|
||||
if (node.original.type != 'folder') {
|
||||
loadFile(node.id);
|
||||
}
|
||||
});
|
||||
|
||||
// 加载文件内容
|
||||
function loadFile(path) {
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path), function(response) {
|
||||
if (response.success) {
|
||||
// 使用js-base64库解码
|
||||
const content = Base64.decode(response.data);
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
switch(ext) {
|
||||
case 'py':
|
||||
editor.setOption('mode', 'text/x-python');
|
||||
break;
|
||||
case 'json':
|
||||
editor.setOption('mode', 'application/json');
|
||||
break;
|
||||
case 'sh':
|
||||
editor.setOption('mode', 'text/x-sh');
|
||||
break;
|
||||
case 'html':
|
||||
editor.setOption('mode', 'text/html');
|
||||
break;
|
||||
case 'js':
|
||||
editor.setOption('mode', 'javascript');
|
||||
break;
|
||||
case 'css':
|
||||
editor.setOption('mode', 'css');
|
||||
break;
|
||||
default:
|
||||
editor.setOption('mode', 'text/plain');
|
||||
}
|
||||
editor.setValue(content);
|
||||
$('#currentFile').text(path);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
}
|
||||
|
||||
// 保存文件
|
||||
$('#saveFile').click(function() {
|
||||
const path = $('#currentFile').text();
|
||||
// 使用js-base64库编码
|
||||
const content = Base64.encode(editor.getValue());
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: content
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('保存文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('保存文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 删除文件
|
||||
$('#deleteFile').click(function() {
|
||||
if (confirm('确定要删除这个文件吗?')) {
|
||||
const path = $('#currentFile').text();
|
||||
$.ajax({
|
||||
url: '/api/script/delete',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件删除成功');
|
||||
$('#currentFile').text('未选择文件');
|
||||
editor.setValue('');
|
||||
$('#saveFile, #deleteFile').prop('disabled', true);
|
||||
$('#fileTree').jstree('refresh');
|
||||
} else {
|
||||
showToast('删除文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('删除文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 刷新文件树
|
||||
$('#refreshTree').click(function() {
|
||||
console.log('刷新文件树');
|
||||
$('#fileTree').jstree('refresh');
|
||||
});
|
||||
|
||||
scriptTabInited = true;
|
||||
}
|
||||
if (target === '#var' && !varTabInited) {
|
||||
// 初始化变量设置标签页
|
||||
varEditor = document.getElementById('varEditor');
|
||||
|
||||
// 设置初始提示文本
|
||||
varEditor.value = "点击'读取变量'按钮来加载当前变量配置...";
|
||||
|
||||
// 绑定读取变量按钮事件
|
||||
$('#getVar').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'get_var'
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('正在读取变量配置...');
|
||||
});
|
||||
|
||||
// 绑定保存变量按钮事件
|
||||
$('#setVar').click(function() {
|
||||
try {
|
||||
// 验证JSON格式
|
||||
const varContent = varEditor.value.trim();
|
||||
if (!varContent) {
|
||||
showToast('请输入变量配置内容');
|
||||
return;
|
||||
}
|
||||
|
||||
// 尝试解析JSON
|
||||
const varData = JSON.parse(varContent);
|
||||
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'set_var',
|
||||
value: varData
|
||||
}
|
||||
wsPublish(topic_control, msg);
|
||||
showToast('正在保存变量配置...');
|
||||
} catch (e) {
|
||||
showToast('JSON格式错误:' + e.message);
|
||||
}
|
||||
});
|
||||
|
||||
varTabInited = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){"use strict";s.defineMode("shell",function(){var o={};function e(e,t){for(var n=0;n<t.length;n++)o[t[n]]=e}var t=["true","false"],n=["if","then","do","else","elif","while","until","for","in","esac","fi","fin","fil","done","exit","set","unset","export","function"],r=["ab","awk","bash","beep","cat","cc","cd","chown","chmod","chroot","clear","cp","curl","cut","diff","echo","find","gawk","gcc","get","git","grep","hg","kill","killall","ln","ls","make","mkdir","openssl","mv","nc","nl","node","npm","ping","ps","restart","rm","rmdir","sed","service","sh","shopt","shred","source","sort","sleep","ssh","start","stop","su","sudo","svn","tee","telnet","top","touch","vi","vim","wall","wc","wget","who","write","yes","zsh"];function i(e,t){if(e.eatSpace())return null;var n,r=e.sol(),i=e.next();if("\\"===i)return e.next(),null;if("'"===i||'"'===i||"`"===i)return t.tokens.unshift(f(i,"`"===i?"quote":"string")),l(e,t);if("#"===i)return r&&e.eat("!")?(e.skipToEnd(),"meta"):(e.skipToEnd(),"comment");if("$"===i)return t.tokens.unshift(u),l(e,t);if("+"===i||"="===i)return"operator";if("-"===i)return e.eat("-"),e.eatWhile(/\w/),"attribute";if("<"==i){if(e.match("<<"))return"operator";r=e.match(/^<-?\s*['"]?([^'"]*)['"]?/);if(r)return t.tokens.unshift((n=r[1],function(e,t){return e.sol()&&e.string==n&&t.tokens.shift(),e.skipToEnd(),"string-2"})),"string-2"}if(/\d/.test(i)&&(e.eatWhile(/\d/),e.eol()||!/\w/.test(e.peek())))return"number";e.eatWhile(/[\w-]/);i=e.current();return"="===e.peek()&&/\w+/.test(i)?"def":o.hasOwnProperty(i)?o[i]:null}function f(i,o){var s="("==i?")":"{"==i?"}":i;return function(e,t){for(var n,r=!1;null!=(n=e.next());){if(n===s&&!r){t.tokens.shift();break}if("$"===n&&!r&&"'"!==i&&e.peek()!=s){r=!0,e.backUp(1),t.tokens.unshift(u);break}if(!r&&i!==s&&n===i)return t.tokens.unshift(f(i,o)),l(e,t);if(!r&&/['"]/.test(n)&&!/['"]/.test(i)){t.tokens.unshift(function(n,r){return function(e,t){return t.tokens[0]=f(n,r),e.next(),l(e,t)}}(n,"string")),e.backUp(1);break}r=!r&&"\\"===n}return o}}s.registerHelper("hintWords","shell",t.concat(n,r)),e("atom",t),e("keyword",n),e("builtin",r);var u=function(e,t){1<t.tokens.length&&e.eat("$");var n=e.next();return/['"({]/.test(n)?(t.tokens[0]=f(n,"("==n?"quote":"{"==n?"def":"string"),l(e,t)):(/\d/.test(n)||e.eatWhile(/\w/),t.tokens.shift(),"def")};function l(e,t){return(t.tokens[0]||i)(e,t)}return{startState:function(){return{tokens:[]}},token:l,closeBrackets:"()[]{}''\"\"``",lineComment:"#",fold:"brace"}}),s.defineMIME("text/x-sh","shell"),s.defineMIME("application/x-sh","shell")});
|
||||
@@ -0,0 +1,214 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>高压电源管理系统1</title>
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/jstree/3.3.12/themes/default/style.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/codemirror.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/theme/monokai.min.css" rel="stylesheet">
|
||||
|
||||
<link href="css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- 导航栏 -->
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="/">高压电源管理系统</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid mt-4">
|
||||
<!-- Toast提示组件 -->
|
||||
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong class="me-auto">系统提示</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="toast-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 选项卡 -->
|
||||
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||
脚本编辑器</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content" id="mainTabContent">
|
||||
<!-- 控制面板 -->
|
||||
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设备控制</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="reboot">重启设备</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_start">启动程序</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_stop">停止程序</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_restart">重启程序</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-danger" id="hvEnable">开启高压</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-success" id="hvDisable">关闭高压</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-danger" id="rayEnable">开启射线</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-success" id="rayDisable">关闭射线</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设定参数</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label for="setVoltage" class="form-label">设定电压 (kV)</label>
|
||||
<input type="number" class="form-control" id="setVoltage" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="setCurrent" class="form-label">设定电流 (mA)</label>
|
||||
<input type="number" class="form-control" id="setCurrent" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="filaPreheatCurrent" class="form-label">灯丝预热电流 (A)</label>
|
||||
<input type="number" class="form-control" id="filaPreheatCurrent" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="filaLimitCurrent" class="form-label">灯丝限制电流 (A)</label>
|
||||
<input type="number" class="form-control" id="filaLimitCurrent" value="0">
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-primary" id="getParams">读取参数</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-primary" id="setParams">设置参数</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">实时状态</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">电源状态</label>
|
||||
<div class="form-control" id="vinState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">高压状态</label>
|
||||
<div class="form-control" id="hvState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">射线状态</label>
|
||||
<div class="form-control" id="rayState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">反馈电压 (kV)</label>
|
||||
<div class="form-control" id="feedbackVoltage">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">反馈电流 (mA)</label>
|
||||
<div class="form-control" id="feedbackCurrent">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">灯丝电压 (V)</label>
|
||||
<div class="form-control" id="filamentVoltage">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">灯丝电流 (A)</label>
|
||||
<div class="form-control" id="filamentCurrent">--</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 脚本编辑器 -->
|
||||
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>文件目录</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="fileTree"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span id="currentFile">未选择文件</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||
<i class="bi bi-save"></i> 保存
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<textarea id="editor"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/jquery.min.js"></script>
|
||||
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> -->
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/jstree/3.3.12/jstree.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/shell/shell.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/htmlmixed/htmlmixed.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/xml/xml.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/css/css.min.js"></script>
|
||||
<script src="js/base64.min.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,190 @@
|
||||
import os
|
||||
import json
|
||||
import binascii
|
||||
import sys
|
||||
sys.path.append('/script/MicroWebSrv')
|
||||
from microWebSrv import MicroWebSrv
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ========== 文件系统API ========== #
|
||||
SCRIPT_ROOT = '/'
|
||||
|
||||
@MicroWebSrv.route('/api/script/list')
|
||||
def api_script_list(httpClient, httpResponse):
|
||||
params = httpClient.GetRequestQueryParams()
|
||||
rel_path = params.get('id', '')
|
||||
if rel_path.startswith('#'):
|
||||
rel_path = rel_path[1:]
|
||||
print("Listing scripts in path: ", rel_path)
|
||||
abs_path = rel_path if rel_path else '/'
|
||||
if abs_path == '#':
|
||||
abs_path = '/'
|
||||
if not abs_path.startswith('/'):
|
||||
abs_path = '/' + abs_path
|
||||
print("abs path: ", abs_path)
|
||||
# 防止越权
|
||||
if not abs_path.startswith(SCRIPT_ROOT):
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
|
||||
return
|
||||
data = []
|
||||
try:
|
||||
for name in os.listdir(abs_path):
|
||||
# item_path = os.path.join(abs_path, name)
|
||||
if abs_path.endswith('/'):
|
||||
item_path = abs_path + name
|
||||
else:
|
||||
item_path = abs_path + '/' + name
|
||||
try:
|
||||
is_dir = os.stat(item_path)[0] & 0x4000 == 0x4000
|
||||
except:
|
||||
is_dir = False
|
||||
file_type = 'folder' if is_dir else 'file'
|
||||
if not is_dir:
|
||||
# ext = os.path.splitext(name)[1].lower()
|
||||
dotidx = name.rfind('.')
|
||||
ext = name[dotidx:].lower() if dotidx >= 0 else ''
|
||||
if ext == '.py': file_type = 'python'
|
||||
elif ext == '.json': file_type = 'json'
|
||||
elif ext == '.sh': file_type = 'shell'
|
||||
elif ext == '.js': file_type = 'js'
|
||||
elif ext == '.css': file_type = 'css'
|
||||
elif ext == '.html': file_type = 'html'
|
||||
# id_path = os.path.join(rel_path, name).replace('\\', '/')
|
||||
if rel_path.endswith('/') or rel_path == '':
|
||||
id_path = rel_path + name
|
||||
else:
|
||||
id_path = rel_path + '/' + name
|
||||
id_path = id_path.replace('\\', '/')
|
||||
data.append({
|
||||
"id": id_path,
|
||||
"text": name,
|
||||
"type": file_type,
|
||||
"children": is_dir,
|
||||
"state": {"opened": False, "disabled": False, "selected": False}
|
||||
})
|
||||
httpResponse.WriteResponseJSONOk({"success": True, "data": data})
|
||||
except Exception as e:
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
|
||||
|
||||
@MicroWebSrv.route('/api/script/read')
|
||||
def api_script_read(httpClient, httpResponse):
|
||||
params = httpClient.GetRequestQueryParams()
|
||||
rel_path = params.get('path', '')
|
||||
# abs_path = os.path.abspath(os.path.join(SCRIPT_ROOT, rel_path.lstrip('/')))
|
||||
abs_path = '/' + rel_path
|
||||
if not abs_path.startswith(SCRIPT_ROOT):
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
|
||||
return
|
||||
# 判断文件是否存在
|
||||
try:
|
||||
st = os.stat(abs_path)
|
||||
is_file = not (st[0] & 0x4000 == 0x4000)
|
||||
except:
|
||||
is_file = False
|
||||
if not is_file:
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": "File not found"})
|
||||
return
|
||||
try:
|
||||
with open(abs_path, 'rb') as f:
|
||||
content = f.read()
|
||||
encoded = binascii.b2a_base64(content).decode('ascii').rstrip('\n')
|
||||
httpResponse.WriteResponseJSONOk({"success": True, "data": encoded})
|
||||
except Exception as e:
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
|
||||
|
||||
@MicroWebSrv.route('/api/script/write', 'POST')
|
||||
def api_script_write(httpClient, httpResponse):
|
||||
try:
|
||||
data = httpClient.ReadRequestContentAsJSON()
|
||||
rel_path = data.get('path', '')
|
||||
content_b64 = data.get('content', '')
|
||||
abs_path = '/' + rel_path
|
||||
if not abs_path.startswith(SCRIPT_ROOT):
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
|
||||
return
|
||||
# 确保目录存在
|
||||
# dir_path = os.path.dirname(abs_path)
|
||||
slash_idx = abs_path.rfind('/')
|
||||
if slash_idx > 0:
|
||||
dir_path = abs_path[:slash_idx]
|
||||
try:
|
||||
os.mkdir(dir_path)
|
||||
except:
|
||||
pass
|
||||
# base64解码
|
||||
content = binascii.a2b_base64(content_b64)
|
||||
with open(abs_path, 'wb') as f:
|
||||
f.write(content)
|
||||
httpResponse.WriteResponseJSONOk({"success": True, "message": "File saved successfully"})
|
||||
except Exception as e:
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
|
||||
|
||||
@MicroWebSrv.route('/api/script/delete', 'POST')
|
||||
def api_script_delete(httpClient, httpResponse):
|
||||
try:
|
||||
data = httpClient.ReadRequestContentAsJSON()
|
||||
rel_path = data.get('path', '')
|
||||
abs_path = '/' + rel_path
|
||||
if not abs_path.startswith(SCRIPT_ROOT):
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
|
||||
return
|
||||
# 判断文件是否存在
|
||||
try:
|
||||
st = os.stat(abs_path)
|
||||
is_file = not (st[0] & 0x4000 == 0x4000)
|
||||
except:
|
||||
is_file = False
|
||||
if is_file:
|
||||
os.remove(abs_path)
|
||||
httpResponse.WriteResponseJSONOk({"success": True, "message": "File deleted successfully"})
|
||||
else:
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": "File not found"})
|
||||
except Exception as e:
|
||||
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
def _acceptWebSocketCallback(webSocket, httpClient) :
|
||||
print("WS ACCEPT")
|
||||
webSocket.RecvTextCallback = _recvTextCallback
|
||||
webSocket.RecvBinaryCallback = _recvBinaryCallback
|
||||
webSocket.ClosedCallback = _closedCallback
|
||||
|
||||
def _recvTextCallback(webSocket, msg) :
|
||||
print("WS RECV TEXT : %s" % msg)
|
||||
webSocket.SendText("Reply for %s" % msg)
|
||||
|
||||
def _recvBinaryCallback(webSocket, data) :
|
||||
print("WS RECV DATA : %s" % data)
|
||||
|
||||
def _closedCallback(webSocket) :
|
||||
print("WS CLOSED")
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
#routeHandlers = [
|
||||
# ( "/test", "GET", _httpHandlerTestGet ),
|
||||
# ( "/test", "POST", _httpHandlerTestPost )
|
||||
#]
|
||||
|
||||
|
||||
def py_server():
|
||||
print('py server start')
|
||||
srv = MicroWebSrv(port=8002,webPath='./')
|
||||
srv.MaxWebSocketRecvLen = 256
|
||||
srv.WebSocketThreaded = True
|
||||
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
|
||||
srv.Start()
|
||||
|
||||
import _thread
|
||||
import time
|
||||
|
||||
_thread.start_new_thread(py_server,())
|
||||
|
||||
print('main thread ')
|
||||
while True:
|
||||
print('hello')
|
||||
time.sleep_ms(1000)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
@@ -0,0 +1,85 @@
|
||||
.card {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.form-control {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
#feedbackVoltage,
|
||||
#feedbackCurrent,
|
||||
#filamentVoltage,
|
||||
#filamentCurrent {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: bold;
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.navbar {
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.nav-link i {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
/* 编辑器相关样式 */
|
||||
.CodeMirror {
|
||||
height: calc(100vh - 200px);
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#fileTree {
|
||||
height: calc(100vh - 200px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-icon {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon {
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.jstree-default .jstree-themeicon-custom {
|
||||
color: #0d6efd;
|
||||
}
|
||||
|
||||
/* 文件类型图标颜色 */
|
||||
.bi-filetype-py {
|
||||
color: #306998;
|
||||
}
|
||||
|
||||
.bi-filetype-json {
|
||||
color: #f7df1e;
|
||||
}
|
||||
|
||||
.bi-filetype-sh {
|
||||
color: #4eaa25;
|
||||
}
|
||||
|
||||
.bi-folder {
|
||||
color: #ffc107;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>高压电源管理系统</title>
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/jstree/3.3.12/themes/default/style.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/codemirror.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/theme/monokai.min.css" rel="stylesheet">
|
||||
|
||||
<link href="css/style.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- 导航栏 -->
|
||||
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||
<div class="container">
|
||||
<a class="navbar-brand" href="/">高压电源管理系统</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="container-fluid mt-4">
|
||||
<!-- Toast提示组件 -->
|
||||
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong class="me-auto">系统提示</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="toast-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 选项卡 -->
|
||||
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||
脚本编辑器</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="tab-content" id="mainTabContent">
|
||||
<!-- 控制面板 -->
|
||||
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设备控制</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="reboot">重启设备</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_start">启动程序</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_stop">停止程序</button>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" id="hv_service_restart">重启程序</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-danger" id="hvEnable">开启高压</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-success" id="hvDisable">关闭高压</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-danger" id="rayEnable">开启射线</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-success" id="rayDisable">关闭射线</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">设定参数</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label for="setVoltage" class="form-label">设定电压 (kV)</label>
|
||||
<input type="number" class="form-control" id="setVoltage" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="setCurrent" class="form-label">设定电流 (mA)</label>
|
||||
<input type="number" class="form-control" id="setCurrent" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="filaPreheatCurrent" class="form-label">灯丝预热电流 (A)</label>
|
||||
<input type="number" class="form-control" id="filaPreheatCurrent" value="0">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="filaLimitCurrent" class="form-label">灯丝限制电流 (A)</label>
|
||||
<input type="number" class="form-control" id="filaLimitCurrent" value="0">
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-primary" id="getParams">读取参数</button>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button class="btn btn-primary" id="setParams">设置参数</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header">实时状态</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">电源状态</label>
|
||||
<div class="form-control" id="vinState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">高压状态</label>
|
||||
<div class="form-control" id="hvState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">射线状态</label>
|
||||
<div class="form-control" id="rayState">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">反馈电压 (kV)</label>
|
||||
<div class="form-control" id="feedbackVoltage">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">反馈电流 (mA)</label>
|
||||
<div class="form-control" id="feedbackCurrent">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">灯丝电压 (V)</label>
|
||||
<div class="form-control" id="filamentVoltage">--</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">灯丝电流 (A)</label>
|
||||
<div class="form-control" id="filamentCurrent">--</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 脚本编辑器 -->
|
||||
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||
<div class="row">
|
||||
<div class="col-md-3">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span>文件目录</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="fileTree"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-9">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span id="currentFile">未选择文件</span>
|
||||
<div>
|
||||
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||
<i class="bi bi-save"></i> 保存
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||
<i class="bi bi-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<textarea id="editor"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/jstree/3.3.12/jstree.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/shell/shell.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/htmlmixed/htmlmixed.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/xml/xml.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/codemirror/5.65.2/mode/css/css.min.js"></script>
|
||||
<script src="https://cdn.bootcdn.net/ajax/libs/mqtt/4.3.7/mqtt.min.js"></script>
|
||||
<script src="js/base64.min.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Minified by jsDelivr using Terser v5.15.1.
|
||||
* Original file: /npm/js-base64@3.7.5/base64.js
|
||||
*
|
||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||
*/
|
||||
!function(t,n){var r,e;"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(r=t.Base64,(e=n()).noConflict=function(){return t.Base64=r,e},t.Meteor&&(Base64=e),t.Base64=e)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,(function(){"use strict";var t,n="3.7.5",r="function"==typeof atob,e="function"==typeof btoa,o="function"==typeof Buffer,u="function"==typeof TextDecoder?new TextDecoder:void 0,i="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),c=(t={},f.forEach((function(n,r){return t[n]=r})),t),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,d=String.fromCharCode.bind(String),s="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){return new Uint8Array(Array.prototype.slice.call(t,0))},l=function(t){return t.replace(/=/g,"").replace(/[+\/]/g,(function(t){return"+"==t?"-":"_"}))},h=function(t){return t.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(t){for(var n,r,e,o,u="",i=t.length%3,c=0;c<t.length;){if((r=t.charCodeAt(c++))>255||(e=t.charCodeAt(c++))>255||(o=t.charCodeAt(c++))>255)throw new TypeError("invalid character found");u+=f[(n=r<<16|e<<8|o)>>18&63]+f[n>>12&63]+f[n>>6&63]+f[63&n]}return i?u.slice(0,i-3)+"===".substring(i):u},y=e?function(t){return btoa(t)}:o?function(t){return Buffer.from(t,"binary").toString("base64")}:p,A=o?function(t){return Buffer.from(t).toString("base64")}:function(t){for(var n=[],r=0,e=t.length;r<e;r+=4096)n.push(d.apply(null,t.subarray(r,r+4096)));return y(n.join(""))},b=function(t,n){return void 0===n&&(n=!1),n?l(A(t)):A(t)},g=function(t){if(t.length<2)return(n=t.charCodeAt(0))<128?t:n<2048?d(192|n>>>6)+d(128|63&n):d(224|n>>>12&15)+d(128|n>>>6&63)+d(128|63&n);var n=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return d(240|n>>>18&7)+d(128|n>>>12&63)+d(128|n>>>6&63)+d(128|63&n)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,x=function(t){return t.replace(B,g)},C=o?function(t){return Buffer.from(t,"utf8").toString("base64")}:i?function(t){return A(i.encode(t))}:function(t){return y(x(t))},m=function(t,n){return void 0===n&&(n=!1),n?l(C(t)):C(t)},v=function(t){return m(t,!0)},U=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,F=function(t){switch(t.length){case 4:var n=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return d(55296+(n>>>10))+d(56320+(1023&n));case 3:return d((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return d((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},w=function(t){return t.replace(U,F)},S=function(t){if(t=t.replace(/\s+/g,""),!a.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(3&t.length));for(var n,r,e,o="",u=0;u<t.length;)n=c[t.charAt(u++)]<<18|c[t.charAt(u++)]<<12|(r=c[t.charAt(u++)])<<6|(e=c[t.charAt(u++)]),o+=64===r?d(n>>16&255):64===e?d(n>>16&255,n>>8&255):d(n>>16&255,n>>8&255,255&n);return o},E=r?function(t){return atob(h(t))}:o?function(t){return Buffer.from(t,"base64").toString("binary")}:S,D=o?function(t){return s(Buffer.from(t,"base64"))}:function(t){return s(E(t).split("").map((function(t){return t.charCodeAt(0)})))},R=function(t){return D(T(t))},z=o?function(t){return Buffer.from(t,"base64").toString("utf8")}:u?function(t){return u.decode(D(t))}:function(t){return w(E(t))},T=function(t){return h(t.replace(/[-_]/g,(function(t){return"-"==t?"+":"/"})))},Z=function(t){return z(T(t))},j=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}},I=function(){var t=function(t,n){return Object.defineProperty(String.prototype,t,j(n))};t("fromBase64",(function(){return Z(this)})),t("toBase64",(function(t){return m(this,t)})),t("toBase64URI",(function(){return m(this,!0)})),t("toBase64URL",(function(){return m(this,!0)})),t("toUint8Array",(function(){return R(this)}))},O=function(){var t=function(t,n){return Object.defineProperty(Uint8Array.prototype,t,j(n))};t("toBase64",(function(t){return b(this,t)})),t("toBase64URI",(function(){return b(this,!0)})),t("toBase64URL",(function(){return b(this,!0)}))},P={version:n,VERSION:"3.7.5",atob:E,atobPolyfill:S,btoa:y,btoaPolyfill:p,fromBase64:Z,toBase64:m,encode:m,encodeURI:v,encodeURL:v,utob:x,btou:w,decode:Z,isValid:function(t){if("string"!=typeof t)return!1;var n=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(n)||!/[^\s0-9a-zA-Z\-_]/.test(n)},fromUint8Array:b,toUint8Array:R,extendString:I,extendUint8Array:O,extendBuiltins:function(){I(),O()},Base64:{}};return Object.keys(P).forEach((function(t){return P.Base64[t]=P[t]})),P}));
|
||||
//# sourceMappingURL=/sm/555281732ed54ee1693a772f485329378d8ea5052ffa4370e9c2e9947eb42d22.map
|
||||
@@ -0,0 +1,392 @@
|
||||
$(document).ready(function() {
|
||||
const topic_control = '/dev/control/hsv/1';
|
||||
const topic_status = '/dev/status/hsv/1';
|
||||
const topic_response = '/dev/response/hsv/1';
|
||||
// ================== 控制面板相关 ==================
|
||||
// MQTT客户端配置
|
||||
const client = mqtt.connect('ws://123.57.81.127:8085/mqtt', {
|
||||
username: 'mqtt',
|
||||
password: '123456',
|
||||
clientId: 'web_client_' + Math.random().toString(16).substr(2, 8)
|
||||
});
|
||||
|
||||
// Toast初始化
|
||||
const toastEl = document.getElementById('toast');
|
||||
const toast = new bootstrap.Toast(toastEl, {
|
||||
autohide: true,
|
||||
delay: 3000
|
||||
});
|
||||
function showToast(message) {
|
||||
$('.toast-body').text(message);
|
||||
toast.show();
|
||||
}
|
||||
|
||||
client.on('connect', function() {
|
||||
showToast('已连接到MQTT服务器');
|
||||
client.subscribe(topic_status, function(err) {
|
||||
if (!err) {
|
||||
showToast('已订阅 主题'+ topic_status);
|
||||
}
|
||||
});
|
||||
client.subscribe(topic_response, function(err) {
|
||||
if (!err) {
|
||||
showToast('已订阅 ' + topic_response + ' 主题');
|
||||
}
|
||||
});
|
||||
});
|
||||
client.on('message', function(topic, message) {
|
||||
if (topic.startsWith(topic_status)) {
|
||||
try {
|
||||
const data = JSON.parse(message.toString());
|
||||
var iin = parseFloat(data.value.Iin);
|
||||
if (iin > 65) {
|
||||
iin = 0;
|
||||
}
|
||||
var vinState = parseFloat(data.value.Vin).toFixed(1) + 'V ' + parseFloat(iin).toFixed(2) + 'A';
|
||||
$('#vinState').text(vinState)
|
||||
$('#hvState').text(data.value.hv == 'on' ? '高压已打开' : '高压已关闭');
|
||||
$('#rayState').text(data.value.xray == 'on' ? '射线已打开' : '射线已关闭');
|
||||
$('#feedbackVoltage').text(parseFloat(data.value.kV).toFixed(2));
|
||||
$('#feedbackCurrent').text(parseFloat(data.value.mA).toFixed(2));
|
||||
$('#filamentVoltage').text(parseFloat(data.value.fV).toFixed(3));
|
||||
$('#filamentCurrent').text(parseFloat(data.value.fI).toFixed(3));
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
}
|
||||
} else if (topic.startsWith(topic_response)) {
|
||||
try {
|
||||
const data = JSON.parse(message.toString());
|
||||
console.log(data)
|
||||
if (data.command == 'get_params') {
|
||||
$('#setVoltage').val(parseFloat(data.value.kV).toFixed(2));
|
||||
$('#setCurrent').val(parseFloat(data.value.mA).toFixed(2));
|
||||
$('#filaPreheatCurrent').val(parseFloat(data.value.filament.preheat / 1000).toFixed(2));
|
||||
$('#filaLimitCurrent').val(parseFloat(data.value.filament.limit / 1000).toFixed(2));
|
||||
showToast('参数已更新');
|
||||
} else {
|
||||
showToast('请求已发送');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('解析消息失败: ' + e.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
$('#setParams').click(function() {
|
||||
const setVoltage = parseFloat($('#setVoltage').val());
|
||||
const setCurrent = parseFloat($('#setCurrent').val());
|
||||
const filaPreheatCurrent = parseFloat($('#filaPreheatCurrent').val()) * 1000;
|
||||
const filaLimitCurrent = parseFloat($('#filaLimitCurrent').val()) * 1000;
|
||||
var msg = {
|
||||
device_id: '2',
|
||||
device_code: '2#HVS',
|
||||
command: 'set_params',
|
||||
value: {
|
||||
kV: setVoltage,
|
||||
mA: setCurrent,
|
||||
filament : {
|
||||
preheat: filaPreheatCurrent,
|
||||
limit: filaLimitCurrent
|
||||
}
|
||||
}
|
||||
}
|
||||
client.publish(topic_control, JSON.stringify(msg));
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
$('#getParams').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '2#HVS',
|
||||
command: 'get_params'
|
||||
}
|
||||
client.publish(topic_control, JSON.stringify(msg));
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#hvEnable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'hv_control',
|
||||
value: 'on'
|
||||
}
|
||||
client.publish(topic_control, JSON.stringify(msg));
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#hvDisable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'hv_control',
|
||||
value: 'off'
|
||||
}
|
||||
client.publish(topic_control, JSON.stringify(msg));
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
$('#rayEnable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'ray_control',
|
||||
value: 'on'
|
||||
}
|
||||
client.publish(topic_control, JSON.stringify(msg));
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
$('#rayDisable').click(function() {
|
||||
var msg = {
|
||||
device_id: '1',
|
||||
device_code: '1#HVS',
|
||||
command: 'ray_control',
|
||||
value: 'off'
|
||||
}
|
||||
client.publish(topic_control, JSON.stringify(msg));
|
||||
showToast('请求已发送!');
|
||||
});
|
||||
|
||||
|
||||
$('#reboot').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/device/reboot',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#hv_service_start').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/hv_service/start',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
$('#hv_service_stop').click(function() {
|
||||
$.ajax({
|
||||
url: '/api/hv_service/stop',
|
||||
type: 'GET',
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('请求已发送');
|
||||
} else {
|
||||
showToast('请求失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('请求失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$(window).on('beforeunload', function() {
|
||||
client.end();
|
||||
});
|
||||
|
||||
// ================== 脚本编辑器相关 ==================
|
||||
let scriptTabInited = false;
|
||||
let editor = null;
|
||||
|
||||
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
|
||||
console.log('tab shown', e);
|
||||
const target = $(e.target).attr('data-bs-target');
|
||||
if (target === '#script' && !scriptTabInited) {
|
||||
// 初始化CodeMirror
|
||||
editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
|
||||
mode: 'text/x-python',
|
||||
theme: 'monokai',
|
||||
lineNumbers: true,
|
||||
indentUnit: 4,
|
||||
lineWrapping: true,
|
||||
matchBrackets: true,
|
||||
autoCloseBrackets: true
|
||||
});
|
||||
|
||||
editor.setValue("请选择一个文件");
|
||||
|
||||
// 初始化文件树
|
||||
$('#fileTree').jstree({
|
||||
'core': {
|
||||
'data': {
|
||||
'url': function(node) {
|
||||
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||
return url;
|
||||
},
|
||||
'data': function(node) {
|
||||
return { 'id': node.id };
|
||||
},
|
||||
'dataFilter': function(data) {
|
||||
var json = {};
|
||||
try {
|
||||
json = JSON.parse(data);
|
||||
} catch (e) {
|
||||
return "[]";
|
||||
}
|
||||
if (json.success && Array.isArray(json.data)) {
|
||||
return JSON.stringify(json.data);
|
||||
}
|
||||
return "[]";
|
||||
},
|
||||
'error': function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件列表失败:' + textStatus);
|
||||
}
|
||||
},
|
||||
'themes': {
|
||||
'name': 'default',
|
||||
'responsive': true
|
||||
},
|
||||
'check_callback': true,
|
||||
'multiple': false
|
||||
},
|
||||
'types': {
|
||||
'default': {
|
||||
'icon': 'bi bi-file-text'
|
||||
},
|
||||
'folder': {
|
||||
'icon': 'bi bi-folder'
|
||||
},
|
||||
'python': {
|
||||
'icon': 'bi bi-filetype-py'
|
||||
},
|
||||
'json': {
|
||||
'icon': 'bi bi-filetype-json'
|
||||
},
|
||||
'shell': {
|
||||
'icon': 'bi bi-filetype-sh'
|
||||
}
|
||||
},
|
||||
'plugins': ['types']
|
||||
}).on('ready.jstree', function() {
|
||||
// 文件树初始化完成
|
||||
});
|
||||
|
||||
// 文件树节点点击事件
|
||||
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||
const node = data.node;
|
||||
if (node.original.type != 'folder') {
|
||||
loadFile(node.id);
|
||||
}
|
||||
});
|
||||
|
||||
// 加载文件内容
|
||||
function loadFile(path) {
|
||||
$.get('/api/script/read?path=' + encodeURIComponent(path), function(response) {
|
||||
if (response.success) {
|
||||
// 使用js-base64库解码
|
||||
const content = Base64.decode(response.data);
|
||||
const ext = path.split('.').pop().toLowerCase();
|
||||
switch(ext) {
|
||||
case 'py':
|
||||
editor.setOption('mode', 'text/x-python');
|
||||
break;
|
||||
case 'json':
|
||||
editor.setOption('mode', 'application/json');
|
||||
break;
|
||||
case 'sh':
|
||||
editor.setOption('mode', 'text/x-sh');
|
||||
break;
|
||||
case 'html':
|
||||
editor.setOption('mode', 'text/html');
|
||||
break;
|
||||
case 'js':
|
||||
editor.setOption('mode', 'javascript');
|
||||
break;
|
||||
case 'css':
|
||||
editor.setOption('mode', 'css');
|
||||
break;
|
||||
default:
|
||||
editor.setOption('mode', 'text/plain');
|
||||
}
|
||||
editor.setValue(content);
|
||||
$('#currentFile').text(path);
|
||||
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||
} else {
|
||||
showToast('加载文件失败:' + response.message);
|
||||
}
|
||||
}).fail(function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('加载文件失败:服务器错误');
|
||||
});
|
||||
}
|
||||
|
||||
// 保存文件
|
||||
$('#saveFile').click(function() {
|
||||
const path = $('#currentFile').text();
|
||||
// 使用js-base64库编码
|
||||
const content = Base64.encode(editor.getValue());
|
||||
$.ajax({
|
||||
url: '/api/script/write',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path,
|
||||
content: content
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件保存成功');
|
||||
} else {
|
||||
showToast('保存文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('保存文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 删除文件
|
||||
$('#deleteFile').click(function() {
|
||||
if (confirm('确定要删除这个文件吗?')) {
|
||||
const path = $('#currentFile').text();
|
||||
$.ajax({
|
||||
url: '/api/script/delete',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
path: path
|
||||
}),
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
showToast('文件删除成功');
|
||||
$('#currentFile').text('未选择文件');
|
||||
editor.setValue('');
|
||||
$('#saveFile, #deleteFile').prop('disabled', true);
|
||||
$('#fileTree').jstree('refresh');
|
||||
} else {
|
||||
showToast('删除文件失败:' + response.message);
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
showToast('删除文件失败:服务器错误');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 刷新文件树
|
||||
$('#refreshTree').click(function() {
|
||||
console.log('刷新文件树');
|
||||
$('#fileTree').jstree('refresh');
|
||||
});
|
||||
|
||||
scriptTabInited = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Web Finsh</title>
|
||||
<link rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
background: #eee;
|
||||
color: #333;
|
||||
font-family: Ubuntu, sans-serif;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
#nav {
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
top: 0;
|
||||
right: 0;
|
||||
background: #eee;
|
||||
z-index: 9999;
|
||||
}
|
||||
#terminal {
|
||||
font-family: Consolas, Monaco, monospace;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
#terminal .input {
|
||||
height: 1em;
|
||||
min-width: 1em;
|
||||
outline-color: transparent;
|
||||
border: none;
|
||||
display: inline-block;
|
||||
}
|
||||
#terminal p {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="nav">
|
||||
<div style="font-size:30px;"><b>Web Terminal for RT-Thread finsh</b>
|
||||
<div class="wsStatus" style="font-size:15px">Web finsh <font color="FF9900" size=5><b>connecting</b></font>...</div>
|
||||
</div>
|
||||
<hr color="#C0C0C0" size="1px"/>
|
||||
</div>
|
||||
<div id="terminal" spellcheck="false">
|
||||
<p class="hidden">
|
||||
<br/>
|
||||
<br/>
|
||||
<br/>
|
||||
<br/>
|
||||
<br/>
|
||||
<span class="prompt"></span>
|
||||
<div contenteditable="true" class="input">
|
||||
<span class="prompt">msh /></span>
|
||||
</div>
|
||||
</p>
|
||||
</div>
|
||||
<script>
|
||||
var Terminal = (function () {
|
||||
var KEY_LEFT = 37,
|
||||
KEY_UP = 38,
|
||||
KEY_RIGHT = 39,
|
||||
KEY_DOWN = 40,
|
||||
KEY_TAB = 9,
|
||||
KEY_ENTER = 13,
|
||||
KEY_BACKSPACE = 8;
|
||||
KEY_DELETE = 46;
|
||||
|
||||
function setFocusToDivEnd(obj) {
|
||||
if (window.getSelection) {
|
||||
obj.focus();
|
||||
var range = window.getSelection();
|
||||
range.selectAllChildren(obj);
|
||||
/* 光标移至最后 */
|
||||
range.collapseToEnd();
|
||||
} else if (document.selection) {
|
||||
var range = document.selection.createRange();
|
||||
/* range定位到obj */
|
||||
range.moveToElementText(obj);
|
||||
/* 光标移至最后 */
|
||||
range.collapse(false);
|
||||
range.select();
|
||||
}
|
||||
}
|
||||
|
||||
self.init = function (elem, wsUrl) {
|
||||
var input = document.querySelector('.input');
|
||||
var wsStatus = document.querySelector('.wsStatus');
|
||||
var line;
|
||||
|
||||
var ws = new WebSocket(wsUrl);
|
||||
ws.onopen = function (ev) {
|
||||
wsStatus.innerHTML = "Web finsh is <font color=\"Green\" size=5><b>connected</b></font>.";
|
||||
console.log(ev);
|
||||
};
|
||||
ws.onerror = function (ev) {
|
||||
wsStatus.innerHTML = "Web finsh connect has <font color=\"Red\" size=5><b>error</b></font>.";
|
||||
console.log(ev);
|
||||
};
|
||||
ws.onclose = function (ev) {
|
||||
wsStatus.innerHTML = "Web finsh connection <font color=\"Red\" size=5><b>closed</b></font>.";
|
||||
console.log(ev);
|
||||
};
|
||||
ws.onmessage = function (ev) {
|
||||
/* console.log(ev); */
|
||||
/* 添加接收到的数据 */
|
||||
var spanEle = document.createElement("span");
|
||||
/* html 转义 */
|
||||
spanEle.innerHTML = ev.data.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/\n/g, '<br/>').replace(/\s/g, ' ');
|
||||
input.appendChild(spanEle);
|
||||
setFocusToDivEnd(input);
|
||||
/* 页面自动滚动至底部 */
|
||||
var bo = document.getElementsByTagName("body")[0];
|
||||
bo.scrollTop = bo.scrollHeight;
|
||||
};
|
||||
|
||||
document.addEventListener("keydown",
|
||||
function (event) {
|
||||
if (event.keyCode == KEY_TAB) {
|
||||
ws.send(String.fromCharCode(event.keyCode));
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_LEFT) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x44)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_UP) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x41)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_DOWN) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x42)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_RIGHT) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x43)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_BACKSPACE) {
|
||||
/* ws.send(String.fromCharCode(event.keyCode)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_DELETE) {
|
||||
/* ws.send(String.fromCharCode(event.keyCode)); */
|
||||
event.preventDefault(true);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
document.addEventListener("keyup",
|
||||
function (event) {
|
||||
return false;
|
||||
});
|
||||
|
||||
document.addEventListener("keypress",
|
||||
function (event) {
|
||||
/* 转发输入数据至 WebSocket 服务器 */
|
||||
ws.send(String.fromCharCode(event.keyCode));
|
||||
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
setFocusToDivEnd(input);
|
||||
return self;
|
||||
};
|
||||
|
||||
return self;
|
||||
})();
|
||||
Terminal.init(document.getElementById("terminal"), 'ws://' + location.host + ':8090/finsh');
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Terminal container.
|
||||
* Important note: The "VT323" font face comes from Google web fonts.
|
||||
*/
|
||||
#terminal {
|
||||
font-family: Consolas, Monaco, monospace;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/**
|
||||
* The input span where the input happens.
|
||||
* Also applied to the previous inputs made in the current session.
|
||||
*/
|
||||
#terminal .input {
|
||||
height: 1em;
|
||||
min-width: 1em;
|
||||
outline-color: transparent;
|
||||
border: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#terminal p {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
var Terminal = (function () {
|
||||
var KEY_LEFT = 37,
|
||||
KEY_UP = 38,
|
||||
KEY_RIGHT = 39,
|
||||
KEY_DOWN = 40,
|
||||
KEY_TAB = 9,
|
||||
KEY_ENTER = 13,
|
||||
KEY_BACKSPACE = 8;
|
||||
KEY_DELETE = 46;
|
||||
|
||||
function setFocusToDivEnd(obj) {
|
||||
if (window.getSelection) {
|
||||
obj.focus();
|
||||
var range = window.getSelection();
|
||||
range.selectAllChildren(obj);
|
||||
/* 光标移至最后 */
|
||||
range.collapseToEnd();
|
||||
} else if (document.selection) {
|
||||
var range = document.selection.createRange();
|
||||
/* range定位到obj */
|
||||
range.moveToElementText(obj);
|
||||
/* 光标移至最后 */
|
||||
range.collapse(false);
|
||||
range.select();
|
||||
}
|
||||
}
|
||||
|
||||
self.init = function (elem, wsUrl) {
|
||||
var input = document.querySelector('.input');
|
||||
var wsStatus = document.querySelector('.wsStatus');
|
||||
var line;
|
||||
|
||||
var ws = new WebSocket(wsUrl);
|
||||
ws.onopen = function (ev) {
|
||||
wsStatus.innerHTML = "Web finsh is <font color=\"Green\" size=5><b>connected</b></font>.";
|
||||
console.log(ev);
|
||||
};
|
||||
ws.onerror = function (ev) {
|
||||
wsStatus.innerHTML = "Web finsh connect has <font color=\"Red\" size=5><b>error</b></font>.";
|
||||
console.log(ev);
|
||||
};
|
||||
ws.onclose = function (ev) {
|
||||
wsStatus.innerHTML = "Web finsh connection <font color=\"Red\" size=5><b>closed</b></font>.";
|
||||
console.log(ev);
|
||||
};
|
||||
ws.onmessage = function (ev) {
|
||||
/* console.log(ev); */
|
||||
/* 添加接收到的数据 */
|
||||
var spanEle = document.createElement("span");
|
||||
/* html 转义 */
|
||||
spanEle.innerHTML = ev.data.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/\n/g, '<br/>').replace(/\s/g, ' ');
|
||||
input.appendChild(spanEle);
|
||||
setFocusToDivEnd(input);
|
||||
/* 页面自动滚动至底部 */
|
||||
var bo = document.getElementsByTagName("body")[0];
|
||||
bo.scrollTop = bo.scrollHeight;
|
||||
};
|
||||
|
||||
document.addEventListener("keydown",
|
||||
function (event) {
|
||||
if (event.keyCode == KEY_TAB) {
|
||||
ws.send(String.fromCharCode(event.keyCode));
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_LEFT) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x44)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_UP) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x41)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_DOWN) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x42)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_RIGHT) {
|
||||
/* ws.send(String.fromCharCode(0x1B, 0x5B, 0x43)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_BACKSPACE) {
|
||||
/* ws.send(String.fromCharCode(event.keyCode)); */
|
||||
event.preventDefault(true);
|
||||
} else if (event.keyCode == KEY_DELETE) {
|
||||
/* ws.send(String.fromCharCode(event.keyCode)); */
|
||||
event.preventDefault(true);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
document.addEventListener("keyup",
|
||||
function (event) {
|
||||
return false;
|
||||
});
|
||||
|
||||
document.addEventListener("keypress",
|
||||
function (event) {
|
||||
/* 转发输入数据至 WebSocket 服务器 */
|
||||
ws.send(String.fromCharCode(event.keyCode));
|
||||
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
setFocusToDivEnd(input);
|
||||
return self;
|
||||
};
|
||||
|
||||
return self;
|
||||
})();
|
||||