-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprovider.go
349 lines (296 loc) · 7.5 KB
/
provider.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
package proxytv
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/csfrancis/proxytv/xmltv"
log "github.com/sirupsen/logrus"
)
type playlistLoader struct {
baseAddress string
filters []*Filter
tracks []Track
priorities map[string]int
m3u strings.Builder
}
func newPlaylistLoader(baseAddress string, filters []*Filter) *playlistLoader {
return &playlistLoader{
baseAddress: baseAddress,
filters: filters,
tracks: make([]Track, 0, len(filters)),
priorities: make(map[string]int),
}
}
func (pl *playlistLoader) findIndexWithID(track *Track) int {
id := track.Tags["tvg-id"]
if len(id) == 0 {
return -1
}
for i := range pl.tracks {
if pl.tracks[i].Tags["tvg-id"] == id {
return i
}
}
return -1
}
func (pl *playlistLoader) OnPlaylistStart() {
pl.m3u.Reset()
pl.m3u.WriteString("#EXTM3U\n")
}
func (pl *playlistLoader) OnTrack(track *Track) {
for i, filter := range pl.filters {
var field string
switch filter.Type {
case "id":
field = "tvg-id"
case "group":
field = "group-title"
case "name":
field = "tvg-name"
default:
log.WithField("type", filter.Type).Panic("invalid filter type")
}
val := track.Tags[field]
if len(val) == 0 {
continue
}
if filter.regexp.Match([]byte(val)) {
name := track.Name
if len(track.Tags["tvg-id"]) == 0 {
log.WithField("track", track).Warn("missing tvg-id")
}
if existingPriority, exists := pl.priorities[name]; !exists || i < existingPriority {
idx := pl.findIndexWithID(track)
if idx != -1 {
if strings.Contains(track.Name, "HD") {
delete(pl.priorities, pl.tracks[idx].Name)
pl.tracks[idx] = *track
} else {
continue
}
} else {
if !exists {
pl.tracks = append(pl.tracks, *track)
}
}
pl.priorities[name] = i
} else if exists {
log.WithField("track", track).Warn("duplicate name")
}
}
}
}
func (pl *playlistLoader) OnPlaylistEnd() {
sort.SliceStable(pl.tracks, func(i, j int) bool {
priorityI, existsI := pl.priorities[pl.tracks[i].Name]
priorityJ, existsJ := pl.priorities[pl.tracks[j].Name]
if !existsI && !existsJ {
return false // Keep original order for unmatched elements
}
if !existsI {
return false // Unmatched elements go to the end
}
if !existsJ {
return true // Matched elements come before unmatched ones
}
return priorityI < priorityJ
})
rewriteURL := len(pl.baseAddress) > 0
reXuiid := regexp.MustCompile(`xui-id="\{[^"]*\}"\s*`)
for i := range len(pl.tracks) {
track := pl.tracks[i]
uri := track.URI.String()
if rewriteURL {
uri = fmt.Sprintf("http://%s/channel/%d", pl.baseAddress, i)
}
// Remove xui-id from the tags
fixedRaw := reXuiid.ReplaceAllString(track.Raw, "")
pl.m3u.WriteString(fmt.Sprintf("%s\n%s\n", fixedRaw, uri))
}
}
func loadReader(uri string, userAgent string) (io.ReadCloser, error) {
var err error
var reader io.ReadCloser
logger := log.WithField("uri", uri)
if isURL(uri) {
req, err := http.NewRequest(http.MethodGet, uri, nil)
if err != nil {
logger.WithError(err).Panic("unable to create request")
}
if userAgent != "" {
req.Header.Set("User-Agent", userAgent)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.WithError(err).Panic("unable to load uri")
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("invalid url response code: %d", resp.StatusCode)
}
reader = resp.Body
} else {
reader, err = os.Open(uri)
if err != nil {
return nil, err
}
}
return reader, nil
}
type Provider struct {
iptvURL string
epgURL string
baseAddress string
userAgent string
filters []*Filter
playlist *playlistLoader
epg *xmltv.TV
epgData []byte
lastRefresh time.Time
}
func NewProvider(config *Config) (*Provider, error) {
provider := &Provider{
iptvURL: config.IPTVUrl,
epgURL: config.EPGUrl,
filters: config.Filters,
}
if len(config.UserAgent) > 0 {
provider.userAgent = config.UserAgent
}
if config.UseFFMPEG {
provider.baseAddress = config.ServerAddress
}
return provider, nil
}
func (p *Provider) loadXMLTv(reader io.Reader) (*xmltv.TV, error) {
start := time.Now()
channels := make(map[string]bool)
for _, track := range p.playlist.tracks {
id := track.Tags["tvg-id"]
if len(id) == 0 {
continue
}
channels[id] = true
}
decoder := xml.NewDecoder(reader)
tvSetup := new(xmltv.TV)
totalChannelCount := 0
totalProgrammeCount := 0
for {
// Decode the next XML token
tok, err := decoder.Token()
if err != nil {
break // Exit on EOF or error
}
// Process the start element
switch se := tok.(type) {
case xml.StartElement:
switch se.Name.Local {
case "tv":
for _, attr := range se.Attr {
switch attr.Name.Local {
case "date":
tvSetup.Date = attr.Value
case "source-info-url":
tvSetup.SourceInfoURL = attr.Value
case "source-info-name":
tvSetup.SourceInfoName = attr.Value
case "source-data-url":
tvSetup.SourceDataURL = attr.Value
case "generator-info-name":
tvSetup.GeneratorInfoName = attr.Value
case "generator-info-url":
tvSetup.GeneratorInfoURL = attr.Value
}
}
case "programme":
var programme xmltv.Programme
err := decoder.DecodeElement(&programme, &se)
if err != nil {
return nil, err
}
if channels[programme.Channel] {
tvSetup.Programmes = append(tvSetup.Programmes, programme)
}
totalProgrammeCount++
case "channel":
var channel xmltv.Channel
err := decoder.DecodeElement(&channel, &se)
if err != nil {
return nil, err
}
if channels[channel.ID] {
tvSetup.Channels = append(tvSetup.Channels, channel)
}
totalChannelCount++
}
}
}
log.WithFields(log.Fields{
"totalChannelCount": totalChannelCount,
"channelCount": len(tvSetup.Channels),
"totalProgrammeCount": totalProgrammeCount,
"programmeCount": len(tvSetup.Programmes),
"duration": time.Since(start),
}).Info("loaded xmltv")
return tvSetup, nil
}
func (p *Provider) Refresh() error {
var err error
log.WithField("url", p.iptvURL).Info("loading IPTV m3u")
start := time.Now()
iptvReader, err := loadReader(p.iptvURL, p.userAgent)
if err != nil {
return err
}
defer iptvReader.Close()
log.WithField("duration", time.Since(start)).Debug("loaded IPTV m3u")
pl := newPlaylistLoader(p.baseAddress, p.filters)
err = loadM3u(iptvReader, pl)
if err != nil {
return err
}
p.playlist = pl
log.WithField("channelCount", len(p.playlist.tracks)).Info("parsed IPTV m3u")
log.WithField("url", p.epgURL).Info("loading EPG")
start = time.Now()
epgReader, err := loadReader(p.epgURL, p.userAgent)
if err != nil {
return err
}
defer epgReader.Close()
log.WithField("duration", time.Since(start)).Debug("loaded EPG")
p.epg, err = p.loadXMLTv(epgReader)
if err != nil {
return err
}
xmlData, err := xml.Marshal(p.epg)
if err != nil {
return err
}
xmlHeader := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE tv SYSTEM \"xmltv.dtd\">")
p.epgData = append(xmlHeader, xmlData...)
p.lastRefresh = time.Now()
return nil
}
func (p *Provider) GetM3u() string {
return p.playlist.m3u.String()
}
func (p *Provider) GetEpgXML() string {
return string(p.epgData)
}
var trackNotFound = Track{}
func (p *Provider) GetTrack(idx int) *Track {
if idx >= len(p.playlist.tracks) {
return &trackNotFound
}
return &p.playlist.tracks[idx]
}
func (p *Provider) GetLastRefresh() time.Time {
return p.lastRefresh
}