Exemplo n.º 1
0
 def __args_to_list(self, func_args):
     if not is_str(func_args):
         return list(func_args)
     lst = []
     for arg in item_to_list(func_args, chrs=','):
         lst += [arg] + [None]
     return lst
Exemplo n.º 2
0
 def __setattr__(self, key, value):
     key_adj = self._key_transform_(key)
     if self._is_protected_(key):
         if not self._is_my_attr_(key):
             raise AttributeError(
                 "Attempted to set protected built-in item %s on %s\n\nMy Attrs: %s"
                 % (key_adj, self.__class__.__name__, self._my_attrs_))
         else:
             super(Dict, self).__setattr__(key_adj, value)
     elif self._default_ and is_str(key_adj) and (
             key_adj.lower() == 'default'
             or key_adj.lower() == self._default_.strip('_')):
         self.setDefault(value)
     elif key_adj in self:
         attr_val = getattr(self, key_adj)
         if self._default_ and isinstance(attr_val, self.__class__):
             attr_val.setSecondary(value.getDefaultAttr(
             ) if isinstance(value, self.__class__) else value)
         else:
             super(self.__class__.mro()[-4],
                   self).__setattr__(key_adj, value)
     else:
         if self._cls_missing_attrs_:
             self[key_adj] = self._new_instance_(self,
                                                 key_name=key_adj,
                                                 override_default=True)
             self[key_adj].setValue(value)
         else:
             super(self.__class__.mro()[-4],
                   self).__setitem__(key_adj, value)
Exemplo n.º 3
0
 def scalar(self, sql='1', *a, **kw):
     log_text = 'Call to DB.ankdb_scalar():'
     if not isinstance(self, ank_DB):
         log_text += '\n   - Self:       ' + pf(self)
     if a:
         log_text += '\n   - Args:       ' + pf(a)
     if kw:
         log_text += '\n   - KWArgs:     ' + pf(kw)
     last_query='<None>'
     if hasattr(self, 'ankdb_lastquery'):
         last_query = self.ankdb_lastquery
         if is_str(last_query):
             last_query = last_query[:50]
         else:
             last_query = pf(last_query)
         log_text += '\n   - Last Query: ' + last_query
     log(log_text + '\n', 'sql\\ankdb_scalar')
     try:
         res = self.execute(sql, a, kw)
     except TypeError as e:
         log(" > ERROR with ankdb_scalar while executing query: %s\n >  LAST QUERY: %s" % (str(e), last_query), 'sql\\ankdb_scalar', crosspost='sql\\ankdb_scalar-error')
         raise
     if not isinstance(res, sqlite.Cursor):
         log(' > Cursor: %s' % pf(res), 'sql\\ankdb_scalar')
     try:
         res = res.fetchone()
     except TypeError as e:
         log(" > ERROR with ankdb_scalar while fetching result: %s\n >  LAST QUERY: %s" % (str(e), last_query), 'sql\\ankdb_scalar', crosspost='sql\\ankdb_scalar-error')
         raise
     log_blank('sql\\ankdb_scalar')
     if res:
         return res[0]
     return None
Exemplo n.º 4
0
def get_evernote_guid_from_anki_fields(fields):
    if isinstance(fields, dict):
        if not FIELDS.EVERNOTE_GUID in fields:
            return None
        return fields[FIELDS.EVERNOTE_GUID].replace(FIELDS.EVERNOTE_GUID_PREFIX, '')
    if is_str(fields):
        fields = splitFields(fields)
        return fields[FIELDS.ORD.EVERNOTE_GUID].replace(FIELDS.EVERNOTE_GUID_PREFIX, '')
Exemplo n.º 5
0
 def __init__(self, max=None, interval=100, info=None, infoStr=None, automated=None, begin=True,
              label=None, display_initial_info=None, max_allowed=None, do_print=False, **kw):
     """
     :type info : ActionInfo
     """
     args = DictCaseInsensitive(kw, locals(), delete='kw infoStr info max self')
     simple_label = False
     self.counts = EvernoteCounter()
     self.__interval = interval
     self.__reported_progress = False
     if not isinstance(max, int):
         if hasattr(max, '__len__'):
             max = len(max)
         else:
             max = None
     self.counts.max = -1
     if max is not None:
         self.counts.max = max
         args.max = self.counts.max
     if is_str(info):
         # noinspection PyTypeChecker
         info = ActionInfo(info, **args)
     elif infoStr and not info:
         info = ActionInfo(infoStr, **args)
     elif label and not info:
         simple_label = True
         if display_initial_info is None:
             display_initial_info = False
         info = ActionInfo(label, **args)
     elif label:
         info.Label = label
     if self.counts.max > 0 and info and (info.Max is None or info.Max < 1):
         info.Max = max
     self.counts.max_allowed = self.counts.max if max_allowed is None else max_allowed
     self.__did_break = True
     self.__do_print = do_print
     self.__info = info
     self.__action_initialized = False
     self.__action_attempted = self.hasActionInfo and (display_initial_info is not False)
     if self.__action_attempted:
         if self.info is None:
             log("Unexpected; Timer '%s' has no ActionInfo instance" % label, do_print=True)
         else:
             self.__action_initialized = self.info.displayInitialInfo(**args) is EvernoteAPIStatus.Initialized
     if begin:
         self.reset(False)
     log_blank(filename='counters')
     log(self.counts.fullSummary(self.name + ': Start'), 'counters')
Exemplo n.º 6
0
 def __getitem__(self, key):
     key_adj = self._key_transform_all_(key)
     if self._default_ and is_str(key_adj) and (key_adj.lower() == 'default' or key_adj.lower() == self._default_.strip('_')):
         return self.getDefault()
     if key_adj not in self:
         if key_adj in dir(self.__class__):
             return super(self.__class__.mro()[-3], self).__getattr__(key_adj)
         elif self._is_protected_(key):
             try:
                 return None if self._is_my_attr_(key) else super(Dict, self).__getattr__(key)
             except KeyError:
                 raise KeyError("Could not find protected built-in item " + key)
         self[key_adj] = self._new_instance_(self, key_name=key_adj, override_default=True)
     try:
         return super(self.__class__.mro()[-4], self).__getitem__(key_adj)
     except TypeError:
         return "<null>"
Exemplo n.º 7
0
 def __setattr__(self, key, value):
     key_adj = self._key_transform_(key)
     if self._is_protected_(key):
         if not self._is_my_attr_(key):
             raise AttributeError("Attempted to set protected built-in item %s on %s\n\nMy Attrs: %s" % (key_adj, self.__class__.__name__, self._my_attrs_))
         else:
             super(Dict, self).__setattr__(key_adj, value)
     elif self._default_ and is_str(key_adj) and (key_adj.lower() == 'default' or key_adj.lower() == self._default_.strip('_')):
         self.setDefault(value)
     elif key_adj in self:
         attr_val = getattr(self, key_adj)
         if self._default_ and isinstance(attr_val, self.__class__):
             attr_val.setSecondary(value.getDefaultAttr() if isinstance(value, self.__class__) else value)
         else:
             super(self.__class__.mro()[-4], self).__setattr__(key_adj, value)
     else:
         if self._cls_missing_attrs_:
             self[key_adj] = self._new_instance_(self, key_name=key_adj, override_default=True)
             self[key_adj].setValue(value)
         else:
             super(self.__class__.mro()[-4], self).__setitem__(key_adj, value)
Exemplo n.º 8
0
 def __getitem__(self, key):
     key_adj = self._key_transform_all_(key)
     if self._default_ and is_str(key_adj) and (
             key_adj.lower() == 'default'
             or key_adj.lower() == self._default_.strip('_')):
         return self.getDefault()
     if key_adj not in self:
         if key_adj in dir(self.__class__):
             return super(self.__class__.mro()[-3],
                          self).__getattr__(key_adj)
         elif self._is_protected_(key):
             try:
                 return None if self._is_my_attr_(key) else super(
                     Dict, self).__getattr__(key)
             except KeyError:
                 raise KeyError("Could not find protected built-in item " +
                                key)
         self[key_adj] = self._new_instance_(self,
                                             key_name=key_adj,
                                             override_default=True)
     try:
         return super(self.__class__.mro()[-4], self).__getitem__(key_adj)
     except TypeError:
         return "<null>"
Exemplo n.º 9
0
 def __init__(self,
              max=None,
              interval=100,
              info=None,
              infoStr=None,
              automated=None,
              begin=True,
              label=None,
              display_initial_info=None,
              max_allowed=None,
              do_print=False,
              **kw):
     """
     :type info : ActionInfo
     """
     args = DictCaseInsensitive(kw,
                                locals(),
                                delete='kw infoStr info max self')
     simple_label = False
     self.counts = EvernoteCounter()
     self.__interval = interval
     self.__reported_progress = False
     if not isinstance(max, int):
         if hasattr(max, '__len__'):
             max = len(max)
         else:
             max = None
     self.counts.max = -1
     if max is not None:
         self.counts.max = max
         args.max = self.counts.max
     if is_str(info):
         # noinspection PyTypeChecker
         info = ActionInfo(info, **args)
     elif infoStr and not info:
         info = ActionInfo(infoStr, **args)
     elif label and not info:
         simple_label = True
         if display_initial_info is None:
             display_initial_info = False
         info = ActionInfo(label, **args)
     elif label:
         info.Label = label
     if self.counts.max > 0 and info and (info.Max is None or info.Max < 1):
         info.Max = max
     self.counts.max_allowed = self.counts.max if max_allowed is None else max_allowed
     self.__did_break = True
     self.__do_print = do_print
     self.__info = info
     self.__action_initialized = False
     self.__action_attempted = self.hasActionInfo and (display_initial_info
                                                       is not False)
     if self.__action_attempted:
         if self.info is None:
             log("Unexpected; Timer '%s' has no ActionInfo instance" %
                 label,
                 do_print=True)
         else:
             self.__action_initialized = self.info.displayInitialInfo(
                 **args) is EvernoteAPIStatus.Initialized
     if begin:
         self.reset(False)
     log_blank(filename='counters')
     log(self.counts.fullSummary(self.name + ': Start'), 'counters')
Exemplo n.º 10
0
    def makeNote(self, noteTitle=None, noteContents=None, tagNames=None, parentNotebook=None, resources=None,
                 noteType=None, guid=None,
                 validated=None, enNote=None):
        """
        Create or Update a Note instance with title and body
        Send Note object to user's account
        :type noteTitle: str
        :param noteContents: Valid ENML without the <en-note></en-note> tags. Will be processed by makeNoteBody
        :type enNote : EvernoteNotePrototype
        :rtype : (EvernoteAPIStatus, EvernoteNote)
        :returns Status and Note
        """
        if tagNames is None:
            tagNames = []
        if enNote:
            guid, noteTitle, noteContents, tagNames, parentNotebook = enNote.Guid, enNote.FullTitle, enNote.Content, enNote.Tags, enNote.NotebookGuid or parentNotebook
        if resources is None:
            resources = []
        callType = "create"
        validation_status = EvernoteAPIStatus.Uninitialized
        if validated is None:
            if not EVERNOTE.UPLOAD.VALIDATION.ENABLED:
                validated = True
            else:
                validation_status = self.addNoteToMakeNoteQueue(noteTitle, noteContents, tagNames, parentNotebook,
                                                                resources, guid)
                if not validation_status.IsSuccess and not self.hasValidator:
                    return validation_status, None
        log('%s%s: %s: ' % ('+VALIDATOR ' if self.hasValidator else '' + noteType, str(validation_status), noteTitle),
            'validation')
        ourNote = EvernoteNote()
        ourNote.title = encode(noteTitle)
        if guid:
            callType = "update"; ourNote.guid = guid

        ## Build body of note
        nBody = self.makeNoteBody(noteContents, resources)
        if validated is not True and not validation_status.IsSuccess:
            status, errors = self.validateNoteBody(nBody, ourNote.title)
            assert isinstance(status, EvernoteAPIStatus)
            if not status.IsSuccess:
                return status, None
        ourNote.content = nBody

        notestore_status = self.initialize_note_store()
        if not notestore_status.IsSuccess:
            return notestore_status, None

        while '' in tagNames: tagNames.remove('')
        if tagNames:
            if EVERNOTE.API.IS_SANDBOXED and not '#Sandbox' in tagNames:
                tagNames.append("#Sandbox")
            ourNote.tagNames = tagNames

        ## parentNotebook is optional; if omitted, default notebook is used
        if parentNotebook:
            if hasattr(parentNotebook, 'guid'):
                ourNote.notebookGuid = parentNotebook.guid
            elif hasattr(parentNotebook, 'Guid'):
                ourNote.notebookGuid = parentNotebook.Guid
            elif is_str(parentNotebook):
                ourNote.notebookGuid = parentNotebook

        ## Attempt to create note in Evernote account

        api_action_str = u'trying to %s a note' % callType
        log_api(callType + "Note", "'%s'" % noteTitle)
        try:
            note = getattr(self.noteStore, callType + 'Note')(self.token, ourNote)
        except EDAMSystemException as e:
            if not HandleEDAMRateLimitError(e, api_action_str) or EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.RateLimitError, None
        except socket.error as v:
            if not HandleSocketError(v, api_action_str) or EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.SocketError, None
        except EDAMUserException as edue:
            ## Something was wrong with the note data
            ## See EDAMErrorCode enumeration for error code explanation
            ## http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
            print "EDAMUserException:", edue
            log_error("-" * 50, crosspost_to_default=False)
            log_error("EDAMUserException:  " + str(edue), crosspost='api')
            log_error(str(ourNote.tagNames), crosspost_to_default=False)
            log_error(str(ourNote.content), crosspost_to_default=False)
            log_error("-" * 50 + "\r\n", crosspost_to_default=False)
            if EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.UserError, None
        except EDAMNotFoundException as ednfe:
            print "EDAMNotFoundException:", ednfe
            log_error("-" * 50, crosspost_to_default=False)
            log_error("EDAMNotFoundException:  " + str(ednfe), crosspost='api')
            if callType is "update":
                log_error('GUID: ' + str(ourNote.guid), crosspost_to_default=False)
            if ourNote.notebookGuid:
                log_error('Notebook GUID: ' + str(ourNote.notebookGuid), crosspost_to_default=False)
            log_error("-" * 50 + "\r\n", crosspost_to_default=False)
            if EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.NotFoundError, None
        except Exception as e:
            print "Unknown Exception:", e
            log_error("-" * 50, crosspost_to_default=False)
            log_error("Unknown Exception:  " + str(e))
            log_error(str(ourNote.tagNames), crosspost_to_default=False)
            log_error(str(ourNote.content), crosspost_to_default=False)
            log_error("-" * 50 + "\r\n", crosspost_to_default=False)
            # return EvernoteAPIStatus.UnhandledError, None
            raise
        # noinspection PyUnboundLocalVariable
        note.content = nBody
        return EvernoteAPIStatus.Success, note
Exemplo n.º 11
0
    def makeNote(self,
                 noteTitle=None,
                 noteContents=None,
                 tagNames=None,
                 parentNotebook=None,
                 resources=None,
                 noteType=None,
                 guid=None,
                 validated=None,
                 enNote=None):
        """
        Create or Update a Note instance with title and body
        Send Note object to user's account
        :type noteTitle: str
        :param noteContents: Valid ENML without the <en-note></en-note> tags. Will be processed by makeNoteBody
        :type enNote : EvernoteNotePrototype
        :rtype : (EvernoteAPIStatus, EvernoteNote)
        :returns Status and Note
        """
        if tagNames is None:
            tagNames = []
        if enNote:
            guid, noteTitle, noteContents, tagNames, parentNotebook = enNote.Guid, enNote.FullTitle, enNote.Content, enNote.Tags, enNote.NotebookGuid or parentNotebook
        if resources is None:
            resources = []
        callType = "create"
        validation_status = EvernoteAPIStatus.Uninitialized
        if validated is None:
            if not EVERNOTE.UPLOAD.VALIDATION.ENABLED:
                validated = True
            else:
                validation_status = self.addNoteToMakeNoteQueue(
                    noteTitle, noteContents, tagNames, parentNotebook,
                    resources, guid)
                if not validation_status.IsSuccess and not self.hasValidator:
                    return validation_status, None
        log(
            '%s%s: %s: ' % ('+VALIDATOR ' if self.hasValidator else '' +
                            noteType, str(validation_status), noteTitle),
            'validation')
        ourNote = EvernoteNote()
        ourNote.title = encode(noteTitle)
        if guid:
            callType = "update"
            ourNote.guid = guid

        ## Build body of note
        nBody = self.makeNoteBody(noteContents, resources)
        if validated is not True and not validation_status.IsSuccess:
            status, errors = self.validateNoteBody(nBody, ourNote.title)
            assert isinstance(status, EvernoteAPIStatus)
            if not status.IsSuccess:
                return status, None
        ourNote.content = nBody

        notestore_status = self.initialize_note_store()
        if not notestore_status.IsSuccess:
            return notestore_status, None

        while '' in tagNames:
            tagNames.remove('')
        if tagNames:
            if EVERNOTE.API.IS_SANDBOXED and not '#Sandbox' in tagNames:
                tagNames.append("#Sandbox")
            ourNote.tagNames = tagNames

        ## parentNotebook is optional; if omitted, default notebook is used
        if parentNotebook:
            if hasattr(parentNotebook, 'guid'):
                ourNote.notebookGuid = parentNotebook.guid
            elif hasattr(parentNotebook, 'Guid'):
                ourNote.notebookGuid = parentNotebook.Guid
            elif is_str(parentNotebook):
                ourNote.notebookGuid = parentNotebook

        ## Attempt to create note in Evernote account

        api_action_str = u'trying to %s a note' % callType
        log_api(callType + "Note", "'%s'" % noteTitle)
        try:
            note = getattr(self.noteStore, callType + 'Note')(self.token,
                                                              ourNote)
        except EDAMSystemException as e:
            if not HandleEDAMRateLimitError(
                    e, api_action_str) or EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.RateLimitError, None
        except socket.error as v:
            if not HandleSocketError(
                    v, api_action_str) or EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.SocketError, None
        except EDAMUserException as edue:
            ## Something was wrong with the note data
            ## See EDAMErrorCode enumeration for error code explanation
            ## http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
            print "EDAMUserException:", edue
            log_error("-" * 50, crosspost_to_default=False)
            log_error("EDAMUserException:  " + str(edue), crosspost='api')
            log_error(str(ourNote.tagNames), crosspost_to_default=False)
            log_error(str(ourNote.content), crosspost_to_default=False)
            log_error("-" * 50 + "\r\n", crosspost_to_default=False)
            if EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.UserError, None
        except EDAMNotFoundException as ednfe:
            print "EDAMNotFoundException:", ednfe
            log_error("-" * 50, crosspost_to_default=False)
            log_error("EDAMNotFoundException:  " + str(ednfe), crosspost='api')
            if callType is "update":
                log_error('GUID: ' + str(ourNote.guid),
                          crosspost_to_default=False)
            if ourNote.notebookGuid:
                log_error('Notebook GUID: ' + str(ourNote.notebookGuid),
                          crosspost_to_default=False)
            log_error("-" * 50 + "\r\n", crosspost_to_default=False)
            if EVERNOTE.API.DEBUG_RAISE_ERRORS:
                raise
            return EvernoteAPIStatus.NotFoundError, None
        except Exception as e:
            print "Unknown Exception:", e
            log_error("-" * 50, crosspost_to_default=False)
            log_error("Unknown Exception:  " + str(e))
            log_error(str(ourNote.tagNames), crosspost_to_default=False)
            log_error(str(ourNote.content), crosspost_to_default=False)
            log_error("-" * 50 + "\r\n", crosspost_to_default=False)
            # return EvernoteAPIStatus.UnhandledError, None
            raise
        # noinspection PyUnboundLocalVariable
        note.content = nBody
        return EvernoteAPIStatus.Success, note