Passed
Push — master ( c7076b...545fb7 )
by
unknown
02:31
created

api_ran_time   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 14
eloc 41
dl 0
loc 60
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
"""
3
:author @night-raise  from github
4
cron: 0 0 */7 * *
5
new Env('随机定时');
6
"""
7
8
from abc import ABC
9
from random import randrange
10
from typing import Dict, List
11
12
import requests
13
14
from notify_mtr import send
15
from utils import get_data
16
from utils_env import get_env_int
17
18
19
class ClientApi(ABC):
20
    def __init__(self):
21
        self.cid = ""
22
        self.sct = ""
23
        self.url = "http://localhost:5700/"
24
        self.twice = False
25
        self.token = ""
26
        self.cron: List[Dict] = []
27
28
    def init_cron(self):
29
        raise NotImplementedError
30
31
    def shuffle_cron(self):
32
        raise NotImplementedError
33
34
    def run(self):
35
        self.init_cron()
36
        self.shuffle_cron()
37
38
    @staticmethod
39
    def get_ran_min() -> str:
40
        return str(randrange(0, 60))
41
42
    def get_ran_hour(self, is_api: bool = False) -> str:
43
        if is_api:
44
            return str(randrange(7, 9))
45
        if self.twice:
46
            start = randrange(0, 12)
47
            return f"{start},{start + randrange(6, 12)}"
48
49
    def random_time(self, origin_time: str, command: str):
50
        if command.find("rssbot") != -1 or command.find("hax") != -1:
51
            return ClientApi.get_ran_min() + " " + " ".join(origin_time.split(" ")[1:])
52
        if command.find("api") != -1:
53
            return ClientApi.get_ran_min() + " " + \
54
                   self.get_ran_hour(True) + " " + \
55
                   " ".join(origin_time.split(" ")[2:])
56
        return ClientApi.get_ran_min() + " " + \
57
               self.get_ran_hour() + " " + \
58
               " ".join(origin_time.split(" ")[2:])
59
60
61
class QLClient(ClientApi):
62
    def __init__(self, client_info:Dict):
63
        super().__init__()
64
        if not client_info or not (cid := client_info.get("client_id")) or not (
65
                sct := client_info.get("client_secret")):
66
            raise KeyError
67
        else:
68
            self.cid = cid
69
            self.sct = sct
70
        self.url = client_info.get("url", "http://localhost:5700").rstrip("/") + "/"
71
        self.twice = client_info.get("twice", False)
72
        self.token = requests.get(url=self.url + "open/auth/token",
73
                                  params={"client_id": self.cid, "client_secret": self.sct}).json()["data"]["token"]
74
        if not self.token:
75
            raise KeyError
76
77
    def init_cron(self):
78
        self.cron: List[Dict] = list(filter(lambda x: not x.get("isDisabled", 1) and
79
                                                      x.get("command", "").find("Oreomeow_checkinpanel_master") != -1,
80
                                            requests.get(url=self.url + "open/crons",
81
                                                         headers={"Authorization": f"Bearer {self.token}"}).json()[
82
                                                "data"]))
83
84
    def shuffle_cron(self):
85
        for c in self.cron:
86
            data = {
87
                "labels": c.get("labels", None),
88
                "command": c["command"],
89
                "schedule": self.random_time(c["schedule"], c["command"]),
90
                "name": c["name"],
91
                "id": c["id"],
92
            }
93
            requests.put(url=self.url + "open/crons",
94
                         data=data,
95
                         headers={"Authorization": f"Bearer {self.token}"})
96
97
98
99
def get_client():
100
    env_type = get_env_int()
101
    if env_type == 5 or env_type == 6:
102
        check_data = get_data()
103
        return QLClient(check_data.get("RANDOM", [[]])[0])
104
105
try:
106
    get_client().run()
107
    send("随机定时", "处于启动状态的任务定时修改成功!")
108
except KeyError:
109
    send("随机定时", "配置错误,请检查你的配置文件!")
110
except AttributeError:
111
    send("随机定时", "你的系统不支持运行随机定时!")