Passed
Branch master (0bcdb7)
by Leon
02:35
created

ck_glados.GLaDOS.main()   A

Complexity

Conditions 4

Size

Total Lines 43
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 27
nop 1
dl 0
loc 43
rs 9.232
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
"""
3
:author @XFY9326
4
cron: 11 6 * * *
5
new Env('GLaDOS');
6
"""
7
8
import traceback
9
from typing import Optional
10
11
import requests
12
13
import utils_tmp
14
from notify_mtr import send
15
from utils import get_data
16
17
18
class GLaDOS:
19
    def __init__(self, check_items: dict):
20
        self.check_items = check_items
21
        self.original_url = "https://glados.rocks"
22
        self.UA = (
23
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
24
            "AppleWebKit/537.36 (KHTML, like Gecko) "
25
            "Chrome/91.0.4472.114 Safari/537.36"
26
        )
27
28
    def api_traffic(self, cookies: str):
29
        traffic_url = f"{self.original_url}/api/user/traffic"
30
        referer_url = f"{self.original_url}/console"
31
32
        with requests.get(
33
            traffic_url,
34
            headers={
35
                "cookie": cookies,
36
                "referer": referer_url,
37
                "origin": self.original_url,
38
                "user-agent": self.UA,
39
                "content-type": "application/json;charset=UTF-8",
40
            },
41
        ) as r:
42
            return r.json()
43
44
    def api_check_in(self, cookies: str) -> dict:
45
        check_in_url = f"{self.original_url}/api/user/checkin"
46
        referer_url = f"{self.original_url}/console/checkin"
47
48
        payload = {"token": "glados.network"}
49
50
        with requests.post(
51
            check_in_url,
52
            headers={
53
                "cookie": cookies,
54
                "referer": referer_url,
55
                "origin": self.original_url,
56
                "user-agent": self.UA,
57
                "content-type": "application/json;charset=UTF-8",
58
            },
59
            json=payload,
60
        ) as r:
61
            return r.json()
62
63
    def api_status(self, cookies: str) -> dict:
64
        status_url = f"{self.original_url}/api/user/status"
65
        referer_url = f"{self.original_url}/console/checkin"
66
67
        with requests.get(
68
            status_url,
69
            headers={
70
                "cookie": cookies,
71
                "referer": referer_url,
72
                "origin": self.original_url,
73
                "user-agent": self.UA,
74
            },
75
        ) as r:
76
            return r.json()
77
78
    @staticmethod
79
    def get_budget(vip_level: Optional[int]) -> dict:
80
        budget_info = utils_tmp.budget_list
81
        user_budgets = [
82
            i
83
            for i in budget_info
84
            if (vip_level is not None and i.get("vip") == vip_level)
85
            or (vip_level is None and "vip" not in i)
86
        ]
87
        if user_budgets:
88
            return user_budgets[0]
89
        raise OSError(f"Budget info not found for this user! VIP: {vip_level}")
90
91
    def main(self):
92
        msg_all = ""
93
        for check_item in self.check_items:
94
            cookie = check_item.get("cookie")
95
            try:
96
                check_in_res = self.api_check_in(cookie)
97
                check_in_msg = check_in_res["message"]
98
                if check_in_msg == "\u6ca1\u6709\u6743\u9650":
99
                    msg = (
100
                        "--------------------\n"
101
                        "Msg: Your cookies are expired!\n"
102
                        "--------------------"
103
                    )
104
                    msg_all += msg
105
                    continue
106
                status_res = self.api_status(cookie)
107
                # print(status_res)
108
                left_days = int(str(status_res["data"]["leftDays"]).split(".")[0])
109
                vip_level = status_res["data"]["vip"]
110
                traffic_res = self.api_traffic(cookie)
111
                used_gb = traffic_res["data"]["today"] / 1024 / 1024 / 1024
112
                user_budget = self.get_budget(vip_level)
113
                total_gb = user_budget["budget"]
114
                plan = user_budget["level"]
115
                msg = (
116
                    "--------------------\n"
117
                    f"Msg: {check_in_msg}\n"
118
                    f"Plan: {plan} Plan\n"
119
                    f"Left days: {left_days}\n"
120
                    f"Usage: {used_gb:.3f} GB\n"
121
                    f"Total: {total_gb} GB\n"
122
                    "--------------------"
123
                )
124
            except Exception:
125
                msg = (
126
                    "--------------------\n"
127
                    "Msg: Check in error!\n"
128
                    "Error:\n"
129
                    f"{traceback.format_exc()}\n"
130
                    "--------------------"
131
                )
132
            msg_all += msg + "\n\n"
133
        return msg_all
134
135
136
if __name__ == "__main__":
137
    _data = get_data()
138
    _check_items = _data.get("GLADOS", [])
139
    result = GLaDOS(check_items=_check_items).main()
140
    send("GLaDOS", result)
141