2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
from webob.dec import wsgify
|
|
|
|
|
from webob.exc import *
|
|
|
|
|
from webob import Response
|
|
|
|
|
|
2013-08-02 01:07:49 +08:00
|
|
|
import sqlite3
|
|
|
|
|
import hashlib
|
|
|
|
|
|
2013-07-13 05:08:16 +08:00
|
|
|
import AnkiServer
|
2013-04-04 03:50:32 +08:00
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
import anki
|
2013-04-04 03:50:32 +08:00
|
|
|
from anki.sync import LocalServer, MediaSyncer
|
2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
import simplejson as json
|
|
|
|
|
except ImportError:
|
|
|
|
|
import json
|
|
|
|
|
|
2013-07-13 05:08:16 +08:00
|
|
|
import os
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
class SyncCollectionHandler(LocalServer):
|
|
|
|
|
operations = ['meta', 'applyChanges', 'start', 'chunk', 'applyChunk', 'sanityCheck2', 'finish']
|
|
|
|
|
|
|
|
|
|
def __init__(self, col):
|
|
|
|
|
LocalServer.__init__(self, col)
|
|
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
|
|
|
|
|
def applyChanges(self, changes):
|
|
|
|
|
#self.lmod, lscm, self.maxUsn, lts, dummy = self.meta()
|
|
|
|
|
# TODO: how should we set this value?
|
|
|
|
|
#self.lnewer = 1
|
|
|
|
|
|
|
|
|
|
result = LocalServer.applyChanges(self, changes)
|
|
|
|
|
|
|
|
|
|
#self.prepareToChunk()
|
|
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
#def chunk(self, ):
|
|
|
|
|
# self.prepareToChunk()
|
|
|
|
|
# return LocalServer.chunk()
|
|
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
class SyncMediaHandler(MediaSyncer):
|
|
|
|
|
operations = ['remove', 'files', 'addFiles', 'mediaSanity']
|
|
|
|
|
|
|
|
|
|
def __init__(self, col):
|
|
|
|
|
MediaSyncer.__init__(self, col)
|
|
|
|
|
|
|
|
|
|
def files(self, minUsn=0):
|
2013-04-04 05:42:28 +08:00
|
|
|
import zipfile, StringIO
|
|
|
|
|
|
|
|
|
|
zipdata, fnames = MediaSyncer.files(self)
|
|
|
|
|
|
|
|
|
|
# add a _usn element to the zipdata
|
|
|
|
|
fd = StringIO.StringIO(zipdata)
|
|
|
|
|
zfd = zipfile.ZipFile(fd, "a", compression=zipfile.ZIP_DEFLATED)
|
|
|
|
|
zfd.writestr("_usn", str(minUsn + len(fnames)))
|
|
|
|
|
zfd.close()
|
|
|
|
|
|
|
|
|
|
return fd.getvalue()
|
2013-04-04 03:50:32 +08:00
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
class SyncUserSession(object):
|
2013-07-13 05:08:16 +08:00
|
|
|
def __init__(self, name, path, collection_manager):
|
2013-04-04 03:50:32 +08:00
|
|
|
import time
|
|
|
|
|
self.name = name
|
|
|
|
|
self.path = path
|
2013-07-13 05:08:16 +08:00
|
|
|
self.collection_manager = collection_manager
|
2013-04-04 03:50:32 +08:00
|
|
|
self.version = 0
|
|
|
|
|
self.created = time.time()
|
|
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
# make sure the user path exists
|
|
|
|
|
if not os.path.exists(path):
|
|
|
|
|
os.mkdir(path)
|
|
|
|
|
|
|
|
|
|
self.collection_handler = None
|
|
|
|
|
self.media_handler = None
|
|
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
def get_collection_path(self):
|
|
|
|
|
return os.path.realpath(os.path.join(self.path, 'collection.anki2'))
|
2013-08-02 01:07:49 +08:00
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
def get_thread(self):
|
2013-07-13 05:08:16 +08:00
|
|
|
return self.collection_manager.get_collection(self.get_collection_path())
|
2013-04-04 07:42:27 +08:00
|
|
|
|
|
|
|
|
def get_handler_for_operation(self, operation, col):
|
|
|
|
|
if operation in SyncCollectionHandler.operations:
|
|
|
|
|
cache_name, handler_class = 'collection_handler', SyncCollectionHandler
|
|
|
|
|
else:
|
|
|
|
|
cache_name, handler_class = 'media_handler', SyncMediaHandler
|
|
|
|
|
|
|
|
|
|
if getattr(self, cache_name) is None:
|
|
|
|
|
setattr(self, cache_name, handler_class(col))
|
|
|
|
|
return getattr(self, cache_name)
|
2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
class SyncApp(object):
|
2013-04-04 07:42:27 +08:00
|
|
|
valid_urls = SyncCollectionHandler.operations + SyncMediaHandler.operations + ['hostKey', 'upload', 'download', 'getDecks']
|
2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
def __init__(self, **kw):
|
2013-07-13 05:08:16 +08:00
|
|
|
from AnkiServer.threading import getCollectionManager
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
self.data_root = os.path.abspath(kw.get('data_root', '.'))
|
|
|
|
|
self.base_url = kw.get('base_url', '/')
|
2013-08-02 11:19:39 +08:00
|
|
|
self.auth_db_path = os.path.abspath(kw.get('auth_db_path', '.'))
|
2013-04-04 07:42:27 +08:00
|
|
|
self.sessions = {}
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-07-13 05:08:16 +08:00
|
|
|
try:
|
|
|
|
|
self.collection_manager = kw['collection_manager']
|
|
|
|
|
except KeyError:
|
|
|
|
|
self.collection_manager = getCollectionManager()
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
# make sure the base_url has a trailing slash
|
|
|
|
|
if len(self.base_url) == 0:
|
|
|
|
|
self.base_url = '/'
|
|
|
|
|
elif self.base_url[-1] != '/':
|
|
|
|
|
self.base_url = base_url + '/'
|
|
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
def authenticate(self, username, password):
|
2013-04-04 07:42:27 +08:00
|
|
|
"""
|
|
|
|
|
Returns True if this username is allowed to connect with this password. False otherwise.
|
|
|
|
|
|
|
|
|
|
Override this to change how users are authenticated.
|
|
|
|
|
"""
|
|
|
|
|
|
2013-08-02 11:57:55 +08:00
|
|
|
return False
|
2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
def username2dirname(self, username):
|
2013-04-04 07:42:27 +08:00
|
|
|
"""
|
|
|
|
|
Returns the directory name for the given user. By default, this is just the username.
|
|
|
|
|
|
|
|
|
|
Override this to adjust the mapping between users and their directory.
|
|
|
|
|
"""
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
return username
|
2013-08-02 01:07:49 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
def generateHostKey(self, username):
|
2013-04-04 07:42:27 +08:00
|
|
|
"""Generates a new host key to be used by the given username to identify their session.
|
|
|
|
|
This values is random."""
|
|
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
import hashlib, time, random, string
|
|
|
|
|
chars = string.ascii_letters + string.digits
|
|
|
|
|
val = ':'.join([username, str(int(time.time())), ''.join(random.choice(chars) for x in range(8))])
|
|
|
|
|
return hashlib.md5(val).hexdigest()
|
|
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
def create_session(self, hkey, username, user_path):
|
|
|
|
|
"""Creates, stores and returns a new session for the given hkey and username."""
|
|
|
|
|
|
2013-07-13 05:08:16 +08:00
|
|
|
session = self.sessions[hkey] = SyncUserSession(username, user_path, self.collection_manager)
|
2013-04-04 07:42:27 +08:00
|
|
|
return session
|
|
|
|
|
|
|
|
|
|
def load_session(self, hkey):
|
|
|
|
|
return self.sessions.get(hkey)
|
|
|
|
|
|
|
|
|
|
def save_session(self, hkey, session):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
def delete_session(self, hkey):
|
|
|
|
|
del self.sessions[hkey]
|
|
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
def _decode_data(self, data, compression=0):
|
|
|
|
|
import gzip, StringIO
|
|
|
|
|
|
|
|
|
|
if compression:
|
|
|
|
|
buf = gzip.GzipFile(mode="rb", fileobj=StringIO.StringIO(data))
|
|
|
|
|
data = buf.read()
|
|
|
|
|
buf.close()
|
|
|
|
|
|
|
|
|
|
# really lame check for JSON
|
|
|
|
|
if data[0] == '{' and data[-1] == '}':
|
|
|
|
|
data = json.loads(data)
|
|
|
|
|
else:
|
|
|
|
|
data = {'data': data}
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
return data
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-07-13 05:08:16 +08:00
|
|
|
def operation_upload(self, col, data, session):
|
2013-04-04 07:42:27 +08:00
|
|
|
# TODO: deal with thread pool
|
|
|
|
|
|
|
|
|
|
fd = open(session.get_collection_path(), 'wb')
|
|
|
|
|
fd.write(data)
|
|
|
|
|
fd.close()
|
|
|
|
|
|
2013-07-13 05:08:16 +08:00
|
|
|
def operation_download(self, col, data, session):
|
2013-04-04 07:42:27 +08:00
|
|
|
pass
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
@wsgify
|
|
|
|
|
def __call__(self, req):
|
2013-04-04 03:50:32 +08:00
|
|
|
print req.path
|
2013-04-03 21:31:44 +08:00
|
|
|
if req.path.startswith(self.base_url):
|
|
|
|
|
url = req.path[len(self.base_url):]
|
|
|
|
|
if url not in self.valid_urls:
|
|
|
|
|
raise HTTPNotFound()
|
2013-04-04 03:50:32 +08:00
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
if url == 'getDecks':
|
|
|
|
|
# This is an Anki 1.x client! Tell them to upgrade.
|
|
|
|
|
import zlib
|
|
|
|
|
return Response(
|
|
|
|
|
status='200 OK',
|
|
|
|
|
content_type='application/json',
|
|
|
|
|
content_encoding='deflate',
|
|
|
|
|
body=zlib.compress(json.dumps({'status': 'oldVersion'})))
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
try:
|
2013-04-04 03:50:32 +08:00
|
|
|
compression = req.POST['c']
|
2013-04-03 21:31:44 +08:00
|
|
|
except KeyError:
|
2013-04-04 03:50:32 +08:00
|
|
|
compression = 0
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
try:
|
2013-04-04 03:50:32 +08:00
|
|
|
data = req.POST['data'].file.read()
|
|
|
|
|
data = self._decode_data(data, compression)
|
2013-04-03 21:31:44 +08:00
|
|
|
except KeyError:
|
2013-04-04 05:42:28 +08:00
|
|
|
data = {}
|
2013-04-04 03:50:32 +08:00
|
|
|
except ValueError:
|
|
|
|
|
# Bad JSON
|
|
|
|
|
raise HTTPBadRequest()
|
|
|
|
|
print 'data:', data
|
2013-08-02 01:07:49 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
if url == 'hostKey':
|
2013-04-03 21:31:44 +08:00
|
|
|
try:
|
2013-04-04 03:50:32 +08:00
|
|
|
u = data['u']
|
|
|
|
|
p = data['p']
|
2013-04-03 21:31:44 +08:00
|
|
|
except KeyError:
|
2013-04-04 03:50:32 +08:00
|
|
|
raise HTTPForbidden('Must pass username and password')
|
|
|
|
|
if self.authenticate(u, p):
|
|
|
|
|
dirname = self.username2dirname(u)
|
|
|
|
|
if dirname is None:
|
|
|
|
|
raise HTTPForbidden()
|
|
|
|
|
|
|
|
|
|
hkey = self.generateHostKey(u)
|
|
|
|
|
user_path = os.path.join(self.data_root, dirname)
|
2013-04-04 07:42:27 +08:00
|
|
|
session = self.create_session(hkey, u, user_path)
|
2013-04-04 03:50:32 +08:00
|
|
|
|
|
|
|
|
result = {'key': hkey}
|
|
|
|
|
return Response(
|
|
|
|
|
status='200 OK',
|
|
|
|
|
content_type='application/json',
|
|
|
|
|
body=json.dumps(result))
|
|
|
|
|
else:
|
|
|
|
|
# TODO: do I have to pass 'null' for the client to receive None?
|
|
|
|
|
raise HTTPForbidden('null')
|
|
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
# Get and verify the session
|
2013-04-04 03:50:32 +08:00
|
|
|
try:
|
|
|
|
|
hkey = req.POST['k']
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise HTTPForbidden()
|
2013-04-04 07:42:27 +08:00
|
|
|
session = self.load_session(hkey)
|
|
|
|
|
if session is None:
|
|
|
|
|
raise HTTPForbidden()
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
if url in SyncCollectionHandler.operations + SyncMediaHandler.operations:
|
|
|
|
|
# 'meta' passes the SYNC_VER but it isn't used in the handler
|
|
|
|
|
if url == 'meta' and data.has_key('v'):
|
2013-04-04 07:42:27 +08:00
|
|
|
session.version = data['v']
|
2013-04-04 03:50:32 +08:00
|
|
|
del data['v']
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
# Create a closure to run this operation inside of the thread allocated to this collection
|
2013-07-13 05:08:16 +08:00
|
|
|
def runFunc(col):
|
|
|
|
|
handler = session.get_handler_for_operation(url, col)
|
2013-04-04 07:42:27 +08:00
|
|
|
func = getattr(handler, url)
|
2013-04-04 03:50:32 +08:00
|
|
|
result = func(**data)
|
2013-04-04 07:42:27 +08:00
|
|
|
handler.col.save()
|
|
|
|
|
return result
|
|
|
|
|
runFunc.func_name = url
|
|
|
|
|
|
|
|
|
|
# Send to the thread to execute
|
|
|
|
|
thread = session.get_thread()
|
2013-07-13 05:08:16 +08:00
|
|
|
result = thread.execute(runFunc)
|
2013-04-04 03:50:32 +08:00
|
|
|
|
2013-04-04 05:42:28 +08:00
|
|
|
# If it's a complex data type, we convert it to JSON
|
|
|
|
|
if type(result) not in (str, unicode):
|
|
|
|
|
result = json.dumps(result)
|
2013-04-04 07:42:27 +08:00
|
|
|
|
|
|
|
|
if url == 'finish':
|
|
|
|
|
self.delete_session(hkey)
|
2013-08-02 01:07:49 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
return Response(
|
|
|
|
|
status='200 OK',
|
|
|
|
|
content_type='application/json',
|
2013-04-04 05:42:28 +08:00
|
|
|
body=result)
|
2013-04-04 03:50:32 +08:00
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
elif url in ('upload', 'download'):
|
|
|
|
|
if url == 'upload':
|
|
|
|
|
func = self.operation_upload
|
|
|
|
|
else:
|
|
|
|
|
func = self.operation_download
|
2013-04-04 03:50:32 +08:00
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
thread = session.get_thread()
|
2013-07-13 05:08:16 +08:00
|
|
|
thread.execute(self.operation_upload, [data['data'], session])
|
2013-04-04 03:50:32 +08:00
|
|
|
|
|
|
|
|
return Response(
|
|
|
|
|
status='200 OK',
|
|
|
|
|
content_type='text/plain',
|
|
|
|
|
body='OK')
|
|
|
|
|
|
2013-04-04 07:42:27 +08:00
|
|
|
# This was one of our operations but it didn't get handled... Oops!
|
|
|
|
|
raise HTTPInternalServerError()
|
2013-04-04 03:50:32 +08:00
|
|
|
|
|
|
|
|
return Response(status='200 OK', content_type='text/plain', body='Anki Sync Server')
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-08-02 11:57:55 +08:00
|
|
|
class DatabaseAuthSyncApp(SyncApp):
|
|
|
|
|
def authenticate(self, username, password):
|
|
|
|
|
"""Returns True if this username is allowed to connect with this password. False otherwise."""
|
|
|
|
|
|
|
|
|
|
conn = sqlite3.connect(self.auth_db_path)
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
param = (username,)
|
|
|
|
|
|
|
|
|
|
cursor.execute("SELECT hash FROM auth WHERE user=?", param)
|
|
|
|
|
|
|
|
|
|
db_ret = cursor.fetchone()
|
|
|
|
|
|
|
|
|
|
if db_ret != None:
|
|
|
|
|
db_hash = str(db_ret[0])
|
|
|
|
|
salt = db_hash[-16:]
|
|
|
|
|
hashobj = hashlib.sha256()
|
|
|
|
|
|
|
|
|
|
hashobj.update(username+password+salt)
|
|
|
|
|
|
|
|
|
|
return (db_ret != None and hashobj.hexdigest()+salt == db_hash)
|
|
|
|
|
|
2013-04-03 21:31:44 +08:00
|
|
|
# Our entry point
|
|
|
|
|
def make_app(global_conf, **local_conf):
|
2013-08-02 11:57:55 +08:00
|
|
|
return DatabaseAuthSyncApp(**local_conf)
|
2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
from wsgiref.simple_server import make_server
|
2013-07-13 05:08:16 +08:00
|
|
|
from AnkiServer.threading import shutdown
|
2013-04-03 21:31:44 +08:00
|
|
|
|
2013-04-04 03:50:32 +08:00
|
|
|
ankiserver = SyncApp()
|
2013-04-03 21:31:44 +08:00
|
|
|
httpd = make_server('', 8001, ankiserver)
|
|
|
|
|
try:
|
2013-04-04 03:50:32 +08:00
|
|
|
print "Starting..."
|
2013-04-03 21:31:44 +08:00
|
|
|
httpd.serve_forever()
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
|
print "Exiting ..."
|
|
|
|
|
finally:
|
2013-07-13 05:08:16 +08:00
|
|
|
shutdown()
|
2013-04-03 21:31:44 +08:00
|
|
|
|
|
|
|
|
if __name__ == '__main__': main()
|
|
|
|
|
|