From 06b553ab3f6355e643049dad0ccb570a0bc0d613 Mon Sep 17 00:00:00 2001 From: kaa Date: Sat, 25 Nov 2023 12:40:23 -0800 Subject: WIP Directory traversal using go. --- cantree/tree.go | 102 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 cantree/tree.go (limited to 'cantree/tree.go') diff --git a/cantree/tree.go b/cantree/tree.go new file mode 100644 index 0000000..8a7464f --- /dev/null +++ b/cantree/tree.go @@ -0,0 +1,102 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "os" + "encoding/json" + "errors" + "io/fs" + "strconv" +) + +var downloadKey string + +func request(dirID string) []byte { + req, err := http.NewRequest("GET", base+dirID, nil) + if err != nil { + log.Fatal(err) + } + + req.Header.Add("Authorization", "Bearer "+downloadKey) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + log.Fatal(err) + } + + rt, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + resp.Body.Close() + + return rt +} + +func traverse(j map[string]interface{}) { + name := j["name"].(string) + /* Internally stored as float64. + Must be converted to int before string. */ + id := strconv.Itoa(int(j["id"].(float64))) + fmt.Println(name, id) + + var files []map[string]interface{} + var err error + str := "folders/" + string(id) + "/files" + fmt.Println(str) + err = json.Unmarshal(request("folders/"+string(id)+"/files"), + &files) + if err != nil { + log.Fatal(err) + } + + for _, i := range files { + for i, j := range i { + fmt.Printf("%s %v\n", i, j) + } + } + + return + err = os.Mkdir(name, 0777) + if err != nil { + log.Fatal(err) + } + + _ = os.Chdir(name) + defer os.Chdir("..") + + +} + +// Traverse and download the contents of the Canvas API. +func main() { + var set bool + downloadKey, set = os.LookupEnv("CANKEY") + if !set { + log.Fatal("Set the environment variable CANKEY to persistently contain your Canvas account API key.") + } + + _, err := os.Stat("root") + if errors.Is(err, fs.ErrNotExist) { + os.Mkdir("root", 0777) + } + err = os.Chdir("root") + if err != nil { + log.Fatal(err) + } + + body := request("users/self/folders") + + var m []map[string]interface{} + err = json.Unmarshal(body, &m) + if err != nil { + log.Fatal(err) + } + + for _, i := range m { + traverse(i) + } +} -- cgit v1.2.3