~online-accounts/account-polld/trunk

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
/*
 Copyright 2016 Canonical Ltd.

 This program is free software: you can redistribute it and/or modify it
 under the terms of the GNU General Public License version 3, as published
 by the Free Software Foundation.

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranties of
 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along
 with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package caldav

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"launchpad.net/account-polld/accounts"
	"launchpad.net/account-polld/plugins"
	"launchpad.net/account-polld/syncmonitor"
)

const (
	APP_ID     = "com.ubuntu.calendar_calendar"
	pluginName = "caldav"
)

type CalDavPlugin struct {
	accountId uint
}

func New(accountId uint) *CalDavPlugin {
	return &CalDavPlugin{accountId: accountId}
}

func (p *CalDavPlugin) ApplicationId() plugins.ApplicationId {
	return plugins.ApplicationId(APP_ID)
}

func (p *CalDavPlugin) Poll(authData *accounts.AuthData) ([]*plugins.PushMessageBatch, error) {
	// This envvar check is to ease testing.
	if token := os.Getenv("ACCOUNT_POLLD_TOKEN_CALDAV"); token != "" {
		log.Print("Using token from: ACCOUNT_POLLD_TOKEN_CALDAV env var")
		authData.AccessToken = token
	}

	log.Print("Check calendar changes for account:", p.accountId)

	syncMonitor := syncmonitor.NewSyncMonitor()
	if syncMonitor == nil {
		log.Print("Sync monitor not available yet.")
		return nil, nil
	}

	state, err := syncMonitor.State()
	if err != nil {
		log.Print("Fail to retrieve sync monitor state ", err)
		return nil, nil
	}
	if state != "idle" {
		log.Print("Sync monitor is not on 'idle' state, try later!")
		return nil, nil
	}

	calendars, err := syncMonitor.ListCalendarsByAccount(p.accountId)
	if err != nil {
		log.Print("Calendar plugin ", p.accountId, ": cannot load calendars: ", err)
		return nil, nil
	}

	var calendarsToSync []string
	log.Print("Number of calendars for account:", p.accountId, " size:", len(calendars))

	for id, calendar := range calendars {
		lastSyncDate, err := syncMonitor.LastSyncDate(p.accountId, id)
		if err != nil {
			log.Print("\tcalendar: ", id, ", cannot load previous sync date: ", err, ". Try next time.")
			continue
		} else {
			log.Print("\tcalendar: ", id, " Url: ", calendar, " last sync date: ", lastSyncDate)
		}

		var needSync bool
		needSync = (len(lastSyncDate) == 0)

		if !needSync {
			resp, err := p.requestChanges(authData, calendar, lastSyncDate)
			if err != nil {
				log.Print("\tERROR: Fail to query for changes: ", err)
				continue
			}

			needSync, err = p.containEvents(resp)
			if err != nil {
				log.Print("\tERROR: Fail to parse changes: ", err)
				if err == plugins.ErrTokenExpired {
					log.Print("\t\tAbort poll")
					return nil, err
				} else {
					continue
				}
			}
		}

		if needSync {
			log.Print("\tCalendar needs sync: ", id)
			calendarsToSync = append(calendarsToSync, id)
		} else {
			log.Print("\tFound no calendar updates for account: ", p.accountId, " calendar: ", id)
		}
	}

	if len(calendarsToSync) > 0 {
		log.Print("Request account sync")
		err = syncMonitor.SyncAccount(p.accountId, calendarsToSync)
		if err != nil {
			log.Print("ERROR: Fail to start account sync ", p.accountId, " message: ", err)
		}
	}

	return nil, nil
}

func (p *CalDavPlugin) containEvents(resp *http.Response) (bool, error) {
	defer resp.Body.Close()
	log.Print("RESPONSE CODE ----:", resp.StatusCode)

	if resp.StatusCode != 207 {
		var errResp errorResp
		log.Print("Invalid response:", errResp.Err.Code)
		return false, nil
	} else {
		data, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return false, err
		}
		fmt.Printf("DATA: %s", data)
		return strings.Contains(string(data), "BEGIN:VEVENT"), nil
	}

	return false, nil
}

func (p *CalDavPlugin) requestChanges(authData *accounts.AuthData, calendar string, lastSyncDate string) (*http.Response, error) {
	u, err := url.Parse(calendar)
	if err != nil {
		return nil, err
	}
	startDate, err := time.Parse(time.RFC3339, lastSyncDate)
	if err != nil {
		log.Print("Fail to parse date: ", lastSyncDate)
		return nil, err
	}

	// Start date will be one minute before last sync
	startDate = startDate.Add(time.Duration(-1) * time.Minute)

	// End Date will be one year in the future from now
	endDate := time.Now().AddDate(1, 0, 0).UTC()

	log.Print("Calendar Url:", calendar)

	query := "<c:calendar-query xmlns:d=\"DAV:\" xmlns:c=\"urn:ietf:params:xml:ns:caldav\">\n"
	query += "<d:prop>\n"
	query += "<d:getetag />\n"
	query += "<c:calendar-data />\n"
	query += "</d:prop>\n"
	query += "<c:filter>\n"
	query += "<c:comp-filter name=\"VCALENDAR\">\n"
	query += "<c:comp-filter name=\"VEVENT\">\n"
	query += "<c:prop-filter name=\"LAST-MODIFIED\">\n"
	query += "<c:time-range start=\"" + startDate.Format("20060102T150405Z") + "\" end=\"" + endDate.Format("20060102T150405Z") + "\"/>\n"
	query += "</c:prop-filter>\n"
	query += "</c:comp-filter>\n"
	query += "</c:comp-filter>\n"
	query += "</c:filter>\n"
	query += "</c:calendar-query>\n"
	log.Print("Query: ", query)
	req, err := http.NewRequest("REPORT", u.String(), bytes.NewBufferString(query))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Depth", "1")
	req.Header.Set("Prefer", "return-minimal")
	req.Header.Set("Content-Type", "application/xml; charset=utf-8")
	req.SetBasicAuth(authData.UserName, authData.Secret)

	return http.DefaultClient.Do(req)
}