Beispiel #1
0
 def __init__(self, params):
     assert isinstance(params, dict), 'params must be of type dict'
     # set all known parameters
     if 'service' in params:
         self.service = params['service']
     else:
         exitWithError('missing parameter service')
     if 'user_id' in params:
         self.user_id = params['user_id']
     else:
         exitWithError('missing parameter user_id')
     if 'link_keys' in params:
         self.link_keys = params['link_keys']
     else:
         exitWithError('missing parameter link_keys')
     if 'notification_emails' in params:
         self.notification_emails = params['notification_emails']
     else:
         exitWithError('missing parameter notification_emails')
     if 'user_email' in params:
         self.user_email = params['user_email']
     else:
         exitWithError('missing parameter user_email')
     # set up inbox filters and labels and set their ids
     self.inbox_manager = InboxManager(self.service, self.user_id)
     ids = self.inbox_manager.initInbox()
     self.label_ids = ids['labels']
     self.filter_id = ids['filter']
Beispiel #2
0
    def initLabels(self):
        """Check if the inbox has the necessary labels, if so return the corresponding label ids.
        If not, create the labels, and return the created ids.

        @return dictionary with keys as label names and values as label ids
        """
        try:
            response = self.service.users().labels().list(userId=self.user_id).execute()
        except Exception as error:
            exitWithError(error)

        labels = response['labels']
        labels_dict = {
            'unprocessed': None,
            'processed': None
        }

        for label in labels:
            if label['name'] == self.needed_labels['unprocessed']:
                labels_dict['unprocessed'] = label['id']
            elif label['name'] == self.needed_labels['processed']:
                labels_dict['processed'] = label['id']

        if labels_dict['unprocessed'] is None:
            unprocessed_id = self._createLabel(self.needed_labels['unprocessed'])
            labels_dict['unprocessed'] = unprocessed_id

        if labels_dict['processed'] is None:
            processed_id = self._createLabel(self.needed_labels['processed'])
            labels_dict['processed'] = processed_id

        return labels_dict
Beispiel #3
0
    def _createLabel(self, label_name):
        """Create a label with the name corresponding to label_name.

        @param label_name name for the new label
        @return id of newly created label
        """
        label_obj = {
            'messageListVisibility': 'show',
            'name': label_name,
            'labelListVisibility': 'labelShow'
        }

        try:
            created_label = self.service.users().labels().create(userId=self.user_id, body=label_obj).execute()
        except Exception as error:
            exitWithError(error)

        print('{} Created label with name {}, and id {}'.format(getTime(), created_label['name'], created_label['id']))
        return created_label['id']
Beispiel #4
0
    def initFilter(self, label_id):
        """Check if the inbox has a filter that sends emails from haro_email to the corresponding
        label. If the filter is not set up, create one or modify an existing one.

        @return filter id for corresponding filter
        """
        try:
            response = self.service.users().settings().filters().list(userId=self.user_id).execute()
        except Exception as error:
            exitWithError(error)

        filters = response['filter']

        for filter_obj in filters:
            if filter_obj['criteria']['from'] == self.haro_email:
                if not label_id in filter_obj['action']['addLabelIds']:
                    filter_obj['action']['addLabelIds'].append(label_id)
                return filter_obj['id']

        return self._createFilter(label_id)
Beispiel #5
0
    def _createFilter(self, label_id):
        """Create a filter that filters emails from haro_email into label corresponding to
        label_id. 

        @param label_id id of label to filter messages into
        @return id of newly created filter
        """
        filter_obj = {
            'id': 'haro_filter',
            'criteria': {
                'from': self.haro_email,
            },
            'action': {
                'addLabelIds': label_id
            }
        }

        try:
            created_filter = self.service.users().settings().filters().create(userId=self.user_id, body=filter_obj).execute()
        except Exception as error:
            exitWithError(error)

        return created_filter['id']
Beispiel #6
0
def performRequest(device, options):
    '''
    Performs a request on the given device using the specified options.

    :param device: A device to perform the request on
    :type device: tadek.connection.device.Device
    :param options: Options representing the request
    :type params: dictionary
    '''
    log.debug("Perform a request on '%s' device using options: %s"
               % (device, options))
    path = accessible.Path(*options.pop("path").split('/')[1:])
    device.connect()
    try:
        if "action" in options:
            status = device.doAccessible(path, options["action"])
        elif "set-text" in options:
            text = options["set-text"]
            status = device.setAccessible(path, text=text)
        elif "set-text-file" in options:
            fn = options["set-text-file"]
            if not os.path.isfile(fn):
                exitWithError("There is no such file: %s" % fn)
            fd = None
            try:
                fd = open(fn)
                text = fd.read()
            finally:
                if fd:
                    fd.close()
            status = device.setAccessible(path, text=text)
        elif "set-value" in options:
            value = float(options["set-value"])
            status = device.setAccessible(path, value=value)
        elif "mouse-click" in options:
            x, y = options["mouse-click"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button, "CLICK")
        elif "mouse-double-click" in options:
            x, y = options["mouse-double-click"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y),
                                       button, "DOUBLE_CLICK")
        elif "mouse-press" in options:
            x, y = options["mouse-press"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button, "PRESS")
        elif "mouse-release" in options:
            x, y = options["mouse-release"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button, "RELEASE")
        elif "mouse-absolute-motion" in options:
            x, y = options["mouse-absolute-motion"]
            status = device.mouseEvent(path, int(x), int(y),
                                       '', "ABSOLUTE_MOTION")
        elif "mouse-relative-motion" in options:
            x, y = options["mouse-relative-motion"]
            status = device.mouseEvent(path, int(x), int(y),
                                       '', "RELATIVE_MOTION")
        elif "key" in options:
            key = options["key"].upper()
            if key in constants.KEY_SYMS:
                key = constants.KEY_SYMS[key]
            elif len(key) == 1:
                key = ord(key)
            elif key.startswith("0X"):
                key = int(key, 16)
            else:
                key = int(key)
            if "modifiers" in options:
                modifiers = [constants.KEY_CODES[mod]
                                    for mod in options["modifiers"]]
            else:
                modifiers = []
            status = device.keyboardEvent(path, key, modifiers)
        elif "dump" in options or "dump-all" in options:
            all = False
            if "dump" in options:
                depth = int(options["dump"])
            else:
                depth = -1
            if "output" in options:
                fn = options["output"]
                all = True
            obj = device.getAccessible(path, depth, all=all)
            if obj is None:
                exitWithStatus("There is no such path: %s" % path, 1)
            if all:
                printSeparator()
                utils.saveXml(obj.marshal(), fn)
                exitWithStatus("Dump saved to file: %s" % fn)
            else:
                printAccessibleTree(obj)
                exitWithStatus()
        else:
            for name in (["all"] + [attr[0] for attr in _ATTRS_EXTRA]):
                if name in options:
                    break
            else:
                exitWithError("Invalid request options: %s" % options)
            obj = device.getAccessible(path, 0, **{name: True})
            if obj is None:
                exitWithStatus("There is no such path: %s" % path, 1)
            printAccessibleDetails(obj, name)
            exitWithStatus()
    finally:
        if device.isConnected():
            device.disconnect()
    printSeparator()
    if status:
        exitWithStatus("SUCCESS")
    else:
        exitWithStatus("FAILURE", 1)
Beispiel #7
0
def performRequest(device, options):
    '''
    Performs a request on the given device using the specified options.

    :param device: A device to perform the request on
    :type device: tadek.connection.device.Device
    :param options: Options representing the request
    :type params: dictionary
    '''
    log.debug("Perform a request on '%s' device using options: %s" %
              (device, options))
    path = accessible.Path(*options.pop("path").split('/')[1:])
    device.connect()
    try:
        if "action" in options:
            status = device.doAccessible(path, options["action"])
        elif "set-text" in options:
            text = options["set-text"]
            status = device.setAccessible(path, text=text)
        elif "set-text-file" in options:
            fn = options["set-text-file"]
            if not os.path.isfile(fn):
                exitWithError("There is no such file: %s" % fn)
            fd = None
            try:
                fd = open(fn)
                text = fd.read()
            finally:
                if fd:
                    fd.close()
            status = device.setAccessible(path, text=text)
        elif "set-value" in options:
            value = float(options["set-value"])
            status = device.setAccessible(path, value=value)
        elif "mouse-click" in options:
            x, y = options["mouse-click"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button, "CLICK")
        elif "mouse-double-click" in options:
            x, y = options["mouse-double-click"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button,
                                       "DOUBLE_CLICK")
        elif "mouse-press" in options:
            x, y = options["mouse-press"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button, "PRESS")
        elif "mouse-release" in options:
            x, y = options["mouse-release"]
            button = options["button"]
            status = device.mouseEvent(path, int(x), int(y), button, "RELEASE")
        elif "mouse-absolute-motion" in options:
            x, y = options["mouse-absolute-motion"]
            status = device.mouseEvent(path, int(x), int(y), '',
                                       "ABSOLUTE_MOTION")
        elif "mouse-relative-motion" in options:
            x, y = options["mouse-relative-motion"]
            status = device.mouseEvent(path, int(x), int(y), '',
                                       "RELATIVE_MOTION")
        elif "key" in options:
            key = options["key"].upper()
            if key in constants.KEY_SYMS:
                key = constants.KEY_SYMS[key]
            elif len(key) == 1:
                key = ord(key)
            elif key.startswith("0X"):
                key = int(key, 16)
            else:
                key = int(key)
            if "modifiers" in options:
                modifiers = [
                    constants.KEY_CODES[mod] for mod in options["modifiers"]
                ]
            else:
                modifiers = []
            status = device.keyboardEvent(path, key, modifiers)
        elif "dump" in options or "dump-all" in options:
            all = False
            if "dump" in options:
                depth = int(options["dump"])
            else:
                depth = -1
            if "output" in options:
                fn = options["output"]
                all = True
            obj = device.getAccessible(path, depth, all=all)
            if obj is None:
                exitWithStatus("There is no such path: %s" % path, 1)
            if all:
                printSeparator()
                utils.saveXml(obj.marshal(), fn)
                exitWithStatus("Dump saved to file: %s" % fn)
            else:
                printAccessibleTree(obj)
                exitWithStatus()
        else:
            for name in (["all"] + [attr[0] for attr in _ATTRS_EXTRA]):
                if name in options:
                    break
            else:
                exitWithError("Invalid request options: %s" % options)
            obj = device.getAccessible(path, 0, **{name: True})
            if obj is None:
                exitWithStatus("There is no such path: %s" % path, 1)
            printAccessibleDetails(obj, name)
            exitWithStatus()
    finally:
        if device.isConnected():
            device.disconnect()
    printSeparator()
    if status:
        exitWithStatus("SUCCESS")
    else:
        exitWithStatus("FAILURE", 1)