forked from EpocDotFr/webtodotxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage_backends.py
96 lines (68 loc) · 2.62 KB
/
storage_backends.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import todotxtio
from io import BytesIO
from flask import request
# Optional modules/packages
try:
import dropbox
except ImportError:
pass
try:
import webdav3.client as wd_client
except ImportError:
pass
__all__ = [
'FileSystem',
'Dropbox',
'WebDav'
]
class StorageBackend:
def __init__(self, config={}):
self.config = config
def retrieve(self, user):
"""Get the Todo.txt content."""
raise NotImplementedError('Must be implemented')
def store(self, todos, user):
"""Update the Todo.txt content."""
raise NotImplementedError('Must be implemented')
class FileSystem(StorageBackend):
def __init__(self, *args, **kwargs):
super(FileSystem, self).__init__(*args, **kwargs)
def retrieve(self, user):
return todotxtio.from_file(self.config['path'])
def store(self, todos, user):
todotxtio.to_file(self.config['path'], todos)
class Dropbox(StorageBackend):
def __init__(self, *args, **kwargs):
super(Dropbox, self).__init__(*args, **kwargs)
self.client = dropbox.Dropbox(self.config['access_token'])
def retrieve(self, user):
_, response = self.client.files_download(self.config['path'])
return todotxtio.from_string(response.content.decode('utf-8'))
def store(self, todos, user):
data = todotxtio.to_string(todos).encode('utf-8')
self.client.files_upload(data, self.config['path'], mode=dropbox.files.WriteMode('overwrite'), mute=True)
def _safe_username(username):
return username.replace("/", "_")
class WebDav(StorageBackend):
def __init__(self, *args, **kwargs):
super(WebDav, self).__init__(*args, **kwargs)
def _make_client(self):
auth = request.authorization
hostname = self.config['webdav_hostname']
username = self.config.get('webdav_login', auth.username)
password = self.config.get('webdav_password', auth.password)
options = {'webdav_hostname': hostname,
'webdav_login': username,
'webdav_password': password}
return wd_client.Client(options)
def retrieve(self, username):
buff = BytesIO()
res = self._make_client().resource(self.config['path'].format(
username=_safe_username(username)))
res.write_to(buff)
return todotxtio.from_string(buff.getvalue().decode('utf-8'))
def store(self, todos, username):
buff = BytesIO(todotxtio.to_string(todos).encode('utf-8'))
res = self._make_client().resource(self.config['path'].format(
username=_safe_username(username)))
res.read_from(buff)