forked from neucn/elise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
215 lines (184 loc) · 6.04 KB
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package elise
import (
"errors"
"fmt"
"github.com/neucn/neugo"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
const (
defaultCourseTableUrl = "http://219.216.96.4/eams/courseTableForStd.action"
defaultCourseTableActionUrl = "http://219.216.96.4/eams/courseTableForStd!courseTable.action"
defaultCurrentWeekUrl = "http://219.216.96.4/eams/homeExt.action"
)
type session struct {
courseTableUrl,
courseTableActionUrl,
currentWeekUrl string
client *http.Client
}
type GenerateFunc func(courses []*Course, startDay time.Time, output string) (path string, err error)
func (s *session) Generate(generateFunc GenerateFunc, output string) (path string, err error) {
var body string
if body, err = s.getCourseTablePage(); err != nil {
return
}
var week int
if week, err = s.getCurrentWeek(); err != nil {
return
}
startDay := getSemesterStartDay(week)
fmt.Println("当前为第", week, "教学周")
fmt.Println("计算得到本学期开始于", startDay.Format("2006-01-02"))
fmt.Println("官方校历 http://www.neu.edu.cn/xl/list.htm")
fmt.Println("\n======开始生成课程表======")
courses := parseCourses(body)
path, err = generateFunc(courses, startDay, output)
fmt.Println("\n======课程表生成成功======")
return
}
func (s *session) getCourseTablePage() (content string, err error) {
var resp *http.Response
// 发送
if resp, err = s.client.Get(s.courseTableUrl); err != nil {
return
}
// 读取
if content, err = readBody(resp); err != nil {
return
}
// 检查
if !strings.Contains(content, "bg.form.addInput(form,\"ids\",\"") {
return "", errors.New("获取必要参数ids失败")
}
content = content[strings.Index(content, "bg.form.addInput(form,\"ids\",\"")+29 : strings.Index(content, "bg.form.addInput(form,\"ids\",\"")+50]
ids := content[:strings.Index(content, "\");")]
semesterId := resp.Cookies()[0].Value
// 第二次请求
requestBody := fmt.Sprintf(
"ignoreHead=1&showPrintAndExport=1&setting.kind=std&startWeek=&semester.id=%s&ids=%s",
semesterId, ids)
req, _ := http.NewRequest(http.MethodPost, s.courseTableActionUrl, strings.NewReader(requestBody))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36")
// 发送
if resp, err = s.client.Do(req); err != nil {
return
}
// 读取
if content, err = readBody(resp); err != nil {
return
}
// 检查
if !strings.Contains(content, "课表格式说明") {
return "", errors.New("获取课表失败")
}
return
}
func (s *session) getCurrentWeek() (week int, err error) {
var resp *http.Response
var content string
// 发送
if resp, err = s.client.Get(s.currentWeekUrl); err != nil {
return
}
// 读取
if content, err = readBody(resp); err != nil {
return
}
// 检查
if !strings.Contains(content, "教学周") {
return 0, errors.New("获取当前教学周失败")
}
content = content[strings.Index(content, "id=\"teach-week\">") : strings.Index(content, "教学周")+10]
reg := regexp.MustCompile(`学期\s*<font size="\d+px">(\d+)</font>\s*教学周`)
res := reg.FindStringSubmatch(content)
if len(res) < 2 {
return 0, errors.New("无法获取当前教学周")
}
return strconv.Atoi(res[1])
}
type Generator interface {
// 传入一个解析函数与目标输出路径,返回一个最终的绝对路径与错误
Generate(generateFunc GenerateFunc, output string) (path string, err error)
}
var _ Generator = &session{}
func New(username, password string, webVPN bool) (Generator, error) {
s := new(session)
var platform neugo.Platform
if webVPN {
platform = neugo.WebVPN
s.currentWeekUrl = neugo.EncryptURLToWebVPN(defaultCurrentWeekUrl)
s.courseTableUrl = neugo.EncryptURLToWebVPN(defaultCourseTableUrl)
s.courseTableActionUrl = neugo.EncryptURLToWebVPN(defaultCourseTableActionUrl)
} else {
platform = neugo.CAS
s.currentWeekUrl = defaultCurrentWeekUrl
s.courseTableUrl = defaultCourseTableUrl
s.courseTableActionUrl = defaultCourseTableActionUrl
}
client := neugo.NewSession()
if err := neugo.Use(client).WithAuth(username, password).Login(platform); err != nil {
return nil, err
}
s.client = client
return s, nil
}
func readBody(resp *http.Response) (string, error) {
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
_ = resp.Body.Close()
return string(content), nil
}
func getSemesterStartDay(week int) time.Time {
now := time.Now()
location := time.FixedZone("UTC+8", 8*60*60)
daySum := int(now.Weekday()) + week*7 - 7
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, location).
AddDate(0, 0, -daySum)
}
// 课程信息
type Course struct {
ID string
Name string
RoomID string
RoomName string
Weeks string
CourseTimes []CourseTime
}
// 课程具体时间,周几第几节
type CourseTime struct {
DayOfTheWeek int
TimeOfTheDay int
}
func parseCourses(body string) []*Course {
var courses []*Course
reg1 := regexp.MustCompile(`TaskActivity\(actTeacherId.join\(','\),actTeacherName.join\(','\),"(.*)","(.*)\(.*\)","(.*)","(.*)","(.*)",null,null,assistantName,"",""\);((?:\s*index =\d+\*unitCount\+\d+;\s*.*\s)+)`)
reg2 := regexp.MustCompile(`\s*index =(\d+)\*unitCount\+(\d+);\s*`)
coursesStr := reg1.FindAllStringSubmatch(body, -1)
for _, courseStr := range coursesStr {
course := &Course{}
course.ID = courseStr[1]
course.Name = courseStr[2]
course.RoomID = courseStr[3]
course.RoomName = courseStr[4]
course.Weeks = courseStr[5]
for _, indexStr := range strings.Split(courseStr[6], "table0.activities[index][table0.activities[index].length]=activity;") {
if !strings.Contains(indexStr, "unitCount") {
continue
}
var courseTime CourseTime
courseTime.DayOfTheWeek, _ = strconv.Atoi(reg2.FindStringSubmatch(indexStr)[1])
courseTime.TimeOfTheDay, _ = strconv.Atoi(reg2.FindStringSubmatch(indexStr)[2])
course.CourseTimes = append(course.CourseTimes, courseTime)
}
courses = append(courses, course)
}
return courses
}