-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmixcloud.go
595 lines (468 loc) · 14.5 KB
/
mixcloud.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
package main
import (
"bufio"
"bytes"
_ "crypto/sha512"
"encoding/json"
"fmt"
"github.com/cheggaaa/pb"
"github.com/ruxton/mixcloud/confirm"
"github.com/ruxton/mixcloud/mixcloud"
"github.com/ruxton/mixcloud/term"
"github.com/mattn/go-colorable"
"io"
flag "launchpad.net/gnuflag"
"mime/multipart"
"net/http"
"os"
"os/user"
"path/filepath"
"strings"
"time"
)
var VERSION string
var MINVERSION string
var OAUTH_CLIENT_ID string
var OAUTH_CLIENT_SECRET string
var OAUTH_REDIRECT_URI = "http://www.rhythmandpoetry.net/mixcloud_code.php"
var API_URL = "https://api.mixcloud.com/upload/?access_token="
var ACCESS_TOKEN_URL = "https://www.mixcloud.com/oauth/access_token?client_id=" + OAUTH_CLIENT_ID + "&redirect_uri=" + OAUTH_REDIRECT_URI + "&client_secret=" + OAUTH_CLIENT_SECRET + "&code=%s"
var API_ME_URL = "https://api.mixcloud.com/me?access_token="
var CONFIG_FILE = "config.json"
var CONFIG_FILE_PATH = ""
var TRACKLIST_OUTPUT_FORMAT = "%d. %s-%s\n"
var CURRENT_USER mixcloud.User = mixcloud.User{}
var configuration = Configuration{}
var aboutFlag = flag.Bool("about", false, "About the application")
var configFlag = flag.Bool("config", false, "Configure the application")
var fileFlag = flag.String("file", "", "The mp3 file to upload to mixcloud")
var coverFlag = flag.String("cover", "", "The image file to upload to mixcloud as the cover")
var trackListFlag = flag.String("tracklist", "", "A file containing a VirtualDJ Tracklist for the cloudcast")
var STD_OUT = bufio.NewWriter(colorable.NewColorableStdout())
var STD_ERR = bufio.NewWriter(colorable.NewColorableStderr())
var STD_IN = bufio.NewReader(os.Stdin)
type Configuration struct {
ACCESS_TOKEN string
DEFAULT_TAGS string
}
func showWelcomeMessage() {
OutputMessage(term.Green + "Mixcloud CLI Uploader v" + VERSION + term.Reset + "\n\n")
}
func showAboutMessage() {
OutputMessage(fmt.Sprintf("Build Number: %s\n", MINVERSION))
OutputMessage("Created by: Greg Tangey (http://ignite.digitalignition.net/)\n")
OutputMessage("Website: http://www.rhythmandpoetry.net/\n")
}
func createConfig() {
OutputMessage("Creating Configuration File...\n")
OutputMessage("Please visit the URL below\n\nhttps://www.mixcloud.com/oauth/authorize?client_id=z3CWHgULyawutvpcD3&redirect_uri=http://www.rhythmandpoetry.net/mixcloud_code.php\n")
OutputMessage("Enter the provided code: ")
code, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Code Error.")
os.Exit(2)
}
code = strings.TrimSpace(code)
access_token := fetchAccessCode(code)
if access_token == "" {
OutputError("Error fetching access token")
os.Exit(2)
} else {
configuration.ACCESS_TOKEN = access_token
}
OutputMessage("Enter default tags (comma separated): ")
tags, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect tag format.")
os.Exit(2)
} else {
configuration.DEFAULT_TAGS = strings.TrimSpace(tags)
}
saveConfig()
}
func build_http(url string, request string) *http.Request {
req, err := http.NewRequest(request, url, nil)
if err != nil {
OutputError(err.Error())
}
req.Header.Set("User-Agent", "Mixcloud CLI Uploader v"+VERSION)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
return req
}
func fetchMe(access_token string) mixcloud.User {
OutputMessage(term.Green + "Fetching your user data.." + term.Reset + "\n")
url := API_ME_URL + access_token
request := build_http(url, "GET")
client := http.Client{}
resp, doError := client.Do(request)
if doError != nil {
OutputError("Error fetching your profile data: " + doError.Error())
os.Exit(2)
}
var user mixcloud.User
jsonError := json.NewDecoder(resp.Body).Decode(&user)
resp.Body.Close()
if jsonError != nil {
OutputError("Error decoding response from API - " + jsonError.Error())
os.Exit(2)
}
return user
}
func fetchAccessCode(code string) string {
url := fmt.Sprintf(ACCESS_TOKEN_URL, code)
request := build_http(url, "GET")
client := &http.Client{}
resp, doError := client.Do(request)
if doError != nil {
OutputError("Error fetching Access Code: " + doError.Error())
os.Exit(2)
}
var jsonResponse map[string]interface{}
jsonError := json.NewDecoder(resp.Body).Decode(&jsonResponse)
resp.Body.Close()
if jsonError != nil {
OutputError("Error decoding response from API - " + jsonError.Error())
os.Exit(2)
}
var access_token = ""
if jsonResponse["access_token"] != nil {
access_token = jsonResponse["access_token"].(string)
}
return access_token
}
func saveConfig() {
file, error := os.Create(CONFIG_FILE)
defer file.Close()
if error != nil {
OutputError(fmt.Sprintf("Unable to save configuration file conf.json - ", error))
os.Exit(2)
}
encoder := json.NewEncoder(file)
err := encoder.Encode(&configuration)
if err != nil {
OutputError(fmt.Sprintf("Error writing to config file: %s", err))
os.Exit(2)
} else {
OutputMessage(term.Green + "Configuration saved." + term.Reset + "\n")
}
}
func loadConfig() {
file, error := os.Open(CONFIG_FILE)
defer file.Close()
if error != nil {
//Config file doesn't exist, create
createConfig()
} else {
decoder := json.NewDecoder(file)
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("Error reading config file: ", err)
os.Exit(2)
}
}
if configuration.ACCESS_TOKEN == "" {
OutputError("Access Token configuration missing.")
os.Exit(2)
}
}
func setupApp() {
usr, _ := user.Current()
CONFIG_FILE_PATH = filepath.Join(usr.HomeDir, ".mixcloud")
CONFIG_FILE = filepath.Join(CONFIG_FILE_PATH, CONFIG_FILE)
if _, err := os.Stat(CONFIG_FILE_PATH); os.IsNotExist(err) {
os.Mkdir(CONFIG_FILE_PATH, 0700)
}
}
func main() {
flag.Parse(true)
showWelcomeMessage()
if *aboutFlag == true {
showAboutMessage()
os.Exit(0)
}
setupApp()
loadConfig()
CURRENT_USER = fetchMe(configuration.ACCESS_TOKEN)
var tracklist []mixcloud.Track
if *configFlag == true {
createConfig()
}
if *trackListFlag != "" {
tracklist = parseVirtualDJTrackList(trackListFlag)
}
if *fileFlag == "" {
OutputError("You must pass a file to upload, use --file or see --help.\n Exiting.")
os.Exit(2)
}
b := &bytes.Buffer{}
writer := multipart.NewWriter(b)
cast_name, cast_desc, tags_arr := GetBasicInput()
BuildBasicHTTPWriter(writer, cast_name, cast_desc, tags_arr, tracklist)
AddPremiumToHTTPWriter(writer)
// Add MP3
if *fileFlag != "" {
loadFileToWriter(*fileFlag, "mp3", writer)
}
// Add cover image
if *coverFlag != "" {
loadFileToWriter(*coverFlag, "picture", writer)
}
writer.Close()
// bufReader := bufio.NewReader(b)
// for line, _, err := bufReader.ReadLine(); err != io.EOF; line, _, err = bufReader.ReadLine() {
// OutputMessage(string(line) + "\n")
// }
request, bar := HttpUploadRequest(b, writer)
bar.Empty = term.Red + "-" + term.Reset
bar.Current = term.Green + "=" + term.Reset
client := &http.Client{}
OutputMessage("\n\n")
STD_OUT.Flush()
bar.Start()
resp, err := client.Do(request)
if err != nil {
OutputError("Error: " + err.Error())
os.Exit(2)
}
bar.Finish()
var Response *mixcloud.Response = new(mixcloud.Response)
error := json.NewDecoder(resp.Body).Decode(&Response)
resp.Body.Close()
if error != nil {
OutputError("Error decoding response from API - " + error.Error())
os.Exit(2)
}
if handleJSONResponse(*Response) {
printTracklist(tracklist)
} else {
os.Exit(2)
}
}
func GetBasicInput() (string, string, []string) {
OutputMessage("Enter a name for the cloudcast: ")
cast_name, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect name.")
os.Exit(2)
}
OutputMessage("Enter a description: ")
cast_desc, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect description.")
os.Exit(2)
}
OutputMessage(fmt.Sprintf("Enter tags (comma separated) [%s]: ", configuration.DEFAULT_TAGS))
cast_tags, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect tag format.")
os.Exit(2)
}
if cast_tags == "" || cast_tags == "\n" {
cast_tags = configuration.DEFAULT_TAGS
}
tags_arr := strings.Split(cast_tags, ",")
return cast_name, cast_desc, tags_arr
}
func printTracklist(tracklist []mixcloud.Track) {
OutputMessage("Tracklist\n")
for i, track := range tracklist {
OutputMessage(fmt.Sprintf(TRACKLIST_OUTPUT_FORMAT, i+1, track.Artist, track.Song))
}
}
func parseVirtualDJTrackList(tracklist *string) []mixcloud.Track {
var list []mixcloud.Track
fin, err := os.Open(*tracklist)
if err != nil {
fmt.Fprintf(os.Stderr, "The file %s does not exist!\n", tracklist)
return nil
}
defer fin.Close()
bufReader := bufio.NewReader(fin)
var last_track_time_str string = ""
for line, _, err := bufReader.ReadLine(); err != io.EOF; line, _, err = bufReader.ReadLine() {
data := strings.Split(string(line), " : ")
tracktimestr, track := data[0], data[1]
thistrack := new(mixcloud.Track)
var trackdata []string = strings.SplitN(string(track), " - ", 2)
if len(trackdata) != 2 {
OutputError("Error parsing track " + string(track) + " at " + tracktimestr)
OutputMessage("Please enter an artist for this track: ")
artist, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect artist entry.")
os.Exit(2)
}
OutputMessage("Please enter a name for this track: ")
track, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect track name entry.")
os.Exit(2)
}
trackdata = []string{artist, track}
}
thistrack.Artist = trackdata[0]
thistrack.Song = trackdata[1]
last_time, _ := time.Parse("15:04", last_track_time_str)
track_time, err := time.Parse("15:04", tracktimestr)
if err != nil {
OutputError("Unable to parse time." + err.Error())
os.Exit(2)
}
if last_track_time_str != "" {
duration := track_time.Sub(last_time)
thistrack.Duration = int(duration.Seconds())
}
last_track_time_str = tracktimestr
list = append(list, *thistrack)
// if !isPrefix {
// fmt.Printf("Lines: %s (error %v)\n", string(bytes), err)
// bytes = bytes[:0]
// }
}
return list
}
func handleJSONResponse(response mixcloud.Response) bool {
if response.Error != nil {
OutputError(response.Error.Message)
fmt.Printf("%v",response.Details)
return false
} else if response.Result.Success {
OutputMessage(term.Green + "Sucessfully uploaded file" + term.Reset + "\n")
path := response.Result.Key
OutputMessage(term.Green + "https://mixcloud.com" + path + "edit" + term.Reset + "\n")
return true
} else {
OutputError("Error uploading, no success")
fmt.Printf("%v",response)
return false
}
}
func OutputError(message string) {
STD_ERR.WriteString(term.Bold + term.Red + message + term.Reset + "\n")
STD_ERR.Flush()
}
func OutputMessage(message string) {
STD_OUT.WriteString(message)
STD_OUT.Flush()
}
func loadFileToWriter(file string, key string, writer *multipart.Writer) {
f, err := os.Open(file)
if err != nil {
OutputError("Error opening file " + file + "\n")
os.Exit(2)
}
defer f.Close()
fw, err := writer.CreateFormFile(key, file)
if err != nil {
OutputError("Error reading file " + file + "\n")
os.Exit(2)
}
if _, err = io.Copy(fw, f); err != nil {
OutputError("Error opening file " + file + " to buffer\n")
os.Exit(2)
}
}
func BuildBasicHTTPWriter(writer *multipart.Writer, name string, desc string, tag_list []string, tracklist []mixcloud.Track) {
// Add information name/description
writer.WriteField("name", name)
writer.WriteField("description", desc)
// Add tags
for i, tag := range tag_list {
field_name := fmt.Sprintf("tags-%d-tag", i)
writer.WriteField(field_name, tag)
}
// Add tracklist
if tracklist != nil {
var total_duration int = 0
for i, track := range tracklist {
artist_field_name := fmt.Sprintf("sections-%d-artist", i)
song_field_name := fmt.Sprintf("sections-%d-song", i)
duration_field_name := fmt.Sprintf("sections-%d-start_time", i)
total_duration += track.Duration
writer.WriteField(artist_field_name, track.Artist)
writer.WriteField(song_field_name, track.Song)
writer.WriteField(duration_field_name, fmt.Sprintf("%d", total_duration))
}
}
}
func ParseDateInputToTime(dateIn string) time.Time {
location, err := time.LoadLocation("Local")
dateTime, err := time.ParseInLocation("02/01/2006 15:04", strings.TrimSpace(dateIn), location)
if err != nil {
OutputError("Incorrect date format - " + err.Error())
os.Exit(2)
}
return dateTime
}
func AddPremiumToHTTPWriter(writer *multipart.Writer) {
// If you're not PRO, you can't do this, get out
if !CURRENT_USER.IsPro {
return
}
OutputMessage("\n" + term.Green + "Setting pro user attributes..." + term.Reset + "\n")
publish_date, disable_comments, hide_stats, unlisted := GetPremiumInput()
if publish_date != "" {
writer.WriteField("publish_date", publish_date)
}
if(disable_comments) {
writer.WriteField("disable_comments", "1")
}
if(hide_stats) {
writer.WriteField("hide_stats", "1")
}
if(unlisted) {
writer.WriteField("unlisted", "1")
}
}
func GetPremiumInput() (string, bool, bool, bool) {
disable_comments := false
hide_stats := false
unlisted := false
publish_date := ""
fmt.Printf("Disable comments? [y/n] ")
if confirm.AskForConfirmation() {
disable_comments = true
}
fmt.Printf("Hide statistics? [y/n] ")
if confirm.AskForConfirmation() {
hide_stats = true
}
fmt.Printf("Set to unlisted? [y/n] ")
if confirm.AskForConfirmation() {
unlisted = true
}
fmt.Printf("Set publish date? [y/n] ")
if confirm.AskForConfirmation() {
publish_date = PublishDateInput()
}
return publish_date, disable_comments, hide_stats, unlisted
}
func PublishDateInput() (string) {
current_time := time.Now().In(time.Local)
zonename, offset := current_time.Zone()
OutputMessage("Enter a publish date in "+zonename+" ("+fmt.Sprintf("%+d",offset/60/60)+" GMT) [DD/MM/YYYY HH:MM]: ")
inPublishDate, err := STD_IN.ReadString('\n')
if err != nil {
OutputError("Incorrect publish date.")
os.Exit(2)
}
publish_date := ParseDateInputToTime(inPublishDate)
if(!publish_date.After(current_time)) {
OutputError("Date "+publish_date.Format(time.RFC1123)+" is not in the future")
return PublishDateInput()
}
return publish_date.UTC().Format(time.RFC3339)
}
func HttpUploadRequest(b *bytes.Buffer, writer *multipart.Writer) (*http.Request, *pb.ProgressBar) {
url := API_URL + configuration.ACCESS_TOKEN
var bar = pb.New(b.Len()).SetUnits(pb.U_BYTES)
reader := bar.NewProxyReader(b)
request, err := http.NewRequest("POST", url, reader)
if err != nil {
OutputError("Error building request")
os.Exit(2)
}
request.Header.Add("Content-Type", writer.FormDataContentType())
return request, bar
}