-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
209 lines (193 loc) · 5.55 KB
/
client.go
File metadata and controls
209 lines (193 loc) · 5.55 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
package main
import (
"context"
"crypto/tls"
"encoding/xml"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
// XML models (subset)
type mediaContainer struct {
XMLName xml.Name `xml:"MediaContainer"`
Size int `xml:"size,attr"`
Directory []Directory `xml:"Directory"`
Video []Video `xml:"Video"`
}
type Directory struct {
Key string `xml:"key,attr"`
Type string `xml:"type,attr"` // "movie", "show"
Title string `xml:"title,attr"` // e.g., "Movies"
}
type Video struct {
RatingKey string `xml:"ratingKey,attr"`
Key string `xml:"key,attr"`
LibrarySectionID string `xml:"librarySectionID,attr"`
Title string `xml:"title,attr"`
Year int `xml:"year,attr"`
Guid string `xml:"guid,attr"`
Media []Media `xml:"Media"`
}
type Media struct {
ID string `xml:"id,attr"`
Duration int `xml:"duration,attr"`
VideoCodec string `xml:"videoCodec,attr"`
AudioCodec string `xml:"audioCodec,attr"`
VideoResolution string `xml:"videoResolution,attr"`
Container string `xml:"container,attr"`
Bitrate int `xml:"bitrate,attr"`
Width int `xml:"width,attr"`
Height int `xml:"height,attr"`
Part []Part `xml:"Part"`
}
type Part struct {
ID string `xml:"id,attr"`
File string `xml:"file,attr"`
Size int64 `xml:"size,attr"`
Duration int `xml:"duration,attr"`
ExistsInt int `xml:"exists,attr"` // with checkFiles=1
AccessibleInt int `xml:"accessible,attr"` // with checkFiles=1
}
// Client
type Client struct {
base *url.URL
token string
http *http.Client
verbose bool
timeout time.Duration
}
// NewClient creates a Plex API client with the given options.
func NewClient(o Options) (*Client, error) {
u, err := url.Parse(o.BaseURL)
if err != nil {
return nil, fmt.Errorf("parse base url: %w", err)
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: o.Timeout,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: o.InsecureTLS}, //nolint:gosec
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
return &Client{
base: u,
token: o.Token,
http: &http.Client{
Transport: tr,
Timeout: o.Timeout,
},
verbose: o.Verbose,
timeout: o.Timeout,
}, nil
}
// buildURL constructs a full URL with the given path and query parameters, adding the auth token.
func (c *Client) buildURL(path string, q url.Values) string {
u := *c.base
u.Path = strings.TrimRight(c.base.Path, "/") + path
if q == nil {
q = url.Values{}
}
q.Set("X-Plex-Token", c.token)
u.RawQuery = q.Encode()
return u.String()
}
// getXML performs a GET request to the given URL and decodes the XML response into a mediaContainer.
func (c *Client) getXML(ctx context.Context, rawURL string) (*mediaContainer, error) {
if c.verbose {
fmt.Fprintln(os.Stderr, "GET", rawURL)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/xml")
req.Header.Set("X-Plex-Product", "goPlexr")
req.Header.Set("X-Plex-Version", "1.3")
req.Header.Set("X-Plex-Client-Identifier", "goPlexr-"+shortHost())
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10))
return nil, fmt.Errorf("plex http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
}
var mc mediaContainer
if err := xml.NewDecoder(resp.Body).Decode(&mc); err != nil {
return nil, fmt.Errorf("decode xml: %w", err)
}
return &mc, nil
}
// shortHost returns a shortened hostname for use in the X-Plex-Client-Identifier header.
func shortHost() string {
h, _ := os.Hostname()
if len(h) > 20 {
return h[:20]
}
return h
}
// Public API
func (c *Client) DiscoverSections(ctx context.Context, includeShows bool) ([]Directory, error) {
u := c.buildURL("/library/sections", nil)
mc, err := c.getXML(ctx, u)
if err != nil {
return nil, err
}
var out []Directory
for _, d := range mc.Directory {
if d.Type == "movie" || (includeShows && d.Type == "show") {
out = append(out, d)
}
}
return out, nil
}
// FetchDuplicatesForSection fetches all items in the given section ID and returns those with multiple versions.
func (c *Client) FetchDuplicatesForSection(ctx context.Context, id string) ([]Video, error) {
q := url.Values{}
q.Set("duplicate", "1")
u := c.buildURL("/library/sections/"+id+"/all", q)
mc, err := c.getXML(ctx, u)
if err != nil {
return nil, err
}
var vids []Video
for _, v := range mc.Video {
if len(v.Media) > 1 {
vids = append(vids, v)
}
}
return vids, nil
}
// DeepFetchItem fetches full details for a single item by its ratingKey, including media and part info.
func (c *Client) DeepFetchItem(ctx context.Context, ratingKey string, verify bool) (*Video, error) {
q := url.Values{}
q.Set("includeChildren", "1")
if verify {
q.Set("checkFiles", "1")
}
u := c.buildURL("/library/metadata/"+ratingKey, q)
mc, err := c.getXML(ctx, u)
if err != nil {
return nil, err
}
if len(mc.Video) == 0 {
return nil, fmt.Errorf("no video for ratingKey %s", ratingKey)
}
return &mc.Video[0], nil
}
// BaseURL returns the server base URL string exactly as configured.
func (c *Client) BaseURL() string {
return c.base.String()
}