Ejemplo n.º 1
0
 def __init__(self, city):
     """初始化账号属性"""
     self.city = city
     self.logging = Logger(self.city)
     if "win" in sys.platform:
         headers_path = ".\\conf\\headers"
     else:
         headers_path = "./conf/headers"
     with open(headers_path) as headers_obj:
         cookie_obj = headers_obj.readlines()
         for line in cookie_obj:
             if "Cookie" in line:
                 self.cookie = line.split("Cookie: ")[1].strip()
             if "tk" in line:
                 self.tk = line.split("tk: ")[1].strip()
Ejemplo n.º 2
0
 def __init__(self, city, custom):
     """初始化监听属性"""
     self.city = city
     self.custom = custom
     self.custom_id = {
         "四价": 2,
         "九价": 3,
     }
     self.logging = Logger(self.city)
     self.user_info = Account(self.city).get_account_info()
     self.session = requests.Session()
     self.headers = self.user_info['headers']
     self.linkman_id = self.user_info['linkman_id']
     self.region = Region(self.city)
     self.appointment_notification_status = {}
     self.subscribe_notification_status = {4698: 0, 25752: 0, 6259: 0, 26225: 0, 26226: 0, 4453: 0, }
Ejemplo n.º 3
0
 def __init__(self, city):
     """初始化通知属性"""
     self.city = city
     self.logging = Logger(self.city)
     self.send_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
     self.notification_urls = {
         "test":
         "https://oapi.dingtalk.com/robot/send?access_token"
         "=0354ddbdf68e36be9e931f2555ba4b4bc4c9751af986dd9497206997cdd71968 ",
         "formal-9":
         "https://oapi.dingtalk.com/robot/send?access_token"
         "=649a092161ceda91c94ec436ca32b5439d60af7287447e8d0767952073723b4b ",
         "formal-4":
         "https://oapi.dingtalk.com/robot/send?access_token"
         "=55f4877383250813c2bc9684c977c01eea81f80f9bb92e5f38ce8be05b0cbeac",
         "debug":
         "https://oapi.dingtalk.com/robot/send?access_token"
         "=2fb637568180850691c13455329bf1122de97b284980f15862a95d5c55af961d",
     }
     if "win" in sys.platform:
         self.isTest = True
     else:
         self.isTest = False
Ejemplo n.º 4
0
from fastapi import APIRouter, Query
from tortoise.transactions import in_transaction

from conf.logger import Logger
from lib.fastapi.error import ClientError
from lib.tortoise import pydantic_queryset_to_json

from .models import Tag, Category, Article
from .serializers import (TagCreateRequest, TagCreateResponse,
                          TagListSerializer, TagListResponse,
                          CategoryCreateRequest, CategoryCreateResponse,
                          CategoryListSerializer, CategoryListResponse,
                          ArticleCreateRequest, ArticleCreateResponse,
                          ArticleListResponse, ArticleListSerializer)

logger = Logger.get_logger(__name__)
router = APIRouter()


# ---- Tag ----
@router.post("/tag",
             response_model=TagCreateResponse,
             summary="Tag create",
             description="Tag create",
             response_description="Tag Instance")
async def tag_create(data: TagCreateRequest):
    instance = await Tag.create(**data.dict(exclude_unset=True))
    return await TagCreateResponse.from_tortoise_orm(instance)


@router.patch("/tag/{pk}",
Ejemplo n.º 5
0
class Notification:
    """钉钉群通知"""
    def __init__(self, city):
        """初始化通知属性"""
        self.city = city
        self.logging = Logger(self.city)
        self.send_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.notification_urls = {
            "test":
            "https://oapi.dingtalk.com/robot/send?access_token"
            "=0354ddbdf68e36be9e931f2555ba4b4bc4c9751af986dd9497206997cdd71968 ",
            "formal-9":
            "https://oapi.dingtalk.com/robot/send?access_token"
            "=649a092161ceda91c94ec436ca32b5439d60af7287447e8d0767952073723b4b ",
            "formal-4":
            "https://oapi.dingtalk.com/robot/send?access_token"
            "=55f4877383250813c2bc9684c977c01eea81f80f9bb92e5f38ce8be05b0cbeac",
            "debug":
            "https://oapi.dingtalk.com/robot/send?access_token"
            "=2fb637568180850691c13455329bf1122de97b284980f15862a95d5c55af961d",
        }
        if "win" in sys.platform:
            self.isTest = True
        else:
            self.isTest = False

    def send_appointment_notification(self, custom, department):
        """发送医院可预约通知"""
        if custom == "四价":
            url = self.notification_urls["test" if self.isTest else "formal-4"]
        else:
            url = self.notification_urls["test" if self.isTest else "formal-9"]
        data = {
            "msgtype": "text",
            "text": {
                "content":
                f"{self.city}:  {department}\n"
                "\n"
                f"时间:  {self.send_time}\n"
            },
            "at": {
                "isAtAll": "false"
            }
        }
        headers = {
            'Content-Type': 'application/json',
            'Connection': 'close',
        }
        res = requests.post(url, json.dumps(data), headers=headers).json()
        errmsg = jsonpath(res, "$.errmsg")
        if 'ok' in errmsg:
            self.logging.info(f"{self.city}群发送{department}{custom}疫苗可预约通知成功")
        else:
            self.logging.error(
                f"{self.city}群发送{department}{custom}疫苗可预约通知失败,请检查~\n"
                f"错误信息:{res}")

    def send_subscribe_notification(self, custom, department):
        """发送医院可订阅通知"""
        url = self.notification_urls["test" if self.isTest else "formal-9"]
        data = {
            "msgtype": "text",
            "text": {
                "content":
                f"{self.city}:  {department}\n"
                "\n"
                f"时间:  {self.send_time}\n"
            },
            "at": {
                "isAtAll": "false"
            }
        }
        headers = {
            'Content-Type': 'application/json',
            'Connection': 'close',
        }
        res = requests.post(url, json.dumps(data), headers=headers).json()
        errmsg = jsonpath(res, "$.errmsg")
        if 'ok' in errmsg:
            self.logging.info(f"{self.city}群发送{department}{custom}疫苗可订阅通知成功")
        else:
            self.logging.error(
                f"{self.city}群发送{department}{custom}疫苗可订阅通知失败,请检查~\n"
                f"错误信息:{res}")

    def send_error_notification(self, custom, message):
        """发送服务异常通知"""
        url = self.notification_urls["test"]
        data = {
            "msgtype": "text",
            "text": {
                "content":
                f"{self.city}{custom}服务异常提醒\n"
                "\n"
                f"{message}\n"
                f"时间:  {self.send_time}\n"
            },
            "at": {
                "isAtAll": "false"
            }
        }
        headers = {
            'Content-Type': 'application/json',
            'Connection': 'close',
        }
        res = requests.post(url, json.dumps(data), headers=headers).json()
        errmsg = jsonpath(res, "$.errmsg")
        if 'ok' in errmsg:
            self.logging.info(f"{self.city}群发送{custom}服务异常提醒成功")
        else:
            self.logging.error(f"{self.city}群发送{custom}服务异常提醒失败,请检查~\n"
                               f"错误信息:{res}")
Ejemplo n.º 6
0
class Account:
    """设置账号相关信息"""

    def __init__(self, city):
        """初始化账号属性"""
        self.city = city
        self.logging = Logger(self.city)
        if "win" in sys.platform:
            headers_path = ".\\conf\\headers"
        else:
            headers_path = "./conf/headers"
        with open(headers_path) as headers_obj:
            cookie_obj = headers_obj.readlines()
            for line in cookie_obj:
                if "Cookie" in line:
                    self.cookie = line.split("Cookie: ")[1].strip()
                if "tk" in line:
                    self.tk = line.split("tk: ")[1].strip()

    def get_account_info(self):
        """获取用户id,name"""
        url = "https://wx.scmttec.com/order/linkman/findByUserId.do"
        headers = {
            'tk': self.tk,
            'cookie': self.cookie,
        }
        try:
            user_info = requests.get(url=url, headers=headers).json()
            code = jsonpath(user_info, "$.code")[0]
            match int(code):
                case 0000:
                    linkman_id = str(jsonpath(user_info, "$.data[0].id")).strip("[]")
                    user_id = str(jsonpath(user_info, "$.data[0].userId")).strip("[]")
                    user_name = str(jsonpath(user_info, "$.data[0].name")).strip("[]").strip("'")
                    return {
                        'headers': headers,
                        'linkman_id': linkman_id,
                        'user_id': user_id,
                        'user_name': user_name,
                    }
                case 1001:
                    message = (f"获取用户信息失败,请检查~\n"
                               f"错误信息:当前登录已过期,正在尝试重新登录")
                    self.logging.error(message)
                    Notification(self.city).send_error_notification("", message)
                    sys.exit(1)
                case _:
                    message = (f"获取用户信息失败,请检查~\n"
                               f"错误信息:{user_info}")
                    self.logging.error(message)
                    Notification(self.city).send_error_notification("", message)
        except JSONDecodeError as error_massage:
            message = (f"获取用户信息失败,请检查~\n"
                       f"错误信息:{error_massage}")
            self.logging.error(message)
            Notification(self.city).send_error_notification("", message)
        except BaseException as error_massage:
            message = (f"获取用户信息失败,请检查~\n"
                       f"错误信息:{error_massage}")
            self.logging.error(message)
            Notification(self.city).send_error_notification("", message)
Ejemplo n.º 7
0
class Listening:
    """设置监听信息"""

    def __init__(self, city, custom):
        """初始化监听属性"""
        self.city = city
        self.custom = custom
        self.custom_id = {
            "四价": 2,
            "九价": 3,
        }
        self.logging = Logger(self.city)
        self.user_info = Account(self.city).get_account_info()
        self.session = requests.Session()
        self.headers = self.user_info['headers']
        self.linkman_id = self.user_info['linkman_id']
        self.region = Region(self.city)
        self.appointment_notification_status = {}
        self.subscribe_notification_status = {4698: 0, 25752: 0, 6259: 0, 26225: 0, 26226: 0, 4453: 0, }

    def get_departments(self):
        """获取医院列表"""
        url = "https://wx.scmttec.com/department/department/getDepartments.do"
        params = {
            "offset": 0,
            "limit": 5,
            "name": "",
            "regionCode": self.region.get_region_info()['region_code'],
            "isOpen": 1,
            "longitude": self.region.get_region_info()['longitude'],
            "latitude": self.region.get_region_info()['latitude'],
            "sortType": 1,
            "vaccineCode": "",
            "customId": self.custom_id[self.custom],
        }
        try:
            departments = self.session.get(url=url, headers=self.headers, params=params).json()
            code = jsonpath(departments, "$.code")[0]
            match int(code):
                case 0000:
                    departments_names = jsonpath(departments, "$.data.rows..name")
                    departments_codes = jsonpath(departments, "$.data.rows..code")
                    vacc_ids = jsonpath(departments, "$.data.rows..depaVaccId")
                    vacc_codes = jsonpath(departments, "$.data.rows..vaccineCode")
                    return {
                        'departments_names': departments_names,
                        'departments_codes': departments_codes,
                        'vacc_ids': vacc_ids,
                        'vacc_codes': vacc_codes,
                    }
                case 1001:
                    message = (f"获取医院列表失败,请检查~\n"
                               f"错误信息:当前登录已过期,正在尝试重新登录")
                    self.logging.error(message)
                    Notification(self.city).send_error_notification(self.custom, message)
                    sys.exit(1)
                case _:
                    message = (f"获取医院列表失败,请检查~\n"
                               f"错误信息:{departments}")
                    self.logging.error(message)
                    Notification(self.city).send_error_notification(self.custom, message)
        except JSONDecodeError as error_massage:
            message = (f"获取医院列表失败,请检查~\n"
                       f"错误信息:{error_massage}")
            self.logging.error(message)
        except BaseException as error_massage:
            message = (f"获取医院列表失败,请检查~\n"
                       f"错误信息:{error_massage}")
            self.logging.error(message)
            Notification(self.city).send_error_notification(self.custom, message)

    def get_departements_status(self):
        """获取医院状态"""
        departments_status = []
        departments = self.get_departments()
        department_index = 0
        if departments:
            for vacc_id in departments['vacc_ids']:
                department = departments["departments_names"][department_index]
                url = "https://wx.scmttec.com/subscribe/subscribe/isCanSubscribe.do"
                params = {
                    "vaccineCode": departments['vacc_codes'][department_index],
                    "linkmanId": self.linkman_id,
                    "id": vacc_id,
                    "depaCode": departments['departments_codes'][department_index]
                }
                try:
                    department_info = self.session.get(url=url, headers=self.headers, params=params).json()
                    time.sleep(10+round(random(), 2))
                    code = jsonpath(department_info, "$.code")[0]
                    match int(code):
                        case 0000:
                            type_code = jsonpath(department_info, "$.data.typeCode")
                            type_code = int(str(type_code).strip("[]"))
                        case 1001:
                            message = (f"获取{department}状态失败,请检查~\n"
                                       f"错误信息:当前登录已过期,正在尝试重新登录")
                            self.logging.error(message)
                            Notification(self.city).send_error_notification(self.custom, message)
                            sys.exit(1)
                        case _:
                            type_code = 0
                            message = (f"获取{department}状态失败,请检查~\n"
                                       f"错误信息:{department_info}")
                            self.logging.error(message)
                            Notification(self.city).send_error_notification(self.custom, message)
                except JSONDecodeError as error_massage:
                    type_code = 0
                    message = (f"获取{department}状态失败,请检查~\n"
                               f"错误信息:{error_massage}")
                    self.logging.error(message)
                except BaseException as error_massage:
                    type_code = 0
                    message = (f"获取{department}状态失败,请检查~\n"
                               f"错误信息:{error_massage}")
                    self.logging.error(message)
                    Notification(self.city).send_error_notification(self.custom, message)
                departments_status.append(type_code)
                department_index += 1
            return {
                "departments_status": departments_status,
                "departments_names": departments["departments_names"],
                "vacc_ids": departments["vacc_ids"],
            }

    def start_listening(self):
        """开始监听,疫苗到货后发送通知"""
        rounds = 1
        while True:
            departements_info = self.get_departements_status()
            if departements_info:
                departements_status_index = 0
                for status in departements_info["departments_status"]:
                    department = departements_info["departments_names"][departements_status_index]
                    vacc_id = departements_info["vacc_ids"][departements_status_index]
                    match status:
                        case 1:
                            self.logging.info(f'{department}可预约')
                            if vacc_id in self.appointment_notification_status:
                                if self.appointment_notification_status[vacc_id] == 0:
                                    Notification(self.city).send_appointment_notification(self.custom, department)
                                    self.appointment_notification_status[vacc_id] = 1
                            else:
                                Notification(self.city).send_appointment_notification(self.custom, department)
                                self.appointment_notification_status[vacc_id] = 1
                            if vacc_id in self.subscribe_notification_status:
                                self.subscribe_notification_status[vacc_id] = 0
                        case 2:
                            self.logging.info(f'{department}可订阅')
                            if vacc_id in self.subscribe_notification_status:
                                if self.subscribe_notification_status[vacc_id] == 0:
                                    Notification(self.city).send_subscribe_notification(self.custom, department)
                                    self.subscribe_notification_status[vacc_id] = 1
                            self.appointment_notification_status[vacc_id] = 0
                        case 3:
                            self.logging.info(f'{department}已订阅等待到苗通知')
                            self.appointment_notification_status[vacc_id] = 0
                            if vacc_id in self.subscribe_notification_status:
                                self.subscribe_notification_status[vacc_id] = 0
                        case 4:
                            self.logging.info(f'{department}暂停订阅')
                            self.appointment_notification_status[vacc_id] = 0
                            if vacc_id in self.subscribe_notification_status:
                                self.subscribe_notification_status[vacc_id] = 0
                        case _:
                            self.logging.info(f'获取{department}状态失败')
                    departements_status_index += 1
            self.logging.info(
                f"--------------------------{self.city}{self.custom}监听已运行{rounds}次-------------------------\n\n")
            rounds += 1