-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschedule.html
712 lines (621 loc) · 23.7 KB
/
schedule.html
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link href="style.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Josefin Sans' rel='stylesheet'>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" rel="stylesheet">
<script defer src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- <script defer src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.min.js"></script> -->
<!-- <script defer src="https://cdn.jsdelivr.net/npm/axios@0/dist/axios.min.js"></script> -->
<script defer src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.slim.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/js/bootstrap.min.js"></script>
<script src="https://apis.google.com/js/api.js"></script>
</head>
<body>
<div id='app' style='margin-bottom:3em;'>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark"
style='background-color:#001d64;font-family: "Josefin Sans";'>
<div class="container-fluid">
<a class="navbar-brand" href="index.html">
<img src="assets/logo.png" class="d-inline-block" style='object-fit:cover;width:8em;height:30px' alt="">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link" :class='{active:idx==navBarSelected}' v-for='x,idx of navBarTextsBadges'
:href="x[1]?x[1]:'#'">{{x[0]}}
</a>
<a class="nav-link" target="_blank" href='https://github.com/epigone707/ExerciseScheduler'>Github
</a>
</div>
</div>
</div>
</nav>
<div class="container">
<div class="row align-items-center d-flex justify-content-center">
<div class="col-10">
<div class="table-responsive d-flex justify-content-start">
<table class="table table-bordered text-center">
<thead>
<tr class="bg-light-gray">
<th class="text-uppercase">Time</th>
<th class="text-uppercase" v-for='dateArr of dateArray'>{{dateArr}}</th>
</tr>
</thead>
<tbody>
<tr v-for='sch,schIdx of schedule'>
<td class="align-middle">{{`${8+2*schIdx}:00-${10+2*schIdx}:00`}}</td>
<td width="14%" v-for="cell,dayIdx of sch">
<button type="button" :class="btnStyle(cell)" style="width:100%"
@click="!submitted?clickCell(cell):clickCellAfterSubmit(cell)">
{{!submitted?(cell.state==AVAILABLE?"Free":"Busy"):cell.weather?.brief||'N/A'}}</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col" v-if="submitted" style="margin:20px 0">
<div id="legend_highly_recommend" class='d-flex align-items-center justify-content-center'>Strongly
Recommended</div>
<div id="legend_recommend" class='d-flex align-items-center justify-content-center'>Recommended</div>
<div id="legend_not_recommend" class='d-flex align-items-center justify-content-center'>Not Recommended</div>
<div id="legend_highly_not_recommend" class='d-flex align-items-center justify-content-center'>Strongly not
Recommended</div>
<div id="legend_not_available" class='d-flex align-items-center justify-content-center'>Busy</div>
</div>
<div class="col" v-if="!submitted" style="margin:20px 0">
<button @click="importCalendar" class="btn btn-outline-primary" style="margin-bottom:20px;width:10em"> Import from
Google Calendar</button>
</div>
</div>
<div class="col d-flex justify-content-center">
<button @click='doSchedule' class="btn btn-outline-success"
style="margin-bottom:20px;width:10em">{{submitted?"Back":"Submit"}}</button>
<a v-if="submitted" href="places.html" class="btn btn-outline-success"
style="margin-bottom:20px;width:10em;margin-left:2em">Schedule Place</a>
</div>
</div>
<div class="container d-flex justify-content-center " v-if="submitted">
<div class="card">
<div class="card-body">
<div v-if="selectedDateWeather!=null">
<img :src="weatherIcon" alt="Weather Icon" width="50" height="50">
<p><span style="font-weight: bold;">Date:</span> {{
`${selectedCell?.dateTime.getFullYear()}-${selectedCell?.dateTime.getMonth()}-${selectedCell?.dateTime.getDay()}`
}}</p>
<p><span style="font-weight: bold;">Weather:</span> {{JSON.stringify(selectedDateWeather.brief)}}</p>
<p> <span style="font-weight: bold;">AQI (PM 2.5): </span>{{ getAirQualityDesc(selectedCell?.aqi?.avgPM25)
}}</p>
<p> <span style="font-weight: bold;">Temperature (°F): </span>{{JSON.stringify(selectedDateWeather.tempF)}}
</p>
<p> <span style="font-weight: bold;">Wind Speed (mph):
</span>{{JSON.stringify(selectedDateWeather.windSpd)}}</p>
<p> <span style="font-weight: bold;">Wind Direction: </span>{{JSON.stringify(selectedDateWeather.windDir)}}
</p>
<p> <span style="font-weight: bold;">Description: </span>{{JSON.stringify(selectedDateWeather.desc)}}</p>
<p class='d-flex justify-content-center'>
<button class='btn btn-outline-primary' data-bs-toggle="modal" data-bs-target="#calModal">Add to
Calendar</button>
</p>
</div>
<div v-else>
<p style="font-weight:bold;text-align: center;">Click on a cell to show more Weather info!</p>
</div>
</div>
</div>
</div>
<div class="modal fade" id="calModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Choose Calendar</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id='calModalBody'>
<div v-if='gCals!=null&&gCals.length>0'>
<div v-for="cal,idx of gCals" :key='cal.id' class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" :id="cal.id" :checked='idx==0'>
<label class="form-check-label" :for="cal.id">
{{cal.desc||cal.summary}}
</label>
</div>
</div>
<div v-else>
No Google Calendar found! Did you import them?
</div>
</div>
<div class="modal-footer">
<button id='calModalCloseBtn' type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button v-if='gCals!=null&&gCals.length>0' @click='addToGCal' type="button" class="btn btn-primary"
:disabled='addingToGcal'>
<span v-if='addingToGcal' class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
Save to GCal
</button>
</div>
</div>
</div>
</div>
<!-- <div>
<button @click='getPosition' class='btn btn-primary'>getPosition</button>
<span>lat={{coord?.lat}} lon={{coord?.lon}}</span>
</div>
<div>
<button @click='getWeatherAQI' class='btn btn-primary'>getWeatherAQI</button>
<div>
<pre>{{JSON.stringify(airQualityInfo,null,2)}}</pre>
<pre>{{JSON.stringify(weatherInfo,null,2)}}</pre>
</div>
</div> -->
</div> <!-- #app -->
</body>
<script> // @ts-check
"use strict"
// USER DIDN'T CHOOSE IT AS BUSY AND GOOD WEATHER
const AVAILABLE = 'AVAILABLE'
// USER CHOOSE IT AS BUSY
const BUSY = 'BUSY'
// BAD WEATHER
const UNAVAILABLE = 'UNAVAILABLE'
const SUNNY = 'SUNNY'
const CLOUDY = 'CLOUDY'
const RAINY = 'RAINY'
const SNOWY = 'SNOWY'
/** @typedef {AVAILABLE|BUSY|UNAVAILABLE} State */
/** @typedef {{
* brief:SUNNY|CLOUDY|RAINY|SNOWY,
* tempF:number,
* windSpd:number,
* windDir:string,
* desc:string,
* }} Weather */
/** @typedef {{avgPM25:number}} AirQuality */
/**
* @typedef {{dateTime:Date,state:State,weather:Weather?,aqi:AirQuality?}} CellInfo
* | | |
* | `----------------`----> could be [undefined] if no data
* `----> [Date] with precise hour; e.g. "2021-11-30 08:00"
* @arg {State} state
*/
/**
* @typedef {{
* id:string,
* summary:string,
* desc:string?
* }} GoogleCalendar
*/
const todayDateBase = new Date()
todayDateBase.setHours(0, 0, 0, 0)
const busy_class = "btn btn-warning"
// free_class: 'bg-green padding-5px-tb padding-15px-lr border-radius-5 margin-10px-bottom text-white font-size16 xs-font-size13',
// free_class: 'btn btn-success',
const free_class = "btn btn-success"
const free_sunny_class = "btn sunny"
const free_cloudy_class = "btn cloudy"
const free_rainy_class = "btn rainy"
const free_snowy_class = "btn snowy"
const highly_recommend = "btn highly_recommend"
const recommend = "btn recommend"
const not_recommend = "btn not_recommend"
const highly_not_recommend = "btn highly_not_recommend"
const busy_class_submited = "btn btn-light"
const data = {
AVAILABLE,
BUSY,
UNAVAILABLE,
/** @type {Date} */
todayDateBase,
navBarTextsBadges: [['Home', 'index.html'], ['Schedule', 'schedule.html'], ['Place', 'places.html'], ['Help', 'help.html'],],
navBarSelected: 1,
dateArray: ["", "", "", "", "", ""],
// schedule: [
// //8-10am
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// //10-12pm
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// [State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE, State.AVAILABLE],
// ],
/** @type {CellInfo[][]} */
schedule: [],
avaliableTimeArray: [],
/** @type {{lat:number,lon:number}} */
coord: null,
/** @type {String?} */
weatherApiKey: null,
/** @type {String?} */
aqiApiKey: null,
/** @type {{[key:number]:Weather}} */
weatherInfo: null,
/** @type {{[key:number]:AirQuality}} */
airQualityInfo: null,
/** @type {Boolean} */
submitted: false,
/** @type {Weather?} */
selectedDateWeather: null,
/** @type {CellInfo?} */
selectedCell: null,
/** @type {String} */
weatherIcon: null,
/** @type {GoogleCalendar[]?} */
gCals: null,
addingToGcal: false
}
let getWeatherApiKey = () => fetch('key-weather.txt').then(r => r.text()).then(r => r.trim())
let getAqiApiKey = () => fetch('key-aqi.txt').then(r => r.text()).then(r => r.trim())
/**
* @arg {Date} date
* @arg {number} n
*/
function addDays(date, n) {
date.setDate(date.getDate() + n)
return date
}
/**
* @arg {Date} date
* @arg {number} n
*/
function addHours(date, n) {
date.setHours(date.getHours() + n)
return date
}
/**
* set the date for 5 coming days
*/
function setDate() {
const months = ["Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."];
const weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
for (let i = 0; i < data.dateArray.length; i++) {
let targetDate = addDays(new Date(data.todayDateBase), i);
let dd = targetDate.getDate();
let mm = months[targetDate.getMonth()];
let day = weekday[targetDate.getDay()];
data.dateArray[i] = mm + " " + dd + " " + day;
}
}
/**
* generate schedule cells, each cell store cellInfo {date, time, availability}
* (see function cellInfo above)
* VUE created() call
*/
function genCell() {
let timeHorizon = [];
for (let t = 0; t < 7; t++) {
timeHorizon = [];
for (let d = 0; d < data.dateArray.length; d++) {
let curdate = addDays(new Date(data.todayDateBase), d);
/** @type {CellInfo} */
let curCell = {
dateTime: addHours(curdate, 8 + 2 * t),
state: AVAILABLE,
weather: null,
aqi: null,
};
timeHorizon.push(curCell);
}
data.schedule.push(timeHorizon);
}
}
/**
* import Google Calendar check free/busy
*/
function calendarAuthenticate() {
return gapi.auth2.getAuthInstance()
.signIn({ scope: "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events" })
.then(function () { console.log("Sign-in successful"); },
function (err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("AIzaSyDiIkrELAExlayhNVh5ncRXu74HQ8LLOTU");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/calendar/v3/rest")
.then(function () { console.log("GAPI client loaded for API"); },
function (err) { console.error("Error loading GAPI client for API", err); });
}
function execute() {
return gapi.client.calendar.calendarList.list({
"minAccessRole": "writer"
}).then(function (response) {
// Handle the results here (response.result has the parsed body).
data.gCals = response.result.items.map(x => {
/** @type {GoogleCalendar} */
let cal = { id: x.id, summary: x.summary, desc: x.description }
return cal
})
console.log(data.gCals);
}, function (err) { console.error("Execute error", err); });
}
function getFreeBusy() {
let timeMax = new Date()
addDays(timeMax, 5);
return gapi.client.calendar.freebusy.query({
resource: {
timeMin: data.todayDateBase.toISOString(),
timeMax: timeMax.toISOString(),
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
items: data.gCals.map(x => { return { id: x.id } })
}
}).then(function (response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response.result);
/** @type {Set<number>} */
let busyTimes = new Set()
Object.values(response.result.calendars).map(x => x.busy).forEach(
arr => arr.forEach(x => {
let start = new Date(x.start)
start.setMinutes(0, 0, 0)
let end = new Date(x.end)
if (end.getMinutes() || end.getSeconds()) {
end.setMinutes(0, 0, 0)
addHours(end, 1)
}
for (let i = start; i < end; i.setHours(i.getHours() + 1)) {
let d = new Date(i)
if (d.getHours() % 2 != 0)
d.setHours(d.getHours() - 1)
busyTimes.add(d.getTime())
}
})
)
console.log(`Found ${busyTimes.size} busy slots!`);
data.schedule.forEach(
r => r.forEach(x => {
if (busyTimes.has(x.dateTime.getTime()))
x.state = BUSY
}))
}, function (err) { console.error("Execute error", err); });
}
function parseWeatherInfo(js) {
/** @type {{[key:number]:Weather}} */
let weather = {}
js.properties.periods.forEach(x => {
/** @type {string} */
let descLC = x.shortForecast.toUpperCase()
weather[new Date(x.startTime).getTime()] = {
brief: descLC.includes(SUNNY) ? SUNNY : (descLC.includes('RAIN') ? RAINY : (descLC.includes('SNOW') ? SNOWY : CLOUDY)),
tempF: x.temperature,
windSpd: x.windSpeed,
windDir: x.windDirection,
desc: x.shortForecast,
}
})
return weather
}
function parseAqiInfo(js) {
/** @type {{[key:number]:AirQuality}} */
let aqiInfo = {}
js.data.forecast.daily.pm25.forEach(x => {
/** @type {number} */
let avg = x.avg
aqiInfo[new Date(x.day + ' 0:').getTime()] = { avgPM25: avg }
})
return aqiInfo
}
function applyAllWeatherAQI() {
data.schedule.forEach(r =>
r.forEach(x => {
let date = new Date(x.dateTime)
x.weather = data.weatherInfo[date.getTime()]
date.setHours(0, 0, 0, 0)
x.aqi = data.airQualityInfo[date.getTime()]
}))
}
const methods = {
/**
* @param {number} pm25
*/
getAirQualityDesc(pm25) {
if (pm25 == null) return 'No Data'
else if (pm25 > 250.5) return pm25 + 'μg/m3 (Harzardous)'
else if (pm25 > 150.5) return pm25 + 'μg/m3 (Very Unhealthy)'
else if (pm25 > 55.5) return pm25 + 'μg/m3 (Unhealthy)'
else if (pm25 > 35.5) return pm25 + 'μg/m3 (Unhealthy for the Sensitive)'
else if (pm25 > 12.1) return pm25 + 'μg/m3 (Moderate)'
else if (pm25 > 0) return pm25 + 'μg/m3 (Excellent)'
else return 'Not Available'
},
/**
* @param {Date} date
*/
isToday(date) {
date = new Date(date)
date.setHours(0, 0, 0, 0)
return date.getTime() == data.todayDateBase.getTime()
},
/**
* @param {CellInfo} cell
*/
btnStyle(cell) {
if (!data.submitted)
return cell.state == AVAILABLE ? free_class : busy_class
if (cell.state == AVAILABLE) {
if (cell.weather == null) {
return busy_class_submited
}
if (cell.weather.brief == SUNNY) {
if (cell.weather.tempF > 35)
return highly_recommend
else
return recommend
}
else if (cell.weather.brief == CLOUDY) {
if (cell.weather.tempF > 38)
return highly_recommend
if (cell.weather.tempF > 30)
return recommend
else {
return not_recommend
}
}
else if (cell.weather.brief == RAINY || cell.weather.brief == SNOWY) {
return highly_not_recommend
}
}
return busy_class_submited
},
/**
* onclick handler when user clicks a time cell
* modify data.schedule
*
* @param {CellInfo} cell
*/
clickCell: function (cell) {
cell.state = cell.state == AVAILABLE ? BUSY : AVAILABLE
},
/**
* onclick handler when user clicks a time cell after submit
* modify data.schedule
*
* @param {CellInfo} cell
*/
clickCellAfterSubmit: function (cell) {
console.log('clickCellAfterSubmit');
console.log(cell);
data.selectedDateWeather = cell.weather
data.selectedCell = cell
if (data.selectedDateWeather != null)
data.weatherIcon = "assets/" + data.selectedDateWeather.brief + ".png";
// let clickedElement = e.target;
// $(clickedElement).text("");
},
getPosition() {
return new Promise((y, n) => {
if (navigator.geolocation) {
console.log('Getting current location ...')
navigator.geolocation.getCurrentPosition(
pos => {
console.log('Got current location!')
data.coord = {
lat: pos.coords.latitude,
lon: pos.coords.longitude
}
y()
},
err => {
console.error(err)
alert(`Cannot get loation: ${err.message}\nUsing default location: Ann Arbor, MI`)
n()
})
} else {
alert('Geolocation API is not supported by your browser!\nUsing default location: Ann Arbor, MI')
n()
}
}).catch(_ => {
data.coord = {
lat: 42.279594,
lon: -83.732124,
}
console.log('Current position set to to default!')
}).then(_ =>
console.log(data.coord))
},
getWeatherAQI() {
Promise.resolve(data.coord != null ? null : methods.getPosition()
).then(_ =>
(data.aqiApiKey != null && data.aqiApiKey.length <= 0)
? data.aqiApiKey : getAqiApiKey()
).then(key => data.aqiApiKey = key
).then(_ => {
const coord = data.coord
const aqiApiKey = data.aqiApiKey
let url;
// weather
let weather = fetch(`https://api.weather.gov/points/${coord.lat},${coord.lon}`
).then(r => r.json()
).then(js => {
console.log('Got weather info ...')
console.log(js)
return fetch(js.properties.forecastHourly)
}).then(r => r.json()
).then(js => {
console.log('Got hourly info ...')
console.log(js)
data.weatherInfo = parseWeatherInfo(js)
}).catch(e => {
alert(e)
console.error(e)
})
// air quality
url = new URL(`https://api.waqi.info/feed/geo:${coord.lat};${coord.lon}/`)
url.searchParams.set('token', aqiApiKey)
let aqi = fetch(url.toString()).then(r => r.json()
).then(js => {
console.log('Got Air Pollution info ...')
console.log(js)
data.airQualityInfo = parseAqiInfo(js)
}).catch(e => {
alert(e)
console.error(e)
})
// sum up
return Promise.all([weather, aqi]).then(_ => {
console.log('Got all info!')
applyAllWeatherAQI()
})
}).catch(e => {
alert(e)
console.error(e)
})
},
doSchedule() {
methods.getWeatherAQI();
data.submitted = !data.submitted;
console.log('You clicked Submit!');
},
importCalendar() {
calendarAuthenticate().then(loadClient).then(execute).then(getFreeBusy);
},
addToGCal() {
data.addingToGcal = true
let calendarId = [...calModalBody.querySelectorAll("input")].filter(x => x.checked)[0].id
let endDT = new Date(data.selectedCell.dateTime);
addHours(endDT, 2);
return gapi.client.calendar.events.insert({
calendarId,
"resource": {
"end": {
"dateTime": endDT.toISOString(),
"timeZone": Intl.DateTimeFormat().resolvedOptions().timeZone,
},
"start": {
"dateTime": data.selectedCell.dateTime.toISOString(),
"timeZone": Intl.DateTimeFormat().resolvedOptions().timeZone,
},
summary: 'Exercise Now!',
description: "Exercise scheduled by OutScheduler",
}
}).then(function (response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response.result);
calModalCloseBtn.click()
data.addingToGcal = false
Promise.resolve(execute()).then(getFreeBusy)
}, function (err) {
console.error("Execute error", err);
data.addingToGcal = false
});
}
}
document.addEventListener('DOMContentLoaded', _ => {
let vapp = new Vue({
el: '#app',
data,
methods,
created() {
setDate()
genCell()
}
})
gapi.load("client:auth2", function () {
gapi.auth2.init({ client_id: "872193871992-n7peatl2l79l1vchts5sn4qdp5shf5eq.apps.googleusercontent.com" });
});
})
</script>
</html>