signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def getMasterToken(self): | return self._keep_api.getAuth().getMasterToken()<EOL> | Get master token for resuming.
Returns:
str: The master token. | f935:c5:m4 |
def load(self, auth, state=None, sync=True): | self._keep_api.setAuth(auth)<EOL>self._reminders_api.setAuth(auth)<EOL>self._media_api.setAuth(auth)<EOL>if state is not None:<EOL><INDENT>self.restore(state)<EOL><DEDENT>if sync:<EOL><INDENT>self.sync(True)<EOL><DEDENT> | 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. | f935:c5:m5 |
def dump(self): | <EOL>nodes = []<EOL>for node in self.all():<EOL><INDENT>nodes.append(node)<EOL>for child in node.children:<EOL><INDENT>nodes.append(child)<EOL><DEDENT><DEDENT>return {<EOL>'<STR_LIT>': self._keep_version,<EOL>'<STR_LIT>': [label.save(False) for label in self.labels()],<EOL>'<STR_LIT>': [node.save(False) for node in nodes]<EOL>}<EOL> | Serialize note data.
Args:
state (dict): Serialized state to load. | f935:c5:m6 |
def restore(self, state): | self._clear()<EOL>self._parseUserInfo({'<STR_LIT>': state['<STR_LIT>']})<EOL>self._parseNodes(state['<STR_LIT>'])<EOL>self._keep_version = state['<STR_LIT>']<EOL> | Unserialize saved note data.
Args:
state (dict): Serialized state to load. | f935:c5:m7 |
def get(self, node_id): | returnself._nodes[_node.Root.ID].get(node_id) orself._nodes[_node.Root.ID].get(self._sid_map.get(node_id))<EOL> | 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. | f935:c5:m8 |
def add(self, node): | if node.parent_id != _node.Root.ID:<EOL><INDENT>raise exception.InvalidException('<STR_LIT>')<EOL><DEDENT>self._nodes[node.id] = node<EOL>self._nodes[node.parent_id].append(node, False)<EOL> | 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. | f935:c5:m9 |
def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): | if labels is not None:<EOL><INDENT>labels = [i.id if isinstance(i, _node.Label) else i for i in labels]<EOL><DEDENT>return (node for node in self.all() if<EOL>(query is None or (<EOL>(isinstance(query, six.string_types) and (query in node.title or query in node.text)) or<EOL>(isinstance(query, Pattern) and (<EOL>query.search(node.title) or query.search(node.text)<EOL>))<EOL>)) and<EOL>(func is None or func(node)) and(labels is None or(not labels and not node.labels.all()) or(any((node.labels.get(i) is not None for i in labels)))<EOL>) and(colors is None or node.color in colors) and(pinned is None or node.pinned == pinned) and(archived is None or node.archived == archived) and(trashed is None or node.trashed == trashed)<EOL>)<EOL> | 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:
List[gkeepapi.node.TopLevelNode]: Results. | f935:c5:m10 |
def createNote(self, title=None, text=None): | node = _node.Note()<EOL>if title is not None:<EOL><INDENT>node.title = title<EOL><DEDENT>if text is not None:<EOL><INDENT>node.text = text<EOL><DEDENT>self.add(node)<EOL>return node<EOL> | 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. | f935:c5:m11 |
def createList(self, title=None, items=None): | if items is None:<EOL><INDENT>items = []<EOL><DEDENT>node = _node.List()<EOL>if title is not None:<EOL><INDENT>node.title = title<EOL><DEDENT>for text, checked in items:<EOL><INDENT>node.add(text, checked)<EOL><DEDENT>self.add(node)<EOL>return node<EOL> | 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. | f935:c5:m12 |
def createLabel(self, name): | if self.findLabel(name):<EOL><INDENT>raise exception.LabelException('<STR_LIT>')<EOL><DEDENT>node = _node.Label()<EOL>node.name = name<EOL>self._labels[node.id] = node <EOL>return node<EOL> | Create a new label.
Args:
name (str): Label name.
Returns:
gkeepapi.node.Label: The new label.
Raises:
LabelException: If the label exists. | f935:c5:m13 |
def findLabel(self, query, create=False): | if isinstance(query, six.string_types):<EOL><INDENT>query = query.lower()<EOL><DEDENT>for label in self._labels.values():<EOL><INDENT>if (isinstance(query, six.string_types) and query == label.name.lower()) or(isinstance(query, Pattern) and query.search(label.name)):<EOL><INDENT>return label<EOL><DEDENT><DEDENT>return self.createLabel(query) if create and isinstance(query, six.string_types) else None<EOL> | 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. | f935:c5:m14 |
def getLabel(self, label_id): | return self._labels.get(label_id)<EOL> | Get an existing label.
Args:
label_id (str): Label id.
Returns:
Union[gkeepapi.node.Label, None]: The label. | f935:c5:m15 |
def deleteLabel(self, label_id): | if label_id not in self._labels:<EOL><INDENT>return<EOL><DEDENT>label = self._labels[label_id]<EOL>label.delete()<EOL>for node in self.all():<EOL><INDENT>node.labels.remove(label)<EOL><DEDENT> | Deletes a label.
Args:
label_id (str): Label id. | f935:c5:m16 |
def labels(self): | return self._labels.values()<EOL> | Get all labels.
Returns:
List[gkeepapi.node.Label]: Labels | f935:c5:m17 |
def getMediaLink(self, blob): | return self._media_api.get(blob)<EOL> | Get the canonical link to media.
Args:
blob (gkeepapi.node.Blob): The media resource.
Returns:
str: A link to the media. | f935:c5:m18 |
def all(self): | return self._nodes[_node.Root.ID].children<EOL> | Get all Notes.
Returns:
List[gkeepapi.node.TopLevelNode]: Notes | f935:c5:m19 |
def sync(self, resync=False): | if resync:<EOL><INDENT>self._clear()<EOL><DEDENT>while True:<EOL><INDENT>logger.debug('<STR_LIT>', self._reminder_version)<EOL>changes = self._reminders_api.list()<EOL>if '<STR_LIT>' in changes:<EOL><INDENT>self._parseTasks(changes['<STR_LIT>'])<EOL><DEDENT>self._reminder_version = changes['<STR_LIT>']<EOL>logger.debug('<STR_LIT>', self._reminder_version)<EOL>history = self._reminders_api.history(self._reminder_version)<EOL>if self._reminder_version == history['<STR_LIT>']:<EOL><INDENT>break<EOL><DEDENT><DEDENT>while True:<EOL><INDENT>logger.debug('<STR_LIT>', self._keep_version)<EOL>labels_updated = any((i.dirty for i in self._labels.values()))<EOL>changes = self._keep_api.changes(<EOL>target_version=self._keep_version,<EOL>nodes=[i.save() for i in self._findDirtyNodes()],<EOL>labels=[i.save() for i in self._labels.values()] if labels_updated else None,<EOL>)<EOL>if changes.get('<STR_LIT>'):<EOL><INDENT>raise exception.ResyncRequiredException('<STR_LIT>')<EOL><DEDENT>if changes.get('<STR_LIT>'):<EOL><INDENT>raise exception.UpgradeRecommendedException('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in changes:<EOL><INDENT>self._parseUserInfo(changes['<STR_LIT>'])<EOL><DEDENT>if '<STR_LIT>' in changes:<EOL><INDENT>self._parseNodes(changes['<STR_LIT>'])<EOL><DEDENT>self._keep_version = changes['<STR_LIT>']<EOL>logger.debug('<STR_LIT>', self._keep_version)<EOL>if not changes['<STR_LIT>']:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if _node.DEBUG:<EOL><INDENT>self._clean()<EOL><DEDENT> | Sync the local Keep tree with the server. If resyncing, local changes will be detroyed. Otherwise, local changes to notes, labels and reminders will be detected and synced up.
Args:
resync (bool): Whether to resync data.
Raises:
SyncException: If there is a consistency issue. | f935:c5:m20 |
def _clean(self): | found_ids = {}<EOL>nodes = [self._nodes[_node.Root.ID]]<EOL>while nodes:<EOL><INDENT>node = nodes.pop()<EOL>found_ids[node.id] = None<EOL>nodes = nodes + node.children<EOL><DEDENT>for node_id in self._nodes:<EOL><INDENT>if node_id in found_ids:<EOL><INDENT>continue<EOL><DEDENT>logger.error('<STR_LIT>', node_id)<EOL><DEDENT>for node_id in found_ids:<EOL><INDENT>if node_id in self._nodes:<EOL><INDENT>continue<EOL><DEDENT>logger.error('<STR_LIT>', node_id)<EOL><DEDENT> | Recursively check that all nodes are reachable. | f935:c5:m25 |
def from_json(raw): | ncls = None<EOL>_type = raw.get('<STR_LIT:type>')<EOL>try:<EOL><INDENT>ncls = _type_map[NodeType(_type)]<EOL><DEDENT>except (KeyError, ValueError) as e:<EOL><INDENT>logger.warning('<STR_LIT>', _type)<EOL>if DEBUG:<EOL><INDENT>raise_from(exception.ParseException('<STR_LIT>' % (_type), raw), e)<EOL><DEDENT>return None<EOL><DEDENT>node = ncls()<EOL>node.load(raw)<EOL>return node<EOL> | Helper to construct a node from a dict.
Args:
raw (dict): Raw node representation.
Returns:
Node: A Node object or None. | f937:m0 |
def load(self, raw): | try:<EOL><INDENT>self._load(raw)<EOL><DEDENT>except (KeyError, ValueError) as e:<EOL><INDENT>raise_from(exception.ParseException('<STR_LIT>' % (type(self)), raw), e)<EOL><DEDENT> | Unserialize from raw representation. (Wrapper)
Args:
raw (dict): Raw.
Raises:
ParseException: If there was an error parsing data. | f937:c10:m2 |
def _load(self, raw): | self._dirty = raw.get('<STR_LIT>', False)<EOL> | Unserialize from raw representation. (Implementation logic)
Args:
raw (dict): Raw. | f937:c10:m3 |
def save(self, clean=True): | ret = {}<EOL>if clean:<EOL><INDENT>self._dirty = False<EOL><DEDENT>else:<EOL><INDENT>ret['<STR_LIT>'] = self._dirty<EOL><DEDENT>return ret<EOL> | Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw. | f937:c10:m4 |
@property<EOL><INDENT>def dirty(self):<DEDENT> | return self._dirty<EOL> | Get dirty state.
Returns:
str: Whether this element is dirty. | f937:c10:m5 |
@property<EOL><INDENT>def title(self):<DEDENT> | return self._title<EOL> | Get the link title.
Returns:
str: The link title. | f937:c12:m3 |
@property<EOL><INDENT>def url(self):<DEDENT> | return self._url<EOL> | Get the link url.
Returns:
str: The link url. | f937:c12:m5 |
@property<EOL><INDENT>def image_url(self):<DEDENT> | return self._image_url<EOL> | Get the link image url.
Returns:
str: The image url or None. | f937:c12:m7 |
@property<EOL><INDENT>def provenance_url(self):<DEDENT> | return self._provenance_url<EOL> | Get the provenance url.
Returns:
url: The provenance url. | f937:c12:m9 |
@property<EOL><INDENT>def description(self):<DEDENT> | return self._description<EOL> | Get the link description.
Returns:
str: The link description. | f937:c12:m11 |
@property<EOL><INDENT>def category(self):<DEDENT> | return self._category<EOL> | Get the category.
Returns:
gkeepapi.node.CategoryValue: The category. | f937:c13:m3 |
@property<EOL><INDENT>def suggest(self):<DEDENT> | return self._suggest<EOL> | Get the suggestion.
Returns:
str: The suggestion. | f937:c14:m3 |
def all(self): | return self._entries.values()<EOL> | Get all sub annotations.
Returns:
List[gkeepapi.node.Annotation]: Sub Annotations. | f937:c15:m3 |
@classmethod<EOL><INDENT>def from_json(cls, raw):<DEDENT> | bcls = None<EOL>if '<STR_LIT>' in raw:<EOL><INDENT>bcls = WebLink<EOL><DEDENT>elif '<STR_LIT>' in raw:<EOL><INDENT>bcls = Category<EOL><DEDENT>elif '<STR_LIT>' in raw:<EOL><INDENT>bcls = TaskAssist<EOL><DEDENT>elif '<STR_LIT>' in raw:<EOL><INDENT>bcls = Context<EOL><DEDENT>if bcls is None:<EOL><INDENT>logger.warning('<STR_LIT>', raw.keys())<EOL>return None<EOL><DEDENT>annotation = bcls()<EOL>annotation.load(raw)<EOL>return annotation<EOL> | Helper to construct an annotation from a dict.
Args:
raw (dict): Raw annotation representation.
Returns:
Node: An Annotation object or None. | f937:c16:m2 |
def all(self): | return self._annotations.values()<EOL> | Get all annotations.
Returns:
List[gkeepapi.node.Annotation]: Annotations. | f937:c16:m3 |
@property<EOL><INDENT>def category(self):<DEDENT> | node = self._get_category_node()<EOL>return node.category if node is not None else None<EOL> | Get the category.
Returns:
Union[gkeepapi.node.CategoryValue, None]: The category or None. | f937:c16:m7 |
@property<EOL><INDENT>def links(self):<DEDENT> | return [annotation for annotation in self._annotations.values()<EOL>if isinstance(annotation, WebLink)<EOL>]<EOL> | Get all links.
Returns:
list[gkeepapi.node.WebLink]: A list of links. | f937:c16:m9 |
def append(self, annotation): | self._annotations[annotation.id] = annotation<EOL>self._dirty = True<EOL>return annotation<EOL> | Add an annotation.
Args:
annotation (gkeepapi.node.Annotation): An Annotation object.
Returns:
gkeepapi.node.Annotation: The Annotation. | f937:c16:m10 |
def remove(self, annotation): | if annotation.id in self._annotations:<EOL><INDENT>del self._annotations[annotation.id]<EOL><DEDENT>self._dirty = True<EOL> | Removes an annotation.
Args:
annotation (gkeepapi.node.Annotation): An Annotation object.
Returns:
gkeepapi.node.Annotation: The Annotation. | f937:c16:m11 |
@classmethod<EOL><INDENT>def str_to_dt(cls, tzs):<DEDENT> | return datetime.datetime.strptime(tzs, cls.TZ_FMT)<EOL> | Convert a datetime string into an object.
Params:
tsz (str): Datetime string.
Returns:
datetime.datetime: Datetime. | f937:c17:m3 |
@classmethod<EOL><INDENT>def int_to_dt(cls, tz):<DEDENT> | return datetime.datetime.utcfromtimestamp(tz)<EOL> | Convert a unix timestamp into an object.
Params:
ts (int): Unix timestamp.
Returns:
datetime.datetime: Datetime. | f937:c17:m4 |
@classmethod<EOL><INDENT>def dt_to_str(cls, dt):<DEDENT> | return dt.strftime(cls.TZ_FMT)<EOL> | Convert a datetime to a str.
Returns:
str: Datetime string. | f937:c17:m5 |
@classmethod<EOL><INDENT>def int_to_str(cls, tz):<DEDENT> | return cls.dt_to_str(cls.int_to_dt(tz))<EOL> | Convert a unix timestamp to a str.
Returns:
str: Datetime string. | f937:c17:m6 |
@property<EOL><INDENT>def created(self):<DEDENT> | return self._created<EOL> | Get the creation datetime.
Returns:
datetime.datetime: Datetime. | f937:c17:m7 |
@property<EOL><INDENT>def deleted(self):<DEDENT> | return self._deleted<EOL> | Get the deletion datetime.
Returns:
datetime.datetime: Datetime. | f937:c17:m9 |
@property<EOL><INDENT>def trashed(self):<DEDENT> | return self._trashed<EOL> | Get the move-to-trash datetime.
Returns:
datetime.datetime: Datetime. | f937:c17:m11 |
@property<EOL><INDENT>def updated(self):<DEDENT> | return self._updated<EOL> | Get the updated datetime.
Returns:
datetime.datetime: Datetime. | f937:c17:m13 |
@property<EOL><INDENT>def edited(self):<DEDENT> | return self._edited<EOL> | Get the user edited datetime.
Returns:
datetime.datetime: Datetime. | f937:c17:m15 |
@property<EOL><INDENT>def new_listitem_placement(self):<DEDENT> | return self._new_listitem_placement<EOL> | Get the default location to insert new listitems.
Returns:
gkeepapi.node.NewListItemPlacementValue: Placement. | f937:c18:m3 |
@property<EOL><INDENT>def graveyard_state(self):<DEDENT> | return self._graveyard_state<EOL> | Get the visibility state for the list graveyard.
Returns:
gkeepapi.node.GraveyardStateValue: Visibility. | f937:c18:m5 |
@property<EOL><INDENT>def checked_listitems_policy(self):<DEDENT> | return self._checked_listitems_policy<EOL> | Get the policy for checked listitems.
Returns:
gkeepapi.node.CheckedListItemsPolicyValue: Policy. | f937:c18:m7 |
def add(self, email): | if email not in self._collaborators:<EOL><INDENT>self._collaborators[email] = ShareRequestValue.Add<EOL><DEDENT>self._dirty = True<EOL> | Add a collaborator.
Args:
str : Collaborator email address. | f937:c19:m4 |
def remove(self, email): | if email in self._collaborators:<EOL><INDENT>if self._collaborators[email] == ShareRequestValue.Add:<EOL><INDENT>del self._collaborators[email]<EOL><DEDENT>else:<EOL><INDENT>self._collaborators[email] = ShareRequestValue.Remove<EOL><DEDENT><DEDENT>self._dirty = True<EOL> | Remove a Collaborator.
Args:
str : Collaborator email address. | f937:c19:m5 |
def all(self): | return [email for email, action in self._collaborators.items() if action in [RoleValue.Owner, RoleValue.User, ShareRequestValue.Add]]<EOL> | Get all collaborators.
Returns:
List[str]: Collaborators. | f937:c19:m6 |
def add(self, label): | self._labels[label.id] = label<EOL>self._dirty = True<EOL> | Add a label.
Args:
label (gkeepapi.node.Label): The Label object. | f937:c20:m4 |
def remove(self, label): | if label.id in self._labels:<EOL><INDENT>self._labels[label.id] = None<EOL><DEDENT>self._dirty = True<EOL> | Remove a label.
Args:
label (gkeepapi.node.Label): The Label object. | f937:c20:m5 |
def get(self, label_id): | return self._labels.get(label_id)<EOL> | Get a label by ID.
Args:
label_id (str): The label ID. | f937:c20:m6 |
def all(self): | return [label for _, label in self._labels.items() if label is not None]<EOL> | Get all labels.
Returns:
List[gkeepapi.node.Label]: Labels. | f937:c20:m7 |
def touch(self, edited=False): | self._dirty = True<EOL>dt = datetime.datetime.utcnow()<EOL>self.timestamps.updated = dt<EOL>if edited:<EOL><INDENT>self.timestamps.edited = dt<EOL><DEDENT> | Mark the node as dirty.
Args:
edited (bool): Whether to set the edited time. | f937:c21:m0 |
@property<EOL><INDENT>def trashed(self):<DEDENT> | return self.timestamps.trashed is not None and self.timestamps.trashed > NodeTimestamps.int_to_dt(<NUM_LIT:0>)<EOL> | Get the trashed state.
Returns:
bool: Whether this item is trashed. | f937:c21:m1 |
@property<EOL><INDENT>def deleted(self):<DEDENT> | return self.timestamps.deleted is not None and self.timestamps.deleted > NodeTimestamps.int_to_dt(<NUM_LIT:0>)<EOL> | Get the deleted state.
Returns:
bool: Whether this item is deleted. | f937:c21:m2 |
def delete(self): | self.timestamps.deleted = datetime.datetime.utcnow()<EOL> | Mark the item as deleted. | f937:c21:m3 |
@property<EOL><INDENT>def sort(self):<DEDENT> | return self._sort<EOL> | Get the sort id.
Returns:
int: Sort id. | f937:c22:m4 |
@property<EOL><INDENT>def version(self):<DEDENT> | return self._version<EOL> | Get the node version.
Returns:
int: Version. | f937:c22:m6 |
@property<EOL><INDENT>def text(self):<DEDENT> | return self._text<EOL> | Get the text value.
Returns:
str: Text value. | f937:c22:m7 |
@text.setter<EOL><INDENT>def text(self, value):<DEDENT> | self._text = value<EOL>self.timestamps.edited = datetime.datetime.utcnow()<EOL>self.touch(True)<EOL> | Set the text value.
Args:
value (str): Text value. | f937:c22:m8 |
@property<EOL><INDENT>def children(self):<DEDENT> | return list(self._children.values())<EOL> | Get all children.
Returns:
list[gkeepapi.Node]: Children nodes. | f937:c22:m11 |
def get(self, node_id): | return self._children.get(node_id)<EOL> | Get child node with the given ID.
Args:
node_id (str): The node ID.
Returns:
gkeepapi.Node: Child node. | f937:c22:m12 |
def append(self, node, dirty=True): | self._children[node.id] = node<EOL>node.parent = self<EOL>if dirty:<EOL><INDENT>self.touch()<EOL><DEDENT>return node<EOL> | Add a new child node.
Args:
node (gkeepapi.Node): Node to add.
dirty (bool): Whether this node should be marked dirty. | f937:c22:m13 |
def remove(self, node, dirty=True): | if node.id in self._children:<EOL><INDENT>self._children[node.id].parent = None<EOL>del self._children[node.id]<EOL><DEDENT>if dirty:<EOL><INDENT>self.touch()<EOL><DEDENT> | Remove the given child node.
Args:
node (gkeepapi.Node): Node to remove.
dirty (bool): Whether this node should be marked dirty. | f937:c22:m14 |
@property<EOL><INDENT>def new(self):<DEDENT> | return self.server_id is None<EOL> | Get whether this node has been persisted to the server.
Returns:
bool: True if node is new. | f937:c22:m15 |
@property<EOL><INDENT>def color(self):<DEDENT> | return self._color<EOL> | Get the node color.
Returns:
gkeepapi.node.Color: Color. | f937:c24:m3 |
@property<EOL><INDENT>def archived(self):<DEDENT> | return self._archived<EOL> | Get the archive state.
Returns:
bool: Whether this node is archived. | f937:c24:m5 |
@property<EOL><INDENT>def pinned(self):<DEDENT> | return self._pinned<EOL> | Get the pin state.
Returns:
bool: Whether this node is pinned. | f937:c24:m7 |
@property<EOL><INDENT>def title(self):<DEDENT> | return self._title<EOL> | Get the title.
Returns:
str: Title. | f937:c24:m9 |
@property<EOL><INDENT>def url(self):<DEDENT> | return '<STR_LIT>' + self._TYPE.value + '<STR_LIT:/>' + self.id<EOL> | Get the url for this node.
Returns:
str: Google Keep url. | f937:c24:m11 |
@property<EOL><INDENT>def blobs(self):<DEDENT> | return [node for node in self.children if isinstance(node, Blob)]<EOL> | Get all media blobs.
Returns:
list[gkeepapi.node.Blob]: Media blobs. | f937:c24:m13 |
def add(self, text, checked=False, sort=None): | node = ListItem(parent_id=self.id, parent_server_id=self.server_id)<EOL>node.checked = checked<EOL>node.text = text<EOL>if sort is not None:<EOL><INDENT>node.sort = sort<EOL><DEDENT>self.append(node, True)<EOL>self.touch(True)<EOL>return node<EOL> | Add a new item to the list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting. | f937:c26:m1 |
@classmethod<EOL><INDENT>def items_sort(cls, items):<DEDENT> | class t(tuple):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __cmp__(self, other):<EOL><INDENT>for a, b in six.moves.zip_longest(self, other):<EOL><INDENT>if a != b:<EOL><INDENT>if a is None:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if b is None:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>return a - b<EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL><DEDENT>def __lt__(self, other):<EOL><INDENT>return self.__cmp__(other) < <NUM_LIT:0><EOL><DEDENT>def __gt_(self, other):<EOL><INDENT>return self.__cmp__(other) > <NUM_LIT:0><EOL><DEDENT>def __le__(self, other):<EOL><INDENT>return self.__cmp__(other) <= <NUM_LIT:0><EOL><DEDENT>def __ge_(self, other):<EOL><INDENT>return self.__cmp__(other) >= <NUM_LIT:0><EOL><DEDENT>def __eq__(self, other):<EOL><INDENT>return self.__cmp__(other) == <NUM_LIT:0><EOL><DEDENT>def __ne__(self, other):<EOL><INDENT>return self.__cmp__(other) != <NUM_LIT:0><EOL><DEDENT><DEDENT>def key_func(x):<EOL><INDENT>if x.indented:<EOL><INDENT>return t((int(x.parent_item.sort), int(x.sort)))<EOL><DEDENT>return t((int(x.sort), ))<EOL><DEDENT>return sorted(items, key=key_func, reverse=True)<EOL> | Sort list items, taking into account parent items.
Args:
items (list[gkeepapi.node.ListItem]): Items to sort.
Returns:
list[gkeepapi.node.ListItem]: Sorted items. | f937:c26:m3 |
@property<EOL><INDENT>def items(self):<DEDENT> | return self._items()<EOL> | Get all listitems.
Returns:
list[gkeepapi.node.ListItem]: List items. | f937:c26:m6 |
@property<EOL><INDENT>def checked(self):<DEDENT> | return self._items(True)<EOL> | Get all checked listitems.
Returns:
list[gkeepapi.node.ListItem]: List items. | f937:c26:m7 |
@property<EOL><INDENT>def unchecked(self):<DEDENT> | return self._items(False)<EOL> | Get all unchecked listitems.
Returns:
list[gkeepapi.node.ListItem]: List items. | f937:c26:m8 |
def add(self, text, checked=False, sort=None): | if self.parent is None:<EOL><INDENT>raise exception.InvalidException('<STR_LIT>')<EOL><DEDENT>node = self.parent.add(text, checked, sort)<EOL>self.indent(node)<EOL>return node<EOL> | Add a new sub item to the list. This item must already be attached to a list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting. | f937:c27:m3 |
def indent(self, node, dirty=True): | if node.subitems:<EOL><INDENT>return<EOL><DEDENT>self._subitems[node.id] = node<EOL>node.super_list_item_id = self.id<EOL>node.parent_item = self<EOL>if dirty:<EOL><INDENT>node.touch(True)<EOL><DEDENT> | Indent an item. Does nothing if the target has subitems.
Args:
node (gkeepapi.node.ListItem): Item to indent.
dirty (bool): Whether this node should be marked dirty. | f937:c27:m4 |
def dedent(self, node, dirty=True): | if node.id not in self._subitems:<EOL><INDENT>return<EOL><DEDENT>del self._subitems[node.id]<EOL>node.super_list_item_id = None<EOL>node.parent_item = None<EOL>if dirty:<EOL><INDENT>node.touch(True)<EOL><DEDENT> | Dedent an item. Does nothing if the target is not indented under this item.
Args:
node (gkeepapi.node.ListItem): Item to dedent.
dirty (bool): Whether this node should be marked dirty. | f937:c27:m5 |
@property<EOL><INDENT>def subitems(self):<DEDENT> | return List.items_sort(<EOL>self._subitems.values()<EOL>)<EOL> | Get subitems for this item.
Returns:
list[gkeepapi.node.ListItem]: Subitems. | f937:c27:m6 |
@property<EOL><INDENT>def indented(self):<DEDENT> | return self.super_list_item_id is not None<EOL> | Get indentation state.
Returns:
bool: Whether this item is indented. | f937:c27:m7 |
@property<EOL><INDENT>def checked(self):<DEDENT> | return self._checked<EOL> | Get the checked state.
Returns:
bool: Whether this item is checked. | f937:c27:m8 |
@property<EOL><INDENT>def url(self):<DEDENT> | raise NotImplementedError()<EOL> | Get a url to the image.
Returns:
str: Image url. | f937:c30:m3 |
@classmethod<EOL><INDENT>def from_json(cls, raw):<DEDENT> | if raw is None:<EOL><INDENT>return None<EOL><DEDENT>bcls = None<EOL>_type = raw.get('<STR_LIT:type>')<EOL>try:<EOL><INDENT>bcls = cls._blob_type_map[BlobType(_type)]<EOL><DEDENT>except (KeyError, ValueError) as e:<EOL><INDENT>logger.warning('<STR_LIT>', _type)<EOL>if DEBUG:<EOL><INDENT>raise_from(exception.ParseException('<STR_LIT>' % (_type), raw), e)<EOL><DEDENT>return None<EOL><DEDENT>blob = bcls()<EOL>blob.load(raw)<EOL>return blob<EOL> | Helper to construct a blob from a dict.
Args:
raw (dict): Raw blob representation.
Returns:
NodeBlob: A NodeBlob object or None. | f937:c33:m1 |
@property<EOL><INDENT>def name(self):<DEDENT> | return self._name<EOL> | Get the label name.
Returns:
str: Label name. | f937:c34:m4 |
@property<EOL><INDENT>def merged(self):<DEDENT> | return self._merged<EOL> | Get last merge datetime.
Returns:
datetime: Datetime. | f937:c34:m6 |
def github_auth_middleware(*, github_id, github_secret, github_org,<EOL>whitelist_handlers=None, api_unauthorized=False): | global gh_id, gh_secret, gh_org<EOL>gh_id = github_id<EOL>gh_secret = github_secret<EOL>gh_org = github_org<EOL>whitelist_handlers = whitelist_handlers or []<EOL>async def middleware_factory(app, handler):<EOL><INDENT>async def auth_handler(request):<EOL><INDENT>session = await get_session(request)<EOL>params = urllib.parse.parse_qs(request.query_string)<EOL>user = session.get('<STR_LIT>')<EOL>if user: <EOL><INDENT>request['<STR_LIT:user>'] = user<EOL><DEDENT>elif handler in whitelist_handlers: <EOL><INDENT>pass<EOL><DEDENT>elif handler == handle_github_callback andsession.get('<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>elif api_unauthorized and request.path.startswith('<STR_LIT>'):<EOL><INDENT>return web.HTTPUnauthorized()<EOL><DEDENT>else:<EOL><INDENT>gh = GithubClient(<EOL>client_id=gh_id,<EOL>client_secret=gh_secret<EOL>)<EOL>state = os.urandom(<NUM_LIT:30>).hex()<EOL>authorize_url = gh.get_authorize_url(<EOL>scope='<STR_LIT>',<EOL>state=state)<EOL>session['<STR_LIT>'] = state<EOL>session['<STR_LIT>'] = request.path<EOL>return web.HTTPFound(authorize_url)<EOL><DEDENT>return await handler(request)<EOL><DEDENT>return auth_handler<EOL><DEDENT>return middleware_factory<EOL> | Middleware for github authentication
:param github_id: github client id
:param github_secret: github secret
:param github_org: github organization for which people are authorized
:param whitelist_handlers: a list of handler methods
which do not need authorization
:param api_unauthorized: if set to True, any call without authorization
made at a path of /api/* will return a 401 instead of
redirecting to github login
:return: middleware_factory | f940:m0 |
@receiver([post_delete, post_save], sender=UserTermsAndConditions)<EOL>def user_terms_updated(sender, **kwargs): | LOGGER.debug("<STR_LIT>")<EOL>if kwargs.get('<STR_LIT>').user:<EOL><INDENT>cache.delete('<STR_LIT>' + kwargs.get('<STR_LIT>').user.get_username())<EOL><DEDENT> | Called when user terms and conditions is changed - to force cache clearing | f950:m0 |
@receiver([post_delete, post_save], sender=TermsAndConditions)<EOL>def terms_updated(sender, **kwargs): | LOGGER.debug("<STR_LIT>")<EOL>cache.delete('<STR_LIT>')<EOL>cache.delete('<STR_LIT>')<EOL>if kwargs.get('<STR_LIT>').slug:<EOL><INDENT>cache.delete('<STR_LIT>' + kwargs.get('<STR_LIT>').slug)<EOL><DEDENT>for utandc in UserTermsAndConditions.objects.all():<EOL><INDENT>cache.delete('<STR_LIT>' + utandc.user.get_username())<EOL><DEDENT> | Called when terms and conditions is changed - to force cache clearing | f950:m1 |
@register.inclusion_tag('<STR_LIT>',<EOL>takes_context=True)<EOL>def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD): | request = context['<STR_LIT>']<EOL>url = urlparse(request.META[field])<EOL>not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(request.user)<EOL>if not_agreed_terms and is_path_protected(url.path):<EOL><INDENT>return {'<STR_LIT>': not_agreed_terms, '<STR_LIT>': url.path}<EOL><DEDENT>else:<EOL><INDENT>return {}<EOL><DEDENT> | Displays a modal on a current page if a user has not yet agreed to the
given terms. If terms are not specified, the default slug is used.
A small snippet is included into your template if a user
who requested the view has not yet agreed the terms. The snippet takes
care of displaying a respective modal. | f952:m0 |
@register.filter<EOL>def as_template(obj): | return template.Template(obj)<EOL> | Converts objects to a Template instance
This is useful in cases when a template variable contains html-like text,
which includes also django template language tags and should be rendered.
For instance, in case of termsandconditions object, its text field may
include a string such as `<a href="{% url 'my-url' %}">My url</a>`,
which should be properly rendered.
To achieve this goal, one can use template `include` with `as_template`
filter:
...
{% include your_variable|as_template %}
... | f952:m1 |
def get_terms(self, kwargs): | slug = kwargs.get("<STR_LIT>")<EOL>version = kwargs.get("<STR_LIT:version>")<EOL>if slug and version:<EOL><INDENT>terms = [TermsAndConditions.objects.filter(slug=slug, version_number=version).latest('<STR_LIT>')]<EOL><DEDENT>elif slug:<EOL><INDENT>terms = [TermsAndConditions.get_active(slug)]<EOL><DEDENT>else:<EOL><INDENT>terms = TermsAndConditions.get_active_terms_not_agreed_to(self.request.user)<EOL><DEDENT>return terms<EOL> | Checks URL parameters for slug and/or version to pull the right TermsAndConditions object | f956:c0:m0 |
def get_context_data(self, **kwargs): | context = super(TermsView, self).get_context_data(**kwargs)<EOL>context['<STR_LIT>'] = getattr(settings, '<STR_LIT>', DEFAULT_TERMS_BASE_TEMPLATE)<EOL>return context<EOL> | Pass additional context data | f956:c1:m0 |
def get_object(self, queryset=None): | LOGGER.debug('<STR_LIT>')<EOL>return self.get_terms(self.kwargs)<EOL> | Override of DetailView method, queries for which T&C to return | f956:c1:m1 |
def get_context_data(self, **kwargs): | context = super(AcceptTermsView, self).get_context_data(**kwargs)<EOL>context['<STR_LIT>'] = getattr(settings, '<STR_LIT>', DEFAULT_TERMS_BASE_TEMPLATE)<EOL>return context<EOL> | Pass additional context data | f956:c2:m0 |
def get_initial(self): | LOGGER.debug('<STR_LIT>')<EOL>terms = self.get_terms(self.kwargs)<EOL>return_to = self.request.GET.get('<STR_LIT>', '<STR_LIT:/>')<EOL>return {'<STR_LIT>': terms, '<STR_LIT>': return_to}<EOL> | Override of CreateView method, queries for which T&C to accept and catches returnTo from URL | f956:c2:m1 |