-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.py
executable file
·384 lines (319 loc) · 11 KB
/
storage.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# -*- coding: utf-8 -*-
import os, sys
import datetime
import pickle
from lib.sqlalchemy import *
from lib.sqlalchemy.orm import *
from lib.sqlalchemy.ext.declarative import declarative_base
from lib.sqlalchemy.orm import sessionmaker
import logging
import config
db_path = os.path.join(config.APP_DIR, 'database.db')
engine = create_engine('sqlite:///' + db_path)
Base = declarative_base()
class Userprop(Base):
__tablename__ = 'user_props'
id = Column(Integer, primary_key=True)
key = Column(String(255))
value = Column(PickleType())
def __init__(self, key, value):
self.key = key
self.value = value
def __repr__(self):
return "<Userprop('{0}','{1})>".format(self.key, self.value)
class Setting(Base):
__tablename__ = 'settings'
id = Column(Integer, primary_key=True)
key = Column(String(255))
value = Column(String(1000))
def __init__(self, key, value):
self.key = key
self.value = value
def __repr__(self):
return "<Setting('{0}','{1})>".format(self.key, self.value)
class Notebook(Base):
__tablename__ = 'notebooks'
id = Column(Integer, primary_key=True)
name = Column(String(255))
guid = Column(String(1000))
timestamp = Column(DateTime(), nullable = False)
def __init__(self, guid, name):
self.guid = guid
self.name = name
self.timestamp = datetime.datetime.now()
def __repr__(self):
return "<Notebook('{0}')>".format(self.name)
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
tag = Column(String(255))
guid = Column(String(1000))
timestamp = Column(DateTime(), nullable = False)
def __init__(self, guid, tag):
self.guid = guid
self.tag = tag
self.timestamp = datetime.datetime.now()
def __repr__(self):
return "<Tag('{0}')>".format(self.tag)
class Search(Base):
__tablename__ = 'search'
id = Column(Integer, primary_key=True)
search_obj = Column(PickleType())
timestamp = Column(DateTime(), nullable = False)
def __init__(self, search_obj):
self.search_obj = search_obj
self.timestamp = datetime.datetime.now()
def __repr__(self):
return "<Search('{0}')>".format(self.timestamp)
class Storage(object):
"""
Class for using database.
"""
session = None
def __init__(self):
logging.debug("Storage engine : %s", engine)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
self.session = Session()
def logging(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception, e:
logging.error("%s : %s", func.__name__, str(e))
return False
return wrapper
@logging
def createUser(self, oAuthToken, info_obj):
"""
Create user. oAuthToken must be not empty string
info_obj must be not empty string
Previous user and user's properties will be removed
return True if all done
return False if something wrong
"""
if not oAuthToken:
raise Exception("Empty oAuth token")
if not info_obj:
raise Exception("Empty user info")
for item in self.session.query(Userprop).all():
self.session.delete(item)
self.setUserprop('oAuthToken', oAuthToken)
self.setUserprop('info', info_obj)
return True
@logging
def removeUser(self):
"""
Remove user.
return True if all done
return False if something wrong
"""
for item in self.session.query(Userprop).all():
self.session.delete(item)
self.session.commit()
return True
@logging
def getUserToken(self):
"""
Get user's oAuth token
return oAuth token if it exists
return None if there is not oAuth token yet
return False if something wrong
"""
return self.getUserprop('oAuthToken')
@logging
def getUserInfo(self):
"""
Get user's oAuth token
return oAuth token if it exists
return None if there is not oAuth token yet
return False if something wrong
"""
return self.getUserprop('info')
@logging
def getUserprops(self):
"""
Get all user's properties
return list of dict if all done
return [] there are not any user's properties yet
return False if something wrong
"""
props = self.session.query(Userprop).all()
return [{item.key: pickle.loads(item.value)} for item in props]
@logging
def getUserprop(self, key):
"""
Get user's property by key
return property's value
return False if something wrong
"""
instance = self.session.query(Userprop).filter_by(key=key).first()
if instance:
return pickle.loads(instance.value)
else:
return None
@logging
def setUserprop(self, key, value):
"""
Set single user's property. User's property must have key and value
return True if all done
return False if something wrong
"""
value = pickle.dumps(value)
instance = self.session.query(Userprop).filter_by(key=key).first()
if instance:
instance.value = value
else:
instance = Userprop(key, value)
self.session.add(instance)
self.session.commit()
return True
@logging
def setSettings(self, settings):
"""
Set multuple settings. Settings must be an instanse dict
return True if all done
return False if something wrong
"""
if not isinstance(settings, dict):
raise Exception("Wrong settings")
for key in settings.keys():
if not settings[key]:
raise Exception("Wrong setting's item")
instance = self.session.query(Setting).filter_by(key=key).first()
if instance:
instance.value = pickle.dumps(settings[key])
else:
instance = Setting(key, pickle.dumps(settings[key]))
self.session.add(instance)
self.session.commit()
return True
@logging
def getSettings(self):
"""
Get all settings
return list of dict if all done
return [] there are not any settings yet
return False if something wrong
"""
settings = self.session.query(Setting).all()
result = {}
for item in settings:
result[item.key] = item.value
return result
@logging
def setSetting(self, key, value):
"""
Set single setting. Settings must have key and value
return True if all done
return False if something wrong
"""
instance = self.session.query(Setting).filter_by(key=key).first()
if instance:
instance.value = value
else:
instance = Setting(key, value)
self.session.add(instance)
self.session.commit()
return True
@logging
def getSetting(self, key):
"""
Get setting by key
return setting's value
return False if something wrong
"""
instance = self.session.query(Setting).filter_by(key=key).first()
if instance:
return instance.value
else:
return None
@logging
def setTags(self, tags):
"""
Set tags. Tags must be an instanse of dict
Previous tags items will be removed
return True if all done
return False if something wrong
"""
if not isinstance(tags, dict):
raise Exception("Wrong tags")
for item in self.session.query(Tag).all():
self.session.delete(item)
for key in tags.keys():
if not tags[key]:
raise Exception("Wrong tag's item")
instance = Tag(key, tags[key])
self.session.add(instance)
self.session.commit()
return True
@logging
def getTags(self):
"""
Get all tags
return list of dicts of tags if all done
return [] there are not any tags yet
return False if something wrong
"""
tags = self.session.query(Tag).all()
result = {}
for item in tags:
result[item.guid] = item.tag
return result
@logging
def setNotebooks(self, notebooks):
"""
Set notebooks. Notebooks must be an instanse of dict
Previous notebooks items will be removed
return True if all done
return False if something wrong
"""
if not isinstance(notebooks, dict):
raise Exception("Wrong notebooks")
for item in self.session.query(Notebook).all():
self.session.delete(item)
for key in notebooks.keys():
if not notebooks[key]:
raise Exception("Wrong notebook's item")
instance = Notebook(key, notebooks[key])
self.session.add(instance)
self.session.commit()
return True
@logging
def getNotebooks(self):
"""
Get all notebooks
return list of notebooks if all done
return [] there are not any notebooks yet
return False if something wrong
"""
notebooks = self.session.query(Notebook).all()
result = {}
for item in notebooks:
result[item.guid] = item.name
return result
@logging
def setSearch(self, search_obj):
"""
Set searching.
Previous searching items will be removed
return True if all done
return False if something wrong
"""
for item in self.session.query(Search).all():
self.session.delete(item)
search = pickle.dumps(search_obj)
instance = Search(search)
self.session.add(instance)
self.session.commit()
return True
@logging
def getSearch(self):
"""
Get last searching
return list of dicts of last searching if all done
return [] there are not any searching yet
return False if something wrong
"""
search = self.session.query(Search).first()
return pickle.loads(search.search_obj)