示例#1
0
    def see_later(self, later_at=60, hide_in='YoUPS see_later'):
        if not isinstance(later_at, datetime) and not isinstance(later_at, (int, long, float)):
            raise TypeError("see_later(): later_at " + later_at + " is not number or datetime")
        
        if isinstance(later_at, datetime) and (later_at.tzinfo is None or later_at.tzinfo.utcoffset(later_at) is None):
            later_at = tz('US/Eastern').localize(later_at)
            later_at = timezone.localtime(later_at)
            logger.info(later_at)

        elif isinstance(later_at, (int, long, float)):
            later_at = timezone.now().replace(microsecond=0) + timedelta(seconds=later_at*60)
            
        current_folder = self._schema.folder_schema.name
        if self._schema.imap_account.is_gmail and current_folder == "INBOX":
            current_folder = 'inbox'
            
        if not self.is_simulate:
            self.move(hide_in)

            import random

            er = EmailRule(uid=random.randint(1, 100000), name='see later', type='see-later', code='imap.select_folder("%s")\nmsg=imap.search(["HEADER", "Message-ID", "%s"])\nif msg:\n    imap.move(msg, "%s")' % (hide_in, self._message_id, current_folder))
            er.save()

            t = TaskManager(email_rule=er, date=later_at, imap_account=self._schema.imap_account)
            t.save()
            logger.critical("here %s" % hide_in)

        print("see_later(): Hide the message until %s at %s" % (later_at, hide_in))
示例#2
0
文件: message.py 项目: haystack/YouPS
    def see_later(self, later_at=60, hide_in='YouPS see later'):
        """Hide a message to a folder and move it back to a original folder

        Args:
            later_at (int): when to move this message back to inbox (in minutes)
            hide_in (string): a name of folder to hide this message temporarily
        """
        if not isinstance(later_at, datetime) and not isinstance(later_at, (int, long, float)):
            raise TypeError("see_later(): later_at " +
                            later_at + " is not number or datetime")

        if isinstance(later_at, datetime) and (later_at.tzinfo is None or later_at.tzinfo.utcoffset(later_at) is None):
            later_at = tz('US/Eastern').localize(later_at)
            later_at = timezone.localtime(later_at)
            logger.info(later_at)

        elif isinstance(later_at, (int, long, float)):
            later_at = timezone.now().replace(microsecond=0) + \
                timedelta(seconds=later_at*60)

        current_folder = self._schema.folder.name
        if self._schema.imap_account.is_gmail and current_folder == "INBOX":
            current_folder = 'inbox'

        if not self._is_simulate:
            self.move(hide_in)

            # find message schema (at folder hide_in) of base message then move back to original message schema 
            code= {"base_message_id": self._schema.base_message.id,
                "hide_in": hide_in,
                "current_folder": current_folder}
            
            er = EmailRule(name='see later', type='see-later', code=json.dumps(code))
            er.save()

            
            
            t = TaskManager(email_rule=er, date=later_at,
                            imap_account=self._schema.imap_account)
            t.save()
            logger.critical("here %s" % hide_in)

        print("see_later(): Hide the message until %s at %s" %
              (later_at, hide_in))
示例#3
0
def create_new_editor(imap_account, rule_type, mode_id):
    editors = []

    try:
        new_er = EmailRule(type=rule_type,
                           mode=MailbotMode.objects.get(id=mode_id),
                           code=get_base_code(rule_type))
    except MailbotMode.DoesNotExist:
        new_mm = MailbotMode(imap_account=imap_account)
        new_mm.save()

        new_er = EmailRule(type=rule_type,
                           mode=new_mm,
                           code=get_base_code(rule_type))
    new_er.save()

    user_inbox = FolderSchema.objects.get(imap_account=imap_account,
                                          name__iexact="inbox")
    new_er.folders.add(user_inbox)

    test_folder = FolderSchema.objects.filter(imap_account=imap_account,
                                              name="_YouPS exercise")
    if test_folder.exists():
        new_er.folders.add(test_folder[0])

    logger.info(new_er.folders.exists())
    folders = FolderSchema.objects.filter(imap_account=imap_account)
    c = {'rule': new_er, 'folders': folders}
    # logger.info('youps/%s.html' % rule_type.replace("-", "_"))
    template = loader.get_template('youps/components/%s.html' %
                                   rule_type.replace("-", "_"))

    e = {'template': template.render(Context(c))}

    editors.append(e)

    return editors
示例#4
0
def run_mailbot(user,
                email,
                current_mode_id,
                modes,
                is_test,
                run_request,
                push=True):
    """This function is called everytime users hit "run", "stop" or "save" their scripts.

        Args:
            user (Model.UserProfile)
            email (string): user's email address
            current_mode_id (integer): ID of currently selected/running mode
            modes (list): a list of dicts that each element is information about each user's mode
            is_test (boolean): if is_test is True, then it just simulates the user's script and prints out log but not actually execute it.  
            run_request (boolean): if False, set the current_mode to None so the event is not fired at interpret()
    """
    res = {'status': False, 'imap_error': False, 'imap_log': ""}
    logger = logging.getLogger('youps')  # type: logging.Logger

    # this log is going to stdout but not going to the logging file
    # why are django settings not being picked up
    logger.info("user %s has run, stop, or saved" % email)

    imap = None

    try:
        imapAccount = ImapAccount.objects.get(email=email)
        auth_res = authenticate(imapAccount)
        if not auth_res['status']:
            raise ValueError(
                'Something went wrong during authentication. Refresh and try again!'
            )

        imap = auth_res['imap']  # noqa: F841 ignore unused

        imapAccount.is_test = is_test
        imapAccount.is_running = run_request

        # TODO these don't work anymore
        # uid = fetch_latest_email_id(imapAccount, imap)
        # imapAccount.newest_msg_id = uid

        # remove all user's tasks of this user to keep tasks up-to-date

        for mode_index, mode in modes.iteritems():
            mode_id = mode['id']
            mode_name = mode['name'].encode('utf-8')

            mailbotMode = MailbotMode.objects.filter(uid=mode_id,
                                                     imap_account=imapAccount)
            if not mailbotMode.exists():
                mailbotMode = MailbotMode(uid=mode_id,
                                          name=mode_name,
                                          imap_account=imapAccount)
                mailbotMode.save()

            else:
                mailbotMode = mailbotMode[0]

            # Remove old editors to re-save it
            # TODO  dont remove it
            er = EmailRule.objects.filter(mode=mailbotMode)
            logger.debug("deleting er editor run request")
            er.delete()

            for value in mode['editors']:
                uid = value['uid']
                name = value['name'].encode('utf-8')
                code = value['code'].encode('utf-8')
                folders = value['folders']
                logger.info("saving editor %s run request" % uid)
                print mode_name
                print code
                print folders

                er = EmailRule(uid=uid,
                               name=name,
                               mode=mailbotMode,
                               type=value['type'],
                               code=code)
                er.save()

                logger.info("user %s test run " % imapAccount.email)

                # res = interpret(MailBox(imapAccount, imap), None, True, {'code' : code})
                # logger.critical(res["appended_log"])

                # # Save selected folder for the mode
                for f in folders:
                    folder = FolderSchema.objects.get(imap_account=imapAccount,
                                                      name=f)
                    logger.info("saving folder to the editor %s run request" %
                                folder.name)
                    er.folders.add(folder)

                er.save()

        if run_request:
            imapAccount.current_mode = MailbotMode.objects.filter(
                uid=current_mode_id, imap_account=imapAccount)[0]

            # if the code execute well without any bug, then save the code to DB
            if not res['imap_error']:
                pass
        else:
            imapAccount.current_mode = None

        imapAccount.save()

        # res['imap_log'] = ("[TEST MODE] Your rule is successfully installed. It won't take actual action but simulate your rule. %s \n" + res['imap_log']) if is_test else ("Your rule is successfully installed. \n" + res['imap_log'])
        #         now = datetime.now()
        #         now_format = now.strftime("%m/%d/%Y %H:%M:%S") + " "
        #         res['imap_log'] = now_format + res['imap_log']
        #     else:
        #         imapAccount.is_running = False
        #         imapAccount.save()
        # else:

        #     res['imap_log'] = "Your mailbot stops running"

        res['status'] = True

    except IMAPClient.Error, e:
        logger.exception("failed while doing a user code run")
        res['code'] = e
示例#5
0
文件: youps.py 项目: haystack/YouPS
def run_mailbot(user,
                email,
                current_mode_id,
                modes,
                is_test,
                run_request,
                push=True):
    """This function is called everytime users hit "run", "stop" or "save" their scripts.

        Args:
            user (Model.UserProfile)
            email (string): user's email address
            current_mode_id (integer): ID of currently selected/running mode
            modes (list): a list of dicts that each element is information about each user's mode
            is_test (boolean): if is_test is True, then it just simulates the user's script and prints out log but not actually execute it.  
            run_request (boolean): if False, set the current_mode to None so the event is not fired at interpret()
    """
    res = {'status': False, 'imap_error': False, 'imap_log': ""}
    logger = logging.getLogger('youps')  # type: logging.Logger

    # this log is going to stdout but not going to the logging file
    # why are django settings not being picked up
    logger.info("user %s has run, stop, or saved" % email)

    imap = None

    try:
        imapAccount = ImapAccount.objects.get(email=email)
        auth_res = authenticate(imapAccount)
        if not auth_res['status']:
            raise ValueError(
                'Something went wrong during authentication. Refresh and try again!'
            )

        imap = auth_res['imap']  # noqa: F841 ignore unused

        imapAccount.is_test = is_test
        turn_on_youps(imapAccount, run_request, "By user's request")

        # TODO these don't work anymore
        # uid = fetch_latest_email_id(imapAccount, imap)'
        # imapAccount.newest_msg_id = uid

        # remove all user's tasks of this user to keep tasks up-to-date
        # old_mailbotMode = MailbotMode.objects.filter(imap_account=imapAccount)
        # old_mailbotMode.delete()

        for mode_index, mode in modes.iteritems():
            mode_name = mode['name'].encode('utf-8')
            mode_name = mode_name.split("<br>")[0] if mode_name else "mode"
            logger.info(mode_name)

            mailbotMode = MailbotMode.objects.filter(id=mode['id'],
                                                     imap_account=imapAccount)
            if mailbotMode.exists():
                mailbotMode = mailbotMode[0]
                mailbotMode.name = mode_name
                mailbotMode.save()
            else:
                mailbotMode = MailbotMode(name=mode_name,
                                          imap_account=imapAccount)
                mailbotMode.save()

            # Remove old editors to re-save it
            # TODO  dont remove it
            er = EmailRule.objects.filter(mode=mailbotMode)
            logger.debug("deleting er editor run request")
            args = EmailRule_Args.objects.filter(rule=er)
            args.delete()
            er.delete()

            for value in mode['editors']:
                name = value['name'].encode('utf-8')
                code = value['code'].encode('utf-8')
                folders = value['folders']
                logger.info(value)

                er = EmailRule(name=name,
                               mode=mailbotMode,
                               type=value['type'],
                               code=code)
                er.save()

                # Save selected folder for the mode
                for f in folders:
                    folder = FolderSchema.objects.get(imap_account=imapAccount,
                                                      name=f)
                    logger.info("saving folder to the editor %s run request" %
                                folder.name)
                    er.folders.add(folder)

                er.save()

                # Save shortcut email args
                if value['type'] == "shortcut":
                    for arg in value['args']:
                        logger.info(arg)

                        new_arg = EmailRule_Args(type=arg['type'], rule=er)
                        if arg['name']:
                            new_arg.name = arg['name']
                        new_arg.save()

            logger.info(
                EmailRule.objects.filter(mode=mailbotMode).values(
                    'name', 'id'))

        if run_request:
            imapAccount.current_mode = MailbotMode.objects.get(
                id=current_mode_id, imap_account=imapAccount)

            # if the code execute well without any bug, then save the code to DB
            if not res['imap_error']:
                pass
        else:
            imapAccount.current_mode = None

        imapAccount.save()

        # res['imap_log'] = ("[TEST MODE] Your rule is successfully installed. It won't take actual action but simulate your rule. %s \n" + res['imap_log']) if is_test else ("Your rule is successfully installed. \n" + res['imap_log'])
        #         now = datetime.now()
        #         now_format = now.strftime("%m/%d/%Y %H:%M:%S") + " "
        #         res['imap_log'] = now_format + res['imap_log']
        #     else:
        #         imapAccount.is_running = False
        #         imapAccount.save()
        # else:

        #     res['imap_log'] = "Your mailbot stops running"

        res['status'] = True

    except IMAPClient.Error as e:
        logger.exception("failed while doing a user code run")
        res['code'] = e
    except ImapAccount.DoesNotExist:
        logger.exception("failed while doing a user code run")
        res['code'] = "Not logged into IMAP"
    except FolderSchema.DoesNotExist:
        logger.exception("failed while doing a user code run")
        logger.debug("Folder is not found, but it should exist!")
    except MailbotMode.DoesNotExist:
        logger.exception("No current mode exist")
        res['code'] = "Currently no mode is selected. Select one of your mode to execute your YouPS."
    except Exception as e:
        # TODO add exception
        logger.exception("failed while doing a user code run")
        print(traceback.format_exc())
        res['code'] = msg_code['UNKNOWN_ERROR']
    finally:
        imap.logout()

    logging.debug(res)
    return res