anki-connect/AnkiConnect.py

658 lines
16 KiB
Python
Raw Normal View History

2016-05-21 22:10:12 +00:00
# Copyright (C) 2016 Alex Yatskov <alex@foosoft.net>
# Author: Alex Yatskov <alex@foosoft.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import anki
import aqt
2016-07-17 05:01:23 +00:00
import hashlib
2016-05-21 22:10:12 +00:00
import json
2017-01-30 01:34:18 +00:00
import os.path
2016-05-21 22:10:12 +00:00
import select
import socket
2016-05-29 22:49:38 +00:00
#
# Constants
#
API_VERSION = 4
2017-02-19 20:07:10 +00:00
TICK_INTERVAL = 25
2016-07-26 05:54:40 +00:00
URL_TIMEOUT = 10
2017-02-19 20:57:55 +00:00
URL_UPGRADE = 'https://raw.githubusercontent.com/FooSoft/anki-connect/master/anki_connect.py'
2017-02-19 20:07:10 +00:00
NET_ADDRESS = '127.0.0.1'
NET_BACKLOG = 5
NET_PORT = 8765
2016-05-29 22:49:38 +00:00
2017-01-29 01:31:33 +00:00
#
# General helpers
#
try:
import urllib2
2017-01-30 01:34:18 +00:00
web = urllib2
2017-01-29 01:31:33 +00:00
except ImportError:
from urllib import request
2017-01-30 01:34:18 +00:00
web = request
2017-01-29 01:31:33 +00:00
try:
2017-02-19 20:46:40 +00:00
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QMessageBox
2017-01-29 01:31:33 +00:00
except ImportError:
2017-02-19 20:46:40 +00:00
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QMessageBox
2017-01-29 01:31:33 +00:00
2017-02-19 20:07:10 +00:00
try:
unicode
except:
unicode = str
2017-02-19 20:46:40 +00:00
#
# Helpers
#
def makeBytes(data):
return data.encode('utf-8')
def makeStr(data):
return data.decode('utf-8')
2017-02-19 20:57:55 +00:00
def download(url):
2017-02-19 20:46:40 +00:00
try:
resp = web.urlopen(url, timeout=URL_TIMEOUT)
except web.URLError:
return None
if resp.code != 200:
return None
return resp.read()
def audioInject(note, fields, filename):
for field in fields:
if field in note:
note[field] += u'[sound:{}]'.format(filename)
def verifyString(string):
t = type(string)
return t == str or t == unicode
def verifyStringList(strings):
for s in strings:
if not verifyString(s):
return False
return True
2017-01-29 01:31:33 +00:00
2016-05-21 22:10:12 +00:00
#
# AjaxRequest
#
class AjaxRequest:
def __init__(self, headers, body):
self.headers = headers
self.body = body
#
# AjaxClient
#
class AjaxClient:
def __init__(self, sock, handler):
self.sock = sock
self.handler = handler
2017-01-29 01:31:33 +00:00
self.readBuff = bytes()
self.writeBuff = bytes()
2016-05-21 22:10:12 +00:00
def advance(self, recvSize=1024):
if self.sock is None:
return False
rlist, wlist = select.select([self.sock], [self.sock], [], 0)[:2]
if rlist:
msg = self.sock.recv(recvSize)
if not msg:
self.close()
return False
self.readBuff += msg
req, length = self.parseRequest(self.readBuff)
if req is not None:
self.readBuff = self.readBuff[length:]
self.writeBuff += self.handler(req)
if wlist and self.writeBuff:
length = self.sock.send(self.writeBuff)
self.writeBuff = self.writeBuff[length:]
if not self.writeBuff:
self.close()
return False
return True
def close(self):
if self.sock is not None:
self.sock.close()
self.sock = None
2017-01-29 01:31:33 +00:00
self.readBuff = bytes()
self.writeBuff = bytes()
2016-05-21 22:10:12 +00:00
def parseRequest(self, data):
2017-01-29 01:31:33 +00:00
parts = data.split(makeBytes('\r\n\r\n'), 1)
2016-05-21 22:10:12 +00:00
if len(parts) == 1:
return None, 0
headers = {}
2017-01-29 01:31:33 +00:00
for line in parts[0].split(makeBytes('\r\n')):
pair = line.split(makeBytes(': '))
2016-05-21 22:10:12 +00:00
headers[pair[0]] = pair[1] if len(pair) > 1 else None
headerLength = len(parts[0]) + 4
bodyLength = int(headers.get(makeBytes('Content-Length'), 0))
2016-05-21 22:10:12 +00:00
totalLength = headerLength + bodyLength
if totalLength > len(data):
return None, 0
body = data[headerLength : totalLength]
return AjaxRequest(headers, body), totalLength
#
# AjaxServer
#
class AjaxServer:
def __init__(self, handler):
self.handler = handler
self.clients = []
self.sock = None
def advance(self):
if self.sock is not None:
self.acceptClients()
self.advanceClients()
def acceptClients(self):
rlist = select.select([self.sock], [], [], 0)[0]
if not rlist:
return
clientSock = self.sock.accept()[0]
if clientSock is not None:
clientSock.setblocking(False)
self.clients.append(AjaxClient(clientSock, self.handlerWrapper))
def advanceClients(self):
2017-01-29 01:31:33 +00:00
self.clients = list(filter(lambda c: c.advance(), self.clients))
2016-05-21 22:10:12 +00:00
2017-02-19 20:07:10 +00:00
def listen(self):
2016-05-21 22:10:12 +00:00
self.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setblocking(False)
2017-02-19 20:07:10 +00:00
self.sock.bind((NET_ADDRESS, NET_PORT))
self.sock.listen(NET_BACKLOG)
2016-05-21 22:10:12 +00:00
def handlerWrapper(self, req):
if len(req.body) == 0:
2017-02-19 21:18:07 +00:00
body = makeBytes('AnkiConnect v.{}'.format(API_VERSION))
else:
try:
params = json.loads(makeStr(req.body))
body = makeBytes(json.dumps(self.handler(params)))
except ValueError:
body = json.dumps(None);
2016-05-21 22:10:12 +00:00
resp = bytes()
2017-01-29 01:31:33 +00:00
headers = [
['HTTP/1.1 200 OK', None],
['Content-Type', 'text/json'],
['Content-Length', str(len(body))]
]
2016-05-21 22:10:12 +00:00
for key, value in headers:
2016-05-21 22:10:12 +00:00
if value is None:
2017-01-29 01:31:33 +00:00
resp += makeBytes('{}\r\n'.format(key))
2016-05-21 22:10:12 +00:00
else:
2017-01-29 01:31:33 +00:00
resp += makeBytes('{}: {}\r\n'.format(key, value))
2016-05-21 22:10:12 +00:00
2017-01-29 01:31:33 +00:00
resp += makeBytes('\r\n')
2016-05-21 22:10:12 +00:00
resp += body
return resp
def close(self):
if self.sock is not None:
self.sock.close()
self.sock = None
for client in self.clients:
client.close()
self.clients = []
2017-02-19 20:07:10 +00:00
#
# AnkiNoteParams
#
class AnkiNoteParams:
def __init__(self, params):
self.deckName = params.get('deckName')
self.modelName = params.get('modelName')
self.fields = params.get('fields', {})
self.tags = params.get('tags', [])
class Audio:
def __init__(self, params):
self.url = params.get('url')
self.filename = params.get('filename')
self.skipHash = params.get('skipHash')
self.fields = params.get('fields', [])
def validate(self):
return (
verifyString(self.url) and
verifyString(self.filename) and os.path.dirname(self.filename) == '' and
verifyStringList(self.fields) and
(verifyString(self.skipHash) or self.skipHash is None)
)
audio = Audio(params.get('audio', {}))
self.audio = audio if audio.validate() else None
def validate(self):
return (
verifyString(self.deckName) and
verifyString(self.modelName) and
type(self.fields) == dict and verifyStringList(list(self.fields.keys())) and verifyStringList(list(self.fields.values())) and
type(self.tags) == list and verifyStringList(self.tags)
)
2016-05-21 22:10:12 +00:00
#
# AnkiBridge
#
class AnkiBridge:
2017-02-19 20:07:10 +00:00
def addNote(self, params):
2016-05-29 17:31:24 +00:00
collection = self.collection()
if collection is None:
return
2017-02-19 20:07:10 +00:00
note = self.createNote(params)
2016-05-21 22:34:09 +00:00
if note is None:
return
2017-02-19 20:07:10 +00:00
if params.audio is not None and len(params.audio.fields) > 0:
2017-02-19 20:57:55 +00:00
data = download(params.audio.url)
2017-01-30 01:34:18 +00:00
if data is not None:
2017-02-19 20:07:10 +00:00
if params.audio.skipHash is None:
2017-01-30 01:34:18 +00:00
skip = False
else:
m = hashlib.md5()
m.update(data)
2017-02-19 20:07:10 +00:00
skip = params.audio.skipHash == m.hexdigest()
2017-01-30 01:34:18 +00:00
if not skip:
2017-02-19 20:07:10 +00:00
audioInject(note, params.audio.fields, params.audio.filename)
self.media().writeData(params.audio.filename, data)
2016-05-21 22:34:09 +00:00
2016-07-17 16:38:33 +00:00
self.startEditing()
2016-05-21 22:34:09 +00:00
collection.addNote(note)
collection.autosave()
2016-07-17 16:38:33 +00:00
self.stopEditing()
2016-05-21 22:34:09 +00:00
return note.id
2016-05-21 22:10:12 +00:00
2017-02-19 20:07:10 +00:00
def canAddNote(self, note):
return bool(self.createNote(note))
2016-05-21 22:10:12 +00:00
2017-02-19 20:07:10 +00:00
def createNote(self, params):
2016-05-29 17:31:24 +00:00
collection = self.collection()
if collection is None:
return
2017-02-19 20:07:10 +00:00
model = collection.models.byName(params.modelName)
2016-05-21 22:10:12 +00:00
if model is None:
2016-05-21 22:34:09 +00:00
return
2016-05-21 22:10:12 +00:00
2017-02-19 20:07:10 +00:00
deck = collection.decks.byName(params.deckName)
2016-05-21 22:10:12 +00:00
if deck is None:
2016-05-21 22:34:09 +00:00
return
2016-05-21 22:10:12 +00:00
2016-05-29 17:31:24 +00:00
note = anki.notes.Note(collection, model)
2016-05-21 22:10:12 +00:00
note.model()['did'] = deck['id']
2017-02-19 20:07:10 +00:00
note.tags = params.tags
2016-05-21 22:10:12 +00:00
2017-02-19 20:07:10 +00:00
for name, value in params.fields.items():
2016-05-21 22:10:12 +00:00
if name in note:
note[name] = value
if not note.dupeOrEmpty():
return note
def startEditing(self):
self.window().requireReset()
def stopEditing(self):
2016-05-29 17:31:24 +00:00
if self.collection() is not None:
2016-05-21 22:10:12 +00:00
self.window().maybeReset()
def window(self):
return aqt.mw
2017-07-01 19:41:27 +00:00
def reviewer(self):
return self.window().reviewer
2016-05-21 22:10:12 +00:00
def collection(self):
return self.window().col
2017-07-01 19:41:27 +00:00
def scheduler(self):
return self.collection().sched
2016-07-17 16:38:33 +00:00
def media(self):
collection = self.collection()
if collection is not None:
return collection.media
2016-05-21 22:10:12 +00:00
def modelNames(self):
2016-05-29 17:31:24 +00:00
collection = self.collection()
if collection is not None:
return collection.models.allNames()
2016-05-21 22:10:12 +00:00
2017-07-01 19:49:44 +00:00
def modelNameFromId(self, modelId):
2016-05-29 17:31:24 +00:00
collection = self.collection()
2017-07-01 19:41:27 +00:00
if collection is not None:
2017-07-01 19:49:44 +00:00
model = collection.models.get(modelId)
2017-07-01 19:41:27 +00:00
if model is not None:
return model['name']
2016-05-29 17:31:24 +00:00
2017-07-01 19:41:27 +00:00
def modelFieldNames(self, modelName):
collection = self.collection()
if collection is not None:
model = collection.models.byName(modelName)
if model is not None:
return [field['name'] for field in model['flds']]
2016-05-21 22:10:12 +00:00
def deckNames(self):
2016-05-29 17:31:24 +00:00
collection = self.collection()
if collection is not None:
return collection.decks.allNames()
2016-05-21 22:10:12 +00:00
2017-07-01 19:49:44 +00:00
def deckNameFromId(self, deckId):
2017-07-01 19:41:27 +00:00
collection = self.collection()
if collection is not None:
2017-07-01 19:49:44 +00:00
deck = collection.decks.get(deckId)
2017-07-01 19:41:27 +00:00
if deck is not None:
return deck['name']
def guiBrowse(self, query):
2017-05-28 22:54:28 +00:00
browser = aqt.dialogs.open('Browser', self.window())
2017-05-27 12:14:40 +00:00
browser.activateWindow()
2017-05-28 22:54:28 +00:00
2017-07-01 19:49:44 +00:00
if len(query) > 0:
2017-05-28 20:55:24 +00:00
query = unicode('"{}"').format(query)
2017-05-27 12:14:40 +00:00
browser.form.searchEdit.lineEdit().setText(query)
browser.onSearch()
2017-05-28 22:54:28 +00:00
2017-05-27 12:14:40 +00:00
return browser.model.cards
def guiAddCards(self):
2017-05-28 22:54:28 +00:00
addCards = aqt.dialogs.open('AddCards', self.window())
addCards.activateWindow()
2017-05-27 12:14:40 +00:00
2017-07-01 19:41:27 +00:00
def guiReviewActive(self):
return self.reviewer().card is not None
def guiCurrentCard(self):
2017-07-01 19:49:44 +00:00
if not self.guiReviewActive():
2017-07-01 19:41:27 +00:00
return False
reviewer = self.reviewer()
card = reviewer.card
2017-06-29 04:17:11 +00:00
if card is not None:
return {
2017-07-01 19:41:27 +00:00
'cardId': card.id,
'question': card._getQA()['q'],
'answer': card._getQA()['a'],
2017-07-01 19:41:27 +00:00
'buttons': map(lambda b: b[0], self.window().reviewer._answerButtonList()),
'modelName': card.model()['name'],
'deckName': self.deckNameFromId(card.did)
}
2017-06-29 04:17:11 +00:00
def guiShowQuestion(self):
2017-07-01 19:41:27 +00:00
if self.guiReviewActive():
self.reviewer()._showQuestion()
return True
else:
return False
def guiShowAnswer(self):
2017-07-01 19:41:27 +00:00
if self.guiReviewActive():
self.window().reviewer._showAnswer()
2017-07-01 19:41:27 +00:00
return True
else:
return False
2017-07-01 20:16:51 +00:00
def guiAnswerCard(self, ease):
2017-07-01 19:41:27 +00:00
if not self.guiReviewActive():
2017-06-29 04:17:11 +00:00
return False
2017-07-01 19:41:27 +00:00
reviewer = self.reviewer()
if reviewer.state != 'answer':
2017-06-29 04:17:11 +00:00
return False
2017-07-01 20:16:51 +00:00
if ease <= 0 or ease > self.scheduler().answerButtons(reviewer.card):
2017-06-29 04:17:11 +00:00
return False
2017-07-01 19:41:27 +00:00
reviewer._answerCard(ease)
return True
def guiDeckOverview(self, name):
collection = self.collection()
if collection is not None:
deck = collection.decks.byName(name)
if deck is not None:
collection.decks.select(deck['id'])
self.window().onOverview()
return True
return False
def guiDeckBrowser(self):
self.window().moveToState("deckBrowser")
2016-05-21 22:10:12 +00:00
#
# AnkiConnect
#
class AnkiConnect:
2017-02-19 20:07:10 +00:00
def __init__(self):
2016-05-21 22:10:12 +00:00
self.anki = AnkiBridge()
self.server = AjaxServer(self.handler)
2017-02-19 20:46:40 +00:00
try:
self.server.listen()
self.timer = QTimer()
self.timer.timeout.connect(self.advance)
self.timer.start(TICK_INTERVAL)
except:
QMessageBox.critical(
self.anki.window(),
'AnkiConnect',
2017-02-19 20:57:55 +00:00
'Failed to listen on port {}.\nMake sure it is available and is not in use.'.format(NET_PORT)
2017-02-19 20:46:40 +00:00
)
2016-05-21 22:10:12 +00:00
def advance(self):
self.server.advance()
def handler(self, request):
2017-02-19 20:07:10 +00:00
action = 'api_' + request.get('action', '')
2017-07-02 00:12:11 +00:00
params = request.get('params', {})
2016-05-21 22:10:12 +00:00
if hasattr(self, action):
2017-02-19 20:07:10 +00:00
try:
2017-07-02 00:12:11 +00:00
return getattr(self, action)(**params)
2017-02-19 20:07:10 +00:00
except TypeError:
return None
2016-05-21 22:10:12 +00:00
2016-05-21 22:34:09 +00:00
def api_deckNames(self):
return self.anki.deckNames()
def api_modelNames(self):
return self.anki.modelNames()
def api_modelFieldNames(self, modelName):
return self.anki.modelFieldNames(modelName)
2016-05-29 06:23:14 +00:00
def api_addNote(self, note):
2017-02-19 20:07:10 +00:00
params = AnkiNoteParams(note)
if params.validate():
return self.anki.addNote(params)
2016-05-29 06:23:14 +00:00
2017-02-05 20:09:12 +00:00
def api_addNotes(self, notes):
results = []
for note in notes:
2017-02-19 20:07:10 +00:00
params = AnkiNoteParams(note)
2017-03-12 16:43:47 +00:00
if params.validate():
2017-02-19 20:07:10 +00:00
results.append(self.anki.addNote(params))
else:
results.append(None)
2017-02-05 20:09:12 +00:00
return results
2016-05-29 06:23:14 +00:00
def api_canAddNotes(self, notes):
results = []
for note in notes:
2017-02-19 20:07:10 +00:00
params = AnkiNoteParams(note)
results.append(params.validate() and self.anki.canAddNote(params))
2016-05-29 06:23:14 +00:00
return results
2017-02-19 20:57:55 +00:00
def api_upgrade(self):
response = QMessageBox.question(
self.anki.window(),
'AnkiConnect',
'Upgrade to the latest version?',
QMessageBox.Yes | QMessageBox.No
)
if response == QMessageBox.Yes:
data = download(URL_UPGRADE)
if data is None:
2017-02-19 21:18:07 +00:00
QMessageBox.critical(self.anki.window, 'AnkiConnect', 'Failed to download latest version.')
2017-02-19 20:57:55 +00:00
else:
2017-02-19 21:18:07 +00:00
path = os.path.splitext(__file__)[0] + '.py'
with open(path, 'w') as fp:
fp.write(makeStr(data))
2017-02-19 23:02:09 +00:00
QMessageBox.information(self.anki.window(), 'AnkiConnect', 'Upgraded to the latest version, please restart Anki.')
return True
2017-02-19 20:57:55 +00:00
2017-02-19 23:02:09 +00:00
return False
2017-02-19 20:57:55 +00:00
2016-05-29 22:49:38 +00:00
def api_version(self):
return API_VERSION
def api_guiBrowse(self, query):
return self.anki.guiBrowse(query)
2017-05-27 12:14:40 +00:00
def api_guiAddCards(self):
return self.anki.guiAddCards()
2017-05-27 12:14:40 +00:00
2017-06-08 14:09:00 +00:00
2017-07-01 19:41:27 +00:00
def api_guiCurrentCard(self):
return self.anki.guiCurrentCard()
2017-07-01 20:16:51 +00:00
def api_guiAnswerCard(self, ease):
return self.anki.guiAnswerCard(ease)
def api_guiShowQuestion(self):
return self.anki.guiShowQuestion()
def api_guiShowAnswer(self):
return self.anki.guiShowAnswer()
def api_guiDeckOverview(self, name):
return self.anki.guiDeckOverview(name)
def api_guiDeckBrowser(self):
return self.anki.guiDeckBrowser()
2017-06-08 14:09:00 +00:00
2016-05-21 22:10:12 +00:00
#
# Entry
#
ac = AnkiConnect()