-
Notifications
You must be signed in to change notification settings - Fork 112
/
__init__.py
1222 lines (982 loc) · 37.7 KB
/
__init__.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
# -*- coding: utf-8 -*-
"""
.. moduleauthor:: Kai <z@kwi.li>
"""
__version__ = "0.14.2"
import logging
import re
import time
import random
from uuid import getnode as get_mac
import gpsoauth
import requests
from . import node as _node
from . import exception
logger = logging.getLogger(__name__)
try:
Pattern = re._pattern_type # pylint: disable=protected-access
except AttributeError:
Pattern = re.Pattern # pylint: disable=no-member
class APIAuth(object):
"""Authentication token manager"""
def __init__(self, scopes):
self._master_token = None
self._auth_token = None
self._email = None
self._device_id = None
self._scopes = scopes
def login(self, email, password, device_id):
"""Authenticate to Google with the provided credentials.
Args:
email (str): The account to use.
password (str): The account password.
device_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in.
"""
self._email = email
self._device_id = device_id
# Obtain a master token.
res = gpsoauth.perform_master_login(self._email, password, self._device_id)
# Bail if browser login is required.
if res.get("Error") == "NeedsBrowser":
raise exception.BrowserLoginRequiredException(res.get("Url"))
# Bail if no token was returned.
if "Token" not in res:
raise exception.LoginException(res.get("Error"), res.get("ErrorDetail"))
self._master_token = res["Token"]
# Obtain an OAuth token.
self.refresh()
return True
def load(self, email, master_token, device_id):
"""Authenticate to Google with the provided master token.
Args:
email (str): The account to use.
master_token (str): The master token.
device_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in.
"""
self._email = email
self._device_id = device_id
self._master_token = master_token
# Obtain an OAuth token.
self.refresh()
return True
def getMasterToken(self):
"""Gets the master token.
Returns:
str: The account master token.
"""
return self._master_token
def setMasterToken(self, master_token):
"""Sets the master token. This is useful if you'd like to authenticate
with the API without providing your username & password.
Do note that the master token has full access to your account.
Args:
master_token (str): The account master token.
"""
self._master_token = master_token
def getEmail(self):
"""Gets the account email.
Returns:
str: The account email.
"""
return self._email
def setEmail(self, email):
"""Sets the account email.
Args:
email (str): The account email.
"""
self._email = email
def getDeviceId(self):
"""Gets the device id.
Returns:
str: The device id.
"""
return self._device_id
def setDeviceId(self, device_id):
"""Sets the device id.
Args:
device_id (str): The device id.
"""
self._device_id = device_id
def getAuthToken(self):
"""Gets the auth token.
Returns:
Union[str, None]: The auth token.
"""
return self._auth_token
def refresh(self):
"""Refresh the OAuth token.
Returns:
string: The auth token.
Raises:
LoginException: If there was a problem refreshing the OAuth token.
"""
# Obtain an OAuth token with the necessary scopes by pretending to be
# the keep android client.
res = gpsoauth.perform_oauth(
self._email,
self._master_token,
self._device_id,
service=self._scopes,
app="com.google.android.keep",
client_sig="38918a453d07199354f8b19af05ec6562ced5788",
)
# Bail if no token was returned.
if "Auth" not in res:
if "Token" not in res:
raise exception.LoginException(res.get("Error"))
self._auth_token = res["Auth"]
return self._auth_token
def logout(self):
"""Log out of the account."""
self._master_token = None
self._auth_token = None
self._email = None
self._device_id = None
class API(object):
"""Base API wrapper"""
RETRY_CNT = 2
def __init__(self, base_url, auth=None):
self._session = requests.Session()
self._auth = auth
self._base_url = base_url
self._session.headers.update(
{
"User-Agent": "x-gkeepapi/%s (https://github.com/kiwiz/gkeepapi)"
% __version__
}
)
def getAuth(self):
"""Get authentication details for this API.
Return:
auth (APIAuth): The auth object
"""
return self._auth
def setAuth(self, auth):
"""Set authentication details for this API.
Args:
auth (APIAuth): The auth object
"""
self._auth = auth
def send(self, **req_kwargs):
"""Send an authenticated request to a Google API.
Automatically retries if the access token has expired.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
dict: The parsed JSON response.
Raises:
APIException: If the server returns an error.
LoginException: If :py:meth:`login` has not been called.
"""
# Send a request to the API servers, with retry handling. OAuth tokens
# are valid for several hours (as of this comment).
i = 0
while True:
# Send off the request. If there was no error, we're good.
response = self._send(**req_kwargs).json()
if "error" not in response:
break
# Otherwise, check if it was a non-401 response code. These aren't
# handled, so bail.
error = response["error"]
if error["code"] != 401:
raise exception.APIException(error["code"], error)
# If we've exceeded the retry limit, also bail.
if i >= self.RETRY_CNT:
raise exception.APIException(error["code"], error)
# Otherwise, try requesting a new OAuth token.
logger.info("Refreshing access token")
self._auth.refresh()
i += 1
return response
def _send(self, **req_kwargs):
"""Send an authenticated request to a Google API.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
requests.Response: The raw response.
Raises:
LoginException: If :py:meth:`login` has not been called.
"""
# Bail if we don't have an OAuth token.
auth_token = self._auth.getAuthToken()
if auth_token is None:
raise exception.LoginException("Not logged in")
# Add the token to the request.
req_kwargs.setdefault("headers", {"Authorization": "OAuth " + auth_token})
return self._session.request(**req_kwargs)
class KeepAPI(API):
"""Low level Google Keep API client. Mimics the Android Google Keep app.
You probably want to use :py:class:`Keep` instead.
"""
API_URL = "https://www.googleapis.com/notes/v1/"
def __init__(self, auth=None):
super(KeepAPI, self).__init__(self.API_URL, auth)
create_time = time.time()
self._session_id = self._generateId(create_time)
@classmethod
def _generateId(cls, tz):
return "s--%d--%d" % (int(tz * 1000), random.randint(1000000000, 9999999999))
def changes(self, target_version=None, nodes=None, labels=None):
"""Sync up (and down) all changes.
Args:
target_version (str): The local change version.
nodes (List[dict]): A list of nodes to sync up to the server.
labels (List[dict]): A list of labels to sync up to the server.
Return:
dict: Description of all changes.
Raises:
APIException: If the server returns an error.
"""
# Handle defaults.
if nodes is None:
nodes = []
if labels is None:
labels = []
current_time = time.time()
# Initialize request parameters.
params = {
"nodes": nodes,
"clientTimestamp": _node.NodeTimestamps.int_to_str(current_time),
"requestHeader": {
"clientSessionId": self._session_id,
"clientPlatform": "ANDROID",
"clientVersion": {
"major": "9",
"minor": "9",
"build": "9",
"revision": "9",
},
"capabilities": [
{"type": "NC"}, # Color support (Send note color)
{"type": "PI"}, # Pinned support (Send note pinned)
{"type": "LB"}, # Labels support (Send note labels)
{"type": "AN"}, # Annotations support (Send annotations)
{"type": "SH"}, # Sharing support
{"type": "DR"}, # Drawing support
{"type": "TR"}, # Trash support (Stop setting the delete timestamp)
{"type": "IN"}, # Indentation support (Send listitem parent)
{"type": "SNB"}, # Allows modification of shared notes?
{"type": "MI"}, # Concise blob info?
{"type": "CO"}, # VSS_SUCCEEDED when off?
# TODO: Figure out what these do:
# {'type': 'EC'}, # ???
# {'type': 'RB'}, # Rollback?
# {'type': 'EX'}, # ???
],
},
}
# Add the targetVersion if set. This tells the server what version the
# client is currently at.
if target_version is not None:
params["targetVersion"] = target_version
# Add any new or updated labels to the request.
if labels:
params["userInfo"] = {"labels": labels}
logger.debug("Syncing %d labels and %d nodes", len(labels), len(nodes))
return self.send(url=self._base_url + "changes", method="POST", json=params)
class MediaAPI(API):
"""Low level Google Media API client. Mimics the Android Google Keep app.
You probably want to use :py:class:`Keep` instead.
"""
API_URL = "https://keep.google.com/media/v2/"
def __init__(self, auth=None):
super(MediaAPI, self).__init__(self.API_URL, auth)
def get(self, blob):
"""Get the canonical link to a media blob.
Args:
blob (gkeepapi.node.Blob): The blob.
Returns:
str: A link to the media.
"""
url = self._base_url + blob.parent.server_id + "/" + blob.server_id
if blob.blob.type == _node.BlobType.Drawing:
url += "/" + blob.blob._drawing_info.drawing_id
return self._send(url=url, method="GET", allow_redirects=False).headers[
"location"
]
class RemindersAPI(API):
"""Low level Google Reminders API client. Mimics the Android Google Keep app.
You probably want to use :py:class:`Keep` instead.
"""
API_URL = "https://www.googleapis.com/reminders/v1internal/reminders/"
def __init__(self, auth=None):
super(RemindersAPI, self).__init__(self.API_URL, auth)
self.static_params = {
"taskList": [
{"systemListId": "MEMENTO"},
],
"requestParameters": {
"userAgentStructured": {
"clientApplication": "KEEP",
"clientApplicationVersion": {
"major": "9",
"minor": "9.9.9.9",
},
"clientPlatform": "ANDROID",
},
},
}
def create(self, node_id, node_server_id, dtime):
"""Create a new reminder.
Args:
node_id (str): The note ID.
node_server_id (str): The note server ID.
dtime (datetime.datetime): The due date of this reminder.
Return: ???
Raises:
APIException: If the server returns an error.
"""
params = {}
params.update(self.static_params)
params.update(
{
"task": {
"dueDate": {
"year": dtime.year,
"month": dtime.month,
"day": dtime.day,
"time": {
"hour": dtime.hour,
"minute": dtime.minute,
"second": dtime.second,
},
},
"snoozed": True,
"extensions": {
"keepExtension": {
"reminderVersion": "V2",
"clientNoteId": node_id,
"serverNoteId": node_server_id,
},
},
},
"taskId": {
"clientAssignedId": "KEEP/v2/" + node_server_id,
},
}
)
return self.send(url=self._base_url + "create", method="POST", json=params)
def update(self, node_id, node_server_id, dtime):
"""Update an existing reminder.
Args:
node_id (str): The note ID.
node_server_id (str): The note server ID.
dtime (datetime.datetime): The due date of this reminder.
Return: ???
Raises:
APIException: If the server returns an error.
"""
params = {}
params.update(self.static_params)
params.update(
{
"newTask": {
"dueDate": {
"year": dtime.year,
"month": dtime.month,
"day": dtime.day,
"time": {
"hour": dtime.hour,
"minute": dtime.minute,
"second": dtime.second,
},
},
"snoozed": True,
"extensions": {
"keepExtension": {
"reminderVersion": "V2",
"clientNoteId": node_id,
"serverNoteId": node_server_id,
},
},
},
"taskId": {
"clientAssignedId": "KEEP/v2/" + node_server_id,
},
"updateMask": {
"updateField": [
"ARCHIVED",
"DUE_DATE",
"EXTENSIONS",
"LOCATION",
"TITLE",
]
},
}
)
return self.send(url=self._base_url + "update", method="POST", json=params)
def delete(self, node_server_id):
"""Delete an existing reminder.
Args:
node_server_id (str): The note server ID.
Return: ???
Raises:
APIException: If the server returns an error.
"""
params = {}
params.update(self.static_params)
params.update(
{
"batchedRequest": [
{
"deleteTask": {
"taskId": [
{"clientAssignedId": "KEEP/v2/" + node_server_id}
]
}
}
]
}
)
return self.send(url=self._base_url + "batchmutate", method="POST", json=params)
def list(self, master=True):
"""List current reminders.
Args:
master (bool): ???
Return:
???
Raises:
APIException: If the server returns an error.
"""
params = {}
params.update(self.static_params)
if master:
params.update(
{
"recurrenceOptions": {
"collapseMode": "MASTER_ONLY",
},
"includeArchived": True,
"includeDeleted": False,
}
)
else:
current_time = time.time()
start_time = int((current_time - (365 * 24 * 60 * 60)) * 1000)
end_time = int((current_time + (24 * 60 * 60)) * 1000)
params.update(
{
"recurrenceOptions": {
"collapseMode": "INSTANCES_ONLY",
"recurrencesOnly": True,
},
"includeArchived": False,
"includeCompleted": False,
"includeDeleted": False,
"dueAfterMs": start_time,
"dueBeforeMs": end_time,
"recurrenceId": [],
}
)
return self.send(url=self._base_url + "list", method="POST", json=params)
def history(self, storage_version):
"""Get reminder changes.
Args:
storage_version (str): The local storage version.
Returns:
???
Raises:
APIException: If the server returns an error.
"""
params = {
"storageVersion": storage_version,
"includeSnoozePresetUpdates": True,
}
params.update(self.static_params)
return self.send(url=self._base_url + "history", method="POST", json=params)
def update(self):
"""Sync up changes to reminders."""
params = {}
return self.send(url=self._base_url + "update", method="POST", json=params)
class Keep(object):
"""High level Google Keep client.
Stores a local copy of the Keep node tree. To start, first login::
keep.login('...', '...')
Individual Notes can be retrieved by id::
some_note = keep.get('some_id')
New Notes can be created::
new_note = keep.createNote()
These Notes can then be modified::
some_note.text = 'Test'
new_note.text = 'Text'
These changes are automatically detected and synced up with::
keep.sync()
"""
OAUTH_SCOPES = "oauth2:https://www.googleapis.com/auth/memento https://www.googleapis.com/auth/reminders"
def __init__(self):
self._keep_api = KeepAPI()
self._reminders_api = RemindersAPI()
self._media_api = MediaAPI()
self._keep_version = None
self._reminder_version = None
self._labels = {}
self._nodes = {}
self._sid_map = {}
self._clear()
def _clear(self):
self._keep_version = None
self._reminder_version = None
self._labels = {}
self._nodes = {}
self._sid_map = {}
root_node = _node.Root()
self._nodes[_node.Root.ID] = root_node
def login(
self,
email,
password,
state=None,
sync=True,
device_id=None,
):
"""Authenticate to Google with the provided credentials & sync.
Args:
email (str): The account to use.
password (str): The account password.
state (dict): Serialized state to load.
sync (bool): Whether to sync after login.
device_id (str): Override for device ID
Raises:
LoginException: If there was a problem logging in.
"""
auth = APIAuth(self.OAUTH_SCOPES)
if device_id is None:
device_id = get_mac()
ret = auth.login(email, password, device_id)
if ret:
self.load(auth, state, sync)
return ret
def resume(self, email, master_token, state=None, sync=True, device_id=None):
"""Authenticate to Google with the provided master token & sync.
Args:
email (str): The account to use.
master_token (str): The master token.
state (dict): Serialized state to load.
sync (bool): Whether to sync after login.
device_id (str): Override for device ID
Raises:
LoginException: If there was a problem logging in.
"""
auth = APIAuth(self.OAUTH_SCOPES)
if device_id is None:
device_id = get_mac()
ret = auth.load(email, master_token, device_id)
if ret:
self.load(auth, state, sync)
return ret
def getMasterToken(self):
"""Get master token for resuming.
Returns:
str: The master token.
"""
return self._keep_api.getAuth().getMasterToken()
def load(self, auth, state=None, sync=True):
"""Authenticate to Google with a prepared authentication object & sync.
Args:
auth (APIAuth): Authentication object.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in.
"""
self._keep_api.setAuth(auth)
self._reminders_api.setAuth(auth)
self._media_api.setAuth(auth)
if state is not None:
self.restore(state)
if sync:
self.sync(True)
def dump(self):
"""Serialize note data.
Args:
state (dict): Serialized state to load.
"""
# Find all nodes manually, as the Keep object isn't aware of new
# ListItems until they've been synced to the server.
nodes = []
for node in self.all():
nodes.append(node)
for child in node.children:
nodes.append(child)
return {
"keep_version": self._keep_version,
"labels": [label.save(False) for label in self.labels()],
"nodes": [node.save(False) for node in nodes],
}
def restore(self, state):
"""Unserialize saved note data.
Args:
state (dict): Serialized state to load.
"""
self._clear()
self._parseUserInfo({"labels": state["labels"]})
self._parseNodes(state["nodes"])
self._keep_version = state["keep_version"]
def get(self, node_id):
"""Get a note with the given ID.
Args:
node_id (str): The note ID.
Returns:
gkeepapi.node.TopLevelNode: The Note or None if not found.
"""
return self._nodes[_node.Root.ID].get(node_id) or self._nodes[
_node.Root.ID
].get(self._sid_map.get(node_id))
def add(self, node):
"""Register a top level node (and its children) for syncing up to the server. There's no need to call this for nodes created by
:py:meth:`createNote` or :py:meth:`createList` as they are automatically added.
LoginException: If :py:meth:`login` has not been called.
Args:
node (gkeepapi.node.Node): The node to sync.
Raises:
Invalid: If the parent node is not found.
"""
if node.parent_id != _node.Root.ID:
raise exception.InvalidException("Not a top level node")
self._nodes[node.id] = node
self._nodes[node.parent_id].append(node, False)
def find(
self,
query=None,
func=None,
labels=None,
colors=None,
pinned=None,
archived=None,
trashed=False,
): # pylint: disable=too-many-arguments
"""Find Notes based on the specified criteria.
Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the title and text.
func (Union[callable, None]): A filter function.
labels (Union[List[str], None]): A list of label ids or objects to match. An empty list matches notes with no labels.
colors (Union[List[str], None]): A list of colors to match.
pinned (Union[bool, None]): Whether to match pinned notes.
archived (Union[bool, None]): Whether to match archived notes.
trashed (Union[bool, None]): Whether to match trashed notes.
Return:
Generator[gkeepapi.node.TopLevelNode]: Results.
"""
if labels is not None:
labels = [i.id if isinstance(i, _node.Label) else i for i in labels]
return (
node
for node in self.all()
if
# Process the query.
(
query is None
or (
(
isinstance(query, str)
and (query in node.title or query in node.text)
)
or (
isinstance(query, Pattern)
and (query.search(node.title) or query.search(node.text))
)
)
)
and
# Process the func.
(func is None or func(node))
and ( # Process the labels.
labels is None
or (not labels and not node.labels.all())
or (any((node.labels.get(i) is not None for i in labels)))
)
and (colors is None or node.color in colors) # Process the colors.
and (pinned is None or node.pinned == pinned) # Process the pinned state.
and ( # Process the archive state.
archived is None or node.archived == archived
)
and (trashed is None or node.trashed == trashed) # Process the trash state.
)
def createNote(self, title=None, text=None):
"""Create a new managed note. Any changes to the note will be uploaded when :py:meth:`sync` is called.
Args:
title (str): The title of the note.
text (str): The text of the note.
Returns:
gkeepapi.node.List: The new note.
"""
node = _node.Note()
if title is not None:
node.title = title
if text is not None:
node.text = text
self.add(node)
return node
def createList(self, title=None, items=None):
"""Create a new list and populate it. Any changes to the note will be uploaded when :py:meth:`sync` is called.
Args:
title (str): The title of the list.
items (List[(str, bool)]): A list of tuples. Each tuple represents the text and checked status of the listitem.
Returns:
gkeepapi.node.List: The new list.
"""
if items is None:
items = []
node = _node.List()
if title is not None:
node.title = title
sort = random.randint(1000000000, 9999999999)
for text, checked in items:
node.add(text, checked, sort)
sort -= _node.List.SORT_DELTA
self.add(node)
return node
def createLabel(self, name):
"""Create a new label.
Args:
name (str): Label name.
Returns:
gkeepapi.node.Label: The new label.
Raises:
LabelException: If the label exists.
"""
if self.findLabel(name):
raise exception.LabelException("Label exists")
node = _node.Label()
node.name = name
self._labels[node.id] = node # pylint: disable=protected-access
return node
def findLabel(self, query, create=False):
"""Find a label with the given name.
Args:
name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.
create (bool): Whether to create the label if it doesn't exist (only if name is a str).
Returns:
Union[gkeepapi.node.Label, None]: The label.
"""
is_str = isinstance(query, str)
name = None
if is_str:
name = query
query = query.lower()
for label in self._labels.values():
# Match the label against query, which may be a str or Pattern.
if (is_str and query == label.name.lower()) or (
isinstance(query, Pattern) and query.search(label.name)
):
return label
return self.createLabel(name) if create and is_str else None
def getLabel(self, label_id):
"""Get an existing label.
Args:
label_id (str): Label id.
Returns:
Union[gkeepapi.node.Label, None]: The label.
"""
return self._labels.get(label_id)
def deleteLabel(self, label_id):
"""Deletes a label.
Args:
label_id (str): Label id.
"""
if label_id not in self._labels:
return
label = self._labels[label_id]
label.delete()
for node in self.all():
node.labels.remove(label)
def labels(self):
"""Get all labels.
Returns:
List[gkeepapi.node.Label]: Labels
"""
return self._labels.values()
def getMediaLink(self, blob):
"""Get the canonical link to media.
Args:
blob (gkeepapi.node.Blob): The media resource.
Returns:
str: A link to the media.
"""
return self._media_api.get(blob)