/
objects.py
723 lines (575 loc) · 23.9 KB
/
objects.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
# -*- encoding: utf-8 -*-
# Copyright (C) 2015-2016 Eric Goller <eric.goller@ninjaduck.solutions>
# This file is part of 'hamster-lib'.
#
# 'hamster-lib' 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.
#
# 'hamster-lib' 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 'hamster-lib'. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import datetime
from collections import namedtuple
from operator import attrgetter
from future.utils import python_2_unicode_compatible
from hamster_lib.helpers import time as time_helpers
from hamster_lib.helpers.helpers import parse_raw_fact
from six import text_type
# Named tuples used to 'serialize' our object instances.
CategoryTuple = namedtuple('CategoryTuple', ('pk', 'name'))
TagTuple = namedtuple('TagTuple', ('pk', 'name'))
ActivityTuple = namedtuple('ActivityTuple', ('pk', 'name', 'category', 'deleted'))
FactTuple = namedtuple('FactTuple', ('pk', 'activity', 'start', 'end', 'description', 'tags'))
@python_2_unicode_compatible
class Category(object):
"""Storage agnostic class for categories."""
def __init__(self, name, pk=None):
"""
Initialize this instance.
Args:
name (str): The name of the category. May contain whitespace!
pk: The unique primary key used by the backend.
"""
self.pk = pk
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if not name:
# Catching ``None`` and ``empty string``.
raise ValueError(_("You need to specify a name."))
self._name = text_type(name)
def as_tuple(self, include_pk=True):
"""
Provide a tuple representation of this categories relevant 'fields'.
Args:
include_pk (bool): Whether to include the instances pk or not. Note that if
``False`` ``tuple.pk = False``!
Returns:
CategoryTuple: Representing this categories values.
"""
pk = self.pk
if not include_pk:
pk = False
return CategoryTuple(pk=pk, name=self.name)
def equal_fields(self, other):
"""
Compare this instances fields with another category. This excludes comparing the PK.
Args:
other (Category): Category to compare this instance with.
Returns:
bool: ``True`` if all fields but ``pk`` are equal, ``False`` if not.
Note:
This is particularly useful if you want to compare a new ``Category`` instance
with a freshly created backend instance. As the latter will probably have a
primary key assigned now and so ``__eq__`` would fail.
"""
if other:
other = other.as_tuple(include_pk=False)
else:
other = None
return self.as_tuple(include_pk=False) == other
def __eq__(self, other):
if other:
if isinstance(other, CategoryTuple):
pass
else:
other = other.as_tuple()
else:
other = None
return self.as_tuple() == other
def __hash__(self):
"""Naive hashing method."""
return hash(self.as_tuple())
def __str__(self):
return text_type('{name}'.format(name=self.name))
def __repr__(self):
"""Return an instance representation containing additional information."""
return str('[{pk}] {name}'.format(pk=repr(self.pk), name=repr(self.name)))
@python_2_unicode_compatible
class Activity(object):
"""Storage agnostic class for activities."""
def __init__(self, name, pk=None, category=None, deleted=False):
"""
Initialize this instance.
Args:
name (str): This is the name of the activity. May contain whitespace!
pk: The unique primary key used by the backend.
category (Category): ``Category`` instance associated with this ``Activity``.
deleted (bool): True if this ``Activity`` has been marked as deleted.
Note:
*Legacy hamster* basically treated ``(Activity.name, Category.name)`` as
*composite keys*. As a consequence ``Activity.names`` themselves are not
unique. They are only in combination with their associated categories name.
"""
# [TODO]
# Elaborate on the consequences of the deleted flag.
self.pk = pk
self.name = name
self.category = category
self.deleted = bool(deleted)
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if not name:
# Catching ``None``
raise ValueError(_("You need to specify a name."))
self._name = text_type(name)
@classmethod
def create_from_composite(cls, name, category_name, deleted=False):
"""
Convenience method that allows creating a new instance providing the 'natural key'.
Args:
name (str): This activities name.
category_name (str): Name of the associated category.
deleted (bool): True if this ``Activity`` has been marked as deleted.
Returns:
Activity: A new ``Activity`` instance.
Note:
* Should future iterations extend ``Category`` this may turn problematic.
* This method does not allow to specify a primary key as it is intended only
for new instances, not ones retrieved by the backend.
"""
category = Category(category_name)
return cls(name, category=category, deleted=deleted)
def as_tuple(self, include_pk=True):
"""
Provide a tuple representation of this activities relevant 'fields'.
Args:
include_pk (bool): Whether to include the instances pk or not. Note that if
``False`` ``tuple.pk = False``!
Returns:
ActivityTuple: Representing this activities values.
"""
pk = self.pk
if not include_pk:
pk = False
if self.category:
category = self.category.as_tuple(include_pk=include_pk)
else:
category = None
return ActivityTuple(pk=pk, name=self.name, category=category, deleted=self.deleted)
def equal_fields(self, other):
"""
Compare this instances fields with another activity. This excludes comparing the PK.
Args:
other (Activity): Activity to compare this instance with.
Returns:
bool: ``True`` if all fields but ``pk`` are equal, ``False`` if not.
Note:
This is particularly useful if you want to compare a new ``Activity`` instance
with a freshly created backend instance. As the latter will probably have a
primary key assigned now and so ``__eq__`` would fail.
"""
return self.as_tuple(include_pk=False) == other.as_tuple(include_pk=False)
def __eq__(self, other):
if not isinstance(other, ActivityTuple):
other = other.as_tuple()
return self.as_tuple() == other
def __hash__(self):
"""Naive hashing method."""
return hash(self.as_tuple())
def __str__(self):
if self.category is None:
string = '{name}'.format(name=self.name)
else:
string = '{name} ({category})'.format(
name=self.name, category=self.category.name)
return text_type(string)
def __repr__(self):
"""Return an instance representation containing additional information."""
if self.category is None:
string = '[{pk}] {name}'.format(pk=repr(self.pk), name=repr(self.name))
else:
string = '[{pk}] {name} ({category})'.format(
pk=repr(self.pk), name=repr(self.name), category=repr(self.category.name))
return str(string)
@python_2_unicode_compatible
class Tag(object):
"""Storage agnostic class for tags."""
def __init__(self, name, pk=None):
"""
Initialize this instance.
Args:
name (str): The name of the tag. May contain whitespace!
pk: The unique primary key used by the backend.
"""
self.pk = pk
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if not name:
# Catching ``None`` and ``empty string``.
raise ValueError(_("You need to specify a name."))
self._name = text_type(name)
def as_tuple(self, include_pk=True):
"""
Provide a tuple representation of this tags relevant 'fields'.
Args:
include_pk (bool): Whether to include the instances pk or not.
Note that if ``False`` ``tuple.pk = False``!
Returns:
TagTuple: Representing this tags values.
"""
pk = self.pk
if not include_pk:
pk = False
return TagTuple(pk=pk, name=self.name)
def equal_fields(self, other):
"""
Compare this instances fields with another tag. This excludes comparing the PK.
Args:
other (Tag): Tag to compare this instance with.
Returns:
bool: ``True`` if all fields but ``pk`` are equal, ``False`` if not.
Note:
This is particularly useful if you want to compare a new ``Tag`` instance
with a freshly created backend instance. As the latter will probably have a
primary key assigned now and so ``__eq__`` would fail.
"""
if other:
other = other.as_tuple(include_pk=False)
else:
other = None
return self.as_tuple(include_pk=False) == other
def __eq__(self, other):
if other:
if isinstance(other, TagTuple):
pass
else:
other = other.as_tuple()
else:
other = None
return self.as_tuple() == other
def __hash__(self):
"""Naive hashing method."""
return hash(self.as_tuple())
def __str__(self):
return text_type('{name}'.format(name=self.name))
def __repr__(self):
"""Return an instance representation containing additional information."""
return str('[{pk}] {name}'.format(pk=repr(self.pk), name=repr(self.name)))
@python_2_unicode_compatible
class Fact(object):
"""Storage agnostic class for facts."""
# [TODO]
# There is some weird black magic still to be integrated from
# ``store.db.Storage``. Among it ``__get_facts()``.
#
def __init__(self, activity, start, end=None, pk=None, description=None, tags=None):
"""
Initiate our new instance.
Args:
activity (hamster_lib.Activity): Activity associated with this fact.
start (datetime.datetime): Start datetime of this fact.
end (datetime.datetime, optional): End datetime of this fact. Defaults to ``None``.
pk (optional): Primary key used by the backend to identify this instance. Defaults
to ``None``.
description (str, optional): Additional information relevant to this singular fact.
Defaults to ``None``.
tags (Iterable, optional): Iterable of ``strings`` identifying *tags*. Defaults to
``None``.
Note:
* For ``start`` and ``end``: Seconds will be stored, but are ignored for all
intends and purposes.
"""
self.pk = pk
self.activity = activity
self.start = start
self.end = end
self.description = description
self.tags = set()
if tags:
self.tags = set(tags)
@classmethod
def create_from_raw_fact(cls, raw_fact, config=None):
"""
Construct a new ``hamster_lib.Fact`` from a ``raw fact`` string.
Please note that this just handles the parsing and construction of a new
Fact including *new* ``Category`` and ``Activity`` instances.
It will require a separate step to check this against the backend in order
to figure out if those probably already exist!
This approach has the benefit of providing this one single point of entry.
Once any such raw fact has been turned in to a proper ``hamster_lib.Fact``
we can rely on it having encapsulated all.
As a consequence extra care has to be taken to mask/escape them.
Args:
raw_fact (str): Raw fact to be parsed.
config (dict, optional): Controller config provided additional settings
relevant for timeframe completion.
Returns:
hamster_lib.Fact: ``Fact`` object with data parsed from raw fact.
Raises:
ValueError: If we fail to extract at least ``start`` or ``activity.name``.
ValueError: If ``end <= start``.
"""
if not config:
config = {'day_start': datetime.time(0, 0, 0)}
extracted_components = parse_raw_fact(raw_fact)
start, end = time_helpers.complete_timeframe(extracted_components['timeinfo'],
config, partial=True)
# Please note that start/end may very well be ``None`` due to the
# partial completion!
start, end = time_helpers.validate_start_end_range((start, end))
activity_name = extracted_components['activity']
if activity_name:
activity = Activity(activity_name)
else:
raise ValueError(_("Unable to extract activity name"))
category_name = extracted_components['category']
if category_name:
activity.category = Category(category_name)
description = extracted_components['description']
return cls(activity, start, end=end, description=description)
@property
def start(self):
return self._start
@start.setter
def start(self, start):
"""
Make sure that we receive a ``datetime.datetime`` instance.
Args:
start (datetime.datetime): Start datetime of this ``Fact``.
Raises:
TypeError: If we receive something other than a ``datetime.datetime`` (sub-)class
or ``None``.
"""
if start:
if not isinstance(start, datetime.datetime):
raise TypeError(_(
"You need to pass a ``datetime.datetime`` instance!"
" {type} instance received instead.".format(type=type(start))
))
else:
start = None
self._start = start
@property
def end(self):
return self._end
@end.setter
def end(self, end):
"""
Make sure that we receive a ``datetime.datetime`` instance.
Args:
end (datetime.datetime): End datetime of this ``Fact``.
Raises:
TypeError: If we receive something other than a ``datetime.datetime`` (sub-)class
or ``None``.
"""
if end:
if not isinstance(end, datetime.datetime):
raise TypeError(_(
"You need to pass a ``datetime.datetime`` instance!"
" {type} instance received instead.".format(type=type(end))
))
else:
end = None
self._end = end
@property
def description(self):
return self._description
@description.setter
def description(self, description):
""""
Normalize all descriptions that evaluate to ``False``. Store everything else as string.
"""
if description:
description = text_type(description)
else:
description = None
self._description = description
@property
def delta(self):
"""
Provide the offset of start to end for this fact.
Returns:
datetime.timedelta or None: Difference between start- and end datetime.
If we only got a start datetime, return ``None``.
"""
result = None
if self.end:
result = self.end - self.start
return result
def get_string_delta(self, format='%M'):
"""
Return a string representation of ``Fact().delta``.
Args:
format (str): Specifies the output format. Valid choices are:
* ``'%M'``: As minutes, rounded down.
* ``'%H:%M'``: As 'hours:minutes'. rounded down.
Returns:
str: String representing this facts *duration* in the given format.capitalize
Raises:
ValueError: If a unrecognized format specifier is received.
"""
seconds = int(self.delta.total_seconds())
if format == '%M':
result = text_type(int(seconds / 60))
elif format == '%H:%M':
result = '{hours:02d}:{minutes:02d}'.format(hours=int(seconds / 3600),
minutes=int((seconds % 3600) / 60))
else:
raise ValueError(_("Got invalid format argument."))
return result
@property
def date(self):
"""
Return the date the fact has started.
Returns:
datetime.datetime: The date the fact has started.
Note:
This is merely a convenience / legacy property to stay in line with
*legacy hamster*.
"""
return self.start.date()
@property
def category(self):
"""For convenience only."""
return self.activity.category
def get_serialized_string(self):
"""
Provide a canonical 'stringified' version of the fact.
This is different from ``__str__`` as we may change what information is
to be included in ``__str__`` anytime (and we may use localization
etc ..) but this property guarantees that all relevant values will be
encoded in the returned string in a canonical way. In that regard it
is in a way a counterpart to ``Fact.create_from_raw_fact``.
This also serves as a go-to reference implementation for 'what does a
complete ``raw fact`` looks like'.
Please be advised though that the ``raw_string`` used to create a
``Fact`` instance is not necessarily identical to this instance's
``serialized_string`` as the ``raw fact`` string may omit certain
values which will be autocompleted while this property always returns
a *complete* string.
A complete serialized fact looks like this:
``2016-02-01 17:30 - 2016-02-01 18:10 making plans@world domination
#tag 1 #tag 2, description``
Please note that we are very liberal with allowing whitespace
for ``Activity.name`` and ``Category.name``.
Attention:
``Fact.tags`` is a set and hence unordered. In order to provide
a deterministic canonical return string we will sort tags by name
and list them alphabetically. This is purely cosmetic and does not
imply any actual ordering of those facts on the instance level.
Returns:
text_type: Canonical string encoding all available fact info.
"""
def get_times_string(fact):
if fact.start:
if fact.end:
result = '{start} - {end} '.format(
start=fact.start.strftime('%Y-%m-%d %H:%M'),
end=fact.end.strftime('%Y-%m-%d %H:%M')
)
else:
result = '{} '.format(fact.start.strftime('%Y-%m-%d %H:%M'))
else:
result = ''
return result
def get_activity_string(fact):
if fact.category:
result = '{a.name}@{a.category.name}'.format(a=fact.activity)
else:
result = '{}'.format(fact.activity.name)
return result
tags = ''
if self.tags:
ordered_tags = sorted(list(self.tags), key=attrgetter('name'))
tags = ' {}'.format(' '.join(['#{}'.format(tag.name) for tag in ordered_tags]))
description = ''
if self.description:
description = ', {}'.format(self.description)
result = '{times}{activity}{tags}{description}'.format(
times=get_times_string(self),
activity=get_activity_string(self),
tags=tags,
description=description
)
return text_type(result)
def as_tuple(self, include_pk=True):
"""
Provide a tuple representation of this facts relevant attributes.
Args:
include_pk (bool): Whether to include the instances pk or not. Note that if
``False`` ``tuple.pk = False``!
Returns:
hamster_lib.FactTuple: Representing this categories values.
"""
pk = self.pk
if not include_pk:
pk = False
return FactTuple(pk, self.activity.as_tuple(include_pk=include_pk), self.start,
self.end, self.description,
frozenset([tag.as_tuple(include_pk=include_pk) for tag in self.tags]))
def equal_fields(self, other):
"""
Compare this instances fields with another fact. This excludes comparing the PK.
Args:
other (Fact): Fact to compare this instance with.
Returns:
bool: ``True`` if all fields but ``pk`` are equal, ``False`` if not.
Note:
This is particularly useful if you want to compare a new ``Fact`` instance
with a freshly created backend instance. As the latter will probably have a
primary key assigned now and so ``__eq__`` would fail.
"""
return self.as_tuple(include_pk=False) == other.as_tuple(include_pk=False)
def __eq__(self, other):
if not isinstance(other, FactTuple):
other = other.as_tuple()
return self.as_tuple() == other
def __hash__(self):
"""Naive hashing method."""
return hash(self.as_tuple())
def __str__(self):
result = text_type(self.activity.name)
if self.category:
result += "@%s" % text_type(self.category.name)
if self.description or self.tags:
# [FIXME]
# Workaround until we address tags!
result += ', {}'.format(text_type(self.description) or '')
# result += "%s, %s" % (" ".join(["#%s" % tag for tag in self.tags]),
# self.description or "")
if self.start:
start = self.start.strftime("%Y-%m-%d %H:%M:%S")
if self.end:
end = self.end.strftime("%Y-%m-%d %H:%M:%S")
if self.start and self.end:
result = '{} to {} {}'.format(start, end, result)
elif self.start and not self.end:
result = '{} {}'.format(start, result)
return text_type(result)
def __repr__(self):
result = repr(self.activity.name)
if self.category:
result += "@%s" % repr(self.category.name)
if self.description or self.tags:
# [FIXME]
# Workaround until we address tags!
result += ', {}'.format(repr(self.description) or '')
# result += "%s, %s" % (" ".join(["#%s" % tag for tag in self.tags]),
# self.description or "")
if self.start:
start = repr(self.start.strftime("%Y-%m-%d %H:%M:%S"))
if self.end:
end = repr(self.end.strftime("%Y-%m-%d %H:%M:%S"))
if self.start and self.end:
result = '{} to {} {}'.format(start, end, result)
elif self.start and not self.end:
result = '{} {}'.format(start, result)
return str(result)