JohnWatson 2021-11-22 19:45:07

CAU-Library-Assistant 通过ServerLess云函数实现自动预定座位

# -*- coding: utf8 -*-
import json
import os
import smtplib
import sys
import time
from email.header import Header
from email.mime.text import MIMEText

import requests

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")

__author__ = "Xinyu Yang"
__email__ = "8@cau.edu.cn"
__copyright__ = "Copyright (C) 2021 Xinyu Yang"
__license__ = "CC 4.0"
__version__ = "1.0"


# Custom variable\
# For Login
openid = "YOUR OPENID"
account = "YOUR ACCOUNT"
upass = "YOUR UPASS"

# For Book
book_info = {
    "SeatID": 00000,
    "date": time.strftime("%Y-%m-%d", time.localtime(time.time())),
    "start": 1200,  # Start time hour * 60
    "end": 1320  # End time hour * 60
}

# SMTP service for sending emails
mail_host = "smtp.qq.com"  # SMTP server
mail_user = "YOUR User"
mail_pass = "YOUR Pass"
mail_port = 465
mail_receiver = "YOUR Receiver"


def get_jsession_id():
    CookieBridge = f"http://libwx.cau.edu.cn/libseat-ibeacon/" \
                   f"wechatIndex?type=currentBook&openid={openid}&account={account}&upass={upass}"
    CBRes = requests.get(CookieBridge, allow_redirects=False)
    return CBRes.headers.get("Set-Cookie")[11:43]


Cookie = {
    "JSESSIONID": get_jsession_id()
}


def sendEmail(fromAddr, toAddr, subject, content):
    sender = fromAddr
    receivers = [toAddr]
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header("CAU Library Assistant", 'utf-8')
    message['To'] = Header(toAddr, 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, mail_port)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("send email success")
        return True
    except smtplib.SMTPException as e:
        print(e)
        print("Error: send email fail")
        return False


def send_by_qq_mail(subject, content):
    sendEmail(mail_user, mail_receiver, subject, content)


def book(STARTRequestID, EventRequestID):
    SaveBook = f"http://libwx.cau.edu.cn/libseat-ibeacon/saveBook?" \
               f"seatId={book_info['SeatID']}&date={book_info['date']}" \
               f"&start={book_info['start']}&end={book_info['end']}&type=1"

    BookRes = requests.get(SaveBook, cookies={
        "JSESSIONID": get_jsession_id()
    }).text

    book_response = json.loads(eval(BookRes))

    print(book_response)
    if book_response['status'] == "success":
        send_by_qq_mail("Reservation success",
                        f"座位: {book_response['data']['location']} 已为您保留.\n"
                        f"保留时间为: {book_response['data']['onDate']} {book_response['data']['begin']} ~ {book_response['data']['end']}\n"
                        f"请尽快进馆签到,祝您学习愉快!加油冲冲冲!(。・ω・。)ノ")
    else:
        send_by_qq_mail("Reservation Failed",
                        f"预定失败,具体信息如下所示:\n{book_response['message']}")


# Useless Code, Unsafe, Not recommended
def get_last_book_info():
    getHistory = "http://libwx.cau.edu.cn/libseat-ibeacon/getUserBookHistory"

    history = requests.get(getHistory, cookies=Cookie).text
    history_dic = json.loads(history)
    return history_dic["params"]["history"][0]


def cancel_reserved_book(bookid):
    URL_Cancel = f"http://libwx.cau.edu.cn/libseat-ibeacon/cancleBook?bookId={bookid}"

    requests.get(URL_Cancel, cookies=Cookie)


def check_book(STARTRequestID, EventRequestID):
    last_book_info = get_last_book_info()

    # If the seat is reserved but is about to expire, cancel and re-book
    if last_book_info["stat"] == "RESERVE":
        book_time = time.mktime(time.strptime(f"{last_book_info['date']}-{last_book_info['begin']}", "%Y-%m-%d-%H:%M"))

        if book_time - time.time() < 600:
            cancel_reserved_book(last_book_info["id"])

        book(None, None)

评论

Home - Wiki
Copyright © 2011-2024 iteam. Current version is 2.138.0. UTC+08:00, 2024-12-22 11:09
浙ICP备14020137号-1 $Map of visitor$