Exemplo n.º 1
0
    def post(self, taskid):
        self.evil(+2)

        user = self.current_user
        task = self.check_permission(self.db.task.get(taskid, fields=('id', 'tplid', 'userid', 'init_env',
            'env', 'session', 'last_success', 'last_failed', 'success_count',
            'failed_count', 'last_failed_count', 'next', 'disabled', 'ontime', 'ontimeflg')), 'w')

        tpl = self.check_permission(self.db.tpl.get(task['tplid'], fields=('id', 'userid', 'sitename',
            'siteurl', 'tpl', 'interval', 'last_success')))

        fetch_tpl = self.db.user.decrypt(
                0 if not tpl['userid'] else task['userid'], tpl['tpl'])
        env = dict(
                variables = self.db.user.decrypt(task['userid'], task['init_env']),
                session = [],
                )
        
        notice = self.db.user.get(task['userid'], fields=('skey', 'barkurl', 'noticeflg'))

        try:
            new_env = yield self.fetcher.do_fetch(fetch_tpl, env)
        except Exception as e:
            if (notice['noticeflg'] & 0x4 != 0):
                pushno2b = send2phone.send2phone(barkurl=notice['barkurl'])
                pushno2s = send2phone.send2phone(skey=notice['skey'])
                t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
                title = u"签到任务 {0} 手动运行失败".format(tpl['sitename'])
                pushno2b.send2bark(title, u"{0} 请排查原因".format(t, e))
                pushno2s.send2s(title, u"{0} 日志:{1}".format(t, e))
                
            self.db.tasklog.add(task['id'], success=False, msg=unicode(e))
            self.finish('<h1 class="alert alert-danger text-center">签到失败</h1><div class="well">%s</div>' % e)
            return

        self.db.tasklog.add(task['id'], success=True, msg=new_env['variables'].get('__log__'))
        if (task["ontimeflg"] == 1):
            nextTime = calNextTimestamp(task["ontime"], todayflg=False)
        else:
            nextTime = time.time() + (tpl['interval'] if tpl['interval'] else 24 * 60 * 60)
            
        self.db.task.mod(task['id'],
                disabled = False,
                last_success = time.time(),
                last_failed_count = 0,
                success_count = task['success_count'] + 1,
                mtime = time.time(),
                next = nextTime)
        
        if (notice['noticeflg'] & 0x8 != 0):
            pushno2b = send2phone.send2phone(barkurl=notice['barkurl'])
            pushno2s = send2phone.send2phone(skey=notice['skey'])
            t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
            title = u"签到任务 {0} 手动运行成功".format(tpl['sitename'])
            pushno2b.send2bark(title, u"{0} 成功".format(t))
            pushno2s.send2s(title, u"{0} 成功".format(t))
        
        self.db.tpl.incr_success(tpl['id'])
        self.finish('<h1 class="alert alert-success text-center">签到成功</h1>')
        return
Exemplo n.º 2
0
    def post(self, userid):
        if ("testschan" in self.request.body_arguments):
            try:
                if (self.request.body_arguments["skey"][0] != ""):
                    skey = self.request.body_arguments["skey"][0]
                    push = send2phone.send2phone(skey=skey)
                    t = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
                    push.send2s(u"正在测试S酱", u"{t} 发送测试".format(t=t))
                else:
                    raise Exception(u"skey")
            except Exception as e:
                self.render('tpl_run_failed.html', log=e)
                return

            self.render('tpl_run_success.html', log=u"测试成功,请检查是否受到推送")
            return

        if ("send" in self.request.body_arguments):
            try:
                if (self.request.body_arguments["skey"][0] != ""):
                    self.db.user.mod(
                        userid, skey=self.request.body_arguments["skey"][0])
                else:
                    raise Exception(u"注册失败")
            except Exception as e:
                self.render('tpl_run_failed.html', log=e)
                return
            self.render('tpl_run_success.html', log=u"注册成功")
            return

        self.redirect('/my/')
Exemplo n.º 3
0
    def post(self, userid):
        env = json.loads(self.request.body_arguments['env'][0])
        token = env["wxpusher_token"]
        uid = env["wxpusher_uid"]
        skey = env["skey"]
        barkurl = env["barkurl"]
        log = ""
        if ("reg" == self.request.body_arguments['func'][0]):
            try:
                if (token != "") and (uid != ""):
                    temp = token + ";" + uid
                    self.db.user.mod(userid, wxpusher=temp)
                    if (self.db.user.get(
                            userid, fields=("wxpusher"))["wxpusher"] == temp):
                        log = u"注册 wxpusher 成功\r\n"
                    else:
                        log = u"注册 wxpusher 失败\r\n"
                else:
                    log = u"wxpusher 未填写完整\r\n"

                if (skey != ""):
                    self.db.user.mod(userid, skey=skey)
                    if (self.db.user.get(userid,
                                         fields=("skey"))["skey"] == skey):
                        log = log + u"注册 S酱 成功\r\n"
                    else:
                        log = log + u"注册 S酱 失败\r\n"
                else:
                    log = log + u"skey 未填写完整\r\n"

                if (barkurl != ""):
                    self.db.user.mod(userid, barkurl=barkurl)
                    if (self.db.user.get(
                            userid, fields=("barkurl"))["barkurl"] == barkurl):
                        log = log + u"注册 Bark 成功\r\n"
                    else:
                        log = log + u"注册 Bark 失败\r\n"
                else:
                    log = log + u"Bark 未填写完整\r\n"

            except Exception as e:
                self.render('tpl_run_failed.html', log=e)
                return

            self.render('tpl_run_success.html', log=log)
            return

        else:
            try:
                t = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')

                if (token != "") and (uid != ""):
                    push = send2phone.send2phone(wxpusher_token=token,
                                                 wxpusher_uid=uid)
                    push.send2wxpusher(u"{t} 发送测试".format(t=t))
                    log = u"wxpusher 已推送\r\n"
                else:
                    log = u"wxpusher 未填写完整\r\n"

                if (skey != ""):
                    push = send2phone.send2phone(skey=skey)
                    push.send2s(u"正在测试S酱", u"{t} 发送测试".format(t=t))
                    log = log + u"S酱 已推送\r\n"
                else:
                    log = log + u"skey 未填写完整\r\n"

                if (barkurl != ""):
                    push = send2phone.send2phone(barkurl=barkurl)
                    push.send2bark(u"正在测试Bark", u"{t} 发送测试".format(t=t))
                    log = log + u"Bark 已推送\r\n"
                else:
                    log = log + u"Bark 未填写完整\r\n"

            except Exception as e:
                self.render('tpl_run_failed.html', log=e)
                return

            self.render('tpl_run_success.html', log=log)
            return
Exemplo n.º 4
0
    def do(self, task):
        task['note'] = self.db.task.get(task['id'], fields=('note'))['note']
        user = self.db.user.get(task['userid'],
                                fields=('id', 'email', 'email_verified',
                                        'nickname'))
        tpl = self.db.tpl.get(task['tplid'],
                              fields=('id', 'userid', 'sitename', 'siteurl',
                                      'tpl', 'interval', 'last_success'))
        ontime = self.db.task.get(task['id'],
                                  fields=('ontime', 'ontimeflg', 'pushsw',
                                          'newontime'))
        newontime = json.loads(ontime["newontime"])
        pushsw = json.loads(ontime['pushsw'])
        notice = self.db.user.get(task['userid'],
                                  fields=('skey', 'barkurl', 'noticeflg',
                                          'wxpusher'))
        temp = notice['wxpusher'].split(";")
        wxpusher_token = temp[0] if (len(temp) >= 2) else ""
        wxpusher_uid = temp[1] if (len(temp) >= 2) else ""
        pushno2b = send2phone.send2phone(barkurl=notice['barkurl'])
        pushno2s = send2phone.send2phone(skey=notice['skey'])
        pushno2w = send2phone.send2phone(wxpusher_token=wxpusher_token,
                                         wxpusher_uid=wxpusher_uid)
        pusher = {}
        pusher["mailpushersw"] = False if (notice['noticeflg']
                                           & 0x80) == 0 else True
        pusher["barksw"] = False if (notice['noticeflg'] & 0x40) == 0 else True
        pusher["schansw"] = False if (notice['noticeflg']
                                      & 0x20) == 0 else True
        pusher["wxpushersw"] = False if (notice['noticeflg']
                                         & 0x10) == 0 else True
        logtime = json.loads(
            self.db.user.get(task['userid'], fields=('logtime'))['logtime'])
        if 'ErrTolerateCnt' not in logtime: logtime['ErrTolerateCnt'] = 0

        if task['disabled']:
            self.db.tasklog.add(task['id'], False, msg='task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if not user:
            self.db.tasklog.add(task['id'],
                                False,
                                msg='no such user, disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if not tpl:
            self.db.tasklog.add(task['id'],
                                False,
                                msg='tpl missing, task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if tpl['userid'] and tpl['userid'] != user['id']:
            self.db.tasklog.add(task['id'],
                                False,
                                msg='no permission error, task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        start = time.time()
        try:
            fetch_tpl = self.db.user.decrypt(
                0 if not tpl['userid'] else task['userid'], tpl['tpl'])
            env = dict(
                variables=self.db.user.decrypt(task['userid'],
                                               task['init_env']),
                session=[],
            )

            new_env = yield self.fetcher.do_fetch(fetch_tpl, env)

            variables = self.db.user.encrypt(task['userid'],
                                             new_env['variables'])
            session = self.db.user.encrypt(
                task['userid'], new_env['session'].to_json() if hasattr(
                    new_env['session'], 'to_json') else new_env['session'])

            # todo next not mid night
            if (newontime['sw']):
                next = calNextTimestamp(newontime, True)
            else:
                next = time.time() + max(
                    (tpl['interval'] if tpl['interval'] else 24 * 60 * 60),
                    1 * 60)
                if tpl['interval'] is None:
                    next = self.fix_next_time(next)

            # success feedback
            self.db.tasklog.add(task['id'],
                                success=True,
                                msg=new_env['variables'].get('__log__'))
            self.db.task.mod(task['id'],
                             last_success=time.time(),
                             last_failed_count=0,
                             success_count=task['success_count'] + 1,
                             env=variables,
                             session=session,
                             mtime=time.time(),
                             next=next)
            self.db.tpl.incr_success(tpl['id'])
            if (notice['noticeflg'] & 0x2 != 0):
                t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
                title = u"签到任务 {0}-{1} 成功".format(tpl['sitename'],
                                                  task['note'])
                logtemp = new_env['variables'].get('__log__')
                if (notice['noticeflg'] & 0x2 != 0) and (pushsw['pushen']):
                    if (pusher["barksw"]):
                        pushno2b.send2bark(title, u"{0} 运行成功".format(t))
                    if (pusher["schansw"]):
                        pushno2s.send2s(title,
                                        u"{0}  日志:{1}".format(t, logtemp))
                    if (pusher["wxpushersw"]):
                        pushno2w.send2wxpusher(
                            title + u"{0}  日志:{1}".format(t, logtemp))
                    if (pusher["mailpushersw"]):
                        if user['email'] and user['email_verified']:
                            self.task_send_mail(
                                title, u"{0}  日志:{1}".format(t, logtemp),
                                user['email'])

            logger.info('taskid:%d tplid:%d successed! %.4fs', task['id'],
                        task['tplid'],
                        time.time() - start)
            # delete log
            self.ClearLog(task['id'])
        except Exception as e:
            # failed feedback
            next_time_delta = self.failed_count_to_time(
                task['last_failed_count'], tpl['interval'])

            t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
            title = u"签到任务 {0}-{1} 失败".format(tpl['sitename'], task['note'])
            content = u"日志:{log}".format(log=e)
            if next_time_delta:
                next = time.time() + next_time_delta
                t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(next))
                content = content + u"下次运行时间:{0}".format(t)
                # 每次都推送通知
                if (logtime['ErrTolerateCnt'] <= task['last_failed_count']):
                    if (notice['noticeflg'] & 0x1 == 1) and (pushsw['pushen']):
                        if (pusher["barksw"]):
                            pushno2b.send2bark(title, u"请自行排查")
                        if (pusher["schansw"]): pushno2s.send2s(title, content)
                        if (pusher["wxpushersw"]):
                            pushno2w.send2wxpusher(title + u"  " + content)
                        if (pusher["mailpushersw"]):
                            if user['email'] and user['email_verified']:
                                self.task_send_mail(title, content,
                                                    user['email'])
                disabled = False
            else:
                disabled = True
                next = None
                # 任务禁用时发送通知
                if (notice['noticeflg'] & 1 == 1):
                    if (pusher["barksw"]): pushno2b.send2bark(title, u"任务已禁用")
                    if (pusher["schansw"]): pushno2s.send2s(title, u"任务已禁用")
                    if (pusher["wxpushersw"]):
                        pushno2w.send2wxpusher(title + u"任务已禁用")
                    if (pusher["mailpushersw"]):
                        if user['email'] and user['email_verified']:
                            self.task_send_mail(title, u"任务已禁用", user['email'])

            self.db.tasklog.add(task['id'], success=False, msg=unicode(e))
            self.db.task.mod(task['id'],
                             last_failed=time.time(),
                             failed_count=task['failed_count'] + 1,
                             last_failed_count=task['last_failed_count'] + 1,
                             disabled=disabled,
                             mtime=time.time(),
                             next=next)
            self.db.tpl.incr_failed(tpl['id'])

            logger.error('taskid:%d tplid:%d failed! %r %.4fs', task['id'],
                         task['tplid'], e,
                         time.time() - start)
            raise gen.Return(False)
        raise gen.Return(True)
Exemplo n.º 5
0
    def post(self, taskid):
        self.evil(+2)
        start_ts = int(time.time())
        user = self.current_user
        task = self.check_permission(
            self.db.task.get(taskid,
                             fields=('id', 'tplid', 'userid', 'init_env',
                                     'env', 'session', 'last_success',
                                     'last_failed', 'success_count', 'note',
                                     'failed_count', 'last_failed_count',
                                     'next', 'disabled', 'ontime', 'ontimeflg',
                                     'pushsw', 'newontime')), 'w')

        tpl = self.check_permission(
            self.db.tpl.get(task['tplid'],
                            fields=('id', 'userid', 'sitename', 'siteurl',
                                    'tpl', 'interval', 'last_success')))
        t = 0 if not tpl['userid'] else task['userid'], tpl['tpl']
        fetch_tpl = self.db.user.decrypt(
            0 if not tpl['userid'] else task['userid'], tpl['tpl'])
        env = dict(
            variables=self.db.user.decrypt(task['userid'], task['init_env']),
            session=[],
        )

        notice = self.db.user.get(task['userid'],
                                  fields=('skey', 'barkurl', 'noticeflg',
                                          'wxpusher', 'qywx_token'))
        temp = notice['wxpusher'].split(u";")
        wxpusher_token = temp[0] if (len(temp) >= 2) else ""
        wxpusher_uid = temp[1] if (len(temp) >= 2) else ""
        qywx_token = notice['qywx_token']
        pushno2b = send2phone.send2phone(barkurl=notice['barkurl'])
        pushno2s = send2phone.send2phone(skey=notice['skey'])
        pushno2w = send2phone.send2phone(wxpusher_token=wxpusher_token,
                                         wxpusher_uid=wxpusher_uid)
        pusher = {}
        pusher["barksw"] = False if (notice['noticeflg'] & 0x40) == 0 else True
        pusher["schansw"] = False if (notice['noticeflg']
                                      & 0x20) == 0 else True
        pusher["wxpushersw"] = False if (notice['noticeflg']
                                         & 0x10) == 0 else True
        pusher["mailpushersw"] = False if (notice['noticeflg']
                                           & 0x80) == 0 else True
        pusher["cuspushersw"] = False if (notice['noticeflg']
                                          & 0x100) == 0 else True
        pusher["qywxpushersw"] = False if (notice['noticeflg']
                                           & 0x200) == 0 else True
        taskpushsw = json.loads(task['pushsw'])
        newontime = json.loads(task['newontime'])
        diypusher = self.db.user.get(task['userid'],
                                     fields=('diypusher'))['diypusher']
        if (diypusher != ''): diypusher = json.loads(diypusher)
        cuspusher = tools()

        try:
            new_env = yield self.fetcher.do_fetch(fetch_tpl, env)
        except Exception as e:
            if (notice['noticeflg'] & 0x4 != 0) and (taskpushsw['pushen']):
                t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
                title = u"签到任务 {0}-{1} 失败".format(tpl['sitename'],
                                                  task['note'])
                logtmp = u"{0} 日志:{1}".format(t, e)
                if pusher["barksw"]:
                    pushno2b.send2bark(title, logtmp)
                if pusher["schansw"]:
                    pushno2s.send2s(title, logtmp)
                if pusher["wxpushersw"]:
                    pushno2w.send2wxpusher(title + logtmp)
                if (pusher["cuspushersw"]):
                    if (diypusher != ''):
                        cuspusher.cus_pusher_send(diypusher, title, logtmp)
                if (pusher["qywxpushersw"]):
                    cuspusher.qywx_pusher_send(qywx_token, title, logtmp)

            self.db.tasklog.add(task['id'], success=False, msg=unicode(e))
            self.finish(
                '<h1 class="alert alert-danger text-center">签到失败</h1><div class="showbut well autowrap" id="errmsg">%s<button class="btn hljs-button" data-clipboard-target="#errmsg" >复制</button></div>'
                % e)
            return

        self.db.tasklog.add(task['id'],
                            success=True,
                            msg=new_env['variables'].get('__log__'))
        if (newontime["sw"]):
            nextTime = calNextTimestamp(newontime, True, start_ts)
        else:
            nextTime = time.time() + (tpl['interval']
                                      if tpl['interval'] else 24 * 60 * 60)

        self.db.task.mod(task['id'],
                         disabled=False,
                         last_success=time.time(),
                         last_failed_count=0,
                         success_count=task['success_count'] + 1,
                         mtime=time.time(),
                         next=nextTime)

        if (notice['noticeflg'] & 0x8 != 0) and (taskpushsw['pushen']):
            t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
            title = u"签到任务 {0}-{1} 成功".format(tpl['sitename'], task['note'])
            logtmp = u"{0} 成功".format(t)
            if pusher["barksw"]:
                pushno2b.send2bark(title, logtmp)
            if pusher["schansw"]:
                pushno2s.send2s(title, logtmp)
            if pusher["wxpushersw"]:
                pushno2w.send2wxpusher(title + logtmp)
            if (pusher["cuspushersw"]):
                if (diypusher != ''):
                    cuspusher.cus_pusher_send(diypusher, title, logtmp)
            if (pusher["qywxpushersw"]):
                cuspusher.qywx_pusher_send(qywx_token, title, logtmp)

        self.db.tpl.incr_success(tpl['id'])
        self.finish('<h1 class="alert alert-success text-center">签到成功</h1>')
        logDay = int(self.db.site.get(1, fields=('logDay'))['logDay'])
        for log in self.db.tasklog.list(taskid=taskid, fields=('id', 'ctime')):
            if (time.time() - log['ctime']) > (logDay * 24 * 60 * 60):
                self.db.tasklog.delete(log['id'])
        return
Exemplo n.º 6
0
    def do(self, task):
        user = self.db.user.get(task['userid'], fields=('id', 'email', 'email_verified', 'nickname'))
        tpl = self.db.tpl.get(task['tplid'], fields=('id', 'userid', 'sitename', 'siteurl', 'tpl',
            'interval', 'last_success'))
        ontime = self.db.task.get(task['id'], fields=('ontime', 'ontimeflg'))

        if task['disabled']:
            self.db.tasklog.add(task['id'], False, msg='task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if not user:
            self.db.tasklog.add(task['id'], False, msg='no such user, disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if not tpl:
            self.db.tasklog.add(task['id'], False, msg='tpl missing, task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if tpl['userid'] and tpl['userid'] != user['id']:
            self.db.tasklog.add(task['id'], False, msg='no permission error, task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        start = time.time()
        try:
            fetch_tpl = self.db.user.decrypt(0 if not tpl['userid'] else task['userid'], tpl['tpl'])
            env = dict(
                    variables = self.db.user.decrypt(task['userid'], task['init_env']),
                    session = [],
                    )

            new_env = yield self.fetcher.do_fetch(fetch_tpl, env)

            variables = self.db.user.encrypt(task['userid'], new_env['variables'])
            session = self.db.user.encrypt(task['userid'],
                    new_env['session'].to_json() if hasattr(new_env['session'], 'to_json') else new_env['session'])

            # todo next not mid night
            if (ontime['ontimeflg'] == 1):
                temp = ontime['ontime']
                now = datetime.datetime.now()
                ehour = int(temp[0:2])
                emin = int(temp[-2:])

                if(ehour >= now.hour):
                    if (emin > now.minute):
                        eday = now.day
                    else:
                        eday = now.day+1
                else :
                    eday = now.day+1
                tz = pytz.timezone('Asia/Shanghai')
                pre = datetime.datetime(year=now.year, 
                                        month=now.month, 
                                        day=eday, 
                                        hour=ehour, 
                                        minute=emin, 
                                        tzinfo=tz)
                next = int(time.mktime(pre.timetuple()) + pre.microsecond/1e6)
            else:
                next = time.time() + max((tpl['interval'] if tpl['interval'] else 24 * 60 * 60), 1*60)
                if tpl['interval'] is None:
                    next = self.fix_next_time(next)

            # success feedback
            self.db.tasklog.add(task['id'], success=True, msg=new_env['variables'].get('__log__'))
            self.db.task.mod(task['id'],
                    last_success=time.time(),
                    last_failed_count=0,
                    success_count=task['success_count']+1,
                    env=variables,
                    session=session,
                    mtime=time.time(),
                    next=next)
            self.db.tpl.incr_success(tpl['id'])

            logger.info('taskid:%d tplid:%d successed! %.4fs', task['id'], task['tplid'], time.time()-start)
        except Exception as e:
            # failed feedback
            next_time_delta = self.failed_count_to_time(task['last_failed_count'], tpl['interval'])

            if next_time_delta:
                # 每次都推送通知
                pushno = send2phone.send2phone()
                pushno.send2bark("签到任务 {0} 失败".format(tpl['sitename']), "请检查状态")
                pushno.send2s("签到任务 {0} 失败".format(tpl['sitename']), "请检查状态")
                pushno.send2BarkAndWJ("签到任务 {0} 失败".format(tpl['sitename']), "请检查状态")
                disabled = False
                next = time.time() + next_time_delta
            else:
                disabled = True
                next = None
                # 任务禁用时发送通知
                pushno.send2bark("签到任务 {0} 失败".format(tpl['sitename']), "任务已禁用")
                pushno.send2s("签到任务 {0} 失败".format(tpl['sitename']), "任务已禁用")
                pushno.send2BarkAndWJ(u"签到任务 {0} 失败".format(tpl['sitename']), u"任务已禁用")

            self.db.tasklog.add(task['id'], success=False, msg=unicode(e))
            self.db.task.mod(task['id'],
                    last_failed=time.time(),
                    failed_count=task['failed_count']+1,
                    last_failed_count=task['last_failed_count']+1,
                    disabled = disabled,
                    mtime = time.time(),
                    next=next)
            self.db.tpl.incr_failed(tpl['id'])

            if task['success_count'] and task['last_failed_count'] and user['email_verified'] and user['email']:
                    #and self.is_tommorrow(next):
                try:
                    _ = yield utils.send_mail(to=user['email'], subject=u"%s - 签到失败%s" % (
                        tpl['sitename'], u' 已停止' if disabled else u""),
                    text=u"""
您的 %(sitename)s [ %(siteurl)s ] 签到任务,执行 %(cnt)d次 失败。%(disable)s

下一次重试在一天之后,为防止签到中断,给您发送这份邮件。

访问: http://%(domain)s/task/%(taskid)s/log 查看日志。
                    """ % dict(
                        sitename=tpl['sitename'] or u'未命名',
                        siteurl=tpl['siteurl'] or u'',
                        cnt=task['last_failed_count'] + 1,
                        disable=u"因连续多次失败,已停止。" if disabled else u"",
                        domain=config.domain,
                        taskid=task['id'],
                        ), async=True)
                except Exception as e:
                    logging.error('send mail error: %r', e)

            logger.error('taskid:%d tplid:%d failed! %r %.4fs', task['id'], task['tplid'], e, time.time()-start)
            raise gen.Return(False)
        raise gen.Return(True)
Exemplo n.º 7
0
    def do(self, task):
        task['note'] = self.db.task.get(task['id'], fields=('note'))['note']
        user = self.db.user.get(task['userid'], fields=('id', 'email', 'email_verified', 'nickname'))
        tpl = self.db.tpl.get(task['tplid'], fields=('id', 'userid', 'sitename', 'siteurl', 'tpl', 'interval', 'last_success'))
        ontime = self.db.task.get(task['id'], fields=('ontime', 'ontimeflg', 'pushsw', 'newontime'))
        newontime = json.loads(ontime["newontime"])
        pushsw = json.loads(ontime['pushsw'])
        notice = self.db.user.get(task['userid'], fields=('skey', 'barkurl', 'noticeflg', 'wxpusher'))
        temp = notice['wxpusher'].split(";")
        wxpusher_token = temp[0] if (len(temp) >= 2) else ""
        wxpusher_uid = temp[1] if (len(temp) >= 2) else "" 
        pushno2b = send2phone.send2phone(barkurl=notice['barkurl'])
        pushno2s = send2phone.send2phone(skey=notice['skey'])
        pushno2w = send2phone.send2phone(wxpusher_token=wxpusher_token, wxpusher_uid=wxpusher_uid)
        pusher =  {}
        pusher["barksw"] = False if (notice['noticeflg'] & 0x40) == 0 else True 
        pusher["schansw"] = False if (notice['noticeflg'] & 0x20) == 0 else True 
        pusher["wxpushersw"] = False if (notice['noticeflg'] & 0x10) == 0 else True
        logtime = json.loads(self.db.user.get(task['userid'], fields=('logtime'))['logtime'])
        if 'ErrTolerateCnt' not in logtime:logtime['ErrTolerateCnt'] = 0 

        if task['disabled']:
            self.db.tasklog.add(task['id'], False, msg='task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if not user:
            self.db.tasklog.add(task['id'], False, msg='no such user, disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if not tpl:
            self.db.tasklog.add(task['id'], False, msg='tpl missing, task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        if tpl['userid'] and tpl['userid'] != user['id']:
            self.db.tasklog.add(task['id'], False, msg='no permission error, task disabled.')
            self.db.task.mod(task['id'], next=None, disabled=1)
            raise gen.Return(False)

        start = time.time()
        try:
            fetch_tpl = self.db.user.decrypt(0 if not tpl['userid'] else task['userid'], tpl['tpl'])
            env = dict(
                    variables = self.db.user.decrypt(task['userid'], task['init_env']),
                    session = [],
                    )

            new_env = yield self.fetcher.do_fetch(fetch_tpl, env)

            variables = self.db.user.encrypt(task['userid'], new_env['variables'])
            session = self.db.user.encrypt(task['userid'],
                    new_env['session'].to_json() if hasattr(new_env['session'], 'to_json') else new_env['session'])

            # todo next not mid night
            if (newontime['sw']):
                next = calNextTimestamp(newontime, True)
            else:
                next = time.time() + max((tpl['interval'] if tpl['interval'] else 24 * 60 * 60), 1*60)
                if tpl['interval'] is None:
                    next = self.fix_next_time(next)

            # success feedback
            self.db.tasklog.add(task['id'], success=True, msg=new_env['variables'].get('__log__'))
            self.db.task.mod(task['id'],
                    last_success=time.time(),
                    last_failed_count=0,
                    success_count=task['success_count']+1,
                    env=variables,
                    session=session,
                    mtime=time.time(),
                    next=next)
            self.db.tpl.incr_success(tpl['id'])
            if (notice['noticeflg'] & 0x2 != 0):
                t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
                title = u"签到任务 {0}-{1} 成功".format(tpl['sitename'], task['note'])
                logtemp = new_env['variables'].get('__log__')
                if (notice['noticeflg'] & 0x2 != 0) and (pushsw['pushen']):
                    if (pusher["barksw"]):pushno2b.send2bark(title, u"{0} 运行成功".format(t))
                    if (pusher["schansw"]):pushno2s.send2s(title, u"{0}  日志:{1}".format(t, logtemp))
                    if (pusher["wxpushersw"]):pushno2w.send2wxpusher(title+u"{0}  日志:{1}".format(t, logtemp))
            logger.info('taskid:%d tplid:%d successed! %.4fs', task['id'], task['tplid'], time.time()-start)
        except Exception as e:
            # failed feedback
            next_time_delta = self.failed_count_to_time(task['last_failed_count'], tpl['interval'])
                        
            t = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
            title = u"签到任务 {0}-{1} 失败".format(tpl['sitename'], task['note'])
            content = u"日志:{log}".format(log=e)
            if next_time_delta:
                # 每次都推送通知
                if (logtime['ErrTolerateCnt'] <= task['last_failed_count']):
                    if (notice['noticeflg'] & 0x1 == 1) and (pushsw['pushen']):
                        if (pusher["barksw"]):pushno2b.send2bark(title, u"请自行排查")
                        if (pusher["schansw"]):pushno2s.send2s(title, content)
                        if (pusher["wxpushersw"]):pushno2w.send2wxpusher(title+u"  "+content)
                disabled = False
                next = time.time() + next_time_delta
            else:
                disabled = True
                next = None
                # 任务禁用时发送通知
                if (notice['noticeflg'] & 1 == 1):
                    if (pusher["barksw"]):pushno2b.send2bark(title, u"任务已禁用")
                    if (pusher["schansw"]):pushno2s.send2s(title, u"任务已禁用")
                    if (pusher["wxpushersw"]):pushno2w.send2wxpusher(title+u"任务已禁用")

            self.db.tasklog.add(task['id'], success=False, msg=unicode(e))
            self.db.task.mod(task['id'],
                    last_failed=time.time(),
                    failed_count=task['failed_count']+1,
                    last_failed_count=task['last_failed_count']+1,
                    disabled = disabled,
                    mtime = time.time(),
                    next=next)
            self.db.tpl.incr_failed(tpl['id'])

            if task['success_count'] and task['last_failed_count'] and user['email_verified'] and user['email']:
                    #and self.is_tommorrow(next):
                try:
                    _ = yield utils.send_mail(to=user['email'], subject=u"%s - 签到失败%s" % (
                        tpl['sitename'], u' 已停止' if disabled else u""),
                    text=u"""
您的 %(sitename)s [ %(siteurl)s ] 签到任务,执行 %(cnt)d次 失败。%(disable)s

下一次重试在一天之后,为防止签到中断,给您发送这份邮件。

访问: http://%(domain)s/task/%(taskid)s/log 查看日志。
                    """ % dict(
                        sitename=tpl['sitename'] or u'未命名',
                        siteurl=tpl['siteurl'] or u'',
                        cnt=task['last_failed_count'] + 1,
                        disable=u"因连续多次失败,已停止。" if disabled else u"",
                        domain=config.domain,
                        taskid=task['id'],
                        ), async=True)
                except Exception as e:
                    logging.error('send mail error: %r', e)

            logger.error('taskid:%d tplid:%d failed! %r %.4fs', task['id'], task['tplid'], e, time.time()-start)
            raise gen.Return(False)
        raise gen.Return(True)