-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_manager.go
292 lines (221 loc) · 6.43 KB
/
list_manager.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
package main
import (
"bufio"
"bytes"
"encoding/json"
"net/http"
"strings"
"time"
)
// JSONHeaders are the set of HTTP headers required to accept the body in JSON.
var JSONHeaders = http.Header{
"Content-Type": {"application/json"},
"Accept": {"application/json"},
}
// LoadSource is a type used for the Local and Network constants.
type LoadSource int
const (
// Unavailable notes that the tasklist manager is still loading.
Unavailable LoadSource = iota
// Local notes that the tasklist manager opted to use local files.
Local
// Network notes that the tasklist manager opted to load from a sync service.
Network
// OutdatedNetwork notes that the tasklist manager detected that the local
// taskfile is newer than the last network update, and will upload the
// local tasklist to the appropriate sync service.
OutdatedNetwork
)
// TasklistManager is responsible for loading and saving taskfiles, both local
// files and Sync service data.
type TasklistManager struct {
source LoadSource
syncID string
syncURL string
lastNetworkUpdate time.Time
}
// ParseSyncfile reads the appropriate syncfile and sets the manager's fields
// to their values.
func (tm *TasklistManager) ParseSyncfile() {
syncfile := OpenSyncfile(true)
if syncfile == nil {
return
}
defer syncfile.Close()
scanner := bufio.NewScanner(syncfile)
for scanner.Scan() {
line := scanner.Text()
// Extract Sync ID
syncIDMatch := SyncIDPattern.FindStringSubmatch(line)
if len(syncIDMatch) == 2 {
tm.syncID = syncIDMatch[1]
continue
}
// Extract Sync URL
syncURLMatch := SyncURLPattern.FindStringSubmatch(line)
if len(syncURLMatch) == 2 {
tm.syncURL = syncURLMatch[1]
continue
}
// Extract lastNetworkUpdate
lastNetworkUpdateMatch := LastNetworkUpdatePattern.FindStringSubmatch(line)
if len(lastNetworkUpdateMatch) == 2 {
lastNetworkUpdate, err := time.Parse(LastNetworkUpdateFormat, lastNetworkUpdateMatch[1])
if err != nil {
Warn("Invalid lastNetworkUpdate date in syncfile \"%s\": %s", SyncfilePath, lastNetworkUpdateMatch[1])
}
tm.lastNetworkUpdate = lastNetworkUpdate
continue
}
}
if err := scanner.Err(); err != nil {
Error(ErrSyncfileRead, SyncfilePath, err)
}
}
// Init sets all the filepaths and initializes both active and finished
// tasklists.
func (tm *TasklistManager) Init() {
InitPathVariables(ConfigOptions.List)
MainList.filePath = TaskfilePath
DoneList.filePath = DonefilePath
MainList.tasks = make(map[int]Task)
DoneList.tasks = make(map[int]Task)
}
// Load loads from network if possible and determines the loading source.
func (tm *TasklistManager) Load() {
tm.source = func() LoadSource {
// "Bouncer" statements
if ConfigOptions.Offline {
return Local
}
tm.ParseSyncfile()
if tm.syncID == "" {
return Local
}
if tm.syncURL == "" {
tm.syncURL = ConfigOptions.FallbackSyncURL
}
if MainList.MTimeAfter(tm.lastNetworkUpdate) || DoneList.MTimeAfter(tm.lastNetworkUpdate) {
Warn("Local tasklist is newer than the synced one. Uploading local tasklist.")
return OutdatedNetwork
}
// Prepare URL
tm.syncURL = strings.TrimSpace(tm.syncURL)
EnsureTrailingSlash(&tm.syncURL)
tm.syncID = strings.TrimSpace(tm.syncID)
url := tm.syncURL + tm.syncID
// Complete GET Request
request, err := http.NewRequest("GET", url, nil)
if err != nil {
Error(ErrGETReqCreate, url, err)
}
request.Header = JSONHeaders
resp, err := http.DefaultClient.Do(request)
if err != nil {
Warn("Could not complete GET request: %v", err)
return Local
}
defer resp.Body.Close()
statusCode := resp.StatusCode
switch statusCode {
case 404:
Warn("Could not find tasklist with Sync ID \"%s\"", tm.syncID)
return Local
case 200:
// Unmarshal JSON stirng into map[string]string
var jsonData []byte
for s := bufio.NewScanner(resp.Body); s.Scan(); {
jsonData = append(jsonData, s.Bytes()...)
}
var data map[string]interface{}
if json.Unmarshal(jsonData, &data) != nil {
Warn("Failed to parse network response: %v", err)
return Local
}
// Parse active and finished tasklists
{
reader := strings.NewReader(data["contents"].(string))
MainList.ParseTasklines("[syncID:"+tm.syncID+"]", reader)
}
{
reader := strings.NewReader(data["doneContents"].(string))
DoneList.ParseTasklines("[syncID:"+tm.syncID+"]", reader)
}
MainList.loaded = true
DoneList.loaded = true
return Network
default:
Warn("Invalid response when loading tasklist: status is " + resp.Status)
return Local
}
}()
}
// EnsureInitialized makes sure that the tasklist is loaded and does so if not.
func (tm *TasklistManager) EnsureInitialized(tasklist *Tasklist) {
if tasklist.loaded {
return
}
if tm.source == Unavailable {
tm.Init()
tm.Load()
}
if tm.source == Local || tm.source == OutdatedNetwork {
tasklist.LoadLocal()
if tm.source == OutdatedNetwork {
tasklist.MarkModified()
}
}
}
// Save is responsible for saving changes to the local taskfile and uploading
// data to the appropriate Sync service.
func (tm *TasklistManager) Save() {
if !MainList.modified && !DoneList.modified {
return
}
MainList.SerializeTasks()
DoneList.SerializeTasks()
// Save local taskfiles
if MainList.modified {
MainList.SaveLocal()
}
if DoneList.modified {
DoneList.SaveLocal()
}
// Upload to Sync service
if tm.source > Local {
// Marshal into JSON
jsonMap := map[string]string{
"contents": string(MainList.serialized),
"doneContents": string(DoneList.serialized),
}
jsonData, err := json.Marshal(jsonMap)
if err != nil {
Error(ErrSerializeJSON, err)
}
// Complete PUT Request
url := tm.syncURL + tm.syncID
request, err := http.NewRequest("PUT", url, bytes.NewReader(jsonData))
if err != nil {
Error(ErrPUTReqCreate, url, err)
}
request.Header = JSONHeaders
resp, err := http.DefaultClient.Do(request)
if err != nil {
Error(ErrPUTReqComplete, url, err)
}
defer resp.Body.Close()
statusCode := resp.StatusCode
switch statusCode {
case 404:
Error(ErrNoSyncID, tm.syncID)
case 200:
// Update LastNetworkUpdate value in Syncfile
newLastNetworkUpdate := StripNanoFromTime(time.Now())
line := "lastNetworkUpdate: " + newLastNetworkUpdate.Format(LastNetworkUpdateFormat) + "\n"
ReplaceOrAppendSyncfileLine(LastNetworkUpdatePattern, line)
default:
Error(ErrInvalidResponse, url, "status is "+resp.Status)
}
}
RunCallback()
}