-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.go
1510 lines (1355 loc) · 45.4 KB
/
api.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
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"os"
"strconv"
"strings"
"syscall"
"time"
"github.com/eventials/go-tus"
"github.com/golang/glog"
"github.com/livepeer/go-api-client/logs"
"github.com/livepeer/go-api-client/metrics"
"github.com/tomnomnom/linkheader"
)
const (
SHORT = 4
DEBUG = 5
VERBOSE = 6
VVERBOSE = 7
INSANE = 12
INSANE2 = 14
)
type HTTPStatusError struct {
StatusCode int
Message string
}
func (e *HTTPStatusError) Error() string {
return e.Message
}
var (
// ErrNotExists returned if receives a 404 error from the API
ErrNotExists error = &HTTPStatusError{404, "not exists"}
// ErrRateLimited returned if receives a 429 error from the API
ErrRateLimited error = &HTTPStatusError{429, "rate limited"}
)
var defaultHTTPClient = &http.Client{
Timeout: 4 * time.Second,
}
var longTimeoutHTTPClient = &http.Client{
Timeout: 2 * time.Minute,
}
var hostName, _ = os.Hostname()
const (
livepeerAPIGeolocateURL = "http://livepeer.com/api/geolocate"
ProdServer = "livepeer.com"
RecordingStatusWaiting = "waiting"
RecordingStatusReady = "ready"
)
type NFTMetadataTemplate string
const (
NFTMetadataTemplatePlayer NFTMetadataTemplate = "player" // default
NFTMetadataTemplateFile NFTMetadataTemplate = "file"
)
type TaskPhase string
const (
TaskPhasePending TaskPhase = "pending"
TaskPhaseWaiting TaskPhase = "waiting"
TaskPhaseRunning TaskPhase = "running"
TaskPhaseFailed TaskPhase = "failed"
TaskPhaseCompleted TaskPhase = "completed"
)
type PlaybackInfoType string
const (
PlaybackInfoTypeLive PlaybackInfoType = "live"
PlaybackInfoTypeVod PlaybackInfoType = "vod"
PlaybackInfoTypeRecording PlaybackInfoType = "recording"
)
type HRN string
const (
HRN_HLS HRN = "HLS (TS)"
)
type PlaybackInfoSourceType string
const (
PlaybackInfoSourceTypeHLS PlaybackInfoSourceType = "html5/application/vnd.apple.mpegurl"
)
type (
// Object with all options given to Livepeer API
ClientOptions struct {
Server string
AccessToken string
UserAgent string
Timeout time.Duration
Presets []string
Metrics metrics.APIRecorder
}
// API object incapsulating Livepeer's hosted API
Client struct {
accessToken string
userAgent string
presets []string
metrics metrics.APIRecorder
chosenServer string
httpClient *http.Client
broadcasters []string
}
geoResp struct {
ChosenServer string `json:"chosenServer,omitempty"`
Servers []struct {
Server string `json:"server,omitempty"`
Duration int `json:"duration,omitempty"`
} `json:"servers,omitempty"`
}
CreateStreamReq struct {
Name string `json:"name"`
ParentID string `json:"parentId,omitempty"`
CreatorID string `json:"creatorId,omitempty"`
// one of: P720p60fps16x9, P720p30fps16x9, P720p30fps4x3, P576p30fps16x9, P360p30fps16x9, P360p30fps4x3, P240p30fps16x9, P240p30fps4x3, P144p30fps16x9
// this is deprecated and Profiles should be used instead.
Presets []string `json:"presets,omitempty"`
Profiles []Profile `json:"profiles,omitempty"`
Record bool `json:"record,omitempty"`
PlaybackPolicy *PlaybackPolicy `json:"playbackPolicy,omitempty"`
RecordObjectStoreId string `json:"recordObjectStoreId,omitempty"`
ObjectStoreId string `json:"objectStoreId,omitempty"`
}
PlaybackPolicy struct {
// one of: public, jwt, webhook
Type string `json:"type"`
WebhookID string `json:"webhookId,omitempty"`
WebhookContext map[string]interface{} `json:"webhookContext,omitempty"`
}
// Profile transcoding profile
Profile struct {
Name string `json:"name,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Bitrate int `json:"bitrate,omitempty"`
Quality int `json:"quality,omitempty"`
Fps int `json:"fps"`
FpsDen int `json:"fpsDen,omitempty"`
Gop string `json:"gop,omitempty"`
Profile string `json:"profile,omitempty"` // enum: - H264Baseline - H264Main - H264High - H264ConstrainedHigh
Encoder string `json:"encoder,omitempty"` // enum: - h264, h265, vp8, vp9
}
MultistreamTargetRef struct {
Profile string `json:"profile,omitempty"`
VideoOnly bool `json:"videoOnly,omitempty"`
ID string `json:"id,omitempty"`
}
// Stream object as returned by the API
Stream struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Presets []string `json:"presets,omitempty"`
Kind string `json:"kind,omitempty"`
UserID string `json:"userId,omitempty"`
StreamKey string `json:"streamKey,omitempty"`
PlaybackID string `json:"playbackId,omitempty"`
ParentID string `json:"parentId,omitempty"`
CreatedAt int64 `json:"createdAt,omitempty"`
LastSeen int64 `json:"lastSeen,omitempty"`
IsActive bool `json:"isActive,omitempty"`
SourceSegments int64 `json:"sourceSegments,omitempty"`
TranscodedSegments int64 `json:"transcodedSegments,omitempty"`
SourceSegmentsDuration float64 `json:"sourceSegmentsDuration,omitempty"`
TranscodedSegmentsDuration float64 `json:"transcodedSegmentsDuration,omitempty"`
Deleted bool `json:"deleted,omitempty"`
Suspended bool `json:"suspended,omitempty"`
Record bool `json:"record"`
Profiles []Profile `json:"profiles,omitempty"`
Multistream struct {
Targets []MultistreamTargetRef `json:"targets,omitempty"`
} `json:"multistream"`
// These can be present on parent stream objects if they are used to stream
// directly to broadcasters (i.e. not using the streamKey through RTMP)
RecordingStatus string `json:"recordingStatus,omitempty"` // ready, waiting
RecordingURL string `json:"recordingUrl,omitempty"`
Mp4Url string `json:"mp4Url,omitempty"`
Pull *StreamPull `json:"pull,omitempty"`
}
StreamPull struct {
Source string `json:"source"`
Headers map[string]string `json:"headers,omitempty"`
Location *struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
} `json:"location,omitempty"`
}
// UserSession user's sessions
UserSession struct {
Stream
}
MultistreamTarget struct {
ID string `json:"id,omitempty"`
URL string `json:"url,omitempty"`
Name string `json:"name,omitempty"`
UserID string `json:"userId,omitempty"`
Disabled bool `json:"disabled,omitempty"`
CreatedAt int64 `json:"createdAt,omitempty"`
}
TranscodeFileTaskOutputPath struct {
Path string `json:"path,omitempty"`
}
Task struct {
ID string `json:"id"`
UserID string `json:"userId"`
CreatedAt int64 `json:"createdAt"`
InputAssetID string `json:"inputAssetId,omitempty"`
OutputAssetID string `json:"outputAssetId,omitempty"`
Type string `json:"type"`
Params struct {
Upload *UploadTaskParams `json:"upload"`
Import *UploadTaskParams `json:"import"`
Export *ExportTaskParams `json:"export"`
ExportData *ExportDataTaskParams `json:"exportData"`
Transcode *TranscodeTaskParams `json:"transcode"`
TranscodeFile *TranscodeFileTaskParams `json:"transcode-file"`
Clip *ClipTaskParams `json:"clip"`
} `json:"params"`
Output *struct {
Export *struct {
IPFS *struct {
VideoFileCid string `json:"videoFileCid"`
NftMetadataCid string `json:"nftMetadataCid"`
VideoFileUrl string `json:"videoFileUrl"`
VideoFileGatewayUrl string `json:"videoFileGatewayUrl"`
NftMetadataUrl string `json:"nftMetadataUrl"`
NftMetadataGatewayUrl string `json:"nftMetadataGatewayUrl"`
} `json:"ipfs"`
} `json:"export"`
TranscodeFile *struct {
BaseUrl string `json:"baseUrl"`
Hls TranscodeFileTaskOutputPath `json:"hls"`
Mp4 []TranscodeFileTaskOutputPath `json:"mp4"`
} `json:"transcodeFile"`
} `json:"output"`
Status TaskStatus `json:"status"`
}
TaskOnlyId struct {
ID string `json:"id"`
}
TaskStatus struct {
Phase TaskPhase `json:"phase"`
Progress float64 `json:"progress"`
Step string `json:"step,omitempty"`
Retries int `json:"retries,omitempty"`
UpdatedAt int64 `json:"updatedAt,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
UploadTaskParams struct {
URL string `json:"url,omitempty"`
Encryption struct {
EncryptedKey string `json:"encryptedKey,omitempty"`
Key string `json:"key,omitempty"`
Algorithm string `json:"algorithm,omitempty"`
} `json:"encryption,omitempty"`
RecordedSessionID string `json:"recordedSessionId,omitempty"`
UploadedObjectKey string `json:"uploadedObjectKey,omitempty"`
CatalystPipelineStrategy string `json:"catalystPipelineStrategy,omitempty"`
Thumbnails bool `json:"thumbnails"`
C2PA bool `json:"c2pa,omitempty"`
Profiles []Profile `json:"profiles,omitempty"`
}
ExportCustomParams struct {
URL string `json:"url"`
Method string `json:"method,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
ExportIPFSParams struct {
Pinata *struct {
JWT string `json:"jwt,omitempty"`
APIKey string `json:"apiKey,omitempty"`
APISecret string `json:"apiSecret,omitempty"`
} `json:"pinata,omitempty"`
NFTMetadataTemplate `json:"nftMetadataTemplate,omitempty"`
NFTMetadata map[string]interface{} `json:"nftMetadata,omitempty"`
}
ExportTaskParams struct {
Custom *ExportCustomParams `json:"custom,omitempty"`
IPFS *ExportIPFSParams `json:"ipfs,omitempty"`
}
ExportDataTaskParams struct {
Content json.RawMessage `json:"content"`
Type string `json:"type"`
ID string `json:"id"`
Custom *ExportCustomParams `json:"custom,omitempty"`
IPFS *ExportIPFSParams `json:"ipfs,omitempty"`
}
TranscodeTaskParams struct {
Profile Profile `json:"profile,omitempty"`
}
TranscodeFileTaskParams struct {
Input struct {
URL string `json:"url"`
} `json:"input"`
Storage struct {
URL string `json:"url"`
} `json:"storage"`
Outputs struct {
HLS struct {
Path string `json:"path"`
} `json:"hls"`
MP4 struct {
Path string `json:"path"`
} `json:"mp4"`
FMP4 struct {
Path string `json:"path"`
} `json:"fmp4"`
} `json:"outputs"`
Profiles []Profile `json:"profiles,omitempty"`
CatalystPipelineStrategy string `json:"catalystPipelineStrategy,omitempty"`
TargetSegmentSizeSecs int64 `json:"targetSegmentSizeSecs,omitempty"`
C2PA bool `json:"c2pa,omitempty"`
}
ClipTaskParams struct {
URL string `json:"url"`
CatalystPipelineStrategy string `json:"catalystPipelineStrategy,omitempty"`
ClipStrategy struct {
StartTime int64 `json:"startTime"`
EndTime int64 `json:"endTime"`
PlaybackId string `json:"playbackId"`
}
InputSessionID string `json:"sessionId"`
InputID string `json:"inputId"`
SourceObjectStoreID string `json:"sourceObjectStoreId"`
}
updateTaskProgressRequest struct {
Status TaskStatus `json:"status"`
}
uploadViaURLRequest struct {
Name string `json:"name,omitempty"`
URL string `json:"url"`
CatalystPipelineStrategy string `json:"catalystPipelineStrategy,omitempty"`
}
requestUploadRequest struct {
Name string `json:"name,omitempty"`
CatalystPipelineStrategy string `json:"catalystPipelineStrategy,omitempty"`
}
transcodeAssetRequest struct {
Name string `json:"name,omitempty"`
Profile Profile `json:"profile,omitempty"`
}
TaskAndAsset struct {
Asset Asset `json:"asset"`
Task Task `json:"task"`
}
UploadUrls struct {
Url string `json:"url"`
TusEndpoint string `json:"tusEndpoint"`
Asset Asset `json:"asset"`
Task TaskOnlyId `json:"task"`
}
Pinata struct {
JWT string `json:"jwt,omitempty"`
APIKey string `json:"apiKey,omitempty"`
APISecret string `json:"apiSecret,omitempty"`
}
IPFS struct {
Pinata *Pinata `json:"pinata,omitempty"`
NFTMetadata interface{} `json:"nftMetadata,omitempty"`
}
exportAssetRequest struct {
IPFS *IPFS `json:"ipfs,omitempty"`
}
ExportAssetResp struct {
Task Task `json:"task"`
}
Asset struct {
ID string `json:"id"`
Deleted bool `json:"deleted,omitempty"`
PlaybackID string `json:"playbackId"`
UserID string `json:"userId"`
CreatedAt int64 `json:"createdAt"`
SourceAssetID string `json:"sourceAssetId,omitempty"`
ObjectStoreID string `json:"objectStoreId"`
DownloadURL string `json:"downloadUrl"`
PlaybackURL string `json:"playbackUrl"`
StaticMp4 bool `json:"staticMp4,omitempty"`
Source AssetSource `json:"source"`
Status AssetStatus `json:"status"`
AssetSpec
SourcePlaybackReady bool `json:"sourcePlaybackReady"`
}
AssetSource struct {
Type string `json:"type,omitempty"`
}
AssetStatus struct {
Phase string `json:"phase"`
UpdatedAt int64 `json:"updatedAt,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
AssetSpec struct {
Name string `json:"name,omitempty"`
Type string `json:"type"`
Size uint64 `json:"size"`
Hash []AssetHash `json:"hash"`
Files []AssetFile `json:"files"`
VideoSpec *AssetVideoSpec `json:"videoSpec,omitempty"`
Storage AssetStorage `json:"storage"`
PlaybackRecordingID string `json:"playbackRecordingId,omitempty"`
}
AssetFile struct {
Type string `json:"type"`
Path string `json:"path"`
Spec AssetFileSpec `json:"spec,omitempty"`
}
AssetFileSpec struct {
Size int64 `json:"size,omitempty"`
Width int64 `json:"width,omitempty"`
Height int64 `json:"height,omitempty"`
Bitrate int64 `json:"bitrate,omitempty"`
}
AssetHash struct {
Hash string `json:"hash"`
Algorithm string `json:"algorithm"`
}
AssetVideoSpec struct {
Format string `json:"format"`
DurationSec float64 `json:"duration"`
Bitrate float64 `json:"bitrate,omitempty"`
Tracks []*AssetTrack `json:"tracks"`
}
AssetTrack struct {
Type string `json:"type"`
Codec string `json:"codec"`
StartTime float64 `json:"startTime,omitempty"`
DurationSec float64 `json:"duration,omitempty"`
Bitrate float64 `json:"bitrate,omitempty"`
// video track fields
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
PixelFormat string `json:"pixelFormat,omitempty"`
FPS float64 `json:"fps,omitempty"`
// auido track fields
Channels int `json:"channels,omitempty"`
SampleRate int `json:"sampleRate,omitempty"`
BitDepth int `json:"bitDepth,omitempty"`
}
AssetStorage struct {
IPFS *AssetIPFS `json:"ipfs,omitempty"`
Status struct {
Phase string `json:"phase"`
ErrorMessage string `json:"errorMessage,omitempty"`
Tasks map[string]string `json:"tasks"`
} `json:"status,omitempty"`
}
AssetIPFS struct {
IPFSFileInfo
NFTMetadata *IPFSFileInfo `json:"nftMetadata,omitempty"`
Spec *struct {
NFTMetadataTemplate `json:"nftMetadataTemplate,omitempty"`
NFTMetadata map[string]interface{} `json:"nftMetadata,omitempty"`
} `json:"spec"`
}
IPFSFileInfo struct {
CID string `json:"cid"`
GatewayUrl string `json:"gatewayUrl,omitempty"`
Url string `json:"url,omitempty"`
}
ObjectStore struct {
ID string `json:"id"`
UserId string `json:"userId"`
CreatedAt int64 `json:"createdAt"`
URL string `json:"url"`
Name string `json:"name,omitempty"`
PublicURL string `json:"publicUrl,omitempty"`
Disabled bool `json:"disabled"`
}
// // Profile ...
// Profile struct {
// Fps int `json:"fps"`
// Name string `json:"name,omitempty"`
// Width int `json:"width,omitempty"`
// Height int `json:"height,omitempty"`
// Bitrate int `json:"bitrate,omitempty"`
// }
addressResp struct {
Address string `json:"address"`
}
setActiveReq struct {
Active bool `json:"active"`
HostName string `json:"hostName"`
StartedAt int64 `json:"startedAt"`
}
deactivateManyReq struct {
IDS []string `json:"ids"`
}
deactivateManyResp struct {
RowCount int `json:"rowCount"`
}
ListOptions struct {
Limit int
Cursor string
AllUsers, IncludeDeleted bool
Filters map[string]interface{}
Order map[string]bool
}
TranscodeFileReq struct {
Input TranscodeFileReqInput `json:"input,omitempty"`
Storage TranscodeFileReqStorage `json:"storage,omitempty"`
Outputs TranscodeFileReqOutputs `json:"outputs,omitempty"`
}
TranscodeFileReqInput struct {
Url string `json:"url,omitempty"`
Type string `json:"type,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Credentials *TranscodeFileReqCredentials `json:"credentials,omitempty"`
Bucket string `json:"bucket,omitempty"`
Path string `json:"path,omitempty"`
}
TranscodeFileReqStorage struct {
Type string `json:"type,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Credentials *TranscodeFileReqCredentials `json:"credentials,omitempty"`
Bucket string `json:"bucket,omitempty"`
}
TranscodeFileReqOutputs struct {
Hls TranscodeFileReqOutput `json:"hls,omitempty"`
Mp4 TranscodeFileReqOutput `json:"mp4,omitempty"`
FMp4 TranscodeFileReqOutput `json:"fmp4,omitempty"`
}
TranscodeFileReqOutput struct {
Path string `json:"path,omitempty"`
}
TranscodeFileReqCredentials struct {
AccessKeyId string `json:"accessKeyId,omitempty"`
SecretAccessKey string `json:"secretAccessKey,omitempty"`
Proof string `json:"proof,omitempty"`
}
PlaybackInfoSource struct {
Hrn HRN `json:"hrn"`
Type PlaybackInfoSourceType `json:"type"`
Url string `json:"url"`
}
PlaybackInfo struct {
Type PlaybackInfoType `json:"type"`
Meta struct {
Live *int `json:"live,omitempty"`
Source []PlaybackInfoSource `json:"source"`
} `json:"meta"`
}
)
// NewAPIClientGeolocated creates a new Livepeer API object calling the
// geolocation endpoint if no server is provided (by default, server is
// production instead)
func NewAPIClientGeolocated(opts ClientOptions) (*Client, string) {
if opts.Server == "" {
opts.Server = MustGeolocateAPIServer()
}
return NewAPIClient(opts), opts.Server
}
// NewAPIClient creates new Livepeer API object with a full configuration.
func NewAPIClient(opts ClientOptions) *Client {
if opts.Server == "" {
opts.Server = ProdServer
}
httpClient := defaultHTTPClient
if opts.Timeout != 0 {
httpClient = &http.Client{
Timeout: opts.Timeout,
}
}
if opts.Metrics == nil {
opts.Metrics = metrics.APIRequestRecorderFunc(func(name string, duration time.Duration, err error) {})
}
return &Client{
chosenServer: addScheme(opts.Server),
accessToken: opts.AccessToken,
userAgent: opts.UserAgent,
presets: opts.Presets,
metrics: opts.Metrics,
httpClient: httpClient,
}
}
func addScheme(uri string) string {
if uri == "" {
return uri
}
luri := strings.ToLower(uri)
if strings.HasPrefix(luri, "http://") || strings.HasPrefix(luri, "https://") {
return uri
}
if strings.Contains(luri, ".local") || strings.HasPrefix(luri, "localhost") {
return "http://" + uri
}
return "https://" + uri
}
// GeolocateAPIServer calls geolocation API endpoint to find the closest server.
func GeolocateAPIServer() (string, error) {
resp, err := http.Get(livepeerAPIGeolocateURL)
if err != nil {
return "", fmt.Errorf("error geolocating Livepeer API server (%s): %w", livepeerAPIGeolocateURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("status error contacting Livepeer API server (%s) status %d body: %s", livepeerAPIGeolocateURL, resp.StatusCode, string(b))
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error geolocating Livepeer API server (%s): %w", livepeerAPIGeolocateURL, err)
}
glog.Info(string(b))
geo := &geoResp{}
err = json.Unmarshal(b, geo)
if err != nil {
return "", err
}
glog.Infof("chosen server: %s, servers num: %d", geo.ChosenServer, len(geo.Servers))
return addScheme(geo.ChosenServer), nil
}
func MustGeolocateAPIServer() string {
server, err := GeolocateAPIServer()
if err != nil {
glog.Fatalf("Failed to geolocate API server: %v", err)
}
return server
}
// GetServer returns chosen server
func (lapi *Client) GetServer() string {
return lapi.chosenServer
}
// Broadcasters returns list of hostnames of broadcasters to use
func (lapi *Client) Broadcasters() ([]string, error) {
u := fmt.Sprintf("%s/api/broadcaster", lapi.chosenServer)
var broadcasters []addressResp
err := lapi.getJSON(u, "broadcaster", "", &broadcasters)
if err != nil {
glog.Errorf("Error getting broadcasters from Livepeer API server (%s) error: %v", u, err)
return nil, err
}
addresses := make([]string, 0, len(broadcasters))
for _, a := range broadcasters {
addresses = append(addresses, a.Address)
}
return addresses, nil
}
// Ingest object
type Ingest struct {
Base string `json:"base,omitempty"`
Playback string `json:"playback,omitempty"`
Ingest string `json:"ingest,omitempty"`
}
// Ingest returns ingest object
func (lapi *Client) Ingest(all bool) ([]Ingest, error) {
u := fmt.Sprintf("%s/api/ingest", lapi.chosenServer)
if all {
u += "?first=false"
}
var ingests []Ingest
err := lapi.getJSON(u, "ingest", "", &ingests)
if err != nil {
glog.Errorf("Error getting ingests from Livepeer API server (%s) error: %v", u, err)
return nil, err
}
return ingests, nil
}
var StandardProfiles = []Profile{
{
Name: "240p0",
Fps: 0,
Bitrate: 250000,
Width: 426,
Height: 240,
Gop: "2.0",
},
{
Name: "360p0",
Fps: 0,
Bitrate: 800000,
Width: 640,
Height: 360,
Gop: "2.0",
},
{
Name: "480p0",
Fps: 0,
Bitrate: 1600000,
Width: 854,
Height: 480,
Gop: "2.0",
},
{
Name: "720p0",
Fps: 0,
Bitrate: 3000000,
Width: 1280,
Height: 720,
Gop: "2.0",
},
}
// DeleteStream deletes stream
func (lapi *Client) DeleteStream(id string) error {
glog.V(logs.DEBUG).Infof("Deleting Livepeer stream '%s' ", id)
u := fmt.Sprintf("%s/api/stream/%s", lapi.chosenServer, id)
err := lapi.doRequest("DELETE", u, "stream", "", nil, nil)
return err
}
// CreateStreamEx creates stream with specified name and profiles
func (lapi *Client) CreateStreamEx(name string, record bool, presets []string, profiles ...Profile) (*Stream, error) {
return lapi.CreateStream(CreateStreamReq{Name: name, Record: record, Presets: presets, Profiles: profiles})
}
// CreateStream creates stream with specified name and profiles
func (lapi *Client) CreateStream(csr CreateStreamReq) (*Stream, error) {
if csr.Name == "" {
return nil, errors.New("stream must have a name")
}
if len(csr.Presets) == 0 && len(csr.Profiles) == 0 {
csr.Profiles = StandardProfiles
}
glog.V(logs.DEBUG).Infof(`Creating Livepeer stream name=%q presets="%v" profiles="%+v"`, csr.Name, csr.Presets, csr.Profiles)
u := fmt.Sprintf("%s/api/stream", lapi.chosenServer)
if csr.ParentID != "" {
u = fmt.Sprintf("%s/api/stream/%s/stream", lapi.chosenServer, csr.ParentID)
}
var stream *Stream
err := lapi.doRequest("POST", u, "stream", "", csr, &stream)
if err != nil {
return nil, err
}
glog.Infof("Created stream name=%q id=%s", csr.Name, stream.ID)
return stream, nil
}
// DefaultPresets returns default presets
func (lapi *Client) DefaultPresets() []string {
return lapi.presets
}
// GetStreamByKey gets stream by streamKey
func (lapi *Client) GetStreamByKey(key string) (*Stream, error) {
if key == "" {
return nil, errors.New("empty key")
}
u := fmt.Sprintf("%s/api/stream/key/%s?main=true", lapi.chosenServer, key)
return lapi.getStream(u, "get_by_key")
}
// GetStreamByPlaybackID gets stream by playbackID
func (lapi *Client) GetStreamByPlaybackID(playbackID string) (*Stream, error) {
if playbackID == "" {
return nil, errors.New("empty playbackID")
}
u := fmt.Sprintf("%s/api/stream/playback/%s", lapi.chosenServer, playbackID)
return lapi.getStream(u, "get_by_playbackid")
}
// GetStream gets stream by id
func (lapi *Client) GetStream(id string, forceRecordingUrl bool) (*Stream, error) {
if id == "" {
return nil, errors.New("empty id")
}
u := fmt.Sprintf("%s/api/stream/%s", lapi.chosenServer, id)
if forceRecordingUrl {
u += "?forceUrl=1"
}
return lapi.getStream(u, "get_by_id")
}
func (lapi *Client) GetSessionsNew(id string, forceUrl bool) ([]UserSession, error) {
if id == "" {
return nil, errors.New("empty id")
}
u := fmt.Sprintf("%s/api/session?parentId=%s", lapi.chosenServer, id)
if forceUrl {
u += "&forceUrl=1"
}
var sessions []UserSession
err := lapi.getJSON(u, "session", "list_sessions", &sessions)
if err != nil {
glog.Errorf("Error getting sessions for stream by id from Livepeer API server (%s) error: %v", u, err)
return nil, err
}
return sessions, nil
}
// GetSessions gets user's sessions for the stream by id
func (lapi *Client) GetSessions(id string, forceUrl bool) ([]UserSession, error) {
if id == "" {
return nil, errors.New("empty id")
}
u := fmt.Sprintf("%s/api/stream/%s/sessions", lapi.chosenServer, id)
if forceUrl {
u += "?forceUrl=1"
}
var sessions []UserSession
err := lapi.getJSON(u, "stream", "list_child_streams", &sessions)
if err != nil {
glog.Errorf("Error getting sessions for stream by id from Livepeer API server (%s) error: %v", u, err)
return nil, err
}
return sessions, nil
}
// Heartbeat updates the stream session
func (lapi *Client) Heartbeat(id string) error {
if id == "" {
return errors.New("empty id")
}
u := fmt.Sprintf("%s/api/stream/%s/heartbeat", lapi.chosenServer, id)
err := lapi.doRequest("POST", u, "stream", "heartbeat", nil, nil)
glog.Infof("Ran heartbeat request id=%s error=%q", id, err)
return err
}
// SetActive set isActive
func (lapi *Client) SetActive(id string, active bool, startedAt time.Time) (ok bool, err error) {
if id == "" {
return false, errors.New("empty id")
}
u := fmt.Sprintf("%s/api/stream/%s/setactive", lapi.chosenServer, id)
req := setActiveReq{
Active: active,
HostName: hostName,
}
if !startedAt.IsZero() {
req.StartedAt = startedAt.UnixNano() / int64(time.Millisecond)
}
err = lapi.doRequest("PUT", u, "stream", "set_active", req, nil)
glog.Infof("Ran setactive request id=%s request=%+v error=%q", id, req, err)
var httpErr *HTTPStatusError
if err == ErrNotExists || (errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusForbidden) {
// return !ok to block the stream from starting if it doesn't exist or is forbidden
return false, nil
} else if err != nil {
lapi.metrics.APIRequest("set_active", 0, err)
return false, err
}
return true, nil
}
// DeactivateMany sets many streams isActive field to false
func (lapi *Client) DeactivateMany(ids []string) (int, error) {
if len(ids) == 0 {
return 0, errors.New("empty ids")
}
u := fmt.Sprintf("%s/api/stream/deactivate-many", lapi.chosenServer)
req := deactivateManyReq{
IDS: ids,
}
var res deactivateManyResp
err := lapi.doRequest("PATCH", u, "stream", "deactivate_many", req, &res)
if err != nil {
return 0, err
}
return res.RowCount, nil
}
func (lapi *Client) getStream(url, metricName string) (*Stream, error) {
var stream *Stream
if err := lapi.getJSON(url, "stream", metricName, &stream); err != nil {
return nil, err
} else if stream == nil {
// API return null if stream does not exists
return nil, ErrNotExists
}
return stream, nil
}
func (lapi *Client) GetTask(id string, strongConsistency bool) (*Task, error) {
var task Task
url := fmt.Sprintf("%s/api/task/%s", lapi.chosenServer, id)
if strongConsistency {
url += "?strongConsistency=1"
}
if err := lapi.getJSON(url, "task", "", &task); err != nil {
return nil, err
}
return &task, nil
}
func (lapi *Client) UpdateTaskStatus(id string, phase TaskPhase, progress float64, step string) error {
var (
url = fmt.Sprintf("%s/api/task/%s/status", lapi.chosenServer, id)
input = &updateTaskProgressRequest{Status: TaskStatus{phase, progress, step, 0, 0, ""}}
output json.RawMessage
)
err := lapi.doRequest("POST", url, "task", "update_task_progress", input, &output)
if err != nil {
return err
}
glog.V(logs.DEBUG).Infof("Updated task progress id=%s phase=%s progress=%v output=%q", id, phase, progress, string(output))
return nil
}
func (lapi *Client) UploadViaURL(url, name, catalystStrategy string) (*Asset, *Task, error) {
var (
requestUrl = fmt.Sprintf("%s/api/asset/upload/url", lapi.chosenServer)
input = &uploadViaURLRequest{
URL: url,
Name: name,
CatalystPipelineStrategy: catalystStrategy,
}
output TaskAndAsset
)
err := lapi.doRequest("POST", requestUrl, "import_asset", "", input, &output)
if err != nil {
return nil, nil, err
}