-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
342 lines (291 loc) · 8.24 KB
/
main.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gocolly/colly"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
tasksapi "google.golang.org/api/tasks/v1"
)
type SceleClient struct {
Username string
Password string
Excluded_Courses []int
Excluded_Keywords []string
Client *http.Client
Cookie []*http.Cookie
}
type SceleConfig struct {
Username string `json:"username"`
Password string `json:"password"`
Excluded_Courses []int `json:"excluded_courses"`
Excluded_Keywords []string `json:"excluded_keywords"`
}
type SceleLoginForm struct {
username string
password string
logintoken string
}
type Task struct {
Name string
Course string
Deadline time.Time
URL string
Excluded bool
}
func NewSceleClient(scele_config SceleConfig) *SceleClient {
jar, _ := cookiejar.New(nil)
return &SceleClient{
scele_config.Username,
scele_config.Password,
scele_config.Excluded_Courses,
scele_config.Excluded_Keywords,
&http.Client{Jar: jar},
[]*http.Cookie{},
}
}
func (sc *SceleClient) NewCollector() *colly.Collector {
c := colly.NewCollector()
c.SetCookies("https://scele.cs.ui.ac.id/", sc.Cookie)
return c
}
func (sc *SceleClient) Login() bool {
log.Println("Logging in to SCeLe...")
req, _ := http.NewRequest("GET", "https://scele.cs.ui.ac.id/login/index.php", nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246")
response, err := sc.Client.Do(req)
if err != nil {
log.Fatalln(err)
return false
}
document, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
log.Fatalln(err)
return false
}
var token string
document.Find("input").Map(func(i int, s *goquery.Selection) string {
name, _ := s.Attr("name")
if name == "logintoken" {
token, _ = s.Attr("value")
}
return ""
})
response, err = sc.Client.PostForm("https://scele.cs.ui.ac.id/login/index.php",
map[string][]string{
"username": {sc.Username},
"password": {sc.Password},
"anchor": {""},
"logintoken": {token},
})
if err != nil {
log.Fatalln(err.Error())
return false
}
url, _ := url.Parse("https://scele.cs.ui.ac.id/")
if sc.Client.Jar.Cookies(url)[0].Name == "MoodleSession" {
sc.Cookie = sc.Client.Jar.Cookies(url)
return true
}
return false
}
func (sc *SceleClient) GetTask(event_url string) Task {
c := sc.NewCollector()
re := regexp.MustCompile(`(?P<event_id>#.*)$`)
matches := re.FindStringSubmatch(event_url)
event_id := matches[re.SubexpIndex("event_id")]
log.Printf("Fetching details from event_id: %v\n", event_id)
var task Task
c.OnHTML(event_id, func(h *colly.HTMLElement) {
var task_name string
var task_url string
var task_course string
var task_excluded bool = true
h.DOM.Find("a[href]").Map(func(i int, s *goquery.Selection) string {
href, _ := s.Attr("href")
if strings.Contains(href, "assign") && !strings.Contains(href, "&action=") {
task_name = s.Text()
task_url = href
}
if strings.Contains(href, "course") && !strings.Contains(href, "update") {
re := regexp.MustCompile(`\?id=(?P<course_id>\d*)$`)
matches := re.FindStringSubmatch(href)
course_id, _ := strconv.Atoi(matches[re.SubexpIndex("course_id")])
if !slices.Contains(sc.Excluded_Courses, course_id) {
task_course = s.Text()
task_excluded = false
}
}
return ""
})
re := regexp.MustCompile(`&time=(?P<epoch>\d*)`)
matches := re.FindStringSubmatch(event_url)
epoch_time, _ := strconv.Atoi(matches[re.SubexpIndex("epoch")])
loc, _ := time.LoadLocation("Asia/Bangkok")
task = Task{
Name: task_name,
URL: task_url,
Course: task_course,
Deadline: time.Unix(int64(epoch_time), 0).In(loc),
Excluded: task_excluded,
}
})
c.Visit(event_url)
return task
}
func (sc *SceleClient) FetchCurrentTasks() []Task {
log.Println("Fetching tasks from SCeLE...")
c := sc.NewCollector()
tasks := make([]Task, 0)
c.OnHTML("li", func(h *colly.HTMLElement) {
h.DOM.Children().Map(func(i int, s *goquery.Selection) string {
href, _ := s.Attr("href")
if strings.Contains(href, "&time=") {
event := s.Nodes[0]
for _, keyword := range sc.Excluded_Keywords {
if strings.Contains(event.FirstChild.Data, keyword) {
return ""
}
}
task := sc.GetTask(event.Attr[0].Val)
if task.Deadline.Before(time.Now()) {
return ""
}
if task.Excluded {
return ""
}
tasks = append(tasks, task)
}
return ""
})
})
c.Visit("https://scele.cs.ui.ac.id/calendar/view.php?view=month")
return tasks
}
func getClient(config *oauth2.Config) *http.Client {
tokFile := "token.json"
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
func saveToken(path string, token *oauth2.Token) {
log.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
func fetch() {
log.Println("Starting fetch...")
ctx := context.Background()
b, err := os.ReadFile("config.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, tasksapi.TasksScope, tasksapi.TasksReadonlyScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
api, err := tasksapi.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve tasks Client %v", err)
}
tasklist, _ := api.Tasklists.List().MaxResults(1).Do()
fetched_tasks, _ := api.Tasks.List(tasklist.Items[0].Id).Do(googleapi.QueryParameter("showHidden", "true"))
var existing_tasks []string
for _, task := range fetched_tasks.Items {
existing_tasks = append(existing_tasks, task.Notes)
}
scele_config_file, err := os.Open("scele_config.json")
if err != nil {
log.Fatalln("SCeLe config not found!")
}
var scele_config SceleConfig
json.NewDecoder(scele_config_file).Decode(&scele_config)
sc := NewSceleClient(scele_config)
ok := sc.Login()
if !ok {
log.Fatalln("Cannot login!")
}
log.Println("Login to SCeLe successful!")
tasks := sc.FetchCurrentTasks()
for _, task := range tasks {
if task.Name == "" {
continue
}
if slices.Contains(existing_tasks, task.Course+"\n"+task.URL) {
log.Printf("Task \"%v\" already exists, skipping...\n", task.Name)
continue
}
task_obj := tasksapi.Task{
Title: task.Name,
Due: task.Deadline.AddDate(0, 0, 1).Format(time.RFC3339),
Notes: task.Course + "\n" + task.URL,
}
_, err = api.Tasks.Insert(tasklist.Items[0].Id, &task_obj).Do()
if err != nil {
log.Fatalln(err)
}
log.Printf("Created task \"%v\"\n", task.Name)
}
log.Printf("Finished fetching!")
}
func ShouldRun() bool {
loc, _ := time.LoadLocation("Asia/Bangkok")
current_time := time.Now().In(loc)
is_9am := current_time.Hour() == 9 && current_time.Minute() == 0 && current_time.Second() == 0
is_9pm := current_time.Hour() == 21 && current_time.Minute() == 0 && current_time.Second() == 0
return is_9am || is_9pm
}
func main() {
fetch()
for {
if ShouldRun() {
fetch()
}
}
}