-
Notifications
You must be signed in to change notification settings - Fork 20
/
XMLTV.cs
480 lines (423 loc) · 17.5 KB
/
XMLTV.cs
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
namespace RoliSoft.TVShowTracker
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using RoliSoft.TVShowTracker.Parsers.Guides;
/// <summary>
/// Provides support for parsing XMLTV files and mapping the programming to shows in your database.
/// </summary>
public class XMLTV : LocalProgrammingPlugin
{
/// <summary>
/// Gets or sets the name of the plugin.
/// </summary>
/// <value>The name of the plugin.</value>
public override string Name
{
get
{
return "XMLTV";
}
}
/// <summary>
/// Gets the URL to the plugin's icon.
/// </summary>
/// <value>The location of the plugin's icon.</value>
public override string Icon
{
get
{
return "http://wiki.xmltv.org/favicon.ico";
}
}
/// <summary>
/// Gets the name of the plugin's developer.
/// </summary>
/// <value>The name of the plugin's developer.</value>
public override string Developer
{
get
{
return "RoliSoft";
}
}
/// <summary>
/// Gets the version number of the plugin.
/// </summary>
/// <value>The version number of the plugin.</value>
public override Version Version
{
get
{
return Utils.DateTimeToVersion("2012-01-07 5:13 AM");
}
}
/// <summary>
/// Gets a list of available programming configurations.
/// </summary>
/// <returns>The list of available programming configurations.</returns>
public override IEnumerable<Configuration> GetConfigurations()
{
var settings = Settings.Get<List<Dictionary<string, object>>>("XMLTV");
if (settings == null || !settings.Any())
{
yield break;
}
foreach (var setting in settings)
{
if (!setting.ContainsKey("Name") || !(setting["Name"] is string) || !setting.ContainsKey("File") || !(setting["File"] is string))
{
continue;
}
yield return new XMLTVConfiguration(this)
{
Name = (string) setting["Name"],
File = (string) setting["File"],
Language = setting.ContainsKey("Language") && setting["Language"] is string ? (string) setting["Language"] : string.Empty,
AdvHuRoParse = setting.ContainsKey("Advanced Parsing") && setting["Advanced Parsing"] is bool && (bool) setting["Advanced Parsing"],
UseMappedNames = setting.ContainsKey("Use English Titles") && setting["Use English Titles"] is bool && (bool) setting["Use English Titles"],
TZCorrection = setting.ContainsKey("Time Zone Correction") && setting["Time Zone Correction"] is double ? (double) setting["Time Zone Correction"] : 0,
};
}
}
/// <summary>
/// Gets a list of upcoming episodes in your area ordered by airdate.
/// </summary>
/// <param name="config">The config.</param>
/// <returns>
/// List of upcoming episodes in your area.
/// </returns>
public override IEnumerable<Programme> GetListing(Configuration config)
{
var xconfig = (XMLTVConfiguration) config;
var listing = (List<XMLTVProgramme>) null;
var cache = Path.Combine(Signature.InstallPath, @"misc\xmltv-" + xconfig.Language + "-" + xconfig.File.GetHashCode().ToString("x"));
if (File.Exists(cache) && File.GetLastWriteTime(cache) > File.GetLastWriteTime(xconfig.File))
{
try
{
using (var fs = File.OpenRead(cache))
using (var br = new BinaryReader(fs))
{
var ver = br.ReadByte();
var upd = br.ReadUInt32();
var cnt = br.ReadUInt32();
listing = new List<XMLTVProgramme>();
for (var i = 0; i < cnt; i++)
{
var prog = new XMLTVProgramme();
prog.ShowID = br.ReadInt32();
prog.Name = br.ReadString();
prog.Number = br.ReadString();
prog.Description = br.ReadString();
prog.Channel = br.ReadString();
prog.Airdate = ((double)br.ReadInt32()).GetUnixTimestamp();
prog.URL = br.ReadString();
listing.Add(prog);
}
}
}
catch
{
listing = null;
}
}
if (listing == null)
{
listing = Filter(ParseFile(xconfig), xconfig).ToList();
}
if (!Directory.Exists(Path.GetDirectoryName(cache)))
{
Directory.CreateDirectory(Path.GetDirectoryName(cache));
}
using (var fs = File.OpenWrite(cache))
using (var bw = new BinaryWriter(fs))
{
bw.Write((byte)1);
bw.Write((uint)DateTime.Now.ToUnixTimestamp());
bw.Write((uint)listing.Count);
foreach (var prog in listing)
{
bw.Write(prog.ShowID);
bw.Write(prog.Name ?? string.Empty);
bw.Write(prog.Number ?? string.Empty);
bw.Write(prog.Description ?? string.Empty);
bw.Write(prog.Channel ?? string.Empty);
bw.Write((int)prog.Airdate.ToUnixTimestamp());
bw.Write(prog.URL ?? string.Empty);
}
}
foreach (var prog in listing.Where(p => p.Airdate.AddHours(xconfig.TZCorrection) > DateTime.Now))
{
if (xconfig.AdvHuRoParse && prog.Description.StartsWith(prog.Name))
{
var ep = Regex.Match(prog.Description, @"(?:(?:(?<sr>[IVXLCDM]+)\.(?: évad)?\s*/\s*)?(?<e>\d{1,3})\. rész|(?<s>\d{1,2})\. évad(?:,? (?<e>\d{1,3})\. rész)?|(?:sezonul (?<s>\d{1,2}), )?episodul (?<e>\d{1,3})|^\s*" + Regex.Escape(prog.Name) + @"\s+(?<e>\d{1,3})\.(?:,\s+)?)");
prog.Description = Regex.Replace(prog.Description, @"^\s*" + Regex.Escape(prog.Name) + @"\s*(\d{1,3}\.(?:,\s+|$))?(?:\([^\)]+\)\s*)?(?:\(ism\.\)\s*)?(?:(?:\d{1,2}|[IVXLCDM]+)\. évad(?:\s*[,/] \d{1,3}\. rész(?:, )?)?)?(?:\-\s*)?(?:\((?:reluare|St)\)\s*)?(?: Utána: .+| Feliratozva .+)?", string.Empty, RegexOptions.IgnoreCase);
if (ep.Success)
{
prog.Number = string.Empty;
if (ep.Groups["sr"].Success)
{
prog.Number = "S" + Utils.RomanToNumber(ep.Groups["sr"].Value).ToString("00");
if (ep.Groups["e"].Success)
{
prog.Number += " #" + int.Parse(ep.Groups["e"].Value);
}
}
else
{
if (ep.Groups["s"].Success)
{
prog.Number = "S" + int.Parse(ep.Groups["s"].Value).ToString("00");
}
else if (ep.Groups["e"].Success)
{
prog.Number += "#" + int.Parse(ep.Groups["e"].Value);
}
if (ep.Groups["s"].Success && ep.Groups["e"].Success)
{
prog.Number += "E" + int.Parse(ep.Groups["e"].Value).ToString("00");
}
}
}
}
if (xconfig.UseMappedNames)
{
prog.Name = prog.Show.Title;
}
if (xconfig.TZCorrection != 0)
{
prog.Airdate = prog.Airdate.AddHours(xconfig.TZCorrection);
}
yield return prog;
}
}
/// <summary>
/// Parses the specified XMLTV file.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>
/// List of extracted programmes.
/// </returns>
public IEnumerable<XMLTVProgramme> ParseFile(XMLTVConfiguration config)
{
var channels = new Dictionary<string, string[]>();
var document = XDocument.Load(config.File);
foreach (var channel in document.Descendants("channel"))
{
var id = channel.Attribute("id");
var name = channel.Descendants("display-name").ToList();
var url = channel.Descendants("url").ToList();
if (id == null || !name.Any())
{
continue;
}
channels.Add(id.Value, new[] { name[0].Value, url.Any() ? url.Last().Value : null });
}
foreach (var programme in document.Descendants("programme"))
{
var channel = programme.Attribute("channel");
var start = programme.Attribute("start");
var title = programme.Descendants("title").ToList();
var descr = programme.Descendants("desc").ToList();
if (channel == null || start == null || !title.Any())
{
continue;
}
DateTime airdate;
if (!DateTime.TryParseExact(start.Value, "yyyyMMddHHmmss zzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out airdate))
{
continue;
}
var prog = new XMLTVProgramme
{
Channel = channels[channel.Value][0],
Name = title[0].Value.Trim(),
Airdate = airdate,
URL = channels[channel.Value][1]
};
if (descr.Any())
{
prog.Description = descr[0].Value.Trim();
}
yield return prog;
}
}
/// <summary>
/// Filters the specified list of programmes and orders them by airdate.
/// </summary>
/// <param name="programmes">The full extracted list of programmes.</param>
/// <param name="config">The configuration.</param>
/// <returns>
/// List of filtered and ordered programmes.
/// </returns>
public IEnumerable<XMLTVProgramme> Filter(IEnumerable<XMLTVProgramme> programmes, XMLTVConfiguration config)
{
var regexes = new Dictionary<Regex, TVShow>();
foreach (var show in Database.TVShows)
{
regexes.Add(new Regex(@"(^|:\s+)" + Regex.Escape(show.Value.Title) + @"(?!(?:[:,0-9]| \- |\s*[a-z&]))", RegexOptions.IgnoreCase), show.Value);
if (!string.IsNullOrWhiteSpace(config.Language) && config.Language.Length == 2)
{
var foreign = show.Value.GetForeignTitle(config.Language);
if (!string.IsNullOrWhiteSpace(foreign))
{
regexes.Add(new Regex(@"(^|:\s+)" + Regex.Escape(foreign.RemoveDiacritics()) + @"(?!(?:[:,0-9]| \- |\s*[a-z&]))", RegexOptions.IgnoreCase), show.Value);
}
}
}
foreach (var prog in programmes.OrderBy(p => p.Airdate))
{
foreach (var regex in regexes)
{
if (regex.Key.IsMatch(prog.Name.RemoveDiacritics()))
{
prog.ShowID = regex.Value.ID;
yield return prog;
break;
}
}
}
}
/// <summary>
/// Represents an XMLTV configuration.
/// </summary>
public class XMLTVConfiguration : Configuration
{
/// <summary>
/// Gets or sets the location of the XML file.
/// </summary>
/// <value>
/// The location of the XML file.
/// </value>
public string File { get; set; }
/// <summary>
/// Gets or sets the language of the titles in the programming.
/// </summary>
/// <value>
/// The language of the titles in the programming.
/// </value>
public string Language { get; set; }
/// <summary>
/// Gets or sets a value indicating whether advanced parsing is enabled.
/// </summary>
/// <remarks>
/// Advanced parsing will remove irrelevant information from the description field and
/// extract the episode notation. This only works for hungarian and romanian listing.
/// </remarks>
/// <value>
/// <c>true</c> if advanced parsing is enabled; otherwise, <c>false</c>.
/// </value>
public bool AdvHuRoParse { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the mapped english names are used or the original ones found in the listing.
/// </summary>
/// <value>
/// <c>true</c> if the mapped english names are used; otherwise, <c>false</c>.
/// </value>
public bool UseMappedNames { get; set; }
/// <summary>
/// Gets or sets the timezone correction information.
/// </summary>
/// <value>
/// The timezone correction information.
/// </value>
public double TZCorrection { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="XMLTVConfiguration"/> class.
/// </summary>
/// <param name="plugin">The plugin.</param>
public XMLTVConfiguration(LocalProgrammingPlugin plugin) : base(plugin)
{
}
}
/// <summary>
/// Represents a programme in the XMLTV listing.
/// </summary>
public class XMLTVProgramme : Programme
{
/// <summary>
/// Gets or sets the ID of the show in the database.
/// </summary>
/// <value>
/// The ID of the show in the database.
/// </value>
public int ShowID
{
get { return base.Show.ID; }
set { base.Show = Database.TVShows[value]; }
}
/// <summary>
/// Gets or sets the name of the show.
/// </summary>
/// <value>
/// The name of the show.
/// </value>
public new string Name
{
get { return base.Name; }
set { base.Name = value; }
}
/// <summary>
/// Gets or sets the episode number.
/// </summary>
/// <value>
/// The episode number.
/// </value>
public new string Number
{
get { return base.Number; }
set { base.Number = value; }
}
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
public new string Description
{
get { return base.Description; }
set { base.Description = value; }
}
/// <summary>
/// Gets or sets the channel.
/// </summary>
/// <value>
/// The channel.
/// </value>
public new string Channel
{
get { return base.Channel; }
set { base.Channel = value; }
}
/// <summary>
/// Gets or sets the airdate.
/// </summary>
/// <value>
/// The airdate.
/// </value>
public new DateTime Airdate
{
get { return base.Airdate; }
set { base.Airdate = value; }
}
/// <summary>
/// Gets or sets an URL to the listing or episode information.
/// </summary>
/// <value>
/// The URL to the listing or episode information.
/// </value>
public new string URL
{
get { return base.URL; }
set { base.URL = value; }
}
}
}
}