-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
soapcallers.go
1476 lines (1227 loc) · 47.3 KB
/
soapcallers.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 soapcalls
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
type States struct {
PreviousState string
NewState string
ProcessStop bool
}
var (
ErrNoMatchingFileType = errors.New("no matching file type")
ErrZombieCallbacks = errors.New("zombie callbacks, we should ignore those")
)
// TVPayload is the heart of Go2TV. We pass that type to the
// webserver. We need to explicitly initialize it.
type TVPayload struct {
Logger zerolog.Logger
LogOutput io.Writer
ctx context.Context
CurrentTimers map[string]*time.Timer
InitialMediaRenderersStates map[string]bool
MediaRenderersStates map[string]*States
EventURL string
ControlURL string
MediaURL string
MediaType string
MediaPath string
SubtitlesURL string
CallbackURL string
ConnectionManagerURL string
RenderingControlURL string
mu sync.RWMutex
initLogOnce sync.Once
Transcode bool
Seekable bool
}
type getMuteRespBody struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
EncodingStyle string `xml:"encodingStyle,attr"`
S string `xml:"s,attr"`
Body struct {
Text string `xml:",chardata"`
GetMuteResponse struct {
Text string `xml:",chardata"`
U string `xml:"u,attr"`
CurrentMute string `xml:"CurrentMute"`
} `xml:"GetMuteResponse"`
} `xml:"Body"`
}
type getVolumeRespBody struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
EncodingStyle string `xml:"encodingStyle,attr"`
S string `xml:"s,attr"`
Body struct {
Text string `xml:",chardata"`
GetVolumeResponse struct {
Text string `xml:",chardata"`
U string `xml:"u,attr"`
CurrentVolume string `xml:"CurrentVolume"`
} `xml:"GetVolumeResponse"`
} `xml:"Body"`
}
type protocolInfoResponse struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
S string `xml:"s,attr"`
EncodingStyle string `xml:"encodingStyle,attr"`
Body struct {
Text string `xml:",chardata"`
GetProtocolInfoResponse struct {
Text string `xml:",chardata"`
U string `xml:"u,attr"`
Source string `xml:"Source"`
Sink string `xml:"Sink"`
} `xml:"GetProtocolInfoResponse"`
} `xml:"Body"`
}
type getMediaInfoResponse struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
EncodingStyle string `xml:"encodingStyle,attr"`
S string `xml:"s,attr"`
Body struct {
Text string `xml:",chardata"`
GetMediaInfoResponse struct {
Text string `xml:",chardata"`
U string `xml:"u,attr"`
NrTracks string `xml:"NrTracks"`
MediaDuration string `xml:"MediaDuration"`
CurrentURI string `xml:"CurrentURI"`
CurrentURIMetaData string `xml:"CurrentURIMetaData"`
NextURI string `xml:"NextURI"`
NextURIMetaData string `xml:"NextURIMetaData"`
PlayMedium string `xml:"PlayMedium"`
RecordMedium string `xml:"RecordMedium"`
WriteStatus string `xml:"WriteStatus"`
} `xml:"GetMediaInfoResponse"`
} `xml:"Body"`
}
type getTransportInfoResponse struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
S string `xml:"s,attr"`
EncodingStyle string `xml:"encodingStyle,attr"`
Body struct {
Text string `xml:",chardata"`
GetTransportInfoResponse struct {
Text string `xml:",chardata"`
U string `xml:"u,attr"`
CurrentTransportState string `xml:"CurrentTransportState"`
CurrentTransportStatus string `xml:"CurrentTransportStatus"`
CurrentSpeed string `xml:"CurrentSpeed"`
} `xml:"GetTransportInfoResponse"`
} `xml:"Body"`
}
type getPositionInfoResponse struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
S string `xml:"s,attr"`
EncodingStyle string `xml:"encodingStyle,attr"`
Body struct {
Text string `xml:",chardata"`
GetPositionInfoResponse struct {
Text string `xml:",chardata"`
U string `xml:"u,attr"`
Track string `xml:"Track"`
TrackDuration string `xml:"TrackDuration"`
TrackMetaData string `xml:"TrackMetaData"`
TrackURI string `xml:"TrackURI"`
RelTime string `xml:"RelTime"`
AbsTime string `xml:"AbsTime"`
RelCount string `xml:"RelCount"`
AbsCount string `xml:"AbsCount"`
} `xml:"GetPositionInfoResponse"`
} `xml:"Body"`
}
func (p *TVPayload) setAVTransportSoapCall() error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedURLtransport, err := url.Parse(p.ControlURL)
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall parse error: %w", err)
}
xmlData, err := setAVTransportSoapBuild(p)
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "setAVTransportSoapBuild").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall soap build error: %w", err)
}
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = 3
retryClient.Logger = nil
client := retryClient.StandardClient()
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedURLtransport.String(), bytes.NewReader(xmlData))
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "setAVTransportSoapCall").Str("Action", "Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlData))
res, err := client.Do(req)
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "Do POST").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall Failed to read response: %w", err)
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "setAVTransportSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("setAVTransportSoapCall Response Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "setAVTransportSoapCall").Str("Action", "Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return nil
}
func (p *TVPayload) setNextAVTransportSoapCall(clear bool) error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedURLtransport, err := url.Parse(p.ControlURL)
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall parse error: %w", err)
}
xmlData, err := setNextAVTransportSoapBuild(p, clear)
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "setNextAVTransportSoapBuild").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall soap build error: %w", err)
}
client := &http.Client{}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedURLtransport.String(), bytes.NewReader(xmlData))
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:AVTransport:1#SetNextAVTransportURI"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "setNextAVTransportSoapCall").Str("Action", "Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlData))
res, err := client.Do(req)
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "Do POST").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall Failed to read response: %w", err)
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "setNextAVTransportSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("setNextAVTransportSoapCall Response Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "setNextAVTransportSoapCall").Str("Action", "Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return nil
}
// PlayPauseStopSoapCall builds and sends the AVTransport actions for Play Pause and Stop.
func (p *TVPayload) PlayPauseStopSoapCall(action string) error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedURLtransport, err := url.Parse(p.ControlURL)
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall parse error: %w", err)
}
var xmlData []byte
retry := false
switch action {
case "Play":
xmlData, err = playSoapBuild()
case "Stop":
xmlData, err = stopSoapBuild()
retry = true
case "Pause":
xmlData, err = pauseSoapBuild()
}
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "Action Error").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall action error: %w", err)
}
client := &http.Client{}
if retry {
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = 3
retryClient.Logger = nil
client = retryClient.StandardClient()
}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedURLtransport.String(), bytes.NewReader(xmlData))
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:AVTransport:1#` + action + `"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "AVTransportActionSoapCall").Str("Action", action+" Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlData))
res, err := client.Do(req)
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "Do POST").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall Failed to read response: %w", err)
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "AVTransportActionSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("AVTransportActionSoapCall Response Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "AVTransportActionSoapCall").Str("Action", action+" Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return nil
}
// SeekSoapCall builds and sends the AVTransport actions for Seek.
func (p *TVPayload) SeekSoapCall(reltime string) error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedURLtransport, err := url.Parse(p.ControlURL)
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall parse error: %w", err)
}
var xmlData []byte
xmlData, err = seekSoapBuild(reltime)
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "Action Error").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall action error: %w", err)
}
client := &http.Client{}
//if retry {
// retryClient := retryablehttp.NewClient()
// retryClient.RetryMax = 3
// retryClient.Logger = nil
// client = retryClient.StandardClient()
//}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedURLtransport.String(), bytes.NewReader(xmlData))
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:AVTransport:1#Seek"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "SeekSoapCall").Str("Action", "Seek Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlData))
res, err := client.Do(req)
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "Do POST").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall Failed to read response: %w", err)
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "SeekSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("SeekSoapCall Response Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "SeekSoapCall").Str("Action", "Seek Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return nil
}
// SubscribeSoapCall send a SUBSCRIBE request to the DMR device.
// If we explicitly pass the UUID, then we refresh it instead.
func (p *TVPayload) SubscribeSoapCall(uuidInput string) error {
if p.ctx == nil {
p.ctx = context.Background()
}
delete(p.CurrentTimers, uuidInput)
parsedURLcontrol, err := url.Parse(p.EventURL)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "URL Parse #1").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall #1 parse error: %w", err)
}
parsedURLcallback, err := url.Parse(p.CallbackURL)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "URL Parse #2").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall #2 parse error: %w", err)
}
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = 3
retryClient.Logger = nil
client := retryClient.StandardClient()
req, err := http.NewRequestWithContext(p.ctx, "SUBSCRIBE", parsedURLcontrol.String(), nil)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "Prepare SUBSCRIBE").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall SUBSCRIBE error: %w", err)
}
var headers http.Header
if uuidInput == "" {
headers = http.Header{
"USER-AGENT": []string{runtime.GOOS + " UPnP/1.1 " + "Go2TV"},
"CALLBACK": []string{"<" + parsedURLcallback.String() + ">"},
"NT": []string{"upnp:event"},
"TIMEOUT": []string{"Second-300"},
"Connection": []string{"close"},
}
} else {
headers = http.Header{
"SID": []string{"uuid:" + uuidInput},
"TIMEOUT": []string{"Second-300"},
"Connection": []string{"close"},
}
}
req.Header = headers
req.Header.Del("User-Agent")
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "SubscribeSoapCall").Str("Action", "Subscribe Request").
RawJSON("Headers", headerBytesReq).
Msg("")
res, err := client.Do(req)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "Do SUBSCRIBE").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall Do SUBSCRIBE error: %w", err)
}
defer res.Body.Close()
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall Failed to read response: %w", err)
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "SubscribeSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("SubscribeSoapCall Response Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "SubscribeSoapCall").Str("Action", "Subscribe Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
var uuid string
if res.Status != "200 OK" {
if uuidInput != "" {
// We're calling the unsubscribe method to make sure
// we clean up any remaining states for the specific
// uuid. The actual UNSUBSCRIBE request to the media
// renderer may still fail with error 412, but it's fine.
_ = p.UnsubscribeSoapCall(uuid)
}
return nil
}
if len(res.Header["Sid"]) == 0 {
// This should be an impossible case
return nil
}
uuid = res.Header["Sid"][0]
uuid = strings.TrimLeft(uuid, "[")
uuid = strings.TrimLeft(uuid, "]")
uuid = strings.TrimPrefix(uuid, "uuid:")
// We don't really need to initialize or set
// the State if we're just refreshing the uuid.
if uuidInput == "" {
p.CreateMRstate(uuid)
}
timeoutReply := "300"
if len(res.Header["Timeout"]) > 0 {
timeoutReply = strings.TrimPrefix(res.Header["Timeout"][0], "Second-")
}
p.RefreshLoopUUIDSoapCall(uuid, timeoutReply)
return nil
}
// UnsubscribeSoapCall sends an UNSUBSCRIBE request to the DMR device
// and cleans up any stored states for the provided UUID.
func (p *TVPayload) UnsubscribeSoapCall(uuid string) error {
if p.ctx == nil {
p.ctx = context.Background()
}
p.DeleteMRstate(uuid)
parsedURLcontrol, err := url.Parse(p.EventURL)
if err != nil {
return fmt.Errorf("UnsubscribeSoapCall parse error: %w", err)
}
client := &http.Client{}
req, err := http.NewRequestWithContext(p.ctx, "UNSUBSCRIBE", parsedURLcontrol.String(), nil)
if err != nil {
return fmt.Errorf("UnsubscribeSoapCall UNSUBSCRIBE error: %w", err)
}
req.Header = http.Header{
"SID": []string{"uuid:" + uuid},
"Connection": []string{"close"},
}
req.Header.Del("User-Agent")
_, err = client.Do(req)
if err != nil {
return fmt.Errorf("UnsubscribeSoapCall Do UNSUBSCRIBE error: %w", err)
}
return nil
}
// RefreshLoopUUIDSoapCall refreshes the UUID.
func (p *TVPayload) RefreshLoopUUIDSoapCall(uuid, timeout string) {
triggerTime := 5
timeoutInt, err := strconv.Atoi(timeout)
if err != nil {
return
}
// Refresh token after Timeout / 2 seconds.
if timeoutInt > 20 {
triggerTime = timeoutInt / 5
}
triggerTimefunc := time.Duration(triggerTime) * time.Second
f := p.refreshLoopUUIDAsyncSoapCall(uuid)
timer := time.AfterFunc(triggerTimefunc, f)
p.CurrentTimers[uuid] = timer
}
func (p *TVPayload) refreshLoopUUIDAsyncSoapCall(uuid string) func() {
return func() {
_ = p.SubscribeSoapCall(uuid)
}
}
// GetMuteSoapCall returns the mute status for our device
func (p *TVPayload) GetMuteSoapCall() (string, error) {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedRenderingControlURL, err := url.Parse(p.RenderingControlURL)
if err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall parse error: %w", err)
}
var xmlbuilder []byte
xmlbuilder, err = getMuteSoapBuild()
if err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "Build").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall build error: %w", err)
}
client := &http.Client{}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedRenderingControlURL.String(), bytes.NewReader(xmlbuilder))
if err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:RenderingControl:1#GetMute"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "GetMuteSoapCall").Str("Action", "Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlbuilder))
res, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("GetMuteSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
var buf bytes.Buffer
tresp := io.TeeReader(res.Body, &buf)
var respGetMute getMuteRespBody
if err = xml.NewDecoder(tresp).Decode(&respGetMute); err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "XML Decode").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall XML Decode error: %w", err)
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall Response Marshaling error: %w", err)
}
resBytes, err := io.ReadAll(&buf)
if err != nil {
p.Log().Error().Str("Method", "GetMuteSoapCall").Str("Action", "Readall").Err(err).Msg("")
return "", fmt.Errorf("GetMuteSoapCall Failed to read response: %w", err)
}
p.Log().Debug().
Str("Method", "GetMuteSoapCall").Str("Action", "Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return respGetMute.Body.GetMuteResponse.CurrentMute, nil
}
// SetMuteSoapCall returns true if muted and false if not muted.
func (p *TVPayload) SetMuteSoapCall(number string) error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedRenderingControlURL, err := url.Parse(p.RenderingControlURL)
if err != nil {
p.Log().Error().Str("Method", "SetMuteSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("SetMuteSoapCall parse error: %w", err)
}
var xmlbuilder []byte
xmlbuilder, err = setMuteSoapBuild(number)
if err != nil {
p.Log().Error().Str("Method", "SetMuteSoapCall").Str("Action", "Build").Err(err).Msg("")
return fmt.Errorf("SetMuteSoapCall build error: %w", err)
}
client := &http.Client{}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedRenderingControlURL.String(), bytes.NewReader(xmlbuilder))
if err != nil {
p.Log().Error().Str("Method", "SetMuteSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return fmt.Errorf("SetMuteSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:RenderingControl:1#SetMute"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "SetMuteSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("SetMuteSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "SetMuteSoapCall").Str("Action", "Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlbuilder))
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("SetMuteSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "SetMuteSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("SetMuteSoapCall Response Marshaling error: %w", err)
}
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "SetMuteSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("SetMuteSoapCall Failed to read response: %w", err)
}
p.Log().Debug().
Str("Method", "SetMuteSoapCall").Str("Action", "Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return nil
}
// GetVolumeSoapCall returns tue volume level for our device.
func (p *TVPayload) GetVolumeSoapCall() (int, error) {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedRenderingControlURL, err := url.Parse(p.RenderingControlURL)
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall parse error: %w", err)
}
var xmlbuilder []byte
xmlbuilder, err = getVolumeSoapBuild()
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Build").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall build error: %w", err)
}
client := &http.Client{}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedRenderingControlURL.String(), bytes.NewReader(xmlbuilder))
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:RenderingControl:1#GetVolume"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "GetVolumeSoapCall").Str("Action", "Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlbuilder))
res, err := client.Do(req)
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Do POST").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
var buf bytes.Buffer
tresp := io.TeeReader(res.Body, &buf)
var respGetVolume getVolumeRespBody
if err = xml.NewDecoder(tresp).Decode(&respGetVolume); err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "XML Decode").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall XML Decode error: %w", err)
}
intVolume, err := strconv.Atoi(respGetVolume.Body.GetVolumeResponse.CurrentVolume)
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Parse Volume").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall failed to parse volume value: %w", err)
}
if intVolume < 0 {
intVolume = 0
}
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall Response Marshaling error: %w", err)
}
resBytes, err := io.ReadAll(&buf)
if err != nil {
p.Log().Error().Str("Method", "GetVolumeSoapCall").Str("Action", "Readall").Err(err).Msg("")
return 0, fmt.Errorf("GetVolumeSoapCall Failed to read response: %w", err)
}
p.Log().Debug().
Str("Method", "GetVolumeSoapCall").Str("Action", "Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return intVolume, nil
}
// SetVolumeSoapCall sets the desired volume level.
func (p *TVPayload) SetVolumeSoapCall(v string) error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedRenderingControlURL, err := url.Parse(p.RenderingControlURL)
if err != nil {
p.Log().Error().Str("Method", "SetVolumeSoapCall").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("SetVolumeSoapCall parse error: %w", err)
}
var xmlbuilder []byte
xmlbuilder, err = setVolumeSoapBuild(v)
if err != nil {
p.Log().Error().Str("Method", "SetVolumeSoapCall").Str("Action", "Build").Err(err).Msg("")
return fmt.Errorf("SetVolumeSoapCall build error: %w", err)
}
client := &http.Client{}
req, err := http.NewRequestWithContext(p.ctx, "POST", parsedRenderingControlURL.String(), bytes.NewReader(xmlbuilder))
if err != nil {
p.Log().Error().Str("Method", "SetVolumeSoapCall").Str("Action", "Prepare POST").Err(err).Msg("")
return fmt.Errorf("SetVolumeSoapCall POST error: %w", err)
}
req.Header = http.Header{
"SOAPAction": []string{`"urn:schemas-upnp-org:service:RenderingControl:1#SetVolume"`},
"content-type": []string{"text/xml"},
"charset": []string{"utf-8"},
"Connection": []string{"close"},
}
headerBytesReq, err := json.Marshal(req.Header)
if err != nil {
p.Log().Error().Str("Method", "SetVolumeSoapCall").Str("Action", "Header Marshaling").Err(err).Msg("")
return fmt.Errorf("SetVolumeSoapCall Request Marshaling error: %w", err)
}
p.Log().Debug().
Str("Method", "SetVolumeSoapCall").Str("Action", "Request").
RawJSON("Headers", headerBytesReq).
Msg(string(xmlbuilder))
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("SetVolumeSoapCall Do POST error: %w", err)
}
defer res.Body.Close()
headerBytesRes, err := json.Marshal(res.Header)
if err != nil {
p.Log().Error().Str("Method", "SetVolumeSoapCall").Str("Action", "Header Marshaling #2").Err(err).Msg("")
return fmt.Errorf("SetVolumeSoapCall Response Marshaling error: %w", err)
}
resBytes, err := io.ReadAll(res.Body)
if err != nil {
p.Log().Error().Str("Method", "SetVolumeSoapCall").Str("Action", "Readall").Err(err).Msg("")
return fmt.Errorf("SetVolumeSoapCall Failed to read response: %w", err)
}
p.Log().Debug().
Str("Method", "SetVolumeSoapCall").Str("Action", "Response").Str("Status Code", strconv.Itoa(res.StatusCode)).
RawJSON("Headers", headerBytesRes).
Msg(string(resBytes))
return nil
}
// GetProtocolInfo requests our device's protocol info.
func (p *TVPayload) GetProtocolInfo() error {
if p.ctx == nil {
p.ctx = context.Background()
}
parsedConnectionManagerURL, err := url.Parse(p.ConnectionManagerURL)
if err != nil {
p.Log().Error().Str("Method", "GetProtocolInfo").Str("Action", "URL Parse").Err(err).Msg("")
return fmt.Errorf("GetProtocolInfo parse error: %w", err)
}
var xmlbuilder []byte
xmlbuilder, err = getProtocolInfoSoapBuild()
if err != nil {
p.Log().Error().Str("Method", "GetProtocolInfo").Str("Action", "Build").Err(err).Msg("")
return fmt.Errorf("GetProtocolInfo build error: %w", err)
}
client := &http.Client{}