-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
337 lines (296 loc) · 7.8 KB
/
main.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/alexflint/go-arg"
"github.com/pkg/errors"
"github.com/shibukawa/configdir"
"github.com/vbauerster/mpb/v4/decor"
"github.com/zalando/go-keyring"
)
var (
appName = "cloudyuploader"
version = "0.0.0-in-dev" // overriden on build
appURL = "https://github.com/Andrew-Morozko/cloudy-uploader"
userAgent = appName + "/" + version + " CLI Uploader; " + appURL
)
var overcastURL = URLMustParse("https://overcast.fm/")
var debug = false
var client = NewHTTPClient()
var keyringUsable = true
var allowedExts = ExtList{"mp3", "m4a", "aac", "wav", "m4b"}
type ExtList []string
func (el ExtList) Inclues(ext string) bool {
ext = strings.ToLower(ext)
ext = strings.TrimLeft(ext, ".")
for _, allowed := range el {
if allowed == ext {
return true
}
}
return false
}
type Args struct {
Files []string `arg:"--file,positional,required" help:"files to be uploaded"`
Login string `help:"email for Overcast account"`
Password string `help:"password for Overcast account"`
SaveCreds *bool `arg:"--save-creds" help:"save credentials in secure system storge"`
NoLoadCreds bool `arg:"--no-load-creds" help:"do not use stored creds"`
MaxParallel int `arg:"-j,--parallel-uploads" help:"maximum number of concurrent uploads" default:"4" placeholder:"N"`
Silent bool `arg:"-s" help:"disable user interaction"`
UnorderedSubmit bool `arg:"--unordered-submit" help:"don't wait to submit uploads in proper order"`
}
func (Args) Description() string {
return `Unofficial CLI file uploader for Overcast. Version ` + version + `
Technically it's just a wrapper around upload a form at https://overcast.fm/uploads
`
}
func migrateToKeyring() {
configDirs := configdir.New("", appName)
configDir := configDirs.QueryFolders(configdir.Global)[0]
if !configDir.Exists("config.json") {
return
}
data, err := configDir.ReadFile("config.json")
if err != nil {
fmt.Printf("[WARN] Failed to read config file: %s\n", err)
return
}
var cfg AuthData
err = json.Unmarshal(data, &cfg)
if err != nil {
fmt.Printf("[WARN] Invalid JSON config file: %s\n", err)
return
}
err = keyring.Set(appName, "creds", string(data))
if err != nil {
fmt.Printf("[WARN] Failed to save credentials: %s\n", err)
}
os.RemoveAll(configDir.Path)
}
func loadCreds() (authData *AuthData) {
if !keyringUsable {
return nil
}
migrateToKeyring()
data, err := keyring.Get(appName, "creds")
if err != nil {
if err == keyring.ErrNotFound {
return
}
if t, ok := err.(*exec.ExitError); ok {
if t.ExitCode() == 36 {
keyringUsable = false
fmt.Println("[WARN] Your keychain is locked!")
fmt.Println(`[WARN] To use stored credentials you should unlock it by running "security unlock-keychain" command.`)
return
}
}
fmt.Printf("[WARN] Failed to load credentials: %s\n", err)
return
}
authData, err = ParseAuthData([]byte(data))
if err != nil {
fmt.Printf("[WARN] Failed to load credentials: %s\n", err)
authData = nil
}
return
}
func saveCreds(ad *AuthData) {
if !keyringUsable {
return
}
data, err := json.Marshal(ad)
if err != nil {
return
}
err = keyring.Set(appName, "creds", string(data))
if err != nil {
if t, ok := err.(*exec.ExitError); ok {
if t.ExitCode() == 36 {
keyringUsable = false
fmt.Println("[WARN] Your keychain is locked!")
fmt.Println(`[WARN] To save credentials you should unlock it by running "security unlock-keychain" command.`)
return
}
}
fmt.Printf("[WARN] Failed to save credentials: %s\n", err)
return
}
}
func parseArgs() (args *Args, err error) {
args = &Args{}
arg.MustParse(args)
if args.MaxParallel < 1 {
err = errors.New("--parallel-uploads should be at least 1")
return
}
if args.Silent {
os.Stdout, err = os.Open(os.DevNull)
if err != nil {
err = errors.WithMessage(err, "can't open devnull")
return
}
}
return
}
func Input(prompt string) (answer string, err error) {
fmt.Print(prompt)
reader := bufio.NewReader(os.Stdin)
answer, err = reader.ReadString('\n')
if err != nil {
return
}
answer = strings.TrimSpace(answer)
return
}
func PerformAuth(args *Args) (uploads *http.Response, err error) {
var ad *AuthData
// auth with command line data
if args.Login != "" && args.Password != "" {
ad = &AuthData{
Creds: &Creds{
args.Login,
args.Password,
},
}
uploads, err = ad.Auth()
if err == nil {
if args.SaveCreds != nil && *args.SaveCreds {
saveCreds(ad)
}
return
} else {
fmt.Printf("[WARN] Failed to authenticate with supplied login/passowrd: %s\n", err)
}
}
// auth with cookies/saved password
if !args.NoLoadCreds {
ad = loadCreds()
if ad != nil {
uploads, err = ad.Auth()
if err == staleCookiesErr {
// refresh saved cookies
saveCreds(ad)
err = nil
}
if err == nil {
return
} else {
fmt.Printf("[WARN] Failed to authenticate with saved login/passowrd: %s\n", err)
}
}
}
// auth with input password
if !args.Silent {
ad = &AuthData{
Creds: inputCreds(),
}
if ad.Creds != nil {
uploads, err = ad.Auth()
if err == nil {
if args.SaveCreds == nil {
// Ask to save
answer, err2 := Input("Do you want to store the email/password securely on your system? [y/N]: ")
if err2 != nil {
fmt.Printf("\n[WARN] Failed to get answer: %s\n", err2)
return
}
if len(answer) >= 1 && (answer[0] == 'Y' || answer[0] == 'y') {
saveCreds(ad)
}
} else {
if *args.SaveCreds {
saveCreds(ad)
}
}
return
} else {
fmt.Printf("[WARN] Failed to authenticate with entered login/passowrd: %s\n", err)
}
}
}
uploads = nil
err = errors.New("all availible methods failed")
return
}
func parseFiles(files []string, overcastParams *OvercastParams) (jobs []*Job) {
for _, file := range files {
if !allowedExts.Inclues(filepath.Ext(file)) {
fmt.Printf("[WARN] File \"%s\" is not allowed. Allowed extentions: %s\n", file, strings.Join(allowedExts, ", "))
continue
}
stat, err := os.Stat(file)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("[WARN] File \"%s\" doesn't exist\n", file)
} else {
fmt.Printf("[WARN] Error with file \"%s\": %s\n", file, err)
}
continue
}
fileSize := stat.Size()
if fileSize > overcastParams.MaxFileSize {
fmt.Printf(
"[WARN] File \"%s\" is too large: file size=% .2f, max file size=% .2f\n",
file, decor.SizeB1000(fileSize), decor.SizeB1000(overcastParams.MaxFileSize),
)
continue
}
jobs = append(jobs, NewJob(file, fileSize))
}
return
}
func main() {
var err error
defer func() {
if err != nil {
fmt.Printf("[ERROR] %s\n", err)
os.Exit(-1)
}
}()
args, err := parseArgs()
if err != nil {
err = errors.WithMessage(err, "Arguments error")
return
}
upl, err := PerformAuth(args)
if err != nil {
err = errors.WithMessage(err, "Auth failed")
return
}
overcastParams, err := parseUploadsPage(upl.Body)
upl.Body.Close()
if err != nil {
err = errors.WithMessage(err, "Failed to parse the uploads page")
return
}
jobs := parseFiles(args.Files, overcastParams)
if len(jobs) == 0 {
err = errors.New("No files to upload!")
return
}
if len(jobs) > overcastParams.MaxFileCount {
err = errors.Errorf("You've chosen too many files(%d), you only have %d files remaining",
len(jobs), overcastParams.MaxFileCount,
)
return
}
var totalSize int64
for _, job := range jobs {
totalSize += job.FileSize
}
if totalSize > overcastParams.SpaceAvailible {
err = errors.Errorf("Files are too large: total size=% .2f; you have % .2f availible\n",
decor.SizeB1000(totalSize), decor.SizeB1000(overcastParams.SpaceAvailible),
)
return
}
performUpload(jobs, args.MaxParallel, args.UnorderedSubmit, overcastParams)
}