]> Sergey Matveev's repositories - mmfileget.git/blob - main.go
Print response when failed
[mmfileget.git] / main.go
1 package main
2
3 import (
4         "fmt"
5         "io/ioutil"
6         "os"
7         "path/filepath"
8         "strings"
9
10         "github.com/mattermost/mattermost-server/v5/model"
11 )
12
13 func main() {
14         url := strings.TrimPrefix(os.Args[1], "-") // -?https://MACHINE/api/v4/files/FILE
15         s := strings.Split(url, "/")
16         machine, fileId := s[2], s[6]
17
18         netrcPath, ok := os.LookupEnv("NETRC")
19         if !ok {
20                 netrcPath = filepath.Join(os.Getenv("HOME"), ".netrc")
21         }
22         data, err := ioutil.ReadFile(netrcPath)
23         if err != nil {
24                 panic(err)
25         }
26         var login string
27         var password string
28         for _, line := range strings.Split(string(data), "\n") {
29                 if i := strings.Index(line, "#"); i >= 0 {
30                         line = line[:i]
31                 }
32                 f := strings.Fields(line)
33                 if len(f) >= 6 &&
34                         f[0] == "machine" && f[1] == machine &&
35                         f[2] == "login" && f[4] == "password" {
36                         login, password = f[3], f[5]
37                         break
38                 }
39         }
40         if login == "" || password == "" {
41                 fmt.Fprintln(os.Stderr, "No credentials found for:", machine)
42                 os.Exit(1)
43         }
44
45         Client := model.NewAPIv4Client("https://" + machine)
46         Client.Login(login, password)
47         info, resp := Client.GetFileInfo(fileId)
48         if info == nil {
49                 fmt.Fprintln(os.Stderr, resp)
50                 os.Exit(1)
51         }
52         filename := info.Name
53         if len(os.Args) > 2 {
54                 filename = os.Args[2]
55         } else {
56                 fmt.Fprintln(os.Stderr, "Name:", info.Name)
57                 fmt.Fprintln(os.Stderr, "Type:", info.MimeType)
58                 fmt.Fprintln(os.Stderr, "Size:", info.Size)
59                 fmt.Fprintln(os.Stderr, "Download? Ctrl-D/C")
60                 os.Stdin.Read(make([]byte, 1))
61         }
62         data, _ = Client.GetFile(fileId)
63         if err = ioutil.WriteFile(filename, data, os.FileMode(0666)); err != nil {
64                 panic(err)
65         }
66 }