From 6860b395e8bb5658b78d8187d31429d6cc87327e Mon Sep 17 00:00:00 2001 From: yjqiang <13307130285@fudan.edu.cn> Date: Thu, 6 Sep 2018 20:47:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=AF=E7=94=A8=E6=96=B0=E7=9A=84sleep?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把sleep数据放到list里面,论证之后,只要判定与存取操作之间没空隙即可保证正确性 --- 0.py | 5 ++- states.py | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ task.py | 44 +++++++++++++++++-- user.py | 94 +++++++++++++++------------------------ 4 files changed, 209 insertions(+), 62 deletions(-) create mode 100644 states.py diff --git a/0.py b/0.py index ad07da9..6cfa329 100644 --- a/0.py +++ b/0.py @@ -1,5 +1,5 @@ from config_loader import ConfigLoader -from task import RaffleHandler, Task +from task import RaffleHandler, Task, StateTask import os import sys from user import User @@ -46,6 +46,7 @@ var_super_user = SuperUser(users[0]) raffle = RaffleHandler(users, var_super_user, loop, True) normal_task = Task(users, var_super_user, loop) +state_task = StateTask(users, var_super_user, loop) var_console = bili_console.Biliconsole(users, var_super_user, loop) console_thread = threading.Thread(target=var_console.cmdloop) @@ -56,6 +57,8 @@ raffle.join_raffle(), # normal_task.heartbeat(), danmu_connection.run(), + state_task.run_workstate(), + state_task.run_timestate() # normal_task.run(), # var_console.run() ] diff --git a/states.py b/states.py new file mode 100644 index 0000000..890f417 --- /dev/null +++ b/states.py @@ -0,0 +1,128 @@ +from datetime import datetime +import random +from task import Task +import printer +import asyncio + + +class BaseState(): + black_list = { + 'handle_1_activity_raffle': 2, + 'handle_1_TV_raffle': 2, + 'handle_1_substantial_raffle': 2, + 'handle_1_guard_raffle': 2, + 'open_silver_box': 1, + 'post_watching_history': 2, + 'fetch_heart_gift': 1 + } + + def check_status(self, func, value): + pass + + +# 工作状态类 +class DayState(BaseState): + def check_status(self, func, value): + # print("工作,精神百倍") + return 0, None + + +# 睡眠状态 +class NightState(BaseState): + def check_status(self, func, value): + # print("睡觉了") + now = datetime.now() + if func == 'daily_task': + seconds = (3 - now.hour - 1) * 3600 + (60 - now.minute - 1) * 60 + (60 - now.second) + sleeptime = seconds + random.uniform(0, 30) + return 1, sleeptime + else: + return self.black_list.get(func, 0), None + + +class JailState(BaseState): + def check_status(self, func, value): + # print('因为进入了监狱') + if func == 'daily_task': + return self.black_list.get(value[0], 0), 1800 + else: + return self.black_list.get(func, 0), 1800 + + +class FreeState(BaseState): + def check_status(self, func, value): + # print('因为是个自由人') + return 0, None + + +class UserStates(): + state_night = NightState() + state_day = DayState() + state_jail = JailState() + state_free = FreeState() + + def __init__(self, user_id, user_name): + self.time_state = self.state_day + self.work_state = self.state_free + self.user_id = user_id + self.user_name = user_name + self.delay_tasks = [] + + def clean_delay_tasks(self): + for func, values in self.delay_tasks: + time_delay = random.uniform(0, 30) + Task().call_after(func, time_delay, values, self.user_id) + del self.delay_tasks[:] + + def go_to_bed(self): + # print('{休眠}') + self.time_state = self.state_night + + def wake_up(self): + # print('{起床}') + self.time_state = self.state_day + self.clean_delay_tasks() + + def fall_in_jail(self): + # print('{入狱}') + self.work_state = self.state_jail + + def out_of_jail(self): + # print('{自由}') + self.work_state = self.state_free + self.clean_delay_tasks() + + def printer_with_id(self, list_msg, tag_time=False): + list_msg[0] += f'(用户id:{self.user_id} 用户名:{self.user_name})' + printer.info(list_msg, tag_time) + + def print_state(self): + work_state = '恭喜中奖' if self.work_state == self.state_jail else '未进入小黑屋' + time_state = '白天工作' if self.time_state == self.state_day else '夜晚休眠' + self.printer_with_id([f'{self.delay_tasks}'], True) + return work_state, time_state + + def check_status(self, func, values): + code, sleeptime = self.time_state.check_status(func, values) + if code: + # print(code, sleeptime) + pass + else: + code, sleeptime = (self.work_state.check_status(func, values)) + # print(code, sleeptime) + + # print('+++++++++++++++++++++++') + if code == 1: + self.printer_with_id([f'sleep模式, 推迟执行{func} {values}'], True) + self.delay_tasks.append((func, values)) + return 1 + elif code == 2: + self.printer_with_id([f'drop模式, 不执行{func} {values}'], True) + return 2 + return 0 + + async def handle_logout(self): + if True: + future = asyncio.Future() + self.lists.append(future) + await future diff --git a/task.py b/task.py index f982eca..f784f28 100644 --- a/task.py +++ b/task.py @@ -1,11 +1,11 @@ import time -import datetime import asyncio import random +from datetime import datetime def CurrentTime(): - currenttime = int(time.mktime(datetime.datetime.now().timetuple())) + currenttime = int(time.time()) return currenttime @@ -100,7 +100,8 @@ def init(self): self.call_after('daily_task', 0, ('judge',), time_range=25) self.call_after('daily_task', 0, ('open_silver_box',), time_range=25) self.call_after('daily_task', 0, ('heartbeat',), time_range=25) - + self.call_after('daily_task', 0, ('fetch_heart_gift',), time_range=25) + def excute_async(self, i): print('执行', i) asyncio.ensure_future(self.notify(*i)) @@ -122,5 +123,42 @@ def call_at(self, func, time_expected, tuple_values, id=None, time_range=None): async def call_right_now(self, func, value, id=-1): # print(func, value) return (await self.notify(func, (value,), id)) + + +class StateTask(Messenger): + def wake_up_all(self): + for user in (self._observers): + user.wake_up() + + def release_all(self): + for user in (self._observers): + user.out_of_jail() + + def sleep_all(self): + for user in (self._observers): + user.go_to_bed() + + async def run_workstate(self): + while True: + await asyncio.sleep(4 * 3600) + # await asyncio.sleep(120) + self.release_all() + + async def run_timestate(self): + while True: + sleeptime = 0 + now = datetime.now() + if now.hour * 60 + now.minute < 180: + self.sleep_all() + seconds = (3 - now.hour - 1) * 3600 + (60 - now.minute - 1) * 60 + (60 - now.second) + # 防止时间卡得过死 + sleeptime = seconds + random.uniform(60, 90) + sleeptime = max(0, seconds) + else: + self.wake_up_all() + seconds = (24 - now.hour - 1) * 3600 + (60 - now.minute - 1) * 60 + (60 - now.second) + sleeptime = seconds + random.uniform(60, 90) + await asyncio.sleep(sleeptime) + diff --git a/user.py b/user.py index 020b9fc..daa5230 100644 --- a/user.py +++ b/user.py @@ -15,19 +15,11 @@ from PIL import Image from io import BytesIO import utils -from datetime import datetime +from states import UserStates class User(): - black_list = { - 'handle_1_activity_raffle': 2, - 'handle_1_TV_raffle': 2, - 'handle_1_substantial_raffle': 2, - 'handle_1_guard_raffle': 2, - 'open_silver_box': 1, - 'post_watching_history': 2 - } - + def __init__(self, user_id, dict_user, dict_bili, task_control, high_concurency): if high_concurency: self.webhub = HostWebHub(user_id, dict_user, dict_bili) @@ -37,8 +29,8 @@ def __init__(self, user_id, dict_user, dict_bili, task_control, high_concurency) self.user_id = user_id self.user_name = dict_user['username'] self.user_password = dict_user['password'] - self.is_injail = False self.task_control = task_control + self.state = UserStates(user_id, self.user_name) if not dict_user['cookie']: self.login() else: @@ -48,6 +40,25 @@ def printer_with_id(self, list_msg, tag_time=False): list_msg[0] += f'(用户id:{self.user_id} 用户名:{self.user_name})' printer.info(list_msg, tag_time) + def go_to_bed(self): + self.state.go_to_bed() + + def wake_up(self): + self.state.wake_up() + + def fall_in_jail(self): + self.state.fall_in_jail() + self.printer_with_id([f'抽奖脚本检测{self.user_id}为小黑屋'], True) + + def out_of_jail(self): + self.state.out_of_jail() + + def print_state(self): + return self.state.print_state() + + def check_status(self, func, values): + return self.state.check_status(func, values) + def handle_login_status(self): if not self.check_token(): if not self.refresh_token(): @@ -134,19 +145,16 @@ def login(self): else: print("[{}] 登录失败,错误信息为:{}".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), json_rsp)) return False - - def fall_in_jail(self): - self.is_injail = True - self.printer_with_id([f'抽奖脚本检测{self.user_id}为小黑屋'], True) - + def write_user(self, dict_new): self.webhub.set_status(dict_new) ConfigLoader().write_user(dict_new, self.user_id) async def get_statistic(self): await asyncio.sleep(0) - status = '恭喜中奖' if self.is_injail else '未进入小黑屋' - self.printer_with_id([f'小黑屋状态: {status}'], True) + work_state, time_state = self.print_state() + self.printer_with_id([f'小黑屋状态: {work_state}'], True) + self.printer_with_id([f'工作状态: {time_state}'], True) self.statistics.getlist() self.statistics.getresult() @@ -156,12 +164,14 @@ async def heartbeat(self): self.printer_with_id(['心跳包(5分钟左右间隔)'], True) json_response = await self.webhub.pcpost_heartbeat() # print(json_response) - if not self.is_injail: - json_response = await self.webhub.heart_gift() - if json_response['code'] == 400: - self.fall_in_jail() return 260 # print(json_response) + + async def fetch_heart_gift(self): + json_response = await self.webhub.heart_gift() + if json_response['code'] == 400: + self.fall_in_jail() + return 260 async def open_silver_box(self): while True: @@ -937,43 +947,11 @@ async def judge(self): self.printer_with_id([f'风纪委员会共获取{num_case}件案例,其中有效投票{num_voted}件'], True) return 3600 - - def check_status(self, func, value): - now = datetime.now() - hour_minute = now.hour * 60 + now.minute - # 0点到3点 sleep模式 - if hour_minute < 180: - self.is_injail = False - # self.printer_with_id(['sleep模式'], True) - if func == 'daily_task': - seconds = (3 - now.hour - 1) * 3600 + (60 - now.minute - 1) * 60 + (60 - now.second) - sleeptime = seconds + random.uniform(0, 30) - return 1, sleeptime - else: - return self.black_list.get(func, 0), now - # 1 sleep - # 2 drop - # 0 True - if func == 'daily_task': - func = value[0] - if self.is_injail: - return self.black_list.get(func, 0), 1800 - else: - return 0, None - - async def update(self, func, value): - status, sleeptime = self.check_status(func, value) + + async def update(self, func, values): + status = self.check_status(func, values) if not status: - return await getattr(self, func)(*value) - if status == 1: - self.printer_with_id([f'sleep模式, 推迟执行{func} {value}'], True) - # 防止负数,不过理论上应该不会的 - time_delay = max(0, sleeptime) - Task().call_after(func, time_delay, value, self.user_id) - return None - elif status == 2: - self.printer_with_id([f'drop模式, 不执行{func} {value}'], True) - return None + return await getattr(self, func)(*values) async def daily_task(self, task_name): time_delay = await getattr(self, task_name)()