56 lines
1.5 KiB
Python
56 lines
1.5 KiB
Python
|
|
||
|
import os
|
||
|
from gi.repository import Gio, WebKit2
|
||
|
from ._mimetypes import get_mimetype
|
||
|
|
||
|
|
||
|
class Protocal:
|
||
|
root = ''
|
||
|
|
||
|
def __init__(self, webroot = ''):
|
||
|
self.root = os.path.realpath(webroot)
|
||
|
|
||
|
def register(self, webview, name = 'app'):
|
||
|
self.protocal = name
|
||
|
ctx = webview.get_context()
|
||
|
ctx.register_uri_scheme(name, self.handle_response)
|
||
|
# 允许网页通知权限
|
||
|
ctx.initialize_notification_permissions([WebKit2.SecurityOrigin.new_for_uri('app:///index.html')], [])
|
||
|
|
||
|
|
||
|
def abspath(self, filepath):
|
||
|
return os.path.join(self.root, filepath)
|
||
|
|
||
|
|
||
|
def handle_response(self, req):
|
||
|
schema = req.get_scheme()
|
||
|
pathname = req.get_path()[1:]
|
||
|
ext = pathname.split('.')[-1]
|
||
|
|
||
|
# print('----------------------------------------')
|
||
|
# print(req.get_uri(),schema, pathname, ext, get_mimetype(ext))
|
||
|
# print('----------------------------------------')
|
||
|
|
||
|
if schema == self.protocal:
|
||
|
data = open(self.abspath(pathname)).read()
|
||
|
data = Gio.MemoryInputStream.new_from_data(data.encode())
|
||
|
|
||
|
# ------- 更多功能的reponse ----------------
|
||
|
# res = WebKit2.URISchemeResponse.new(data, -1)
|
||
|
# res.set_content_type(get_mimetype(ext))
|
||
|
# res.set_http_headers('text/html')
|
||
|
# res.set_status(200)
|
||
|
# req.finish_with_response(res)
|
||
|
# ----------------------------------------
|
||
|
|
||
|
# 简单的response
|
||
|
req.finish(data, -1, get_mimetype(ext))
|
||
|
|
||
|
|
||
|
def create_protocal(root):
|
||
|
proto = Protocal(root)
|
||
|
|
||
|
def wrapper(app, extra = None):
|
||
|
proto.register(app)
|
||
|
|
||
|
return wrapper
|