-
Notifications
You must be signed in to change notification settings - Fork 0
/
hybus.js
503 lines (411 loc) · 15.6 KB
/
hybus.js
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
"use strict";
// This scriptable widget is from https://github.com/BusHanyang/hybus-ios-widget
// By Taewan Park
const VERSION = '1.1.0';
const API_URL = 'https://api.hybus.app/';
const getTimetable = async (week, season, location) => {
const url = `${API_URL}/timetable/${season}/${week}/${location}`;
let req = new Request(url);
const result = req.loadJSON().then((response) => {
if (response["error"] !== undefined) {
return Array(1);
}
return response
}).catch((error) => {
console.error(error);
return Array(2);
})
return result;
}
const getSettings = async () => {
const url = `${API_URL}/settings/`;
let req = new Request(url);
const result = req.loadJSON().then((response) => {
if (response["error"] !== undefined) {
return {};
}
return response
}).catch((error) => {
console.error(error);
return {};
})
return result;
}
const convertLocationString = (loc) => {
if (loc == "셔틀콕") {
return "shuttlecoke_o"
} else if (loc == "한대앞") {
return "subway"
} else if (loc == "예술인") {
return "yesulin"
} else if (loc == "중앙역") {
return "jungang"
} else if (loc == "기숙사") {
return "residence"
} else if (loc == "건너편") {
return "shuttlecoke_i"
}
return "invalid"
}
const isWeekend = () => {
const today = new Date();
const day = today.getDay();
return day == 0 || day == 6;
}
const getSeason = (settings) => {
const today = new Date();
if (settings == null || settings == undefined) {
return ['error', '']
}
try {
const [semesterStart, semesterEnd] = [new Date(settings["semester"]["start_date"]), new Date(`${settings["semester"]["end_date"]}T23:59:59+09:00`)];
const [vacationSessionStart, vacationSessionEnd] = [new Date(settings["vacation_session"]["start_date"]), new Date(`${settings["vacation_session"]["end_date"]}T23:59:59+09:00`)];
const [vacationStart, vacationEnd] = [new Date(settings["vacation"]["start_date"]), new Date(`${settings["vacation"]["end_date"]}T23:59:59+09:00`)];
const todayUnix = +today; // In milliseconds, not to do /1000 operation in all comparisons
const convertedHoliday = settings["holiday"].map((s) => { return new Date(s) });
const convertedHaltday = settings["halt"].map((s) => { return new Date(s) });
let isHoliday = false
for (const holiday of convertedHoliday) {
if (
today.getFullYear() == holiday.getFullYear() &&
today.getMonth() == holiday.getMonth() &&
today.getDate() == holiday.getDate()
) {
isHoliday = true;
break;
}
}
for (const haltDay of convertedHaltday) {
if (
today.getFullYear() == haltDay.getFullYear() &&
today.getMonth() == haltDay.getMonth() &&
today.getDate() == haltDay.getDate()
) {
return ['halt', '']
}
}
if (+semesterStart < todayUnix && todayUnix < +semesterEnd) {
// Semester
if (isWeekend() || isHoliday) {
return ['semester', 'weekend']
} else {
return ['semester', 'week']
}
} else if (
+vacationSessionStart < todayUnix &&
todayUnix < +vacationSessionEnd
) {
// Vacation Session
if (isWeekend() || isHoliday) {
return ['vacation_session', 'weekend']
} else {
return ['vacation_session', 'week']
}
} else if (
+vacationStart < todayUnix &&
todayUnix < +vacationEnd
) {
// Vacation
if (isWeekend() || isHoliday) {
return ['vacation', 'weekend']
} else {
return ['vacation', 'week']
}
} else {
// Error!
return ['error', '']
}
} catch (error) {
return ['error', '']
}
}
const isAfterCurrentTime = (sch) => {
const today = new Date();
const timestamp = +today
const year = today.getFullYear();
let month = `${today.getMonth() + 1}`;
let date = `${today.getDate()}`;
if (month.length == 1) { month = `0${month}`}
if (date.length == 1) { date = `0${date}`}
const schedule = new Date(`${year}-${month}-${date}T${sch["time"]}:00+09:00`);
return +schedule - timestamp >= 0
}
const getDestinationType = (busType, loc) => {
if (loc == 'shuttlecoke_o') {
if (busType == 'C' || busType == 'DH' || busType == 'DHJ') {
return '한대앞행'
} else if (busType == 'DY') {
return '예술인행'
} else {
return '로딩중..'
}
} else if (loc == 'subway') {
if (busType == 'C') {
return '예술인행'
} else if (busType == 'DHJ') {
return '중앙역행'
} else {
return '캠퍼스행'
}
} else if (loc == 'yesulin') {
return '캠퍼스행'
} else if (loc == 'jungang') {
return '캠퍼스행'
} else if (loc == 'shuttlecoke_i') {
if (busType == 'NA') {
return '행선지X'
} else if (busType == 'R') {
return '기숙사행'
} else {
return '로딩중..'
}
} else if (loc == 'residence') {
return '셔틀콕행'
} else {
return '로딩중..'
}
}
const getCurrentInfo = async (loc) => {
// Based on hybus-genesis/Card.tsx
const settings = await getSettings();
if (settings == {} || settings == null || settings == undefined) {
console.log("Error while retrieving settings");
return [];
}
const [s, w] = getSeason(settings);
if (s === 'error' || s === 'halt') {
return "오늘 운행하는 셔틀이 없습니다."
}
const timetable = await getTimetable(w, s, loc);
if (timetable.length === 0) {
// No shuttle bus for today
return "오늘 운행하는 셔틀이 없습니다."
} else if (timetable.length === 1) {
// Input error
return "시간표를 불러오는 중 오류가 발생했습니다."
} else if (timetable.length === 2) {
// Network error
return "네트워크 오류입니다."
}
const filteredTimetable = timetable.filter(isAfterCurrentTime);
if (filteredTimetable.length == 0) {
// Service is done for today
return "오늘 셔틀 운행이 종료되었습니다."
}
const converted = filteredTimetable.map((sch, i) => {
if (i < 2) {
return { "time": sch["time"], "destination": getDestinationType(sch["type"], loc) }
}
})
const result = converted.filter((sch) => sch);
return result
}
const generateAlert = async (message, options) => {
let alert = new Alert()
alert.message = message
for (const option of options) {
alert.addAction(option)
}
let response = await alert.presentAlert()
return response
}
const updateCode = async () => {
let files = FileManager.local()
const usingiCloud = files.isFileStoredIniCloud(module.filename)
files = usingiCloud ? FileManager.iCloud() : files
const UPDATE_URL = "https://raw.githubusercontent.com/BusHanyang/hybus-ios-widget/main/hybus.js"
let req = new Request(UPDATE_URL);
let code = await req.loadString().then((response) => {
if (!(response.substring(0, 15).includes("use strict"))) {
return null
}
return response
}).catch((error) => {
console.log(error);
return null;
})
if (code === null) {
await generateAlert("업데이트에 실패했습니다.", ["확인"]);
} else {
files.writeString(module.filename, code);
await generateAlert("업데이트에 성공했습니다. 스크립트를 닫고, 재시작해 주세요.", ["확인"]);
}
}
const createMediumWidget = async () => {
let widget = new ListWidget();
widget.url = "https://hybus.app";
let mainStack = widget.addStack();
mainStack.layoutHorizontally();
let locationStack = mainStack.addStack()
let simpleGradient = new LinearGradient()
simpleGradient.colors = [new Color("102027"), new Color("001148")]
simpleGradient.locations = [0, 1]
widget.backgroundGradient = simpleGradient
var location = null;
if (config.runsInWidget) {
location = args.widgetParameter;
if (location == null || location == undefined || location == "") {
let title = mainStack.addText("정류장 파라미터를 설정해 주세요!");
title.textColor = Color.white();
return widget;
}
} else {
location = "셔틀콕"
}
const convertedLocation = convertLocationString(location);
const busInfo = await getCurrentInfo(convertedLocation);
locationStack.layoutVertically();
let locationText = locationStack.addText(location);
locationText.font = Font.boldSystemFont(36);
locationText.textColor = Color.white();
mainStack.addSpacer(30);
let shuttleStack = mainStack.addStack();
shuttleStack.layoutVertically();
if (busInfo.length == 2) {
let firstBusStack = shuttleStack.addStack();
let firstBusType = firstBusStack.addText(busInfo[0]["destination"]);
firstBusType.font = Font.systemFont(14);
firstBusType.textColor = Color.white();
firstBusStack.addSpacer(10);
let firstBusTime = firstBusStack.addText(busInfo[0]["time"]);
firstBusTime.font = new Font("CourierNewPS-BoldMT", 25);
firstBusTime.textColor = Color.white();
firstBusStack.addSpacer(10);
let firstBusDepartText = firstBusStack.addText("출발");
firstBusDepartText.font = Font.systemFont(14);
firstBusDepartText.textColor = Color.white();
firstBusStack.centerAlignContent();
shuttleStack.addSpacer(8);
let secondBusStack = shuttleStack.addStack();
let secondBusType = secondBusStack.addText(busInfo[1]["destination"]);
secondBusType.font = Font.systemFont(14);
secondBusType.textColor = Color.white();
secondBusStack.addSpacer(10);
let secondBusTime = secondBusStack.addText(busInfo[1]["time"]);
secondBusTime.font = new Font("CourierNewPS-BoldMT", 25);
secondBusTime.textColor = Color.white();
secondBusStack.addSpacer(10);
let secondBusDepartText = secondBusStack.addText("출발");
secondBusDepartText.font = Font.systemFont(14);
secondBusDepartText.textColor = Color.white();
secondBusStack.centerAlignContent();
} else if (busInfo.length == 1) {
shuttleStack.addSpacer(18)
let firstBusStack = shuttleStack.addStack();
let firstBusType = firstBusStack.addText(busInfo[0]["destination"]);
firstBusType.font = Font.systemFont(14);
firstBusType.textColor = Color.white();
firstBusStack.addSpacer(10);
let firstBusTime = firstBusStack.addText(busInfo[0]["time"]);
firstBusTime.font = new Font("CourierNewPS-BoldMT", 25);
firstBusTime.textColor = Color.white();
firstBusStack.addSpacer(10);
let firstBusDepartText = firstBusStack.addText("출발");
firstBusDepartText.font = Font.systemFont(14);
firstBusDepartText.textColor = Color.white();
firstBusStack.centerAlignContent();
} else {
shuttleStack.addSpacer(14);
let doneText = shuttleStack.addText(busInfo);
doneText.font = Font.systemFont(14)
doneText.textColor = Color.white();
doneText.centerAlignText();
}
mainStack.centerAlignContent();
return widget;
}
const createSmallWidget = async () => {
let widget = new ListWidget();
widget.url = "https://hybus.app"
let titleStack = widget.addStack();
const loc = args.widgetParameter;
let mainStack = widget.addStack();
mainStack.layoutVertically();
let locationStack = mainStack.addStack();
let simpleGradient = new LinearGradient()
simpleGradient.colors = [new Color("141414"), new Color("001148")]
simpleGradient.locations = [0, 1]
widget.backgroundGradient = simpleGradient
var location = null;
if (config.runsInWidget) {
location = args.widgetParameter;
if (location == null || location == undefined || location == "") {
let title = mainStack.addText("정류장 파라미터를 설정해 주세요!");
title.textColor = Color.white();
return widget;
}
} else {
location = "셔틀콕"
}
const convertedLocation = convertLocationString(location);
const busInfo = await getCurrentInfo(convertedLocation);
locationStack.layoutHorizontally();
let locationText = locationStack.addText(location);
locationText.font = Font.boldSystemFont(32);
locationText.textColor = Color.white();
mainStack.addSpacer(10);
let shuttleStack = mainStack.addStack();
shuttleStack.layoutVertically();
if (busInfo.length == 1 || busInfo.length == 2) {
let busTypeStack = shuttleStack.addStack();
let busTypeText = busTypeStack.addText(busInfo[0]["destination"]);
busTypeText.font = Font.systemFont(14);
busTypeText.textColor = Color.white();
shuttleStack.addSpacer(5);
let busTimeStack = shuttleStack.addStack();
busTimeStack.layoutHorizontally();
let busTimeText = busTimeStack.addText(busInfo[0]["time"]);
busTimeText.font = new Font("CourierNewPS-BoldMT", 28);
busTimeText.textColor = Color.white();
busTimeStack.addSpacer(10);
let busDepartText = busTimeStack.addText("출발");
busDepartText.font = Font.systemFont(14);
busDepartText.textColor = Color.white();
busTimeStack.centerAlignContent();
} else {
shuttleStack.addSpacer(14);
let doneText = shuttleStack.addText(busInfo);
doneText.font = Font.systemFont(14)
doneText.textColor = Color.white();
doneText.centerAlignText();
}
return widget;
}
if (config.runsInApp) {
const prompt = "옵션을 선택하세요.";
const options = ["위젯 미리보기 (2x2)", "위젯 미리보기 (2x4)", "최신 버전으로 업데이트하기"];
let response = await generateAlert(prompt, options);
if (response === 0) {
const widget = await createSmallWidget();
Script.setWidget(widget);
widget.presentSmall();
} else if (response === 1) {
const widget = await createMediumWidget();
Script.setWidget(widget);
widget.presentMedium();
}
else if (response === 2) {
await updateCode();
}
} else {
let nextRefresh = Date.now() + 1000 * 30
if (config.widgetFamily === "small") {
const widget = await createSmallWidget();
Script.setWidget(widget);
widget.presentSmall();
widget.refreshAfterDate = new Date(nextRefresh);
} else if (config.widgetFamily === "medium") {
const widget = await createMediumWidget();
Script.setWidget(widget);
widget.presentMedium();
widget.refreshAfterDate = new Date(nextRefresh);
} else if (config.widgetFamily === "accessoryRectangular") {
// Not made yet
} else {
// Others just render in medium size
const widget = await createMediumWidget();
Script.setWidget(widget);
widget.presentMedium();
widget.refreshAfterDate = new Date(nextRefresh);
}
}