forked from onejgordon/flow-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
1615 lines (1423 loc) · 55.9 KB
/
models.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf8 -*-
from datetime import datetime, timedelta, time
from google.appengine.ext import ndb
from google.appengine.api import mail, search
from constants import EVENT, USER, TASK, READABLE, JOURNALTAG, REPORT, NEW_USER_NOTIFICATIONS, HABIT, JOURNAL
import tools
import json
import random
import logging
import re
import imp
import hashlib
from common.decorators import auto_cache
try:
imp.find_module('secrets', ['settings'])
except ImportError:
from settings import secrets_template as secrets
else:
from settings import secrets
class UserSearchable(ndb.Model):
'''
Parent class for items that can be searched via FTS
'''
def get_doc_id(self):
'''Can override'''
return str(self.key.id())
def get_index(self):
return User.get_search_index(self.key.parent(), self._get_kind())
def generate_sd(self):
'''Override'''
return None
def doc_from_fields(self, text_fields=None, atom_fields=None, repeated_attom_fields=None):
fields = []
if text_fields:
for tf in text_fields:
fields.append(search.TextField(name=tf, value=getattr(self, tf)))
if atom_fields:
for af in atom_fields:
fields.append(search.AtomField(name=af, value=getattr(self, af)))
if repeated_attom_fields:
for raf in repeated_attom_fields:
values = getattr(self, raf)
if values:
for val in values:
fields.append(search.AtomField(name=raf, value=val))
sd = search.Document(doc_id=self.get_doc_id(), fields=fields, language='en')
return sd
def update_sd(self, delete=False, index_put=True):
index = self.get_index()
sd = None
try:
doc_id = self.get_doc_id()
if doc_id:
if delete:
index.delete([doc_id])
else:
sd = self.generate_sd()
if sd and index_put:
index.put(sd)
return (sd, index)
except search.Error, e:
logging.warning(
"Search Index Error when updating search doc: %s" % e)
return (None, None)
@staticmethod
def put_sd_batch(items):
sds = []
if items:
index = items[0].get_index()
# Batches of 50 to avoid 'ValueError: too many documents to index'
for batch in tools.chunks(items, 50):
sds = []
for i in batch:
sds.append(i.generate_sd())
index.put(sds)
@classmethod
def Search(cls, user, term, limit=20):
kind = cls._get_kind()
index = User.get_search_index(user.key, kind)
message = None
success = False
items = []
try:
query_options = search.QueryOptions(limit=limit)
query = search.Query(query_string=term, options=query_options)
search_results = index.search(query)
except Exception, e:
logging.debug("Error in search api: %s" % e)
message = str(e)
else:
keys = [ndb.Key(kind, sd.doc_id, parent=user.key) for sd in search_results.results if sd]
items = ndb.get_multi(keys)
success = True
return (success, message, items)
class User(ndb.Model):
"""
Key - ID
"""
name = ndb.StringProperty()
email = ndb.StringProperty()
pw_sha = ndb.StringProperty(indexed=False)
pw_salt = ndb.StringProperty(indexed=False)
create_dt = ndb.DateTimeProperty(auto_now_add=True)
login_dt = ndb.DateTimeProperty(auto_now_add=True)
level = ndb.IntegerProperty(default=USER.USER)
timezone = ndb.StringProperty(default="UTC", indexed=False)
birthday = ndb.DateProperty()
integrations = ndb.TextProperty() # Flat JSON dict
settings = ndb.TextProperty() # JSON
sync_services = ndb.StringProperty(repeated=True) # See AppConstants.INTEGRATIONS
plugins = ndb.StringProperty(repeated=True, indexed=False) # Lowercase
# Integration IDs
g_id = ndb.StringProperty()
fb_id = ndb.StringProperty()
evernote_id = ndb.StringProperty()
def __str__(self):
parts = [x for x in [self.name, self.email] if x]
return ' - '.join(parts)
def json(self, is_self=False):
return {
'id': self.key.id(),
'name': self.name,
'email': self.email,
'level': self.level,
'integrations': tools.getJson(self.integrations),
'settings': tools.getJson(self.settings, {}),
'timezone': self.timezone,
'birthday': tools.iso_date(self.birthday) if self.birthday else None,
'evernote_id': self.evernote_id,
'sync_services': self.sync_services,
'plugins': self.plugins if self.plugins else []
}
@staticmethod
def GetByEmail(email, create_if_missing=False, name=None):
u = User.query().filter(User.email == email.lower()).get()
if not u and create_if_missing:
u = User.Create(email=email, name=name)
u.put()
return u
@staticmethod
def GetByGoogleId(id):
u = User.query().filter(User.g_id == id).get()
return u
@staticmethod
def SyncActive(sync_integration_id, limit=200):
multi = type(sync_integration_id) is list
if multi:
fltr = User.sync_services.IN(sync_integration_id)
else:
fltr = User.sync_services == sync_integration_id
return [u for u in User.query().filter(fltr).fetch(limit=limit) if not u.inactive()]
@staticmethod
def Create(email=None, g_id=None, name=None, password=None):
from constants import ADMIN_EMAIL, SENDER_EMAIL, SITENAME, \
APP_OWNER, DEFAULT_USER_SETTINGS
if email or g_id:
u = User(email=email.lower() if email else None, g_id=g_id, name=name)
if email.lower() == APP_OWNER:
u.level = USER.ADMIN
if not password:
password = tools.GenPasswd()
u.setPass(password)
u.Update(settings=DEFAULT_USER_SETTINGS)
if not tools.on_dev_server() and NEW_USER_NOTIFICATIONS:
try:
mail.send_mail(to=ADMIN_EMAIL, sender=SENDER_EMAIL,
subject="[ %s ] New User - %s" % (SITENAME, email),
body="That's all")
except Exception, e:
logging.warning("Failed to send email")
return u
return None
def Update(self, **params):
if 'name' in params:
self.name = params.get('name')
if 'timezone' in params:
self.timezone = params.get('timezone')
if 'birthday' in params:
self.birthday = tools.fromISODate(params.get('birthday'))
if 'settings' in params:
self.settings = json.dumps(params.get('settings'), {})
if 'fb_id' in params:
self.fb_id = params.get('fb_id')
if 'evernote_id' in params:
self.evernote_id = params.get('evernote_id')
if 'password' in params:
self.setPass(pw=params.get('password'))
if 'sync_services' in params:
self.sync_services = params.get('sync_services')
def get(self, cls, id=None, str_id=False):
'''
Get entity accessible to user (child of user)
'''
if id:
if isinstance(id, basestring) and id.isdigit() and not str_id:
id = int(id)
return cls.get_by_id(id, parent=self.key)
@classmethod
def get_search_index(cls, user_key, kind):
return search.Index(name="FTS_UID:%s_%s" % (user_key.id(), kind))
def inactive(self):
'''
Consider users inactive (disable sync) when no login for 6 months
'''
if not self.login_dt:
return True
return (datetime.now() - self.login_dt).days >= 6 * 30
def admin(self):
return self.level == USER.ADMIN
def setPass(self, pw=None):
if not pw:
pw = tools.GenPasswd(length=6)
self.pw_salt, self.pw_sha = tools.getSHA(pw)
return pw
def checkPass(self, pw):
pw_salt, pw_sha = tools.getSHA(pw, salt=self.pw_salt)
return self.pw_sha == pw_sha
def get_timezone(self):
return self.timezone if self.timezone else "UTC"
def local_time(self):
return tools.local_time(self.get_timezone())
def first_name(self):
if self.name:
return self.name.split(' ')[0]
return ""
def get_integration_prop(self, prop, default=None):
integrations = tools.getJson(self.integrations)
if integrations:
val = integrations.get(prop, default)
if val is None:
val = default
return val
return default
def get_setting_prop(self, path, default=None):
settings = tools.getJson(self.settings)
if settings:
cursor = settings
for i, pi in enumerate(path):
cursor = cursor.get(pi, {})
last = i == len(path) - 1
if last:
empty = isinstance(cursor, dict) and len(cursor.keys()) == 0
if empty:
return default
else:
return cursor if cursor is not None else default
return default
def set_integration_prop(self, prop, value):
integrations = tools.getJson(self.integrations)
if not integrations:
integrations = {}
integrations[prop] = value
self.integrations = json.dumps(integrations)
def aes_token(self, client_id='google', add_props=None):
from common.aes_cypher import AESCipher
cypher = AESCipher(secrets.AES_CYPHER_KEY)
data = {
'client_id': client_id,
'user_id': self.key.id()
}
if add_props:
data.update(add_props)
msg = cypher.encrypt(json.dumps(data))
return msg
def aes_access_token(self, client_id='google', add_props=None):
return self.aes_token(client_id=client_id)
@staticmethod
def user_id_from_aes_access_token(access_token):
from common.aes_cypher import AESCipher
cypher = AESCipher(secrets.AES_CYPHER_KEY)
raw = cypher.decrypt(access_token)
loaded = tools.getJson(raw)
if loaded:
return loaded.get('user_id')
class Project(ndb.Model):
"""
Ongoing projects with links
Key - ID
"""
dt_created = ndb.DateTimeProperty(auto_now_add=True)
dt_completed = ndb.DateTimeProperty()
dt_archived = ndb.DateTimeProperty()
dt_due = ndb.DateTimeProperty()
urls = ndb.TextProperty(repeated=True)
title = ndb.TextProperty()
subhead = ndb.TextProperty()
starred = ndb.BooleanProperty(default=False)
archived = ndb.BooleanProperty(default=False)
progress = ndb.IntegerProperty(default=0) # 1 - 10 (-1 disabled)
progress_ts = ndb.IntegerProperty(repeated=True, indexed=False) # Timestamp (ms) for each progress step (len 10)
milestones = ndb.TextProperty(repeated=True)
def json(self):
return {
'id': self.key.id(),
'ts_created': tools.unixtime(self.dt_created),
'ts_completed': tools.unixtime(self.dt_completed),
'ts_archived': tools.unixtime(self.dt_archived),
'due': tools.iso_date(self.dt_due),
'title': self.title,
'subhead': self.subhead,
'progress': self.progress,
'progress_ts': self.progress_ts,
'milestones': self.milestones,
'archived': self.archived,
'starred': self.starred,
'complete': self.is_completed(),
'urls': [url for url in self.urls if url]
}
@staticmethod
def Active(user):
return Project.query(ancestor=user.key).filter(Project.archived == False).order(Project.starred).order(-Project.dt_created).fetch(limit=20)
@staticmethod
def Fetch(user, limit=30, offset=0):
return Project.query(ancestor=user.key).order(-Project.dt_created).fetch(limit=limit, offset=offset)
@staticmethod
def Create(user):
return Project(parent=user.key)
def Update(self, **params):
if 'urls' in params:
self.urls = params.get('urls')
if 'title' in params:
self.title = params.get('title')
if 'subhead' in params:
self.subhead = params.get('subhead')
if 'starred' in params:
self.starred = params.get('starred')
if 'archived' in params:
change = self.archived != params.get('archived')
self.archived = params.get('archived')
if change and self.archived:
self.dt_archived = datetime.now()
if 'progress' in params:
self.set_progress(params.get('progress'))
if 'due' in params:
self.dt_due = params.get('due')
if 'milestones' in params:
milestones = params.get('milestones', [])
if milestones is not None:
self.milestones = [x if x else "" for x in milestones]
def set_progress(self, progress):
regression = progress < self.progress
if not self.progress_ts:
self.progress_ts = [0 for x in range(10)] # Initialize
if progress:
# Avoid updating last array element
self.progress_ts[progress-1] = tools.unixtime()
if regression:
clear_index = progress
while clear_index < 10:
self.progress_ts[clear_index] = 0
clear_index += 1
changed = progress != self.progress
self.progress = progress
if changed and self.is_completed():
self.dt_completed = datetime.now()
return changed
def is_completed(self):
return self.progress == 10
class Task(ndb.Model):
"""
Tasks (currently not linked with projects)
For tracking daily 'top tasks'
Key - ID
"""
dt_created = ndb.DateTimeProperty(auto_now_add=True)
dt_due = ndb.DateTimeProperty()
dt_done = ndb.DateTimeProperty()
title = ndb.TextProperty()
status = ndb.IntegerProperty(default=TASK.NOT_DONE)
wip = ndb.BooleanProperty(default=False)
archived = ndb.BooleanProperty(default=False)
project = ndb.KeyProperty()
timer_last_start = ndb.DateTimeProperty(indexed=False)
timer_target_ms = ndb.IntegerProperty(indexed=False, default=0) # For current timer run
timer_pending_ms = ndb.IntegerProperty(indexed=False, default=0)
timer_total_ms = ndb.IntegerProperty(indexed=False, default=0) # Cumulative
timer_complete_sess = ndb.IntegerProperty(indexed=False, default=0)
def json(self, references=['project']):
res = {
'id': self.key.id(),
'ts_created': tools.unixtime(self.dt_created),
'ts_due': tools.unixtime(self.dt_due),
'ts_done': tools.unixtime(self.dt_done),
'status': self.status,
'archived': self.archived,
'wip': self.wip,
'title': self.title,
'done': self.is_done(),
'project_id': self.project.id() if self.project else None,
'timer_total_ms': self.timer_total_ms or 0,
'timer_target_ms': self.timer_target_ms or 0,
'timer_pending_ms': self.timer_pending_ms or 0,
'timer_complete_sess': self.timer_complete_sess or 0,
'timer_last_start': tools.unixtime(self.timer_last_start) if self.timer_last_start else 0
}
if references:
if 'project' in references:
if self.project:
res['project'] = self.project.get().json()
return res
@staticmethod
def CountCompletedSince(user, since):
return Task.query(ancestor=user.key).order(-Task.dt_done).filter(Task.dt_done > since).count(limit=None)
@staticmethod
def Open(user, limit=10):
return Task.query(ancestor=user.key).filter(Task.status == TASK.NOT_DONE).order(-Task.dt_created).fetch(limit=limit)
@staticmethod
def Recent(user, limit=10, offset=0, with_archived=False, project_id=None, prefetch=None):
q = Task.query(ancestor=user.key).order(-Task.dt_created)
if not with_archived:
q = q.filter(Task.archived == False)
if project_id:
q = q.filter(Task.project == ndb.Key('User', user.key.id(), 'Project', project_id))
tasks = q.fetch(limit=limit, offset=offset)
if prefetch:
for t in tasks:
if 'project' in prefetch and t.project:
t.project.get_async()
return tasks
@staticmethod
def DueInRange(user, start, end, limit=100):
q = Task.query(ancestor=user.key).order(-Task.dt_due)
if start:
q = q.filter(Task.dt_due >= start)
if end:
q = q.filter(Task.dt_due <= end)
return q.fetch(limit=limit)
@staticmethod
def Create(user, title, due=None, tomorrow=None):
if not due:
tz = user.get_timezone()
local_now = tools.local_time(tz)
task_prefs = user.get_setting_prop(['tasks', 'preferences'], {})
same_day_hour = tools.safe_number(task_prefs.get('same_day_hour', 16), default=16, integer=True)
due_hour = tools.safe_number(task_prefs.get('due_hour', 22), default=22, integer=True)
if tomorrow is not None:
# Paramter takes precedence
schedule_for_same_day = not tomorrow
else:
schedule_for_same_day = local_now.hour < same_day_hour
dt_due = local_now
if due_hour > 23:
due_hour = 0
schedule_for_same_day = False
if due_hour < 0:
due_hour = 0
time_due = time(due_hour, 0)
due = datetime.combine(dt_due.date(), time_due)
if not schedule_for_same_day:
due += timedelta(days=1)
if due:
due = tools.server_time(tz, due)
return Task(title=tools.capitalize(title), dt_due=due, parent=user.key)
def Update(self, **params):
from constants import TASK_DONE_REPLIES
message = None
if 'title' in params:
self.title = params.get('title')
if 'status' in params:
change = self.status != params.get('status')
self.status = params.get('status')
if change and self.is_done():
self.dt_done = datetime.now()
self.wip = False
message = random.choice(TASK_DONE_REPLIES)
if 'archived' in params:
self.archived = params.get('archived')
if self.archived:
self.wip = False
if 'wip' in params:
self.wip = params.get('wip')
if 'project_id' in params:
if params['project_id']:
self.project = ndb.Key('User', self.key.parent().id(), 'Project', params.get('project_id'))
else:
self.project = None
if 'timer_total_ms' in params:
self.timer_total_ms = params.get('timer_total_ms')
if 'timer_pending_ms' in params:
self.timer_pending_ms = params.get('timer_pending_ms')
if 'timer_last_start' in params:
last_start_ms = params.get('timer_last_start')
if last_start_ms:
self.timer_last_start = tools.dt_from_ts(last_start_ms)
else:
self.timer_last_start = None
if 'timer_target_ms' in params:
self.timer_target_ms = params.get('timer_target_ms')
if 'timer_complete_sess' in params:
self.timer_complete_sess = params.get('timer_complete_sess')
return message
def mark_done(self):
message = self.Update(status=TASK.DONE)
return message
def is_done(self):
return self.status == TASK.DONE
def archive(self):
self.archived = True
self.wip = False
class Habit(ndb.Model):
"""
Key - ID
"""
dt_created = ndb.DateTimeProperty(auto_now_add=True)
name = ndb.TextProperty()
description = ndb.TextProperty()
color = ndb.TextProperty()
tgt_weekly = ndb.IntegerProperty(indexed=False)
tgt_daily = ndb.IntegerProperty(indexed=False, default=0) # 0 = disabled
archived = ndb.BooleanProperty(default=False)
icon = ndb.TextProperty()
def json(self):
return {
'id': self.key.id(),
'ts_created': tools.unixtime(self.dt_created),
'name': self.name,
'description': self.description,
'color': self.color,
'archived': self.archived,
'tgt_weekly': self.tgt_weekly,
'tgt_daily': self.tgt_daily,
'icon': self.icon,
}
def slug_name(self):
return tools.strip_symbols(self.name.replace(' ','')).lower().strip()
def has_daily_count(self):
return self.tgt_daily is not None and self.tgt_daily > 0
@staticmethod
def All(user):
return Habit.query(ancestor=user.key).fetch(limit=50)
@staticmethod
def Active(user):
return Habit.query(ancestor=user.key).filter(Habit.archived == False).fetch(limit=HABIT.ACTIVE_LIMIT)
@staticmethod
def Create(user):
return Habit(parent=user.key)
def Update(self, **params):
if 'name' in params:
self.name = params.get('name').title()
if 'description' in params:
self.description = params.get('description').title()
if 'color' in params:
self.color = params.get('color')
if 'icon' in params:
self.icon = params.get('icon').strip().replace(' ', '_')
if 'archived' in params:
self.archived = params.get('archived')
if 'tgt_weekly' in params:
self.tgt_weekly = params.get('tgt_weekly')
if 'tgt_daily' in params:
self.tgt_daily = params.get('tgt_daily')
class HabitDay(ndb.Model):
"""
Key - ID: habit:[habit_id]_day:[iso_date]
"""
dt_created = ndb.DateTimeProperty(auto_now_add=True)
dt_updated = ndb.DateTimeProperty(auto_now_add=True)
habit = ndb.KeyProperty(Habit)
date = ndb.DateProperty()
done = ndb.BooleanProperty(default=False)
committed = ndb.BooleanProperty(default=False)
count = ndb.IntegerProperty(default=0, indexed=False)
def json(self):
return {
'id': self.key.id(),
'ts_created': tools.unixtime(self.dt_created),
'ts_updated': tools.unixtime(self.dt_updated),
'habit_id': self.habit.id(),
'done': self.done,
'committed': self.committed,
'count': self.get_count()
}
@staticmethod
def Range(user, habits, since_date, until_date=None):
'''
Fetch habit days for specified habits in date range
Args:
habits (list of Habit() objects)
...
Returns:
list: HabitDay() ordered sequentially
'''
today = datetime.today()
if not until_date:
until_date = today
cursor = since_date
ids = []
while cursor <= until_date:
for h in habits:
ids.append(ndb.Key('HabitDay', HabitDay.ID(h, cursor), parent=user.key))
cursor += timedelta(days=1)
if ids:
return [hd for hd in ndb.get_multi(ids) if hd]
return []
@staticmethod
def GetOrInsert(habit, date):
id = HabitDay.ID(habit, date)
hd = HabitDay.get_or_insert(id,
habit=habit.key,
date=date,
parent=habit.key.parent())
return hd
@staticmethod
def ID(habit, date):
return "habit:%s_day:%s" % (habit.key.id(), tools.iso_date(date))
def Update(self, **params):
if 'done' in params:
self.done = params.get('done')
self.dt_updated = datetime.now()
@staticmethod
def Toggle(habit, date, force_done=False):
hd = HabitDay.GetOrInsert(habit, date)
if not force_done or not hd.done:
# If force_done, only toggle if not done
hd.toggle()
hd.put()
return (hd.done, hd)
@staticmethod
def Increment(habit, date, cancel=False):
'''
Increase (or, if cancel, decrease) the count for this habit/day by 1
'''
hd = HabitDay.GetOrInsert(habit, date)
if not hd.count:
hd.count = 0
inc = 1 if not cancel else -1
hd.count += inc
if hd.count < 0:
hd.count = 0
hd.dt_updated = datetime.now()
marked_done = False
if habit.tgt_daily:
was_done = hd.done
hd.done = hd.count >= habit.tgt_daily
marked_done = not was_done and hd.done
hd.put()
return (marked_done, hd)
@staticmethod
def Commit(habit, date=None):
if not date:
date = datetime.today()
hd = HabitDay.GetOrInsert(habit, date)
hd.commit()
hd.put()
return hd
def toggle(self):
self.dt_updated = datetime.now()
self.done = not self.done
if not self.done and self.count:
# Reset count to 0 if we've untoggled
self.count = 0
return self.done
def commit(self):
if not self.done:
self.committed = True
def get_count(self):
if self.count:
return self.count
else:
return 1 if self.done else 0
class JournalTag(ndb.Model):
"""
Stores frequent activities/tags/people for daily journal
Key - ID: Full tag with @/#, e.g. '#DinnerOut', '@BarackObama'
"""
dt_added = ndb.DateTimeProperty(auto_now_add=True)
name = ndb.TextProperty()
type = ndb.IntegerProperty(default=JOURNALTAG.PERSON)
def json(self):
return {
'id': self.key.id(),
'name': self.name,
'type': self.type
}
@staticmethod
def All(user, limit=400):
return JournalTag.query(ancestor=user.key).fetch(limit=limit)
@staticmethod
def Key(user, name, prefix='@'):
if name:
name = tools.capitalize(name)
return ndb.Key('JournalTag', prefix+name, parent=user.key)
@staticmethod
def CreateFromText(user, text):
new_jts = []
all_jts = []
if text and isinstance(text, basestring):
people = re.findall(r'@([a-zA-Z]{3,30})', text)
hashtags = re.findall(r'#([a-zA-Z]{3,30})', text)
people_ids = [JournalTag.Key(user, p) for p in people]
hashtag_ids = [JournalTag.Key(user, ht, prefix='#') for ht in hashtags]
existing_tags = ndb.get_multi(people_ids + hashtag_ids)
for existing_tag, key in zip(existing_tags, people_ids + hashtag_ids):
if not existing_tag:
prefix = key.id()[0]
tag_type = JOURNALTAG.HASHTAG if prefix == '#' else JOURNALTAG.PERSON
jt = JournalTag(id=key.id(), name=key.id()[1:], type=tag_type, parent=user.key)
new_jts.append(jt)
all_jts.append(jt)
else:
all_jts.append(existing_tag)
ndb.put_multi(new_jts)
return all_jts
def person(self):
return self.type == JOURNALTAG.PERSON
class MiniJournal(ndb.Model):
"""
Key - ID: [ISO_date]
Capture some basic data points from the day via 1-2 questions?
Questions defined on client side.
Optionally collect and track completion of top 3 tasks (decided tonight for tomorrow)
"""
date = ndb.DateProperty() # Date for entry
dt_created = ndb.DateTimeProperty(auto_now_add=True)
data = ndb.TextProperty() # JSON (keys are data names, values are responses)
tags = ndb.KeyProperty(repeated=True) # IDs of JournalTags()
location = ndb.GeoPtProperty()
def json(self):
res = {
'id': self.key.id(),
'iso_date': tools.iso_date(self.date),
'data': tools.getJson(self.data),
'tags': [tag.id() for tag in self.tags]
}
if self.location:
res.update({
'lat': self.location.lat,
'lon': self.location.lon
})
return res
@staticmethod
def Create(user, date=None):
if not date:
date = MiniJournal.CurrentSubmissionDate()
id = tools.iso_date(date)
return MiniJournal(id=id, date=date, parent=user.key)
@staticmethod
def Fetch(user, start, end):
journal_keys = []
iso_dates = []
if start < end:
date_cursor = start
while date_cursor < end:
date_cursor += timedelta(days=1)
iso_date = tools.iso_date(date_cursor)
journal_keys.append(ndb.Key('MiniJournal', iso_date, parent=user.key))
iso_dates.append(iso_date)
return ([j for j in ndb.get_multi(journal_keys) if j], iso_dates)
@staticmethod
def Get(user, date=None):
if not date:
date = MiniJournal.CurrentSubmissionDate()
id = tools.iso_date(date)
return MiniJournal.get_by_id(id, parent=user.key)
@staticmethod
def CurrentSubmissionDate():
HOURS_BACK = JOURNAL.HOURS_BACK
now = datetime.now()
return (now - timedelta(hours=HOURS_BACK)).date()
def Update(self, **params):
if 'data' in params:
self.data = json.dumps(params.get('data'))
if 'lat' in params and 'lon' in params:
gp = ndb.GeoPt("%s, %s" % (params.get('lat'), params.get('lon')))
self.location = gp
if 'tags' in params:
self.tags = params.get('tags', [])
def parse_tags(self):
user = self.key.parent().get()
questions = tools.getJson(user.settings, {}).get('journals', {}).get('questions', [])
parse_questions = [q.get('name') for q in questions if q.get('parse_tags')]
tags = []
for q in parse_questions:
response_text = tools.getJson(self.data).get(q)
if response_text:
tags.extend(JournalTag.CreateFromText(user, response_text))
for tag in tags:
if tag.key not in self.tags:
self.tags.append(tag.key)
def get_data_value(self, prop):
data = tools.getJson(self.data, {})
return data.get(prop)
class Snapshot(ndb.Model):
"""
Key - ID
Randomly collect data points throughout day/week (frequency customizable)
Metrics:
- Activity
- Location (generic, e.g. home/office/restaurant)
- People (who with)
Passive metrics:
- GPS location, if available
"""
ACTIVITY_SEPS = [" - ", ": "]
date = ndb.DateProperty(auto_now_add=True) # Date for entry
dt_created = ndb.DateTimeProperty(auto_now_add=True)
activity = ndb.StringProperty()
activity_sub = ndb.StringProperty()
place = ndb.StringProperty()
people = ndb.StringProperty(repeated=True)
metrics = ndb.TextProperty() # JSON
location = ndb.GeoPtProperty()
def json(self):
res = {
'id': self.key.id(),
'ts': tools.unixtime(self.dt_created),
'iso_date': tools.iso_date(self.date),
'metrics': tools.getJson(self.metrics),
'people': self.people,
'place': self.place,
'activity': self.activity,
'activity_sub': self.activity_sub
}
if self.location:
res.update({
'lat': self.location.lat,
'lon': self.location.lon
})
return res
@staticmethod
def Create(user, activity=None, place=None, people=None, metrics=None, lat=None, lon=None, date=None):
if not date:
date = datetime.now()
location = activity_sub = None
if lat and lon:
gp = ndb.GeoPt("%s, %s" % (lat, lon))
location = gp
if activity:
for sep in Snapshot.ACTIVITY_SEPS:
if sep in activity:
act_list = activity.split(sep)
if act_list:
activity = act_list[0]
if len(act_list) > 1:
activity_sub = act_list[1]
break
if metrics:
return Snapshot(dt_created=date, place=place, people=people if people else [],
activity=activity, activity_sub=activity_sub, metrics=json.dumps(metrics),
location=location, parent=user.key)
@staticmethod
def Recent(user, limit=500):
return Snapshot.query(ancestor=user.key).order(-Snapshot.dt_created).fetch(limit=limit)
def get_data_value(self, prop):
metrics = tools.getJson(self.metrics, {})
return metrics.get(prop)
def has_data(self):
return bool(self.metrics)
class Event(ndb.Model):
"""
Key - ID
Events (single date or ranges) that are meaningful
"""
date_start = ndb.DateProperty()
date_end = ndb.DateProperty()
title = ndb.TextProperty()
details = ndb.TextProperty()
color = ndb.StringProperty() # Hex
private = ndb.BooleanProperty(default=True)
type = ndb.IntegerProperty(default=EVENT.PERSONAL)
ongoing = ndb.BooleanProperty(default=False)
def json(self):
res = {
'id': self.key.id(),
'date_start': tools.iso_date(self.date_start),
'date_end': tools.iso_date(self.date_end),
'title': self.title,
'details': self.details,
'color': self.color,
'private': self.private,
'single': self.single(),
'type': self.type,
'ongoing': self.ongoing
}
return res
@staticmethod
def Fetch(user, limit=20, offset=0):
return Event.query(ancestor=user.key).order(Event.date_start).fetch(limit=limit, offset=offset)
@staticmethod
def Create(user, date_start, date_end=None, title=None, details=None, color=None, **params):
if not date_end:
date_end = date_start
return Event(date_start=date_start, date_end=date_end, title=title, details=details,