Make plugin importable

Don't start the web server if imported not from inside Anki

Make sure Anki Connect instance is not garbage collected.
This kills the timer that's responsible for the web server.
This commit is contained in:
oakkitten 2022-03-30 19:43:31 +01:00
parent d6061affad
commit 748310def4

View File

@ -58,14 +58,19 @@ class AnkiConnect:
def __init__(self): def __init__(self):
self.log = None self.log = None
self.timer = None
self.server = web.WebServer(self.handler)
def initLogging(self):
logPath = util.setting('apiLogPath') logPath = util.setting('apiLogPath')
if logPath is not None: if logPath is not None:
self.log = open(logPath, 'w') self.log = open(logPath, 'w')
def startWebServer(self):
try: try:
self.server = web.WebServer(self.handler)
self.server.listen() self.server.listen()
# only keep reference to prevent garbage collection
self.timer = QTimer() self.timer = QTimer()
self.timer.timeout.connect(self.advance) self.timer.timeout.connect(self.advance)
self.timer.start(util.setting('apiPollInterval')) self.timer.start(util.setting('apiPollInterval'))
@ -1698,4 +1703,9 @@ class AnkiConnect:
# Entry # Entry
# #
# when run inside Anki, `__name__` would be either numeric,
# or, if installed via `link.sh`, `AnkiConnectDev`
if __name__ != "plugin":
ac = AnkiConnect() ac = AnkiConnect()
ac.initLogging()
ac.startWebServer()