forked from FreedomBen/outcomes-import-tool
/
outcomes_import_tool.go
355 lines (315 loc) · 9.16 KB
/
outcomes_import_tool.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
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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
)
const ConfigFile string = ".outcomes-import-tool.json"
type config struct {
Apikey string `json:"apikey"`
MigrationId int `json:"migration_id"`
Domain string `json:"domain"`
Guids []importableGuid `json:"guids"`
}
type request struct {
Body string
Apikey string
Domain string
Method string
Endpoint string
}
type importableGuid struct {
Title string `json:"title"`
Guid string `json:"guid"`
}
type migrationIssue struct {
Id int `json:"id"`
IssueType string `json:"issue_type"`
Description string `json:"description"`
ErrorReportUrl string `json:"error_report_html_url"`
ErrorMessage string `json:"error_message"`
}
type migrationStatus struct {
Id int `json:"id"`
WorkflowState string `json:"workflow_state"`
MigrationIssuesCount int `json:"migration_issues_count"`
MigrationIssues []migrationIssue `json:"migration_issues"`
Errors []apiError `json:"errors"`
}
type newImport struct {
MigrationId int `json:"migration_id"`
Guid string `json:"guid"`
Errors []apiError `json:"errors"`
Error string `json:"errors"`
}
type apiErrors struct {
Errors []apiError `json:"errors"`
}
type apiError struct {
Message string `json:"message"`
}
func configFromFile() *config {
if f, err := os.Open(configFile()); err == nil {
var cf config
if err := json.NewDecoder(f).Decode(&cf); err != nil {
log.Fatalln("Config file json error:", err)
}
return &cf
} else {
return nil
}
}
func (c *config) writeToFile() {
current := configFromFile()
// we only want to store the API key if the user already stores it
if current == nil || current.Apikey == "" {
c.Apikey = ""
}
b, err := json.MarshalIndent(*c, "", " ")
if err != nil {
log.Fatalln("Error writing to", configFile())
}
ioutil.WriteFile(configFile(), b, 0600)
}
func configFile() string {
return fmt.Sprintf("%s/%s", os.Getenv("HOME"), ConfigFile)
}
func main() {
var apikey = flag.String("apikey", "", "Canvas API key")
var domain = flag.String(
"domain",
"",
"The domain. You can just say the school name if they have a \"<school>.instructure.com\" domain, or 'localhost'",
)
var status = flag.Int("status", 0, "migration ID to check status")
var available = flag.Bool("available", false, "Check available migration IDs")
var guid = flag.String("guid", "", "GUID to schedule for import")
flag.Parse()
if cf := configFromFile(); cf != nil {
if *apikey == "" {
log.Println("Using API key from config file")
apikey = &cf.Apikey
}
if *status == 0 {
log.Println("Using migration ID from config file")
status = &cf.MigrationId
}
if *domain == "" {
log.Println("Using domain from config file")
domain = &cf.Domain
}
}
req := request{Apikey: *apikey, Domain: *domain}
verifyRequest(&req)
req.Domain = normalizeDomain(req.Domain)
if *available {
printAvailable(req)
} else if *guid != "" {
importGuid(req, *guid)
} else if *status != 0 {
getStatus(req, *status)
} else {
log.Fatalln("No recent migration ID, and none specified to query status on")
}
}
func normalizeDomain(domain string) string {
retval := domain
if domain == "localhost" {
return "http://localhost:3000"
// if we start with http then don't add it, otherwise do
} else if !strings.HasPrefix(retval, "http") {
retval = fmt.Sprintf("https://%s", retval)
if !strings.HasSuffix(retval, "com") && !strings.HasSuffix(retval, "/") {
retval = fmt.Sprintf("%s.instructure.com", retval)
}
}
return strings.TrimSuffix(retval, "/")
}
func errAndExit(message ...interface{}) {
// flag.Usage()
log.Fatalln(message...)
os.Exit(1)
}
func verifyRequest(req *request) {
if req.Apikey == "" {
errAndExit(fmt.Sprintf("Whoops, no API key stored in config file \"%s\" and none passed as an arg", configFile()))
}
if req.Domain == "" {
errAndExit(fmt.Sprintf("Whoops, no canvas domain stored in config file \"%s\" and none passed as an arg", configFile()))
}
}
func httpRequest(req request) (*http.Client, *http.Request) {
client := &http.Client{}
hreq, err := http.NewRequest(
req.Method,
fmt.Sprintf("%s%s", req.Domain, req.Endpoint),
strings.NewReader(req.Body),
)
if err != nil {
log.Fatalln(err)
}
hreq.Header.Add("Authorization", fmt.Sprintf("Bearer %s", req.Apikey))
return client, hreq
}
func printAvailable(req request) {
guids := getAvailable(req)
printImportableGuids(guids)
migId := 0
if cff := configFromFile(); cff != nil {
migId = cff.MigrationId
}
(&config{
Apikey: req.Apikey,
Domain: req.Domain,
MigrationId: migId,
Guids: guids,
}).writeToFile()
}
func getAvailable(req request) []importableGuid {
req.Body = ""
req.Method = "GET"
req.Endpoint = "/api/v1/global/outcomes_import/available"
client, hreq := httpRequest(req)
log.Printf("Requesting available guids from %s", hreq.URL)
resp, err := client.Do(hreq)
if err != nil {
log.Fatalln(err)
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
var errs apiErrors
if json.NewDecoder(bytes.NewReader(body)).Decode(&errs); len(errs.Errors) > 0 {
printErrors(errs.Errors)
os.Exit(1)
}
var guids []importableGuid
if e := json.NewDecoder(bytes.NewReader(body)).Decode(&guids); e != nil {
log.Fatalln("JSON decoding error. Make sure your API key is correct and that you have permission to read global outcomes", e)
}
return guids
}
func getStatus(req request, migrationId int) {
req.Body = ""
req.Method = "GET"
req.Endpoint = fmt.Sprintf(
"/api/v1/global/outcomes_import/migration_status/%d",
migrationId,
)
client, hreq := httpRequest(req)
log.Printf("Retrieving status for migration %d", migrationId)
resp, err := client.Do(hreq)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
var mstatus migrationStatus
if e := json.NewDecoder(resp.Body).Decode(&mstatus); e != nil {
log.Fatalln("JSON decoding error. Make sure your API key is correct and that you have permission to read global outcomes", e)
}
printMigrationStatus(mstatus)
prevConfig := configFromFile()
(&config{
Apikey: req.Apikey,
Domain: req.Domain,
MigrationId: migrationId,
Guids: prevConfig.Guids,
}).writeToFile()
}
func importGuid(req request, guid string) {
// first check to see if what we've been passed is a proper GUID
match, _ := regexp.MatchString(
"[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}",
guid,
)
if !match {
log.Println("GUID is not valid. Checking to see if it matches a valid title...")
// then check to see if we've been given a title
config := configFromFile()
var guids []importableGuid
if len(config.Guids) > 0 {
log.Println("Using cached guid from config file")
guids = config.Guids
} else {
log.Println("Cache file does not contain guids. Fetching guids from AB")
guids = getAvailable(req)
}
for _, val := range guids {
if val.Title == guid {
guid = val.Guid
break
}
}
}
req.Body = fmt.Sprintf("guid=%s", guid)
req.Method = "POST"
req.Endpoint = "/api/v1/global/outcomes_import/"
client, hreq := httpRequest(req)
log.Printf("Requesting import of GUID %s", guid)
resp, err := client.Do(hreq)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
var nimport newImport
if e := json.NewDecoder(resp.Body).Decode(&nimport); e != nil {
log.Fatalln("JSON decoding error. Make sure your API key is correct and that you have permission to read global outcomes.", e)
}
printImportResults(nimport)
prevConfig := configFromFile()
(&config{
Apikey: req.Apikey,
Domain: req.Domain,
MigrationId: nimport.MigrationId,
Guids: prevConfig.Guids,
}).writeToFile()
}
func printImportableGuids(guids []importableGuid) {
fmt.Printf("GUIDs available to import:\n\n")
for _, guid := range guids {
fmt.Printf("%s - %s\n", guid.Guid, guid.Title)
}
}
func printMigrationStatus(mstatus migrationStatus) {
if len(mstatus.Errors) > 0 {
printErrors(mstatus.Errors)
} else {
if mstatus.Id == 0 {
fmt.Println("\nThe server returned an error. Are you sure that migration ID exists?")
} else {
fmt.Printf("\nMigration status for migration '%d':\n", mstatus.Id)
fmt.Printf(" - Workflow state: %s\n", mstatus.WorkflowState)
fmt.Printf(" - Migration issues count: %d\n", mstatus.MigrationIssuesCount)
fmt.Printf(" - Migration issues:\n")
for _, val := range mstatus.MigrationIssues {
fmt.Printf(" - ID: %d\n", val.Id)
fmt.Printf(" - Link: %s\n", val.ErrorReportUrl)
fmt.Printf(" - Issue type: %s\n", val.IssueType)
fmt.Printf(" - Error message: %s\n", val.ErrorMessage)
fmt.Printf(" - Description: %s\n", val.Description)
}
}
}
}
func printImportResults(nimport newImport) {
log.Println(nimport)
if len(nimport.Errors) > 0 {
printErrors(nimport.Errors)
} else if nimport.Error != "" {
fmt.Printf("\nError: %s\n", nimport.Error)
} else {
fmt.Printf("\nMigration ID is %d\n", nimport.MigrationId)
}
}
func printErrors(errors []apiError) {
fmt.Println("\nErrors encountered:")
for _, err := range errors {
fmt.Println(err)
}
}