From 1fb6123f5abf4a87b812298681c090addf6cb576 Mon Sep 17 00:00:00 2001 From: Glutanimate Date: Tue, 26 Feb 2019 13:07:06 +0100 Subject: [PATCH] Extend mediasrv to also serve media files in addons directory RequestsHandler now rewrites "/_addons" references to addons folder. --- aqt/main.py | 3 ++- aqt/mediasrv.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/aqt/main.py b/aqt/main.py index 279e9f1d2..fe5495107 100644 --- a/aqt/main.py +++ b/aqt/main.py @@ -1350,7 +1350,8 @@ Please ensure a profile is open and Anki is not busy, then try again."""), ########################################################################## def setupMediaServer(self): - self.mediaServer = aqt.mediasrv.MediaServer() + self.mediaServer = aqt.mediasrv.MediaServer( + addonFolder=self.pm.addonFolder()) self.mediaServer.start() def baseHTML(self): diff --git a/aqt/mediasrv.py b/aqt/mediasrv.py index 7ae437ca7..9d1218d32 100644 --- a/aqt/mediasrv.py +++ b/aqt/mediasrv.py @@ -47,7 +47,12 @@ class MediaServer(threading.Thread): _port = None _ready = threading.Event() + def __init__(self, addonFolder=None, *args, **kwargs): + super().__init__(*args, **kwargs) + self._addonFolder = addonFolder + def run(self): + RequestHandler = createRequestHandler(self._addonFolder) self.server = ThreadedHTTPServer(("127.0.0.1", 0), RequestHandler) self._ready.set() self.server.serve_forever() @@ -59,9 +64,15 @@ class MediaServer(threading.Thread): def shutdown(self): self.server.shutdown() +def createRequestHandler(addonFolder): + """RequestHandler factory""" + return type("RequestHandler", (RequestHandler, ), + {"_addonFolder": addonFolder}) + class RequestHandler(http.server.SimpleHTTPRequestHandler): timeout = 1 + _addonFolder = None def do_GET(self): f = self.send_head() @@ -121,11 +132,16 @@ class RequestHandler(http.server.SimpleHTTPRequestHandler): format%args)) # catch /_anki references and rewrite them to web export folder + # catch /_addons references and rewrite them to addons folder def _redirectWebExports(self, path): targetPath = os.path.join(os.getcwd(), "_anki", "") if path.startswith(targetPath): newPath = os.path.join(_exportFolder, path[len(targetPath):]) return newPath + targetPath = os.path.join(os.getcwd(), "_addons", "") + if self._addonFolder and path.startswith(targetPath): + newPath = os.path.join(self._addonFolder, path[len(targetPath):]) + return newPath return path # work around Windows machines with incorrect mime type