-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_google.php
68 lines (65 loc) · 2.55 KB
/
_google.php
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
<?php
function google_create_date($dateobj)
{
if (property_exists($dateobj, "dateTime")) {
return date_create($dateobj->dateTime);
} else return date_create($dateobj->date);
}
function google_is_appointment($item)
{
// TODO: and if in specific calendar
return property_exists($item->start, "dateTime") && property_exists($item->end, "dateTime");
}
function google_get_next_events($config, $force_reload = false)
{
// Get next Google events from now
$now = date(DATE_RFC3339);
if (property_exists($config, 'last_google_check')) {
$from = $config->last_google_check;
// check if last call to Google was less than caching time ago
// TODO make configurable
// weird code. Explanation: check if last check + 15min is in the future by checking if we need to go backwards from there to get to now.
// note the PT that is necessary because weird PHP uses M for months and minutes whyyyyy it does not in date()
if(!$force_reload && date_diff(date_add(date_create($from), new DateInterval("PT15M")), date_create($now))->invert == 1) {
return [];
}
} else {
$from = $now;
}
// @TODO limit to 4 weeks
// @TODO handle multiple pages - Google returns plenty, but we must not rely on the first page to contain everything we need
$items = [];
for($i = 0; $i < count($config->google_calendars); $i++) {
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $config->google_calendars[$i] . '/events';
$params['singleEvents'] = 'true';
$params['orderBy'] = 'startTime';
$params['timeMin'] = $from;
$json = get_json_google($url, $params);
$items = array_merge($items, $json->items);
}
$config->last_google_check = $now;
file_put_contents('data/config.json', json_encode($config));
return $items;
}
function google_write_items_to_database(PDO $conn, $items)
{
// Write events to database
$ioi = $conn->prepare('INSERT OR IGNORE INTO tasks (description, duration, date, google_id, deadline_day) VALUES (:description, :duration, :date, :google_id, :deadline_day)');
$conn->beginTransaction();
foreach ($items as $item) {
$start = google_create_date($item->start);
$end = google_create_date($item->end);
$duration = calculate_duration($start, $end);
$ioi->bindValue(':description', $item->summary);
$ioi->bindValue(':google_id', $item->id);
if (google_is_appointment($item)) {
$ioi->bindValue(':deadline_day', $end->format('Y-m-d'));
} else {
$ioi->bindValue(':deadline_day', null);
}
$ioi->bindValue(':duration', $duration, PDO::PARAM_INT);
$ioi->bindValue(':date', $start->format('Y-m-d'));
$ioi->execute();
}
return $conn->commit();
}