-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlp-api.go
More file actions
680 lines (630 loc) · 17.1 KB
/
lp-api.go
File metadata and controls
680 lines (630 loc) · 17.1 KB
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/pelletier/go-toml/v2"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
)
type Credential struct {
Key string `toml:"oauth_consumer_key"`
Token string `toml:"oauth_token"`
Secret string `toml:"oauth_token_secret"`
}
// FileAttachment represents a file to be uploaded to Launchpad
type FileAttachment struct {
Path string
Filename string
ContentType string
Data []byte
}
// isFileAttachment checks if a parameter value starts with @ indicating a file path
func isFileAttachment(param string) bool {
return strings.HasPrefix(param, "@")
}
// extractFilePath extracts the file path from a parameter value with @ prefix
func extractFilePath(param string) string {
if isFileAttachment(param) {
return strings.TrimPrefix(param, "@")
}
return ""
}
// detectContentType detects MIME type from file extension
func detectContentType(filepath string) string {
ext := strings.ToLower(filepath[strings.LastIndex(filepath, "."):])
contentType := mime.TypeByExtension(ext)
if contentType == "" {
return "application/octet-stream"
}
return contentType
}
// readFileContent reads file content from disk into memory
func readFileContent(filepath string) ([]byte, error) {
data, err := os.ReadFile(filepath)
if err != nil {
return nil, err
}
return data, nil
}
// buildMultipartBody constructs a multipart/form-data request body with file content and form fields
func buildMultipartBody(attachment FileAttachment, params map[string]string) (*bytes.Buffer, string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add file data field
part, err := writer.CreateFormFile("data", attachment.Filename)
if err != nil {
return nil, "", err
}
if _, err := io.Copy(part, bytes.NewReader(attachment.Data)); err != nil {
return nil, "", err
}
// Add other form fields
for key, value := range params {
if err := writer.WriteField(key, value); err != nil {
return nil, "", err
}
}
if err := writer.Close(); err != nil {
return nil, "", err
}
return body, writer.FormDataContentType(), nil
}
func (c *Credential) RequestToken(oauth_consumer_key string) error {
resp, err := http.PostForm("https://launchpad.net/+request-token",
url.Values{
"oauth_consumer_key": {oauth_consumer_key},
"oauth_signature_method": {"PLAINTEXT"},
"oauth_signature": {"&"},
},
)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
mesg := string(body)
if *debug {
log.Print(mesg)
}
m, err := url.ParseQuery(mesg)
if err != nil {
return err
}
c.Key = oauth_consumer_key
c.Token = m["oauth_token"][0]
c.Secret = m["oauth_token_secret"][0]
return nil
}
func (c *Credential) AccessToken() error {
again:
time.Sleep(time.Second)
resp, err := http.PostForm("https://launchpad.net/+access-token",
url.Values{
"oauth_token": {c.Token},
"oauth_consumer_key": {c.Key},
"oauth_signature_method": {"PLAINTEXT"},
"oauth_signature": {"&" + c.Secret},
},
)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
mesg := string(body)
if mesg == "Request token has not yet been reviewed. Try again later." {
goto again
} else if mesg == "End-user refused to authorize request token." {
return errors.New(mesg)
}
if *debug {
log.Print(mesg)
}
m, err := url.ParseQuery(mesg)
if err != nil {
return err
}
c.Token = m["oauth_token"][0]
c.Secret = m["oauth_token_secret"][0]
return nil
}
func (c *Credential) GetCredential() error {
token := os.Getenv("LAUNCHPAD_TOKEN")
if token != "" {
keys := strings.SplitN(token, ":", 3)
c.Key = keys[2]
c.Token = keys[0]
c.Secret = keys[1]
} else if _, err := os.Stat(*conf); os.IsNotExist(err) {
err = c.RequestToken(*key)
if err != nil {
return err
}
if strings.HasPrefix(*key, "System-wide: ") {
log.Print(fmt.Sprintf("Please open https://launchpad.net/+authorize-token?oauth_token=%s&allow_permission=DESKTOP_INTEGRATION to authorize the token.", c.Token))
} else {
log.Print(fmt.Sprintf("Please open https://launchpad.net/+authorize-token?oauth_token=%s to authorize the token.", c.Token))
}
err = c.AccessToken()
if err != nil {
return err
}
fp, err := os.Create(*conf)
if err != nil {
return err
}
defer fp.Close()
err = toml.NewEncoder(fp).Encode(&c)
if err != nil {
return err
}
} else {
data, err := os.ReadFile(*conf)
if err != nil {
return err
}
err = toml.Unmarshal([]byte(data), &c)
if err != nil {
return err
}
if c.Secret == "" {
return errors.New("Read " + *conf + " failed.")
}
if *debug {
log.Print("Found " + c.Key + " " + c.Token)
}
}
return nil
}
type LaunchpadAPI struct {
Credential Credential
}
func (lp LaunchpadAPI) SetAuthHeader(header *http.Header) {
var timestamp = time.Now().Unix()
var auth = fmt.Sprintf("OAuth realm=\"https://api.launchpad.net/\", oauth_consumer_key=\"%s\", oauth_token=\"%s\", oauth_signature=\"&%s\", oauth_nonce=\"%d\", oauth_signature_method=\"PLAINTEXT\", oauth_timestamp=\"%d\", oauth_version=\"1.0\"", lp.Credential.Key, lp.Credential.Token, lp.Credential.Secret, timestamp, timestamp)
if *debug {
log.Print(auth)
}
header.Add("Authorization", auth)
}
func (lp LaunchpadAPI) QueryProcess(req *http.Request, args []string) {
if len(args) > 0 {
q := req.URL.Query()
for _, arg := range args {
fields := strings.Split(arg, "==")
key := fields[0]
value := strings.Join(fields[1:], "==")
if len(key) > 0 && !strings.Contains(key, "=") {
q.Add(key, value)
}
}
req.URL.RawQuery = q.Encode()
if *debug {
log.Print("Query: ", req.URL.RawQuery)
}
}
}
func (lp LaunchpadAPI) DoProcess(req *http.Request) (string, error) {
client := &http.Client{
Timeout: *timeout,
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
payload := string(body)
statusOK := resp.StatusCode >= 200 && resp.StatusCode < 300
if !statusOK {
var msg string
if strings.HasPrefix(payload, "Expired token") {
msg = payload + "\nPlease remove ~/.config/lp-api.toml if it exists and try it again."
} else {
msg = strconv.Itoa(resp.StatusCode) + " " + http.StatusText(resp.StatusCode) + "\n" + payload
}
return payload, errors.New(msg)
}
return payload, nil
}
func (lp *LaunchpadAPI) Delete(resource string) (string, error) {
if *debug {
log.Print("DELETE ", resource)
}
req, err := http.NewRequest("DELETE", resource, nil)
if err != nil {
return "", err
}
lp.SetAuthHeader(&req.Header)
return lp.DoProcess(req)
}
func (lp *LaunchpadAPI) Get(resource string, args []string) (string, error) {
if *debug {
log.Print("GET ", resource, " ", args)
}
req, err := http.NewRequest("GET", resource, nil)
if err != nil {
return "", err
}
lp.SetAuthHeader(&req.Header)
lp.QueryProcess(req, args)
return lp.DoProcess(req)
}
func (lp *LaunchpadAPI) Download(fileUrl string) error {
if *debug {
log.Print("DOWNLOAD ", fileUrl)
}
_, err := url.Parse(fileUrl)
if err != nil {
log.Fatal(err)
}
filename := path.Base(fileUrl)
client := &http.Client{}
req, err := http.NewRequest("GET", strings.Replace(fileUrl, "https://launchpad.net/", lpAPI, 1), nil)
if err != nil {
return err
}
lp.SetAuthHeader(&req.Header)
resp, err := client.Do(req)
if err != nil {
return err
}
// Try to get the filename from Content-Disposition header
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
if name, ok := params["filename"]; ok {
filename = name
}
}
} else if resp.Request != nil && resp.Request.URL != nil {
// If not found in header, use the final URL path (after redirects)
filename = path.Base(resp.Request.URL.Path)
}
length := int64(0)
if len(resp.Header["Content-Length"]) == 1 {
length, _ = strconv.ParseInt(resp.Header["Content-Length"][0], 10, 64)
}
defer resp.Body.Close()
done := make(chan int64)
file, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
if length != 0 {
go func(done chan int64, filename string, length int64) {
var stop bool = false
var prev int64 = 0
var begin = time.Now()
fmt.Printf("Downloading %s ...\n", filename)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
for {
select {
case <-done:
stop = true
default:
fi, err := file.Stat()
if err != nil {
log.Fatal(err)
}
size := fi.Size()
if size-prev != 0 {
var percent float64 = float64(size) / float64(length) * 100
var diff = strconv.FormatInt((length-size)/(size-prev)+1, 10) + "s"
var left, _ = time.ParseDuration(diff)
fmt.Printf("%.0f%% (%d/%d bytes) about %s left \r", percent, size, length, left)
prev = size
}
}
if stop {
var now = time.Now()
var diff = now.Sub(begin).Truncate(time.Second)
fmt.Printf("%s (%d bytes took %s) is downloaded. \n", filename, length, diff)
break
}
time.Sleep(time.Second)
}
}(done, filename, length)
}
defer file.Close()
size, err := io.Copy(file, resp.Body)
if length != 0 {
done <- size
} else {
fmt.Printf("%s (%d bytes) is downloaded.\n", filename, size)
}
return err
}
func (lp *LaunchpadAPI) Patch(resource string, args []string) (string, error) {
if *debug {
log.Print("PATCH ", resource, " ", args)
}
data := make(map[string]interface{})
if len(args) > 0 {
for _, arg := range args {
fields := strings.Split(arg, ":=")
key := fields[0]
value := strings.Join(fields[1:], ":=")
if len(key) > 0 && !strings.Contains(key, "=") {
if json.Valid([]byte(value)) {
var v interface{}
json.Unmarshal([]byte(value), &v)
data[key] = v
} else {
log.Fatal("Invalid JSON input: " + value)
}
}
}
}
payload, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
if *debug {
log.Print("JSON: ", string(payload))
}
req, err := http.NewRequest("PATCH", resource, bytes.NewBuffer(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
lp.SetAuthHeader(&req.Header)
lp.QueryProcess(req, args)
return lp.DoProcess(req)
}
func (lp *LaunchpadAPI) Put(resource string, jsonFile string) (string, error) {
if *debug {
log.Print("PUT ", resource, " ", jsonFile)
}
payload, err := ioutil.ReadFile(jsonFile)
if err != nil {
log.Fatal("Error when opening file: ", err)
}
if !json.Valid(payload) {
log.Fatal("Invalid JSON file: " + jsonFile)
}
if *debug {
log.Print("JSON: ", string(payload))
}
req, err := http.NewRequest("PUT", resource, bytes.NewBuffer(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
lp.SetAuthHeader(&req.Header)
return lp.DoProcess(req)
}
func (lp *LaunchpadAPI) Post(resource string, args []string) (string, error) {
if *debug {
log.Print("POST ", resource, " ", args)
}
// Check for file attachment
var attachment *FileAttachment
params := make(map[string]string)
if len(args) > 0 {
for _, arg := range args {
fields := strings.Split(arg, "=")
key := fields[0]
if len(key) == 0 {
continue
}
key_last := key[len(key)-1:]
value := strings.Join(fields[1:], "=")
value_first := ""
if len(value) > 0 {
value_first = value[0:1]
}
if len(value) > 0 && value_first != "=" && key_last != ":" { // Check if this is a file attachment
if key == "attachment" && isFileAttachment(value) {
filePath := extractFilePath(value)
// Read file content
data, err := readFileContent(filePath)
if err != nil {
if os.IsNotExist(err) {
return "", fmt.Errorf("Error: File not found: %s", filePath)
}
if os.IsPermission(err) {
return "", fmt.Errorf("Error: Cannot read file: permission denied")
}
return "", fmt.Errorf("Error: Failed to read file: %v", err)
}
attachment = &FileAttachment{
Path: filePath,
Filename: filepath.Base(filePath),
ContentType: detectContentType(filePath),
Data: data,
}
if *debug {
log.Printf("Detected file attachment: %s (%s, %d bytes)", attachment.Filename, attachment.ContentType, len(attachment.Data))
}
} else {
params[key] = value
}
}
}
}
var req *http.Request
var err error
// If we have a file attachment, use multipart/form-data
if attachment != nil {
// Ensure filename parameter is included (required by Launchpad API)
if _, ok := params["filename"]; !ok {
params["filename"] = attachment.Filename
}
// Check if comment is provided (required by Launchpad API)
if _, ok := params["comment"]; !ok {
return "", fmt.Errorf("Error: 'comment' parameter is required when attaching files")
}
body, contentType, err := buildMultipartBody(*attachment, params)
if err != nil {
return "", fmt.Errorf("Error: Failed to build multipart body: %v", err)
}
if *debug {
log.Print("Using multipart/form-data for file upload")
}
req, err = http.NewRequest("POST", resource, body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", contentType)
} else {
// Regular form-encoded POST
data := url.Values{}
for key, value := range params {
data.Set(key, value)
}
if *debug {
log.Print("Body: ", data.Encode())
}
req, err = http.NewRequest("POST", resource, strings.NewReader(data.Encode()))
if err != nil {
return "", err
}
}
lp.QueryProcess(req, args)
lp.SetAuthHeader(&req.Header)
return lp.DoProcess(req)
}
func (lp *LaunchpadAPI) Pipe(node string) (string, error) {
bytes, err := io.ReadAll(os.Stdin)
if err != nil {
return "", err
}
var v map[string]interface{}
json.Unmarshal(bytes, &v)
if v[node] == nil {
return "", errors.New("There is no such '" + node + "' key.")
}
if *debug {
log.Print("PIPE ", v[node])
}
apiUrl, ok := v[node].(string)
if !ok {
return "", errors.New("The value of '" + node + "' key is not string.")
}
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
return "", err
}
lp.SetAuthHeader(&req.Header)
return lp.DoProcess(req)
}
func getHostName() string {
hostname, err := os.Hostname()
if err != nil {
return "golang"
}
return hostname
}
var conf = flag.String("conf", os.Getenv("HOME")+"/.config/lp-api.toml", "Specify the Launchpad API config file.")
var debug = flag.Bool("debug", false, "Show debug messages")
var help = flag.Bool("help", false, "Show help")
var key = flag.String("key", fmt.Sprintf("System-wide: %s (https://github.com/fourdollars/lp-api)", getHostName()), "Specify the OAuth Consumer Key.")
var lpAPI = "https://api.launchpad.net/devel/"
var output = flag.String("output", "", "Specify the output file.")
var staging = flag.Bool("staging", false, "Use Launchpad staging server.")
var timeout = flag.Duration("timeout", 10*time.Second, "Timeout for Launchpad API requests.")
func main() {
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
}
if *staging {
lpAPI = "https://api.staging.launchpad.net/devel/"
}
args := flag.Args()
if len(args) == 0 {
fmt.Println("Usage: lp-api {get,patch,put,post,delete} resource, such as `lp-api get people/+me` or `lp-api get bugs/1`.\n\tCheck api.html generated by `lp-api get / > api.html` for details.")
flag.Usage()
os.Exit(0)
} else if len(args) == 1 && !strings.HasPrefix(args[0], ".") {
fmt.Println("Usage: lp-api {get,patch,put,post,delete} resource, such as `lp-api get people/+me` or `lp-api get bugs/1`.\n\tCheck api.html generated by `lp-api get / > api.html` for details.")
flag.Usage()
os.Exit(1)
}
lp := LaunchpadAPI{}
c := Credential{}
err := c.GetCredential()
if err != nil {
log.Fatal(err)
}
lp.Credential = c
var resource string
if len(args) == 1 {
resource = ""
} else if strings.HasPrefix(args[1], "https://api.launchpad.net/devel/") {
resource = args[1]
lpAPI = "https://api.launchpad.net/devel/"
} else if strings.HasPrefix(args[1], "https://api.staging.launchpad.net/devel/") {
resource = args[1]
lpAPI = "https://api.staging.launchpad.net/devel/"
} else {
resource = lpAPI + args[1]
}
var payload string
switch method := args[0]; {
case method == "delete":
payload, err = lp.Delete(resource)
case method == "get":
payload, err = lp.Get(resource, args[2:])
case method == "patch":
payload, err = lp.Patch(resource, args[2:])
case method == "put":
payload, err = lp.Put(resource, args[2])
case method == "post":
payload, err = lp.Post(resource, args[2:])
case method == "download":
err = lp.Download(args[1])
case strings.HasPrefix(method, ".") && len(args) == 1:
payload, err = lp.Pipe(args[0][1:])
default:
fmt.Printf("'%s' method is not supported.\n", method)
os.Exit(1)
}
if err != nil {
log.Fatal(err)
}
if *output != "" {
if *debug {
log.Print("OUTPUT: " + payload)
}
file, err := os.Create(*output)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.WriteString(payload)
if err != nil {
log.Fatal(err)
}
} else {
fmt.Println(payload)
}
}