├── .gitignore ├── requirements.txt ├── exam ├── convert.py └── exam.py ├── zjuam ├── base.py ├── ugrs.py └── grs.py ├── utils ├── const.py └── config.py ├── configs ├── config.json └── config.2025-2026.FW.json ├── main └── integration.py ├── zjuical.py ├── ical └── ical.py ├── README.md ├── webical.py ├── course ├── ugrs_course.py ├── convert.py ├── grs_course.py └── course.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | __pycache__ 3 | *.ics 4 | *.local* 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.32.3 2 | loguru>=0.7.0 3 | waitress>=3.0.0 4 | flask>=3.0.0 -------------------------------------------------------------------------------- /exam/convert.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | DUMMY_DATE = datetime(1970, 1, 1, 0, 0) 4 | 5 | 6 | def parseExamDateTime(time: str) -> tuple[datetime, datetime]: 7 | if len(time) == len("2024年06月28日(08:00-10:00)"): 8 | # old format 9 | date = time[:11] 10 | start = time[12:17] 11 | end = time[18:23] 12 | start = datetime.strptime(date + start, "%Y年%m月%d日%H:%M") 13 | end = datetime.strptime(date + end, "%Y年%m月%d日%H:%M") 14 | elif "考试第" in time: 15 | # new format: 冬考试第2天(10:30-12:30) 16 | # TODO: 由于校历未发布,无法计算日期。当前解决方案是返回一个 dummy 日期(GitHub #3) 17 | start = end = DUMMY_DATE 18 | return start, end 19 | -------------------------------------------------------------------------------- /zjuam/base.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from course.course import CourseTable 3 | from exam.exam import ExamTable 4 | from utils.const import Term 5 | from abc import ABC, abstractmethod 6 | 7 | 8 | class Zjuam(ABC): 9 | LOGIN_URL = "https://zjuam.zju.edu.cn/cas/login" 10 | PUBKEY_URL = "https://zjuam.zju.edu.cn/cas/v2/getPubKey" 11 | 12 | def __init__(self, username: str, password: str): 13 | self.username = username 14 | self.password = password 15 | self.r = requests.Session() 16 | 17 | @abstractmethod 18 | def login(self) -> None: 19 | pass 20 | 21 | @abstractmethod 22 | def getCourses(self, year: str, term: Term, exams: ExamTable) -> CourseTable: 23 | pass 24 | -------------------------------------------------------------------------------- /utils/const.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, unique 2 | 3 | 4 | @unique 5 | class WeekType(Enum): 6 | Normal = 2 # 每周都有 7 | OddOnly = 0 # 单周 8 | EvenOnly = 1 # 双周 9 | 10 | 11 | @unique 12 | class Term(Enum): 13 | Autumn = "秋" # 秋学期 14 | Winter = "冬" # 冬学期 15 | ShortA = "短1" # 短学期A (NotImplemented) 16 | SummerVacation = "暑" # 暑学期 (NotImplemented) 17 | Spring = "春" # 春学期 18 | Summer = "夏" # 夏学期 19 | ShortB = "短2" # 短学期B (NotImplemented) 20 | 21 | 22 | @unique 23 | class TweakMethod(Enum): 24 | Clear = "Clear" # 清空 [From, To] 的所有课程 25 | Copy = "Copy" # 从 From 复制到 To 26 | Move = "Move" # 从 From 移动到 To 27 | Exchange = "Exchange" # 交换 From 和 To 的课程 28 | Pending = "Pending" # 待定,不起任何作用 29 | 30 | 31 | @unique 32 | class ExamType(Enum): 33 | MidTerm = "期中考试" 34 | FinalTerm = "期末考试" 35 | NoExam = "无考试" 36 | -------------------------------------------------------------------------------- /configs/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "lastUpdated": 20250619, 3 | "tweaks": [ 4 | { 5 | "TweakType": "Clear", 6 | "Description": "[国庆中秋] 10月1日(周三)至10月8日(周三)停课", 7 | "From": 20251001, 8 | "To": 20251008 9 | }, 10 | { 11 | "TweakType": "Clear", 12 | "Description": "[元旦] 1月1日(周四)停课", 13 | "From": 20260101, 14 | "To": 20260101 15 | }, 16 | { 17 | "TweakType": "Exchange", 18 | "Description": "[国庆中秋] 10月7日(周二)与9月28日(周日)的课对调", 19 | "From": 20251007, 20 | "To": 20250928 21 | }, 22 | { 23 | "TweakType": "Exchange", 24 | "Description": "[国庆中秋] 10月8日(周三)与10月11日(周六)的课对调", 25 | "From": 20251008, 26 | "To": 20251011 27 | }, 28 | { 29 | "TweakType": "Move", 30 | "Description": "[秋季校运会] 10月24日(周五)停课,安排在10月18日(周六)补课", 31 | "From": 20251024, 32 | "To": 20251018 33 | }, 34 | { 35 | "TweakType": "Move", 36 | "Description": "[学生节] 12月31日(周三)停课,安排在1月5日(周一)补课", 37 | "From": 20251231, 38 | "To": 20260105 39 | }, 40 | { 41 | "TweakType": "Pending", 42 | "Description": "[元旦] 调休安排另行通知", 43 | "From": 20260101, 44 | "To": 20260101 45 | } 46 | ], 47 | "termConfigs": [ 48 | { 49 | "Year": "2025-2026", 50 | "Term": "秋", 51 | "Begin": 20250915, 52 | "End": 20251109, 53 | "FirstWeekNo": 1 54 | }, 55 | { 56 | "Year": "2025-2026", 57 | "Term": "冬", 58 | "Begin": 20251110, 59 | "End": 20260104, 60 | "FirstWeekNo": 1 61 | } 62 | ], 63 | "classTerms": ["2025-2026:秋", "2025-2026:冬"] 64 | } 65 | -------------------------------------------------------------------------------- /main/integration.py: -------------------------------------------------------------------------------- 1 | from ical.ical import Calender 2 | from loguru import logger 3 | from utils.config import config, ClassYearAndTerm, TermConfig 4 | from zjuam.ugrs import UgrsZjuam 5 | from zjuam.grs import GrsZjuam 6 | 7 | 8 | def getCalender(username: str, password: str, skip_verification: bool) -> str: 9 | match username[0]: 10 | case "3": 11 | logger.info("检测到本科生学号,使用本科生途径登录") 12 | zjuam = UgrsZjuam(username, password) 13 | case "1" | "2": 14 | logger.info("检测到研究生学号,使用研究生途径登录") 15 | zjuam = GrsZjuam(username, password) 16 | case _: 17 | if skip_verification: 18 | logger.warning("跳过学号验证") 19 | else: 20 | logger.error("学号不以 1/2/3 开头,不确保本项目能在除本科生/研究生之外的账号使用") 21 | logger.info( 22 | "你可以通过 --skip-verification 参数跳过此检查,同时欢迎向作者反馈其他类型账号使用情况") 23 | raise NotImplementedError("不支持的用户类型") 24 | 25 | zjuam.login() 26 | 27 | termConfigs = config.termConfigs 28 | 29 | def firstMatchTerm(item: ClassYearAndTerm) -> None | TermConfig: 30 | for tc in termConfigs: 31 | if tc.Year == item.Year and tc.Term == item.Term: 32 | return tc 33 | return None 34 | 35 | cal = Calender() 36 | exams = zjuam.getExams() 37 | 38 | for item in config.classTerms: 39 | tc = firstMatchTerm(item) 40 | if tc is None: 41 | logger.error(f"配置文件错误,未找到 {item.Year}-{item.Term.value} 的学期配置") 42 | exit(1) 43 | 44 | courses = zjuam.getCourses(item.Year, item.Term, exams) 45 | courseEvents = courses.toEvents(termConfig=tc) 46 | if exams is not None: 47 | examEvents = exams.toEvents(courses) 48 | 49 | cal.addEvents(courseEvents) 50 | if exams is not None: 51 | cal.addEvents(examEvents) 52 | 53 | return cal.getICS(icalName=config.toTermString() + "课程表") 54 | -------------------------------------------------------------------------------- /configs/config.2025-2026.FW.json: -------------------------------------------------------------------------------- 1 | { 2 | "lastUpdated": 20250619, 3 | "tweaks": [ 4 | { 5 | "TweakType": "Clear", 6 | "Description": "[国庆中秋] 10月1日(周三)至10月8日(周三)停课", 7 | "From": 20251001, 8 | "To": 20251008 9 | }, 10 | { 11 | "TweakType": "Move", 12 | "Description": "[元旦] 1月1日(周四)停课,安排在1月6日(周二)补课", 13 | "From": 20260101, 14 | "To": 20260106 15 | }, 16 | { 17 | "TweakType": "Exchange", 18 | "Description": "[元旦] 1月2日(周五)与1月4日(周日)的课对调", 19 | "From": 20260102, 20 | "To": 20260104 21 | }, 22 | { 23 | "TweakType": "Exchange", 24 | "Description": "[国庆中秋] 10月7日(周二)与9月28日(周日)的课对调", 25 | "From": 20251007, 26 | "To": 20250928 27 | }, 28 | { 29 | "TweakType": "Exchange", 30 | "Description": "[国庆中秋] 10月8日(周三)与10月11日(周六)的课对调", 31 | "From": 20251008, 32 | "To": 20251011 33 | }, 34 | { 35 | "TweakType": "Move", 36 | "Description": "[秋季校运会] 10月24日(周五)停课,安排在10月18日(周六)补课", 37 | "From": 20251024, 38 | "To": 20251018 39 | }, 40 | { 41 | "TweakType": "Move", 42 | "Description": "[学生节] 12月31日(周三)停课,安排在1月5日(周一)补课", 43 | "From": 20251231, 44 | "To": 20260105 45 | } 46 | ], 47 | "termConfigs": [ 48 | { 49 | "Year": "2025-2026", 50 | "Term": "秋", 51 | "Begin": 20250915, 52 | "End": 20251109, 53 | "FirstWeekNo": 1 54 | }, 55 | { 56 | "Year": "2025-2026", 57 | "Term": "冬", 58 | "Begin": 20251110, 59 | "End": 20260104, 60 | "FirstWeekNo": 1 61 | } 62 | ], 63 | "classTerms": ["2025-2026:秋", "2025-2026:冬"] 64 | } 65 | -------------------------------------------------------------------------------- /zjuical.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | from loguru import logger 4 | from utils.config import config 5 | from main.integration import getCalender 6 | 7 | VERSION = "1.0.3" 8 | 9 | if __name__ == "__main__": 10 | def formatter(prog): 11 | return argparse.HelpFormatter(prog, max_help_position=52) 12 | 13 | parser = argparse.ArgumentParser( 14 | prog="zjuical.py", 15 | description="A command-line utility for generating \ 16 | class schedule iCalender file from extracting \ 17 | data from ZJU ZDBK API. Refactored based \ 18 | on Python by Xecades.", 19 | formatter_class=formatter 20 | ) 21 | parse = parser.add_argument 22 | 23 | parse("-u", "--username", type=str, required=True, help="ZJUAM username") 24 | parse("-p", "--password", type=str, required=True, help="ZJUAM password") 25 | parse("-c", "--config", type=str, default="configs/config.json", 26 | help="config file (default \"configs/config.json\")") 27 | parse("-o", "--output", type=str, default="zjuical.ics", 28 | help="output file (default \"zjuical.ics\")") 29 | parse("-f", "--force", action="store_true", 30 | help="force write to target file") 31 | parse("--skip-verification", action="store_true", 32 | help="skip verification for non-undergraduate account") 33 | parse("-v", "--version", action="version", 34 | version=f"%(prog)s v{VERSION}", help="version for zjuical") 35 | 36 | args = parser.parse_args() 37 | 38 | logger.info(f"ZJU-ICAL-PY (v{VERSION}) by Xecades") 39 | 40 | if os.path.exists(args.output): 41 | if not args.force: 42 | logger.error(f"输出文件 {args.output} 已存在,请使用 -f 参数强制覆盖") 43 | exit(1) 44 | else: 45 | logger.warning(f"输出文件 {args.output} 已存在,将被覆盖") 46 | 47 | config.load(args.config) 48 | cal = getCalender(args.username, args.password, args.skip_verification) 49 | with open(args.output, "w", encoding="utf-8") as f: 50 | logger.info(f"正在写入文件 {args.output}") 51 | f.write(cal) 52 | 53 | logger.success(f"日历文件生成完毕") 54 | -------------------------------------------------------------------------------- /utils/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | from datetime import datetime 4 | from dataclasses import dataclass 5 | from utils.const import Term, TweakMethod 6 | from course.convert import isoToDate 7 | from loguru import logger 8 | from collections import defaultdict 9 | 10 | 11 | @dataclass 12 | class TermConfig: 13 | Year: str 14 | Term: Term 15 | Begin: datetime 16 | End: datetime 17 | FirstWeekNo: int 18 | 19 | 20 | @dataclass 21 | class Tweak: 22 | TweakType: TweakMethod 23 | Description: str 24 | From: datetime 25 | To: datetime 26 | 27 | 28 | @dataclass 29 | class ClassYearAndTerm: 30 | Year: str 31 | Term: Term 32 | 33 | 34 | class Config: 35 | config: dict 36 | lastUpdated: datetime 37 | classTerms: list[ClassYearAndTerm] 38 | termConfigs: list[TermConfig] 39 | tweaks: list[Tweak] 40 | 41 | def __init__(self) -> None: 42 | pass 43 | 44 | def toTermString(self) -> str: 45 | terms = defaultdict(str) 46 | for ct in self.classTerms: 47 | terms[ct.Year] += f"{ct.Term.value}" 48 | return ", ".join(f"{year} {terms[year]}" for year in sorted(terms.keys())) 49 | 50 | def load(self, path: str) -> None: 51 | logger.info("开始读取配置文件") 52 | 53 | if not os.path.exists(path): 54 | logger.error(f"配置文件 {path} 不存在") 55 | exit(1) 56 | 57 | self.config = json.load(open(path, "r", encoding="utf-8")) 58 | self.lastUpdated = isoToDate(self.config["lastUpdated"]) 59 | self.classTerms = [] 60 | self.termConfigs = [] 61 | self.tweaks = [] 62 | 63 | for ct in self.config["classTerms"]: 64 | year, term = ct.split(":") 65 | term = Term(term) 66 | self.classTerms.append(ClassYearAndTerm(year, term)) 67 | 68 | for tc in self.config["termConfigs"]: 69 | tc["Begin"] = isoToDate(tc["Begin"]) 70 | tc["End"] = isoToDate(tc["End"]) 71 | tc["Term"] = Term(tc["Term"]) 72 | self.termConfigs.append(TermConfig(**tc)) 73 | 74 | for tk in self.config["tweaks"]: 75 | tk["From"] = isoToDate(tk["From"]) 76 | tk["To"] = isoToDate(tk["To"]) 77 | tk["TweakType"] = TweakMethod(tk["TweakType"]) 78 | self.tweaks.append(Tweak(**tk)) 79 | 80 | logger.info("配置文件读取处理完成") 81 | 82 | 83 | config = Config() 84 | -------------------------------------------------------------------------------- /ical/ical.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, UTC 2 | from dataclasses import dataclass 3 | from course.convert import toISOString 4 | from hashlib import sha1 5 | from loguru import logger 6 | 7 | 8 | @dataclass 9 | class Event: 10 | summary: str 11 | location: str 12 | description: str 13 | start: datetime 14 | end: datetime 15 | 16 | @property 17 | def uid(self) -> str: 18 | m = sha1() 19 | m.update(self.description.encode()) 20 | m.update(self.summary.encode()) 21 | m.update(self.location.encode()) 22 | m.update(toISOString(self.start).encode()) 23 | return m.hexdigest() 24 | 25 | @property 26 | def string(self) -> str: 27 | utcStr = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") 28 | stStr = toISOString(self.start) 29 | etStr = toISOString(self.end) 30 | 31 | res = f"BEGIN:VEVENT\r\nCLASS:PUBLIC\r\nCREATED:{utcStr}\r\n" 32 | if self.description: 33 | if "=0D=0A" in self.description: 34 | res += f"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:{self.description}\r\n" 35 | else: 36 | res += f"DESCRIPTION:{self.description}\r\n" 37 | res += f"DTSTAMP:{utcStr}\r\n" 38 | res += f"DTSTART;TZID=Asia/Shanghai:{stStr}\r\n" 39 | res += f"DTEND;TZID=Asia/Shanghai:{etStr}\r\n" 40 | res += f"LAST-MODIFIED:{utcStr}\r\n" 41 | if self.location: 42 | res += f"LOCATION:{self.location}\r\n" 43 | res += f"SEQUENCE:0\r\nSUMMARY;LANGUAGE=zh-cn:{self.summary}\r\nTRANSP:OPAQUE\r\nUID:{self.uid}\r\n" 44 | res += "END:VEVENT\r\n" 45 | return res 46 | 47 | 48 | class Calender: 49 | events: list[Event] 50 | 51 | def __init__(self): 52 | self.events = [] 53 | 54 | def add(self, **kwargs) -> None: 55 | self.events.append(Event(**kwargs)) 56 | 57 | def addEvents(self, events: list[Event]) -> None: 58 | self.events.extend(events) 59 | 60 | def getICS(self, icalName: str = "ZJU-ICAL 课程表") -> str: 61 | logger.info("开始生成日历文件") 62 | res = f"BEGIN:VCALENDAR\r\nX-WR-CALNAME:{icalName}\r\nX-APPLE-CALENDAR-COLOR:#2BBFF0\r\nPRODID:-//ZJU-ICAL-PY//Ejector 0.2//EN\r\nVERSION:2.0\r\nMETHOD:PUBLISH\r\nBEGIN:VTIMEZONE\r\nTZID:Asia/Shanghai\r\nBEGIN:STANDARD\r\nDTSTART:16010101T000000\r\nTZOFFSETFROM:+0800\r\nTZOFFSETTO:+0800\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n" 63 | for event in self.events: 64 | res += event.string 65 | res += "END:VCALENDAR\r\n" 66 | return res 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ZJU-ICAL-PY 2 | 3 | > [!NOTE] 4 | > 本项目是基于 [ZJU-ICAL 项目](https://github.com/cxz66666/zju-ical)的 Python 重构版本,更换了调用 API,目前**支持本科生和研究生的课程表**生成。本文档部分参考原项目的 README。 5 | > 6 | > 原项目按 LGPL-2.1 协议开源,本项目继承了原项目的协议。 7 | > 8 | > 研究生系统的 API 调用参考了 [Celechron 项目](https://github.com/Celechron/Celechron/blob/main/lib/http/zjuServices/grs_new.dart)。 9 | 10 | 将 ZJU 本科生/研究生课程表转换为 iCal 日历格式,方便地导入到 Windows/macOS/Linux/Android/Harmony OS/iOS/iPadOS/watchOS/Wear OS 上,支持: 11 | 12 | - 自动调休安排(由作者不定期维护) 13 | - 考试安排,包括考点教室、考试座位(**目前仅支持本科生**) 14 | 15 | > [!WARNING] 16 | > 当前项目仍处于测试阶段,可能存在未知的问题,欢迎提交 Issue 或 Pull Request。 17 | 18 | ## 免责声明 19 | 20 | **该项目仅供学习交流使用,作者不对产生结果正确性与时效性做实时保证,使用者需自行承担因程序逻辑错误或课程时间变动导致的后果。** 21 | 22 | 所有服务均在使用者的本地设备上运行,ZJUAM 登录密码加密传输,不会存在任何有关用户隐私的蓄意记录/收集行为。 23 | 24 | ## 开始使用 25 | 26 | 首先使用 `git` 将本项目克隆到本地,安装 **3.12** 及以上的 Python 环境(更低版本未经测试),然后使用以下命令安装依赖库: 27 | 28 | ```sh 29 | pip install -r requirements.txt 30 | ``` 31 | 32 | > [!CAUTION] 33 | > 由于所有代码均在本地运行,请在使用前使用 `git pull` 确保代码是最新的,**尤其是调休安排发生了更新的时候**,你也可能希望在考试安排出来之后重新运行程序来获得考试地点、座位等信息。 34 | 35 | `zjuical.py` 即为主程序,使用以下命令运行: 36 | 37 | ```sh 38 | python zjuical.py -u [username] -p '[password]' 39 | ``` 40 | 41 | 其中 `[username]` 为浙江大学统一身份认证用户名(即学号),`[password]` 为统一认证密码,无需方括号,外部引号需保留(防止密码中有特殊字符导致参数传递错误)。例如,假如你的学号为 3230100000,密码为 123456,那么你需要运行: 42 | 43 | ```sh 44 | python zjuical.py -u 3230100000 -p '123456' 45 | ``` 46 | 47 | 运行后即可在当前目录下生成 `zjuical.ics` 文件,导入到日历应用即可,更多的参数请使用 `python zjuical.py --help` 查看。 48 | 49 | ## 代码更新 50 | 51 | 由于代码完全在本地运行,所以**需要用户手动更新仓库**,强烈建议在每次运行前使用 `git pull` 命令更新代码,以确保获取到最新的调休安排和考试安排。 52 | 53 | ## 进阶使用 / `webical.py` 54 | 55 | 如果你想省去每次**代码更新**、**手动运行**的麻烦,可以使用 `webical.py` 脚本,它会在后台自动更新自身代码、运行并生成日历文件,并提供 HTTP 服务,从而能够在日历软件中直接订阅。 56 | 57 | > [!CAUTION] 58 | > 部分日历软件要求订阅链接**可在公网访问**,例如 Apple Calendar。因此以下步骤假定你已拥有一个公网 IP 或域名。除此之外,**理论上**日历的爬取是需要 ZJU 校网的,因此可能需要使用 [zju-connect](https://github.com/Mythologyli/zju-connect) 等工具在服务器上部署校网 VPN。(但是本人在测试的时候发现偶尔不需要校网也能访问,如果你能正常使用可以忽略这一步) 59 | > 60 | > **注意**:当前 `webical.py` 未做 HTTP Auth 鉴权,因此任何人只要知道你的公网 IP 和端口号就能访问你的日历文件,存在一定的隐私风险,请谨慎使用,见 [\#6](https://github.com/Xecades/zju-ical-py/issues/6)。 61 | 62 | 在安装完依赖后,使用以下命令运行: 63 | 64 | ```sh 65 | python webical.py "[传递给zjuical.py的参数]" 66 | # 例如: 67 | # python webical.py "-u 3230100000 -p '123456' -f" 68 | ``` 69 | 70 | 注意,**引号必须保留**,其内部的值会被直接传递给 `zjuical.py` 作为参数。默认设定每隔 1 小时自动更新并运行一次日历爬取,由于 `zjuical.py` 会生成 `zjuical.ics` 文件,因此你**必须在其中添加 `-f` 参数**以强制覆盖之前的文件,否则会导致日历文件无法更新。 71 | 72 | 除此之外,可通过 `-p` 参数指定 HTTP 服务端口,默认端口为 5273。开启服务后,你可以在日历软件中订阅 `http://[你的公网IP]:5273/zjuical.ics`。使用 `--help` 可查看更多参数。 73 | 74 | ## 开发计划 75 | 76 | - [x] 提供网页版订阅,自动推送更新 77 | - [x] 支持研究生课程表 by [\#11](https://github.com/Xecades/zju-ical-py/pull/11) 78 | - [ ] 支持研究生考试安排 79 | - [ ] 提供更安全的传参方式 80 | - [ ] 整合 zju-connect 81 | -------------------------------------------------------------------------------- /webical.py: -------------------------------------------------------------------------------- 1 | import time 2 | import sys 3 | import shlex 4 | import argparse 5 | import subprocess 6 | import threading 7 | from waitress import serve 8 | from loguru import logger 9 | from flask import Flask, Response 10 | 11 | app = Flask(__name__) 12 | VERSION = "1.0.0" 13 | INTERVAL = 60 * 60 # 1 hour 14 | 15 | 16 | def parse_args(): 17 | def formatter(prog): 18 | return argparse.HelpFormatter(prog, max_help_position=52) 19 | 20 | parser = argparse.ArgumentParser( 21 | prog="webical.py", 22 | description="Web server for ZJU-ICAL-PY that performs \ 23 | code & data updates automatically every hour, and \ 24 | serves the latest iCalendar file.", 25 | formatter_class=formatter 26 | ) 27 | parse = parser.add_argument 28 | 29 | parse("-p", "--port", type=int, default=5273, 30 | help="port to run the web server on") 31 | parse("--host", type=str, default="127.0.0.1", 32 | help="host of the web server (just for display)") 33 | parse("-v", "--version", action="version", 34 | version=f"%(prog)s v{VERSION}", help="version for zjuical web server") 35 | parse("zjuical", type=str, 36 | help="arguments for zjuical.py, e.g. '-u [username] -p [password]'") 37 | 38 | return parser.parse_args() 39 | 40 | 41 | def git_pull(): 42 | logger.info("执行 Git pull 命令以更新源代码...") 43 | result = subprocess.run(["git", "pull"], capture_output=True, text=True) 44 | logger.info(f"Git pull 输出: {result.stdout.strip()}") 45 | if result.returncode != 0: 46 | logger.error(f"Git pull 失败: {result.stderr.strip()}") 47 | else: 48 | logger.success("Git pull 成功") 49 | 50 | 51 | def run_zjuical(zjuical_args: str): 52 | executable = sys.executable 53 | cmd = [executable, "zjuical.py"] + shlex.split(zjuical_args) 54 | logger.info("启动 zjuical.py...") 55 | print() 56 | subprocess.run(cmd) 57 | print() 58 | logger.info("zjuical.py 执行完毕") 59 | 60 | 61 | def periodic_task(zjuical_args: str): 62 | while True: 63 | try: 64 | git_pull() 65 | run_zjuical(zjuical_args) 66 | except Exception as e: 67 | logger.error(f"Periodic task 错误: {e}") 68 | logger.info(f"等待 {INTERVAL} 秒后再次执行任务...") 69 | time.sleep(INTERVAL) 70 | 71 | 72 | @app.route("/zjuical.ics") 73 | def serve_file(): 74 | with open("zjuical.ics", "r", encoding="utf-8") as f: 75 | content = f.read() 76 | return Response(content, mimetype="text/calendar") 77 | 78 | 79 | if __name__ == "__main__": 80 | args = parse_args() 81 | logger.info(f"ZJU-ICAL-PY WEB-SERVER (v{VERSION}) by Xecades") 82 | logger.info(f"日历访问地址为 http://{args.host}:{args.port}/zjuical.ics") 83 | 84 | t = threading.Thread( 85 | target=periodic_task, 86 | daemon=True, 87 | args=(args.zjuical,) 88 | ) 89 | t.start() 90 | 91 | serve(app, host="0.0.0.0", port=args.port) 92 | -------------------------------------------------------------------------------- /course/ugrs_course.py: -------------------------------------------------------------------------------- 1 | from loguru import logger 2 | from course.course import Course, CourseTable 3 | from utils.const import WeekType 4 | 5 | 6 | class UGRSCourse(Course): 7 | timeString: str 8 | 9 | def __init__(self, raw: dict): 10 | self.credit = None 11 | # 不确定为什么要截取前22位,但Celechron是这样做的 12 | self.classId = raw["xkkh"][:22] # 选课课号 13 | self.dayOfWeek = int(raw["xqj"]) # 星期几 14 | 15 | self.setWeekType(raw["dsz"]) # 单双周 16 | 17 | # 课程表 18 | kcb = raw["kcb"] 19 | kcb = kcb.split("zwf")[0].split("
") 20 | self.name = kcb[0].replace("(", "(").replace(")", ")") 21 | self.timeString = kcb[1] 22 | self.teacher = kcb[2] 23 | self.location = None if kcb[3] == "" else kcb[3] 24 | 25 | # 学期 26 | xxq: str = raw["xxq"] 27 | self.setTerms(xxq) 28 | 29 | self.start = int(raw["djj"]) # 第几节 30 | self.end = self.start + int(raw["skcd"]) # 上课长度 31 | 32 | self.printLog() 33 | 34 | def setWeekType(self, raw: str) -> None: 35 | # 单双周 36 | if raw == "0": 37 | self.weekType = WeekType.OddOnly 38 | elif raw == "1": 39 | self.weekType = WeekType.EvenOnly 40 | else: 41 | self.weekType = WeekType.Normal 42 | 43 | @property 44 | def description(self) -> str: 45 | res = super().description 46 | res += "\\n" + self.timeString + " " 47 | 48 | if self.start == self.end - 1: 49 | res += f"第{self.start}节" 50 | else: 51 | res += f"第{self.start}-{self.end - 1}节" 52 | return res 53 | 54 | 55 | class UGRSCourseTable(CourseTable): 56 | courses: list[UGRSCourse] 57 | 58 | def fromRes(self, res: list[dict]) -> None: 59 | for raw in res: 60 | c = UGRSCourse(raw) 61 | self.courses.append(c) 62 | 63 | def communicate(self, exams: "ExamTable") -> None: 64 | for course in self.courses: 65 | examsOfCourse = exams.find(course) 66 | if len(examsOfCourse) == 0: 67 | continue 68 | course.credit = examsOfCourse[0].credit 69 | 70 | def merge(self) -> None: 71 | logger.info("本科生:开始相连时段课程表合并") 72 | try: 73 | for i in range(len(self.courses)): 74 | if self.courses[i] is None: 75 | continue 76 | for j in range(i + 1, len(self.courses)): 77 | if self.courses[j] is None: 78 | continue 79 | 80 | if overlap := self.courses[i].overlap(self.courses[j]): 81 | start, end = overlap 82 | self.courses[i].start = start 83 | self.courses[i].end = end 84 | self.courses[j] = None 85 | self.courses = list(filter(lambda c: c is not None, self.courses)) 86 | except Exception as e: 87 | logger.error(f"本科生:课程表合并失败: {e}") 88 | raise e 89 | -------------------------------------------------------------------------------- /course/convert.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | from datetime import date, datetime 3 | from utils.const import Term 4 | 5 | Time = namedtuple("Time", ["hour", "minute"]) 6 | 7 | 8 | def toISOString(date: date) -> str: 9 | return date.strftime("%Y%m%dT%H%M%S") 10 | 11 | 12 | def isoToDate(iso: int) -> datetime: 13 | return datetime.fromisoformat(str(iso)) 14 | 15 | 16 | def isEvenWeek(mondayOfTermBegin: date, date: date) -> bool: 17 | return (date - mondayOfTermBegin).days // 7 % 2 == 1 18 | 19 | 20 | def dayOfWeekToWeekString(day: int) -> None | str: 21 | if day == 1: 22 | return "星期一" 23 | elif day == 2: 24 | return "星期二" 25 | elif day == 3: 26 | return "星期三" 27 | elif day == 4: 28 | return "星期四" 29 | elif day == 5: 30 | return "星期五" 31 | elif day == 6: 32 | return "星期六" 33 | elif day == 7: 34 | return "星期日" 35 | return None 36 | 37 | 38 | def ugrsClassTermToQueryString(term: Term) -> None | str: 39 | if term == Term.Autumn: 40 | return "1|秋" 41 | elif term == Term.Winter: 42 | return "1|冬" 43 | elif term == Term.ShortA: 44 | return "1|短" 45 | elif term == Term.SummerVacation: 46 | return "1|暑" 47 | elif term == Term.Spring: 48 | return "2|春" 49 | elif term == Term.Summer: 50 | return "2|夏" 51 | elif term == Term.ShortB: 52 | return "2|短" 53 | return None 54 | 55 | def grsGetYear(year: str, term: Term) -> None | str: 56 | years = year.split('-') 57 | if term == Term.Autumn or term == Term.Winter: 58 | return years[0] 59 | elif term == Term.Spring or term == Term.Summer: 60 | return years[1] 61 | return None 62 | 63 | def grsClassTermToQueryString(term: Term) -> None | str: 64 | if term == Term.Autumn: 65 | return "13" 66 | elif term == Term.Winter: 67 | return "14" 68 | elif term == Term.Spring: 69 | return "11" 70 | elif term == Term.Summer: 71 | return "12" 72 | return None 73 | 74 | def periodToTime(period: int) -> None | Time: 75 | if period == 1: 76 | return Time(8, 0) 77 | elif period == 2: 78 | return Time(8, 50) 79 | elif period == 3: 80 | return Time(10, 0) 81 | elif period == 4: 82 | return Time(10, 50) 83 | elif period == 5: 84 | return Time(11, 40) 85 | elif period == 6: 86 | return Time(13, 25) 87 | elif period == 7: 88 | return Time(14, 15) 89 | elif period == 8: 90 | return Time(15, 5) 91 | elif period == 9: 92 | return Time(16, 15) 93 | elif period == 10: 94 | return Time(17, 5) 95 | elif period == 11: 96 | return Time(18, 50) 97 | elif period == 12: 98 | return Time(19, 40) 99 | elif period == 13: 100 | return Time(20, 30) 101 | elif period == 14: 102 | return Time(21, 20) 103 | elif period == 15: 104 | return Time(22, 10) 105 | return None 106 | -------------------------------------------------------------------------------- /course/grs_course.py: -------------------------------------------------------------------------------- 1 | from loguru import logger 2 | from course.convert import dayOfWeekToWeekString 3 | from course.course import Course, CourseTable 4 | from utils.const import WeekType 5 | 6 | 7 | class GRSCourse(Course): 8 | termInfo: str = "" 9 | courseType: str = "" 10 | comment: str = "" 11 | school: str = "" 12 | 13 | def __init__(self, raw: dict): 14 | self.credit = None 15 | self.classId = raw["bjbh"][:7] # 班级编号 16 | self.dayOfWeek = int(raw["xqj"]) # 星期几 17 | 18 | # 学期 19 | pkxqMc: str = raw["pkxqMc"] # 排课学期名称 20 | self.setTerms(pkxqMc) 21 | 22 | self.setWeekType(raw["zc"]) # 周次 23 | 24 | self.name = raw["kcmc"] # 课程名称 25 | self.teacher = raw["xm"] # 姓名 26 | self.location = raw["cdmc"] if raw["cdmc"] else "" # 场地名称 27 | 28 | self.start = int(raw["ksjc"]) # 开始节次 29 | self.end = int(raw["jsjc"]) + 1 # 结束节次 30 | 31 | self.printLog() 32 | 33 | def setWeekType(self, raw: str) -> None: 34 | week_list = [int(w) for w in raw.split(",") if w] if raw else [] 35 | 36 | # 设置单双周标志 37 | threshold = 8 if len(self.terms) > 1 else 4 38 | if len(week_list) > threshold: 39 | self.weekType = WeekType.Normal 40 | else: 41 | odd_week_count = sum(1 for w in week_list if w % 2 == 1) 42 | if odd_week_count > len(week_list) / 2: 43 | self.weekType = WeekType.OddOnly 44 | else: 45 | self.weekType = WeekType.EvenOnly 46 | 47 | @property 48 | def description(self) -> str: 49 | res = super().description 50 | res += f"\\n课号: {self.classId}" 51 | res += f"\\n课程类型: {self.courseType}" 52 | res += f"\\n学期: {self.termInfo}" 53 | res += f"\\n时间: {dayOfWeekToWeekString(self.dayOfWeek)}" 54 | if self.start == self.end - 1: 55 | res += f" 第{self.start}节" 56 | else: 57 | res += f" 第{self.start}-{self.end - 1}节" 58 | res += f"\\n开课学院: {self.school}" 59 | res += f"\\n备注: {self.comment}" 60 | return res 61 | 62 | 63 | class GRSCourseTable(CourseTable): 64 | courses: list[GRSCourse] 65 | 66 | def fromRes(self, res: dict) -> None: 67 | for day in range(1, 7): 68 | if str(day) not in res: 69 | continue 70 | classesOfDay = res[str(day)] 71 | for period in range(1, 15): 72 | if str(period) not in classesOfDay: 73 | continue 74 | classesOfPeriod = classesOfDay[str(period)]["pyKcbjSjddVOList"] 75 | for raw in classesOfPeriod: 76 | if "," not in raw["zc"]: 77 | continue # 跳过因为调休而单列的课程 78 | c = GRSCourse(raw) 79 | self.courses.append(c) 80 | 81 | def grsGetInfo(self, res: list[dict]) -> None: 82 | for course in self.courses: 83 | for r in res: 84 | if r.get("kcbh") == course.classId: 85 | course.credit = float(r.get("xf", 0)) 86 | course.courseType = r.get("kcxzDm") if r.get( 87 | "kcxzDm") else "" # 课程性质代码 88 | course.courseType += ("(" + r.get("bx") + 89 | ")") if r.get("bx") else "" # 必选修 90 | course.comment = r.get("bz") if r.get("bz") else "" # 备注 91 | course.school = r.get("kkxyMc") if r.get( 92 | "kkxyMc") else "" # 开课学院名称 93 | if course.location == "" and any(x in course.comment for x in ["线上", "录播", "直播"]): 94 | course.location = "线上" 95 | courseInfo = r.get("sjddBz") if r.get( 96 | "sjddBz") else "" # 时间地点备注 97 | course.termInfo = courseInfo.split("
")[0] 98 | 99 | break 100 | 101 | def deDup(self) -> None: 102 | logger.info("研究生:开始去重课程表") 103 | try: 104 | uniqueCourses = {} 105 | for course in self.courses: 106 | key = (course.classId, course.dayOfWeek, course.start, 107 | course.end, course.location, course.teacher) 108 | if key not in uniqueCourses: 109 | uniqueCourses[key] = course 110 | self.courses = list(uniqueCourses.values()) 111 | except Exception as e: 112 | logger.error(f"研究生:课程表去重失败: {e}") 113 | raise e 114 | -------------------------------------------------------------------------------- /zjuam/ugrs.py: -------------------------------------------------------------------------------- 1 | # Undergraduate Students 2 | import re 3 | import json 4 | import time 5 | from zjuam.base import Zjuam 6 | from course.ugrs_course import UGRSCourseTable 7 | from exam.exam import ExamTable 8 | from utils.const import Term 9 | from loguru import logger 10 | from course.convert import ugrsClassTermToQueryString 11 | 12 | 13 | class UgrsZjuam(Zjuam): 14 | COURSE_URL = "https://zdbk.zju.edu.cn/jwglxt/kbcx/xskbcx_cxXsKb.html" 15 | EXAM_URL = "https://zdbk.zju.edu.cn/jwglxt/xskscx/kscx_cxXsgrksIndex.html?doType=query&gnmkdm=N509070&su=%s" # gnmkdm=功能模块代码 16 | ZDBK_LOGIN_URL = "https://zjuam.zju.edu.cn/cas/login?service=https%3A%2F%2Fzdbk.zju.edu.cn%2Fjwglxt%2Fxtgl%2Flogin_ssologin.html" 17 | 18 | def __init__(self, username: str, password: str): 19 | super().__init__(username, password) 20 | 21 | def login(self) -> None: 22 | logger.info("开始通过 ZJUAM 本科生途径登录") 23 | 24 | # stage 1: get csrf key 25 | try: 26 | res = self.r.get(self.ZDBK_LOGIN_URL) 27 | assert res.status_code == 200, "状态码错误" 28 | regex = r"\"execution\" value=\"(.*?)\" \/>" 29 | csrf = re.search(regex, res.text).group(1) 30 | assert csrf, "CSRF Key 为空" 31 | except Exception as e: 32 | logger.error(f"CSRF Key 获取失败: {e}") 33 | raise e 34 | logger.success("CSRF Key 获取成功") 35 | 36 | # stage 2: get pub key 37 | try: 38 | res = self.r.get(self.PUBKEY_URL) 39 | pubkey = res.json() 40 | N, E = pubkey["modulus"], pubkey["exponent"] 41 | N, E = int(N, 16), int(E, 16) 42 | plain = int.from_bytes(self.password.encode(), "big") 43 | cipher = hex(pow(plain, E, N))[2:] 44 | cipher = "0" * (128 - len(cipher)) + cipher 45 | except Exception as e: 46 | logger.error(f"RSA 公钥获取失败: {e}") 47 | raise e 48 | logger.success("RSA 公钥获取成功") 49 | 50 | # stage 3: fire target 51 | try: 52 | res = self.r.post(self.LOGIN_URL, data={ 53 | "username": self.username, 54 | "password": cipher, 55 | "authcode": "", 56 | "execution": csrf, 57 | "_eventId": "submit", 58 | }) 59 | assert "用户名或密码错误" not in res.text, "用户名或密码错误,请确保用户名密码正确后再运行程序,否则有账号被锁定的风险" 60 | assert "账号被锁定" not in res.text, "输错密码次数太多,账号被锁定,请过段时间再使用" 61 | except Exception as e: 62 | logger.error(f"ZJUAM 登录失败: {e}") 63 | raise e 64 | logger.success("ZJUAM 登录成功") 65 | 66 | def getCourses(self, year: str, term: Term, exams: ExamTable) -> UGRSCourseTable: 67 | logger.info(f"开始获取[{year}-{term.value}]课程信息") 68 | res = None 69 | try: 70 | termQuery = ugrsClassTermToQueryString(term) 71 | assert termQuery, "学期参数错误" 72 | res = self.r.post(self.COURSE_URL, data={ 73 | "xnm": year, 74 | "xqm": termQuery, 75 | }) 76 | content = res.json() 77 | 78 | kblist = content["kbList"] 79 | ct = UGRSCourseTable() 80 | ct.fromRes(kblist) 81 | ct.merge() 82 | ct.communicate(exams) 83 | except json.JSONDecodeError as e: 84 | logger.error(f"课程信息获取失败: {e}") 85 | if res is not None: 86 | logger.info(f"返回内容: {res.text}") 87 | raise e 88 | except Exception as e: 89 | logger.error(f"课程信息获取失败: {e}") 90 | raise e 91 | logger.success(f"[{year}-{term.value}]课程信息获取成功") 92 | return ct 93 | 94 | def getExams(self, count: int = 5000) -> ExamTable: 95 | logger.info("开始获取考试信息") 96 | res = None 97 | try: 98 | res = self.r.post(self.EXAM_URL % self.username, data={ 99 | "_search": "false", 100 | "nd": str(int(time.time() * 1000)), 101 | "queryModel.showCount": str(count), 102 | "queryModel.currentPage": "1", 103 | "queryModel.sortName": "xkkh", 104 | "queryModel.sortOrder": "asc", 105 | "time": "0", 106 | }) 107 | content = res.json() 108 | items = content["items"] 109 | et = ExamTable() 110 | et.fromZdbk(items) 111 | except json.JSONDecodeError as e: 112 | logger.error(f"考试信息获取失败: {e}") 113 | if res is not None: 114 | logger.info(f"返回内容: {res.text}") 115 | raise e 116 | except Exception as e: 117 | logger.error(f"考试信息获取失败: {e}") 118 | raise e 119 | logger.success("考试信息获取成功") 120 | return et 121 | -------------------------------------------------------------------------------- /exam/exam.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from utils.const import ExamType 3 | from exam.convert import parseExamDateTime, DUMMY_DATE 4 | from ical.ical import Event 5 | from loguru import logger 6 | from course.course import Course, CourseTable 7 | 8 | 9 | class Exam: 10 | SCHEME_ZDBK = "ZDBK" 11 | 12 | classId: str 13 | name: str 14 | credit: float 15 | examType: ExamType 16 | start: None | datetime 17 | end: None | datetime 18 | location: None | str 19 | seat: None | str 20 | 21 | isEventGenerated: bool 22 | 23 | def __init__(self, raw: dict, scheme: str, examType: ExamType): 24 | if scheme != Exam.SCHEME_ZDBK: 25 | raise NotImplementedError("不支持的考试查询方案") 26 | 27 | self.isEventGenerated = False 28 | 29 | self.examType = examType 30 | self.classId = raw["xkkh"][:22] # 选课课号 31 | self.name = raw["kcmc"].replace("(", "(").replace(")", ")") # 课程名称 32 | self.credit = float(raw["xf"]) # 学分 33 | 34 | if examType == ExamType.FinalTerm: 35 | self.start, self.end = parseExamDateTime(raw["kssj"]) # 考试时间 36 | self.location = raw.get("jsmc", None) # 教室名称 37 | self.seat = raw.get("zwxh", None) # 座位序号 38 | elif examType == ExamType.MidTerm: 39 | self.start, self.end = parseExamDateTime(raw["qzkssj"]) # 期中考试时间 40 | self.location = raw.get("qzjsmc", None) # 期中教室名称 41 | self.seat = raw.get("qzzwxh", None) 42 | else: 43 | self.start = None 44 | self.end = None 45 | self.location = None 46 | self.seat = None 47 | 48 | if self.start == self.end == DUMMY_DATE: 49 | logger.info( 50 | f"{self.examType.value}: {self.name} {self.classId} (考试时间获取失败,可能是由于校历未发布无法计算时间,通常不影响当前学期日历,请参见 GitHub #3)") 51 | logger.info(f"{self.examType.value}: {self.name} {self.classId}") 52 | 53 | def __repr__(self) -> str: 54 | res = "Exam(\n" 55 | res += f" name={self.name},\n" 56 | res += f" examType={self.examType},\n" 57 | res += f" start={self.start},\n" 58 | res += f" end={self.end},\n" 59 | res += f" location={self.location}\n" 60 | res += ")" 61 | return res 62 | 63 | @property 64 | def summary(self) -> str: 65 | return f"[务必核对!]{self.name} {self.examType.value}" 66 | 67 | @property 68 | def locationString(self) -> str: 69 | res = "" 70 | if self.location is not None: 71 | res += self.location 72 | else: 73 | res += "地点待定" 74 | if self.seat is not None: 75 | res += f" (座位号: {self.seat})" 76 | return res 77 | 78 | @property 79 | def description(self) -> str: 80 | return "学分: %.1f" % self.credit 81 | 82 | 83 | class ExamTable: 84 | exams: list[Exam] 85 | 86 | def __init__(self): 87 | self.exams: list[Exam] = [] 88 | 89 | def __repr__(self) -> str: 90 | return str(self.exams) 91 | 92 | def fromZdbk(self, raw: list[dict]) -> None: 93 | ZDBK = Exam.SCHEME_ZDBK 94 | for item in raw: 95 | if "qzkssj" in item: 96 | self.exams.append(Exam(item, ZDBK, ExamType.MidTerm)) 97 | if "kssj" in item: 98 | self.exams.append(Exam(item, ZDBK, ExamType.FinalTerm)) 99 | if "qzkssj" not in item and "kssj" not in item: 100 | self.exams.append(Exam(item, ZDBK, ExamType.NoExam)) 101 | 102 | def find(self, course: "Course") -> list[Exam]: 103 | res = [] 104 | for exam in self.exams: 105 | if exam.classId == course.classId: 106 | assert exam.name == course.name 107 | res.append(exam) 108 | return res 109 | 110 | def toEvents(self, courses: "CourseTable") -> list[Event]: 111 | logger.info("开始生成考试日历事件") 112 | 113 | try: 114 | events: list[Event] = [] 115 | 116 | for course in courses.courses: 117 | for exam in self.find(course): 118 | if exam.examType == ExamType.NoExam: 119 | continue 120 | if exam.isEventGenerated: 121 | continue 122 | 123 | desc_tail = f"\\n教师: {course.teacher}" 124 | 125 | exam.isEventGenerated = True 126 | events.append(Event( 127 | summary=exam.summary, 128 | location=exam.locationString, 129 | description=exam.description + desc_tail, 130 | start=exam.start, 131 | end=exam.end 132 | )) 133 | except Exception as e: 134 | logger.error(f"考试日历事件生成失败: {e}") 135 | raise e 136 | 137 | return events 138 | -------------------------------------------------------------------------------- /zjuam/grs.py: -------------------------------------------------------------------------------- 1 | # Undergraduate Students 2 | import re 3 | from zjuam.base import Zjuam 4 | from course.grs_course import GRSCourseTable 5 | from exam.exam import ExamTable 6 | from utils.const import Term 7 | from loguru import logger 8 | from course.convert import grsGetYear, grsClassTermToQueryString 9 | from urllib.parse import urlparse, parse_qs 10 | import json 11 | 12 | 13 | class GrsZjuam(Zjuam): 14 | COURSE_URL = "https://yjsy.zju.edu.cn/dataapi/py/pyKcbj/queryXskbByLoginUser?" 15 | EXAM_URL = "https://yjsy.zju.edu.cn/dashboard/workplace?dm=py_grks" 16 | INFO_URL = "https://yjsy.zju.edu.cn/dataapi/py/pyXsxk/queryXsxkByXnxqXs" 17 | YJSY_LOGIN_URL = "https://zjuam.zju.edu.cn/cas/login?service=https%3A%2F%2Fyjsy.zju.edu.cn%2F" 18 | YJSY_TOKEN_URL = "https://yjsy.zju.edu.cn/dataapi/sys/cas/client/validateLogin?service=https:%2F%2Fyjsy.zju.edu.cn%2F" 19 | 20 | def __init__(self, username: str, password: str): 21 | super().__init__(username, password) 22 | 23 | def login(self) -> None: 24 | logger.info("开始通过 ZJUAM 研究生途径登录") 25 | 26 | # stage 1: get csrf key 27 | try: 28 | res = self.r.get(self.YJSY_LOGIN_URL) 29 | assert res.status_code == 200, "状态码错误" 30 | regex = r"\"execution\" value=\"(.*?)\" \/>" 31 | csrf = re.search(regex, res.text).group(1) 32 | assert csrf, "CSRF Key 为空" 33 | except Exception as e: 34 | logger.error(f"CSRF Key 获取失败: {e}") 35 | raise e 36 | logger.success("CSRF Key 获取成功") 37 | 38 | # stage 2: get pub key 39 | try: 40 | res = self.r.get(self.PUBKEY_URL) 41 | pubkey = res.json() 42 | N, E = pubkey["modulus"], pubkey["exponent"] 43 | N, E = int(N, 16), int(E, 16) 44 | plain = int.from_bytes(self.password.encode(), "big") 45 | cipher = hex(pow(plain, E, N))[2:] 46 | cipher = "0" * (128 - len(cipher)) + cipher 47 | except Exception as e: 48 | logger.error(f"RSA 公钥获取失败: {e}") 49 | raise e 50 | logger.success("RSA 公钥获取成功") 51 | 52 | # stage 3: fire target 53 | try: 54 | res = self.r.post(self.LOGIN_URL, data={ 55 | "username": self.username, 56 | "password": cipher, 57 | "authcode": "", 58 | "execution": csrf, 59 | "_eventId": "submit", 60 | }) 61 | assert "用户名或密码错误" not in res.text, "用户名或密码错误,请确保用户名密码正确后再运行程序,否则有账号被锁定的风险" 62 | assert "账号被锁定" not in res.text, "输错密码次数太多,账号被锁定,请过段时间再使用" 63 | self.sso_cookie = { 64 | 'iPlanetDirectoryPro': self.r.cookies['iPlanetDirectoryPro']} 65 | except Exception as e: 66 | logger.error(f"ZJUAM 登录失败: {e}") 67 | raise e 68 | logger.success("ZJUAM 登录成功") 69 | 70 | # stage 4: login yjsy 71 | try: 72 | # 第一步:使用SSO Cookie获取ticket 73 | response = self.r.get( 74 | self.YJSY_LOGIN_URL, 75 | cookies=self.sso_cookie, 76 | allow_redirects=False # 不自动跟随重定向 77 | ) 78 | 79 | # 检查重定向位置 80 | location_header = response.headers.get('location') 81 | if not location_header: 82 | raise Exception("Invalid location header") 83 | 84 | # 从重定向URL中提取ticket参数 85 | parsed_url = urlparse(location_header) 86 | query_params = parse_qs(parsed_url.query) 87 | ticket = query_params.get('ticket', [None])[0] 88 | if not ticket: 89 | raise Exception("Invalid location header - no ticket found") 90 | 91 | # 第二步:使用ticket获取token 92 | second_url = self.YJSY_TOKEN_URL + f"&ticket={ticket}" 93 | response = self.r.get(second_url) 94 | 95 | # 解析JSON响应 96 | login_info = response.json() 97 | if not login_info.get("success"): 98 | raise Exception("Invalid login info") 99 | 100 | login_result = login_info.get("result", {}) 101 | self._token = login_result.get("token") 102 | 103 | if not self._token: 104 | raise Exception("Invalid token") 105 | except Exception as e: 106 | logger.error(f"YJSY 登录失败: {e}") 107 | raise e 108 | logger.success("YJSY 登录成功") 109 | 110 | def getCourses(self, year: str, term: Term, exams: ExamTable) -> GRSCourseTable: 111 | logger.info(f"开始获取[{year}-{term.value}]课程信息") 112 | try: 113 | year = grsGetYear(year, term) 114 | termQuery = grsClassTermToQueryString(term) 115 | assert year, "学年参数错误" 116 | assert termQuery, "学期参数错误" 117 | 118 | courseUrl = self.COURSE_URL + f"xn={year}&pkxq={termQuery}" 119 | res = self.r.get(courseUrl, headers={ 120 | "X-Access-Token": self._token}).json() 121 | if not res.get("success"): 122 | raise Exception("课程信息获取失败") 123 | res = res["result"]["kcbMap"] 124 | ct = GRSCourseTable() 125 | ct.fromRes(res) 126 | ct.deDup() 127 | 128 | res = self.r.post(self.INFO_URL, headers={ 129 | "X-Access-Token": self._token}).json() 130 | if not res.get("success"): 131 | raise Exception("课程附加信息获取失败") 132 | res = res["result"]["xxjhnList"] 133 | ct.grsGetInfo(res) 134 | 135 | except Exception as e: 136 | logger.error(f"课程信息获取失败: {e}") 137 | raise e 138 | logger.success(f"[{year}-{term.value}]课程信息获取成功") 139 | return ct 140 | 141 | # TODO: implement exam fetching for graduate system 142 | def getExams(self, count: int = 5000) -> ExamTable: 143 | logger.info("研究生系统暂未适配考试信息查询") 144 | return None 145 | -------------------------------------------------------------------------------- /course/course.py: -------------------------------------------------------------------------------- 1 | from utils.const import Term, WeekType, TweakMethod 2 | from utils.config import config, TermConfig 3 | from loguru import logger 4 | from datetime import date, datetime, timedelta 5 | from course.convert import isEvenWeek, periodToTime, dayOfWeekToWeekString 6 | from ical.ical import Event 7 | from abc import ABC, abstractmethod 8 | 9 | 10 | def daterange(start: date, end: date): 11 | days = int((end - start).days) 12 | for n in range(days): 13 | yield start + timedelta(n) 14 | 15 | 16 | class Course(ABC): 17 | 18 | weekType: WeekType 19 | start: int 20 | end: int 21 | teacher: str 22 | classId: str 23 | name: str 24 | location: str 25 | terms: list[Term] 26 | dayOfWeek: int 27 | credit: None | float 28 | 29 | @abstractmethod 30 | def __init__(self, raw: dict): 31 | pass 32 | 33 | def __repr__(self) -> str: 34 | res = "Course(\n" 35 | res += f" name={self.name},\n" 36 | res += f" weekType={self.weekType},\n" 37 | res += f" dayOfWeek={self.dayOfWeek},\n" 38 | res += f" start={self.start},\n" 39 | res += f" end={self.end}\n" 40 | res += ")" 41 | return res 42 | 43 | def overlap(self, other: "Course") -> bool | tuple[int, int]: 44 | if self.classId != other.classId: 45 | return False 46 | if self.dayOfWeek != other.dayOfWeek: 47 | return False 48 | if self.weekType != other.weekType: 49 | return False 50 | if self.location != other.location: 51 | return False 52 | if self.teacher != other.teacher: 53 | return False 54 | 55 | if self.start > other.start: 56 | return other.overlap(self) 57 | 58 | if self.end < other.start: 59 | return False 60 | 61 | assert self.end == other.start, "相同课程不应该发生重叠,请联系开发者" 62 | return self.start, other.end 63 | 64 | def isInTerm(self, term: Term) -> bool: 65 | return term in self.terms 66 | 67 | def getStartDateTime(self, day: date) -> datetime: 68 | time = periodToTime(self.start) 69 | return datetime(day.year, day.month, day.day, time.hour, time.minute) 70 | 71 | def getEndDateTime(self, day: date) -> datetime: 72 | time = periodToTime(self.end - 1) 73 | dt = timedelta(minutes=45) 74 | return datetime(day.year, day.month, day.day, time.hour, time.minute) + dt 75 | 76 | def setTerms(self, termsStr: str) -> None: 77 | self.terms = [] 78 | if "春" in termsStr: 79 | self.terms.append(Term.Spring) 80 | if "夏" in termsStr: 81 | self.terms.append(Term.Summer) 82 | if "秋" in termsStr: 83 | self.terms.append(Term.Autumn) 84 | if "冬" in termsStr: 85 | self.terms.append(Term.Winter) 86 | if any([x not in "春夏秋冬" for x in termsStr]): 87 | raise NotImplementedError(f"当前学期安排 {termsStr} 不在支持范围内,欢迎提交 PR") 88 | 89 | def printLog(self) -> None: 90 | weekString = dayOfWeekToWeekString(self.dayOfWeek) 91 | logger.info(f"{self.name}: {weekString} / {self.start}-{self.end - 1}") 92 | 93 | @abstractmethod 94 | def setWeekType(self, raw: str) -> None: 95 | pass 96 | 97 | @property 98 | @abstractmethod 99 | def description(self) -> str: 100 | res = f"教师: {self.teacher}" 101 | if self.credit is not None: 102 | res += "\\n学分: %.1f" % self.credit 103 | return res 104 | 105 | 106 | class CourseTable(ABC): 107 | 108 | def __init__(self): 109 | self.courses: list[Course] = [] 110 | 111 | def __repr__(self) -> str: 112 | return str(self.courses) 113 | 114 | @abstractmethod 115 | def fromRes(self, res) -> None: 116 | pass 117 | 118 | def GetClassOfDay(self, day: int, term: int) -> list[Course]: 119 | res = [] 120 | for course in self.courses: 121 | if course.dayOfWeek == day and course.isInTerm(term): 122 | res.append(course) 123 | return res 124 | 125 | def toEvents(self, termConfig: TermConfig) -> list[Event]: 126 | logger.info("开始生成课程表日历事件") 127 | 128 | try: 129 | termBegin = termConfig.Begin 130 | termEnd = termConfig.End 131 | 132 | oneDay = timedelta(days=1) 133 | 134 | shadowDates = {} 135 | modDescriptions = {} 136 | 137 | for d in daterange(termBegin, termEnd + oneDay): 138 | shadowDates[d] = d 139 | 140 | tweaks = config.tweaks 141 | for tweak in tweaks: 142 | if tweak.To < termBegin or tweak.From > termEnd: 143 | continue 144 | if tweak.TweakType == TweakMethod.Clear: 145 | for d in daterange(tweak.From, tweak.To + oneDay): 146 | del shadowDates[d] 147 | elif tweak.TweakType == TweakMethod.Copy: 148 | shadowDates[tweak.To] = tweak.From 149 | modDescriptions[tweak.To] = tweak.Description 150 | elif tweak.TweakType == TweakMethod.Move: 151 | shadowDates[tweak.To] = tweak.From 152 | del shadowDates[tweak.From] 153 | modDescriptions[tweak.From] = tweak.Description 154 | elif tweak.TweakType == TweakMethod.Exchange: 155 | shadowDates[tweak.To] = tweak.From 156 | shadowDates[tweak.From] = tweak.To 157 | modDescriptions[tweak.To] = tweak.Description 158 | modDescriptions[tweak.From] = tweak.Description 159 | elif tweak.TweakType == TweakMethod.Pending: 160 | pass 161 | else: 162 | raise ValueError(f"未知的调整类型: {tweak.TweakType}") 163 | 164 | classOfDay = {} 165 | for i in range(1, 8): 166 | classOfDay[i] = self.GetClassOfDay(i, termConfig.Term) 167 | 168 | termBeginDayOfWeek = termBegin.weekday() + 1 169 | mondayOfFirstWeek = termBegin - \ 170 | timedelta(days=termBeginDayOfWeek - 1) - \ 171 | timedelta(weeks=termConfig.FirstWeekNo - 1) 172 | 173 | events: list[Event] = [] 174 | 175 | for actualDate, dateOfClass in shadowDates.items(): 176 | classesOfCurrentDate = classOfDay[dateOfClass.weekday() + 1] 177 | isCurrentDateEvenWeek = isEvenWeek( 178 | mondayOfFirstWeek, dateOfClass) 179 | for course in classesOfCurrentDate: 180 | if isCurrentDateEvenWeek and course.weekType == WeekType.OddOnly: 181 | continue 182 | if not isCurrentDateEvenWeek and course.weekType == WeekType.EvenOnly: 183 | continue 184 | 185 | description = course.description 186 | if dateOfClass in modDescriptions: 187 | description = modDescriptions[dateOfClass] + \ 188 | "\\n\\n" + description 189 | 190 | events.append(Event( 191 | summary=course.name, 192 | location=course.location, 193 | description=description, 194 | start=course.getStartDateTime(actualDate), 195 | end=course.getEndDateTime(actualDate) 196 | )) 197 | except Exception as e: 198 | logger.error(f"课程表日历事件生成失败: {e}") 199 | raise e 200 | 201 | return events 202 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | --------------------------------------------------------------------------------