/[xmltv_parser]/trunk/GBPVRProgramDatabaseFixer/SQLLITE.cs
ViewVC logotype

Contents of /trunk/GBPVRProgramDatabaseFixer/SQLLITE.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 229 - (show annotations) (download)
Sun Mar 17 04:13:59 2013 UTC (6 years, 8 months ago) by william
File size: 57342 byte(s)

1 //#define SQLLITE_CONNECTION_TEST
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Text;
6 using System.Data.SQLite;
7 using System.Diagnostics;
8 using Enterprise.Logging;
9 using libxmltv;
10 using libxmltv.Interfaces;
11 using libxmltv.Core;
12 namespace GBPVRProgramDatabaseFixer
13 {
14 public interface ICloneable<T>
15 {
16 T Clone();
17 }
18 public interface IOldNewProgram
19 {
20 SQLLITE.IPROGRAMME OldProgram { get; }
21 SQLLITE.IPROGRAMME NewProgram { get; }
22 }
23 public interface ISQLLITE
24 {
25 List<SQLLITE.IPROGRAMME> Programs { get; }
26 List<SQLLITE.IRECORDING_SCHEDULE> Recordings { get; }
27 List<SQLLITE.ICHANNEL> Channels { get; }
28 IDateTimeRange GetProgramsDateRange(List<SQLLITE.IPROGRAMME> programs);
29 List<IOldNewProgram> FixGBPVRProgramsDatabase(List<SQLLITE.IPROGRAMME> gbpvr_programs, List<libxmltv.Interfaces.IProgramDefinition> xmltv_programs, out List<SQLLITE.IPROGRAMME> removed_programs);
30
31 void RemoveOldGBPVRPrograms(List<SQLLITE.IPROGRAMME> programs);
32 void UpdateGBPVRPrograms(List<IOldNewProgram> programs);
33
34 }
35 public class SQLLITE : ISQLLITE
36 {
37 private class OldNewProgram : IOldNewProgram
38 {
39 public OldNewProgram() : this(new PROGRAMME()) { }
40 public OldNewProgram(IPROGRAMME _old) : this(_old,_old) { }
41 public OldNewProgram(IPROGRAMME _old, IPROGRAMME _new) { OldProgram = _old; NewProgram = _new; }
42
43 public IPROGRAMME OldProgram { get; private set; }
44 public IPROGRAMME NewProgram { get; private set; }
45 }
46 public static ISQLLITE Create(string database, EventHandler<EventArgs> OnInstanceCreated)
47 {
48 return new SQLLITE(database, OnInstanceCreated);
49 }
50
51 #region DATABASE DEFINITIONS
52 #region BaseDatabaseDefinition
53 private static class BaseDatabaseDefinition<T>
54 {
55 public static void CreateDefault(T instance)
56 {
57 try
58 {
59 Type t = typeof(T);
60 var props = t.GetProperties();
61 foreach (var prop in props)
62 {
63 Type prop_type = prop.PropertyType;
64 object field_value = null;
65 try
66 {
67 if (prop_type == typeof(string))
68 {
69 field_value = string.Empty;
70 }
71 else
72 {
73 field_value = Activator.CreateInstance(prop_type);
74 }
75 }
76 catch (Exception ex)
77 {
78 throw ex;
79 }
80 prop.SetValue(instance, field_value, null);
81 }
82 }
83 catch (Exception ex)
84 {
85 throw ex;
86 }
87 }
88 public static void Create(T source, ref T destination)
89 {
90 Type t = source.GetType();
91 var props = t.GetProperties();
92 foreach (var prop in props)
93 {
94 try
95 {
96 object value = prop.GetValue(source, null);
97 prop.SetValue(destination, value, null);
98 }
99 catch (Exception ex)
100 {
101 throw ex;
102 }
103 }
104 }
105 public static void Create(ref T instance, SQLiteDataReader r, int index)
106 {
107 string field_name = r.GetName(index);
108 Type field_type = r.GetFieldType(index);
109 object field_value = r.GetValue(index);
110 //gLog.Verbose.Debug.WriteLine("Name: '{0}' Type: '{1}' Value: '{2}'", field_name, field_type.Name, field_value == null ? "null" : field_value.ToString());
111
112 Type t = typeof(T);
113 var props = t.GetProperties();
114 foreach (var prop in props)
115 {
116 if (prop.Name.ToLower() == field_name.ToLower())
117 {
118 if (prop.PropertyType == field_type)
119 {
120 Type db_type = field_value.GetType();
121 try
122 {
123 if (db_type == typeof(System.DBNull))
124 {
125 prop.SetValue(instance, null, null);
126 }
127 else
128 {
129 prop.SetValue(instance, field_value, null);
130 }
131
132 }
133 catch (Exception ex)
134 {
135 throw ex;
136 }
137 }
138 else
139 {
140 gLog.Verbose.Debug.WriteLine("Found Property: {0} but there was a type mismatch. Property Type: '{1}' Expected: '{2}'", prop.Name, prop.PropertyType.Name, field_type.Name);
141 throw new InvalidOperationException(string.Format("Found Property: {0} but there was a type mismatch. Property Type: '{1}' Expected: '{2}'", prop.Name, prop.PropertyType.Name, field_type.Name));
142 }
143 }
144 }
145
146 }
147 }
148 #endregion
149 public interface ICHANNEL : ICloneable<ICHANNEL>
150 {
151 Int64 oid { get; }
152 String name { get; }
153 String channelID { get; }
154 Int64 channel_number { get; }
155 String favourite_channel { get; }
156 String display_name { get; }
157 }
158 private class CHANNEL : ICHANNEL, ICloneable<CHANNEL>
159 {
160 public CHANNEL()
161 {
162 BaseDatabaseDefinition<CHANNEL>.CreateDefault(this);
163 }
164 //public RECORDING_SCHEDULE(SQLiteDataReader r, int index) { BaseDatabaseDefinition<RECORDING_SCHEDULE>.Create(this, r, index); }
165
166 public static void Create(ref CHANNEL instance, SQLiteDataReader r, int index)
167 {
168 BaseDatabaseDefinition<CHANNEL>.Create(ref instance, r, index);
169 }
170 #region ICHANNEL members
171 public Int64 oid { get; set; }
172 public String name { get; set; }
173 public String channelID { get; set; }
174 public Int64 channel_number { get; set; }
175 public String favourite_channel { get; set; }
176 public String display_name { get; set; }
177 #endregion
178
179 ICHANNEL ICloneable<ICHANNEL>.Clone()
180 {
181 return Clone();
182 }
183 public CHANNEL Clone()
184 {
185 CHANNEL p = new CHANNEL();
186 BaseDatabaseDefinition<CHANNEL>.Create(this, ref p);
187 return p;
188 }
189 }
190 public interface IRECORDING_SCHEDULE : ICloneable<IRECORDING_SCHEDULE>
191 {
192 Int64 oid { get; }
193 Int64 programme_oid { get; }
194 Int64 capture_source_oid { get; }
195 Int16 status { get; }
196 String filename { get; }
197 Int64 recording_type { get; }
198 Int64 recording_group { get; }
199 DateTime manual_start_time { get; }
200 DateTime manual_end_time { get; }
201 Int64 manual_channel_oid { get; }
202 Int64 quality_level { get; }
203 Int64 pre_pad_minutes { get; }
204 Int64 post_pad_minutes { get; }
205 Int32 priority { get; }
206 String conversion_profile { get; }
207 }
208 private class RECORDING_SCHEDULE : IRECORDING_SCHEDULE, ICloneable<RECORDING_SCHEDULE>
209 {
210 public RECORDING_SCHEDULE()
211 {
212 BaseDatabaseDefinition<RECORDING_SCHEDULE>.CreateDefault(this);
213 }
214 //public RECORDING_SCHEDULE(SQLiteDataReader r, int index) { BaseDatabaseDefinition<RECORDING_SCHEDULE>.Create(this, r, index); }
215
216 public static void Create(ref RECORDING_SCHEDULE instance, SQLiteDataReader r, int index)
217 {
218 BaseDatabaseDefinition<RECORDING_SCHEDULE>.Create(ref instance, r, index);
219 }
220 IRECORDING_SCHEDULE ICloneable<IRECORDING_SCHEDULE>.Clone()
221 {
222 return Clone();
223 }
224 public RECORDING_SCHEDULE Clone()
225 {
226 RECORDING_SCHEDULE p = new RECORDING_SCHEDULE();
227 BaseDatabaseDefinition<RECORDING_SCHEDULE>.Create(this, ref p);
228 return p;
229 }
230 #region IRECORDING_SCHEDULE members
231 public Int64 oid { get; set; }
232 public Int64 programme_oid { get; set; }
233 public Int64 capture_source_oid { get; set; }
234 public Int16 status { get; set; }
235 public String filename { get; set; }
236 public Int64 recording_type { get; set; }
237 public Int64 recording_group { get; set; }
238 public DateTime manual_start_time { get; set; }
239 public DateTime manual_end_time { get; set; }
240 public Int64 manual_channel_oid { get; set; }
241 public Int64 quality_level { get; set; }
242 public Int64 pre_pad_minutes { get; set; }
243 public Int64 post_pad_minutes { get; set; }
244 public Int32 priority { get; set; }
245 public String conversion_profile { get; set; }
246 #endregion
247
248
249 }
250 public interface IPROGRAMME : IEquatable<IPROGRAMME>, ICloneable<IPROGRAMME>
251 {
252 Int64 oid { get; set; }
253 String name { get; set; }
254 String sub_title { get; set; }
255 String description { get; set; }
256 DateTime start_time { get; set; }
257 DateTime end_time { get; set; }
258 Int64 channel_oid { get; set; }
259 String unique_identifier { get; set; }
260 String rating { get; set; }
261
262 string ToString();
263 IProgramDefinition AsXMLTVProgramDefinition(ISQLLITE sqllite);
264 }
265 private class PROGRAMME : IPROGRAMME, ICloneable<PROGRAMME>
266 {
267
268 IPROGRAMME ICloneable<IPROGRAMME>.Clone()
269 {
270 return Clone();
271 }
272 public PROGRAMME Clone()
273 {
274 PROGRAMME p = new PROGRAMME();
275 BaseDatabaseDefinition<PROGRAMME>.Create(this, ref p);
276 return p;
277 }
278 public PROGRAMME()
279 {
280 BaseDatabaseDefinition<PROGRAMME>.CreateDefault(this);
281 }
282 //public PROGRAMME(SQLiteDataReader r, int index) : base(r, index) { }
283 public static void Create(ref PROGRAMME instance, SQLiteDataReader r, int index)
284 {
285 BaseDatabaseDefinition<PROGRAMME>.Create(ref instance, r, index);
286 }
287 #region IPROGRAMME members
288 public Int64 oid { get; set; }
289 public String name { get; set; }
290 public String sub_title { get; set; }
291 public String description { get; set; }
292 public DateTime start_time { get; set; }
293 public DateTime end_time { get; set; }
294 public Int64 channel_oid { get; set; }
295 public String unique_identifier { get; set; }
296 public String rating { get; set; }
297 public IProgramDefinition AsXMLTVProgramDefinition(ISQLLITE sqllite)
298 {
299 ProgramList.ProgramDefintion definition = new ProgramList.ProgramDefintion();
300
301 var channel = sqllite.Channels.Find(s => s.oid == this.channel_oid);
302 var channelname = channel.display_name;
303 var split = channelname.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
304 definition.ChannelNumber = Convert.ToInt32(split.First());
305 definition.ChannelName = string.IsNullOrEmpty(split.Last()) ? string.Empty : split.Last().ToString();
306 definition.Description = this.description;
307 definition.Start = this.start_time.ToDateTimeString();
308 definition.Stop = this.end_time.ToDateTimeString();
309 definition.SubTitle = this.sub_title;
310 definition.Title = this.name;
311 definition.Rating = this.rating;
312 return definition;
313 }
314 #endregion
315
316 public bool Equals(IPROGRAMME other)
317 {
318 return this.ToString() == other.ToString();
319 }
320 public override string ToString()
321 {
322 StringBuilder builder = new StringBuilder();
323
324 builder.AppendFormat("oid: '{0}' ", oid);
325 builder.AppendFormat("name: '{0}' ", name);
326 builder.AppendFormat("sub_title: '{0}' ", sub_title);
327 builder.AppendFormat("description: '{0}' ", description);
328 builder.AppendFormat("start_time: '{0}' ", start_time.ToDateTimeString());
329 builder.AppendFormat("end_time: '{0}' ", end_time.ToDateTimeString());
330 builder.AppendFormat("channel_oid: '{0}' ", channel_oid);
331 builder.AppendFormat("unique_identifier: '{0}' ", unique_identifier);
332 builder.AppendFormat("rating: '{0}'", rating);
333
334 return builder.ToString();
335 }
336 public override bool Equals(object obj)
337 {
338 if (obj == null) { throw new ArgumentNullException("obj", "Object to compare cannot be null"); }
339 if (obj.GetType().IsAssignableFrom(typeof(IPROGRAMME)))
340 {
341 return this.Equals((IPROGRAMME)obj);
342 }
343 return base.Equals(obj);
344 }
345 public override int GetHashCode()
346 {
347 return this.ToString().GetHashCode();
348 }
349
350
351
352
353
354
355
356
357 }
358 #endregion
359 private static class TABLES
360 {
361 public const string RECORDING_SCHEDULE = "RECORDING_SCHEDULE";
362 public const string PROGRAMME = "PROGRAMME";
363 public const string CHANNEL = "CHANNEL";
364 }
365 private string DATABASE_BACKUP_FILE = string.Empty;
366 //public SQLLite() { }
367 protected SQLLITE(string database, EventHandler<EventArgs> OnInstanceCreated)
368 {
369 this.OnInstanceCreated = OnInstanceCreated;
370 //CreateConnection(database);
371 this.Database = database;
372 if (!CreateDatabaseBackup())
373 {
374 gLog.Error.WriteLine("Failed to backup database.");
375 return;
376 }
377 ConnectionTest();
378 ReadChannelData();
379 ReadRecodringScheduleData();
380 ReadProgrammeData();
381 OnCreatedInstance(this, new EventArgs());
382 }
383
384 [NonSerialized]
385 private EventHandler<EventArgs> _OnInstanceCreated;
386 private EventHandler<EventArgs> OnInstanceCreated { get { return _OnInstanceCreated; } set { _OnInstanceCreated = value; } }
387
388 private void OnCreatedInstance(object sender, EventArgs e)
389 {
390 if (OnInstanceCreated != null) { OnInstanceCreated.Invoke(sender, e); }
391 }
392
393 private string Database;
394 #region ISQLLITE members
395 public List<IPROGRAMME> Programs { get; private set; }
396 public List<IRECORDING_SCHEDULE> Recordings { get; private set; }
397 public List<ICHANNEL> Channels { get; private set; }
398
399 public IDateTimeRange GetProgramsDateRange(List<SQLLITE.IPROGRAMME> programs)
400 {
401 var list = new List<IPROGRAMME>(programs.ToArray());
402 DateTime first = new DateTime();
403 DateTime last = new DateTime();
404 first = list.OrderBy(s => s.start_time).ToList().First().start_time;
405 last = list.OrderBy(s => s.start_time).ToList().Last().start_time;
406 gLog.Verbose.Debug.WriteLine("\tFirst: {0} = ({1})", first.ToString("yyyy/MM/dd HH:mm:ss.fffffff"), first.ToDateTimeString());
407 gLog.Verbose.Debug.WriteLine("\tLast: {0} = ({1})", last.ToString("yyyy/MM/dd HH:mm:ss.fffffff"), last.ToDateTimeString());
408 var range = DateTimeRange.Create(first, last);
409 return range;
410 }
411
412 public List<IOldNewProgram> FixGBPVRProgramsDatabase(List<SQLLITE.IPROGRAMME> gbpvr_programs, List<libxmltv.Interfaces.IProgramDefinition> xmltv_programs, out List<SQLLITE.IPROGRAMME> source_invalid)
413 {
414 source_invalid = new List<IPROGRAMME>();
415 List<IOldNewProgram> source_valid = new List<IOldNewProgram>();
416 gbpvr_programs = gbpvr_programs.OrderBy(s => s.start_time).ToList();
417 xmltv_programs = xmltv_programs.OrderBy(s => DateTime.Parse(s.Start)).ToList();
418 gbpvr_programs.TrimExcess();
419 xmltv_programs.TrimExcess();
420
421 int updated_program_count = 0;
422 double total = gbpvr_programs.Count;
423 double index = 0;
424 double progress = 0;
425 foreach (var program in gbpvr_programs)
426 {
427 progress = 100.0 * (index / total);
428 gLog.ReportProgress(this, new ReportProgressEventArgs((int)progress, string.Format("Filtering GBPVR Programs: {0:00}%", (int)progress)));
429 // find an entry in xmltv_programs by Channel Number & StartDate
430 var program_xmltv_entry = program.AsXMLTVProgramDefinition(this);
431 var xmltv_entry = xmltv_programs.Find(s => s.ChannelNumber == program_xmltv_entry.ChannelNumber && s.Start == program_xmltv_entry.Start);
432 if (xmltv_entry == null)
433 {
434 // xmltv entry was not found
435 source_invalid.Add(program);
436 }
437 else
438 {
439 // check if the xmltv entry has different data from the current program
440 if (!xmltv_entry.Equals(program_xmltv_entry))
441 {
442 // data is different
443 var updated_program = program.Clone();
444
445 if (program_xmltv_entry.Title != xmltv_entry.Title)
446 {
447 gLog.Verbose.Warn.WriteLine(" Program oid: '{0}' - replacing title", updated_program.oid);
448 updated_program.name = xmltv_entry.Title;
449 }
450 if (program_xmltv_entry.SubTitle != xmltv_entry.SubTitle)
451 {
452 gLog.Verbose.Warn.WriteLine(" Program oid: '{0}' - replacing sub_title", updated_program.oid);
453 updated_program.sub_title = xmltv_entry.SubTitle;
454 }
455 if (program_xmltv_entry.Stop != xmltv_entry.Stop)
456 {
457 gLog.Verbose.Warn.WriteLine(" Program oid: '{0}' - replacing end_time", updated_program.oid);
458 updated_program.end_time = DateTime.Parse(xmltv_entry.Stop);
459 }
460 if (program_xmltv_entry.Start != xmltv_entry.Start)
461 {
462 gLog.Verbose.Warn.WriteLine(" Program oid: '{0}' - replacing start_time", updated_program.oid);
463 updated_program.start_time = DateTime.Parse(xmltv_entry.Start);
464 }
465 if (program_xmltv_entry.Description != xmltv_entry.Description)
466 {
467 gLog.Verbose.Warn.WriteLine(" Program oid: '{0}' - replacing description", updated_program.oid);
468 updated_program.description = xmltv_entry.Description;
469 }
470
471 if(program_xmltv_entry.Rating != xmltv_entry.Rating)
472 {
473 gLog.Verbose.Warn.WriteLine(" Program oid: '{0}' - replacing rating", updated_program.oid);
474 updated_program.rating = xmltv_entry.Rating;
475 }
476
477 var updated_xmltv_entry = updated_program.AsXMLTVProgramDefinition(this);
478 if (!xmltv_entry.Equals(updated_xmltv_entry))
479 {
480 throw new Exception(string.Format("Program oid '{0}' was not properly updated.", updated_program.oid));
481 }
482 //source_valid.Add(new OldNewProgram(program, updated_program));
483 source_valid.Add(new OldNewProgram(program, updated_program));
484 updated_program_count++;
485 }
486 else
487 {
488 // data is the same
489 //source_valid.Add(new OldNewProgram(program, program));
490 source_valid.Add(new OldNewProgram(program));
491 }
492 }
493 index++;
494 }
495 gLog.Info.WriteLine("Total XMLTV Programs: 0x{0:x8}", xmltv_programs.Count);
496 gLog.Info.WriteLine("Total Valid GB-PVR Programs: 0x{0:x8}", source_valid.Count);
497 gLog.Info.WriteLine("Total Invalid GB-PVR Programs: 0x{0:x8}", source_invalid.Count);
498 gLog.Info.WriteLine("Total GB-PVR Programs (Valid+Invalid): 0x{0:x8} == 0x{1:x8}", source_valid.Count + source_invalid.Count, gbpvr_programs.Count);
499 gLog.Info.WriteLine("GB-PVR Programs needing an update: 0x{0:x8}", updated_program_count);
500 #region old-code
501 //List<OldNewProgram> source_update = new List<OldNewProgram>();
502 ////if (range == null)
503 ////{
504 //// gLog.Warn.WriteLine("The DateTimeRange passed in is null...returning the original program list");
505 //// return list;
506 ////}
507 ////gLog.Warn.WriteLine("FilterProgramsByDateRange has not been implemented");
508 //double total = gbpvr_programs.Count;
509 //double index = 0;
510 //double progress = 0;
511 //foreach (var program in gbpvr_programs)
512 //{
513 // progress = 100.0 * (index / total);
514 // gLog.ReportProgress(this, new ReportProgressEventArgs((int)progress, string.Format("Filtering GBPVR Programs: {0:00}%", (int)progress)));
515 // var channel_oid = program.channel_oid;
516 // var channel = this.Channels.Find(s => s.oid == channel_oid);
517 // var start_date = program.start_time;
518 // //var xmltv_entry_list = xmltv_programs.FindAll(s => s.ChannelNumber == channel.channel_number && s.Start == start_date.ToDateTimeString());
519 // var query = from c in xmltv_programs
520 // where
521 // c.ChannelNumber == channel.channel_number &&
522 // c.Start == start_date.ToDateTimeString()
523 // select c;
524 // IProgramDefinition xmltv_entry = null;
525 // if (query.Count()-1 > 0)
526 // {
527 // gLog.Verbose.Error.WriteLine("Found more than one entry: Matching channel='{0}' and start='{1}'", channel.channel_number, start_date.ToDateTimeString());
528 // gLog.Verbose.Error.WriteLine(" GB-PVR Program Data: oid='{0}' channel_oid='{1}' name='{2}' sub_title='{3}' description='{4}'", program.oid, program.channel_oid, program.name, program.sub_title, program.description);
529 // if (Debugger.IsAttached)
530 // {
531 // gLog.Error.WriteLine(" Found: {0} matching entries", query.Count());
532 // int k_index = 0;
533 // foreach (var k in query)
534 // {
535 // gLog.Verbose.Error.WriteLine(" query[{0}]: channel='{1}' start='{2}' ('{3}') title='{4}' subtitle='{5}' description='{6}'", k_index, k.ChannelNumber, k.Start, DateTime.Parse(k.Start).ToString("yyyy/MM/dd HH:mm:ss.fffffff"), k.Title, k.SubTitle, k.Description);
536 // k_index++;
537 // }
538 // Debugger.Break();
539 // }
540 // }
541 // else
542 // {
543 // xmltv_entry = query.FirstOrDefault();
544 // }
545 // if (xmltv_entry == null)
546 // {
547 // //gLog.Verbose.Warn.WriteLine("Invalidating GB-PVR Program: oid='{0}' channel_oid='{1}' title='{2}' start='{3}'", program.oid, program.channel_oid, program.name, program.start_time.ToDateTimeString());
548 // source_invalid.Add(program);
549 // }
550 // else
551 // {
552 // //gLog.Verbose.Warn.WriteLine("Updating GB-PVR Program (if needed): oid='{0}' channel_oid='{1}' title='{2}' subtitle='{3}' start='{4}'", program.oid, program.channel_oid, program.name, program.sub_title, program.start_time.ToDateTimeString());
553 // var updated_program = program;
554 // bool needsupdate = false;
555 // if (xmltv_entry.Title != program.name)
556 // {
557 // //gLog.Verbose.Warn.WriteLine(" Updating:");
558 // //gLog.Verbose.Warn.WriteLine(" Old Title: {0}", program.name);
559 // //gLog.Verbose.Warn.WriteLine(" New Title: {0}", xmltv_entry.Title);
560 // updated_program.name = xmltv_entry.Title;
561 // needsupdate = true;
562 // }
563 // if (xmltv_entry.SubTitle != program.sub_title)
564 // {
565 // //gLog.Verbose.Warn.WriteLine(" Updating:");
566 // //gLog.Verbose.Warn.WriteLine(" Old SubTile: {0}", program.sub_title);
567 // //gLog.Verbose.Warn.WriteLine(" New SubTile: {0}", xmltv_entry.SubTitle);
568 // updated_program.sub_title = xmltv_entry.SubTitle;
569 // needsupdate = true;
570 // }
571 // if (xmltv_entry.Description != program.description)
572 // {
573 // //gLog.Verbose.Warn.WriteLine(" Updating:");
574 // //gLog.Verbose.Warn.WriteLine(" Old Descption: {0}", program.description);
575 // //gLog.Verbose.Warn.WriteLine(" New Descption: {0}", xmltv_entry.Description);
576 // updated_program.description = xmltv_entry.Description;
577 // needsupdate = true;
578 // }
579 // if (DateTime.Parse(xmltv_entry.Start) != program.start_time)
580 // {
581 // //gLog.Verbose.Warn.WriteLine(" Updating:");
582 // //gLog.Verbose.Warn.WriteLine(" Old StartTime: {0}", program.start_time.ToDateTimeString());
583 // //gLog.Verbose.Warn.WriteLine(" New StartTime: {0}", DateTime.Parse(xmltv_entry.Start).ToDateTimeString());
584 // updated_program.start_time = DateTime.Parse(xmltv_entry.Start);
585 // needsupdate = true;
586 // }
587 // if (DateTime.Parse(xmltv_entry.Stop) != program.end_time)
588 // {
589 // //gLog.Verbose.Warn.WriteLine(" Updating:");
590 // //gLog.Verbose.Warn.WriteLine(" Old EndTime: {0}", program.end_time.ToDateTimeString());
591 // //gLog.Verbose.Warn.WriteLine(" New EndTime: {0}", DateTime.Parse(xmltv_entry.Stop).ToDateTimeString());
592 // updated_program.end_time = DateTime.Parse(xmltv_entry.Stop);
593 // needsupdate = true;
594 // }
595 // if (needsupdate)
596 // {
597 // OldNewProgram p = new OldNewProgram();
598 // p.OldProgram = program;
599 // p.NewProgram = updated_program;
600 // source_update.Add(p);
601 // }
602 // source_valid.Add(updated_program);
603 // }
604 // index++;
605 //}
606 //source_valid = source_valid.OrderBy(s => s.channel_oid).ThenBy(s => s.start_time).ToList();
607 //source_invalid = source_invalid.OrderBy(s => s.channel_oid).ThenBy(s => s.start_time).ToList();
608 //if (source_invalid.Count > 0)
609 //{
610 // double source_invalid_count = source_valid.Count;
611 // double source_invalid_index = 0;
612 // double source_invalid_progress = 0;
613 // foreach (var old_program in source_invalid)
614 // {
615 // source_invalid_progress = 100.0 * (source_invalid_index / source_invalid_count);
616 // gLog.ReportProgress(this, new ReportProgressEventArgs((int)source_invalid_progress, string.Format("Removing old GBPVR Programs: {0:00}%", (int)source_invalid_progress)));
617 // // remove database entry
618 // if (!RemoveProgramDatabaseEntry(old_program))
619 // {
620 // gLog.Error.WriteLine("Failed to remove program with oid: '{0}'", old_program.oid);
621 // }
622 // else
623 // {
624 // gLog.Verbose.Info.WriteLine("Removed program with oid: '{0}'", old_program.oid);
625 // }
626 // source_invalid_index++;
627 // }
628 //}
629 //else
630 //{
631 // gLog.Info.WriteLine("No old GB-PVR Programs needed to be removed.");
632 //}
633 //if (source_update.Count > 0)
634 //{
635 // double source_update_count = source_valid.Count;
636 // double source_update_index = 0;
637 // double source_update_progress = 0;
638 // foreach (var p in source_update)
639 // {
640 // source_update_progress = 100.0 * (source_update_index / source_update_count);
641 // gLog.ReportProgress(this, new ReportProgressEventArgs((int)source_update_progress, string.Format("Updating GBPVR Programs: {0:00}%", (int)source_update_progress)));
642 // // remove database entry
643 // if (!UpdateProgramDatabaseEntry(p.OldProgram,p.NewProgram))
644 // {
645 // gLog.Error.WriteLine("Failed to update program with oid: '{0}'", p.OldProgram.oid);
646 // }
647 // else
648 // {
649 // gLog.Verbose.Info.WriteLine("Upated program with oid: '{0}'", p.OldProgram.oid);
650 // }
651 // source_update_index++;
652 // }
653 //}
654 //else
655 //{
656 // gLog.Info.WriteLine("No GB-PVR Programs needed to be updated.");
657 //}
658 //gLog.Info.WriteLine("Total XMLTV Programs: 0x{0:x8}", xmltv_programs.Count);
659 //gLog.Info.WriteLine("Updated: 0x{0:x8} GB-PVR Programs", source_valid.Count);
660 //gLog.Info.WriteLine("Removed: 0x{0:x8} GB-PVR Programs", source_invalid.Count);
661 //gLog.Info.WriteLine("Total GB-PVR Programs (Updated & Removed): 0x{0:x8}", source_valid.Count + source_invalid.Count);
662 #endregion
663
664 return source_valid;
665 }
666 #endregion
667
668
669 private string CreateConnectionString()
670 {
671 string connection_string = string.Format("Data Source={0}", this.Database);
672 return connection_string;
673 }
674
675 private SQLiteConnection CreateConnection() { SQLiteConnection connection = new SQLiteConnection(CreateConnectionString()); return connection; }
676
677 [Conditional("SQLLITE_CONNECTION_TEST")]
678 private void ConnectionTest()
679 {
680 try
681 {
682 using (SQLiteConnection con = CreateConnection())
683 {
684 con.Open();
685 string command_text = string.Format("select * from {0};", TABLES.CHANNEL);
686 gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
687 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
688 {
689 using (SQLiteDataReader r = cmd.ExecuteReader())
690 {
691 if (!r.HasRows)
692 {
693 gLog.Warn.WriteLine("Query: '{0}' returned no rows.", cmd.CommandText);
694 }
695 else
696 {
697 while (r.Read())
698 {
699 for (int i = 0; i < r.FieldCount; i++)
700 {
701 string field_name = r.GetName(i);
702 Type field_type = r.GetFieldType(i);
703 object field_value = r.GetValue(i);
704 gLog.Verbose.Debug.WriteLine("Name: '{0}' Type: '{1}' Value: '{2}'", field_name, field_type.Name, field_value == null ? "null" : field_value.ToString());
705 }
706 break;
707 }
708 }
709 }
710 }
711 con.Clone();
712 }
713 OnCreatedInstance(this, new EventArgs());
714 }
715 catch (Exception ex)
716 {
717 gLog.Error.WriteLine(ex.ToString());
718 }
719 }
720
721
722 private bool CreateDatabaseBackup()
723 {
724 try
725 {
726 string backup_file = string.Format("{0}.{1}", this.Database, DateTime.Now.ToString("yyyyMMddHHmmss"));
727 gLog.Info.WriteLine("Creating Database backup...");
728 gLog.Info.WriteLine("\tSource: {0}", this.Database);
729 gLog.Info.WriteLine("\tDestination: {0}", backup_file);
730
731 System.IO.File.Copy(this.Database, backup_file);
732 DATABASE_BACKUP_FILE = backup_file;
733 return true;
734 }
735 catch (Exception ex)
736 {
737 gLog.Error.WriteLine(ex.ToString());
738 return false;
739 }
740 }
741 private void ReadChannelData()
742 {
743 try
744 {
745 List<ICHANNEL> channels = new List<ICHANNEL>();
746 using (SQLiteConnection con = CreateConnection())
747 {
748 try
749 {
750 con.Open();
751 string command_text = string.Format("select * from {0};", TABLES.CHANNEL);
752 gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
753 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
754 {
755 using (SQLiteDataReader r = cmd.ExecuteReader())
756 {
757 if (!r.HasRows)
758 {
759 gLog.Warn.WriteLine("Query: '{0}' returned no rows.", cmd.CommandText);
760 }
761 else
762 {
763 while (r.Read())
764 {
765 CHANNEL channel = new CHANNEL();
766 for (int i = 0; i < r.FieldCount; i++)
767 {
768 CHANNEL.Create(ref channel, r, i);
769 }
770 channels.Add(channel);
771 }
772 }
773 }
774 }
775 }
776 catch (SQLiteException ex)
777 {
778 gLog.Error.WriteLine(ex.ToString());
779 }
780 finally
781 {
782 con.Close();
783 }
784 }
785 this.Channels = channels;
786 }
787 catch (Exception ex)
788 {
789 gLog.Error.WriteLine(ex.ToString());
790 }
791 }
792 private void ReadProgrammeData()
793 {
794 try
795 {
796 List<IPROGRAMME> programs = new List<IPROGRAMME>();
797 using (SQLiteConnection con = CreateConnection())
798 {
799 try
800 {
801 con.Open();
802 string command_text = string.Format("select * from {0};", TABLES.PROGRAMME);
803 gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
804 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
805 {
806 using (SQLiteDataReader r = cmd.ExecuteReader())
807 {
808 if (!r.HasRows)
809 {
810 gLog.Warn.WriteLine("Query: '{0}' returned no rows.", cmd.CommandText);
811 }
812 else
813 {
814 while (r.Read())
815 {
816 PROGRAMME program = new PROGRAMME();
817 for (int i = 0; i < r.FieldCount; i++)
818 {
819 PROGRAMME.Create(ref program, r, i);
820 }
821 programs.Add(program);
822 }
823 }
824 }
825 }
826 }
827 catch (SQLiteException ex)
828 {
829 gLog.Error.WriteLine(ex.ToString());
830 }
831 finally
832 {
833 con.Close();
834 }
835 }
836 this.Programs = programs;
837 }
838 catch (Exception ex)
839 {
840 gLog.Error.WriteLine(ex.ToString());
841 }
842 }
843 private void ReadRecodringScheduleData()
844 {
845 try
846 {
847 List<IRECORDING_SCHEDULE> recordings = new List<IRECORDING_SCHEDULE>();
848 using (SQLiteConnection con = CreateConnection())
849 {
850 try
851 {
852 con.Open();
853 string command_text = string.Format("select * from {0};", TABLES.RECORDING_SCHEDULE);
854 gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
855 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
856 {
857 using (SQLiteDataReader r = cmd.ExecuteReader())
858 {
859 if (!r.HasRows)
860 {
861 gLog.Warn.WriteLine("Query: '{0}' returned no rows.", cmd.CommandText);
862 }
863 else
864 {
865 while (r.Read())
866 {
867 RECORDING_SCHEDULE recording = new RECORDING_SCHEDULE();
868 for (int i = 0; i < r.FieldCount; i++)
869 {
870 RECORDING_SCHEDULE.Create(ref recording, r, i);
871 }
872 recordings.Add(recording);
873 }
874 }
875 }
876 }
877 }
878 catch (SQLiteException ex)
879 {
880 gLog.Error.WriteLine(ex.ToString());
881 }
882 finally
883 {
884 con.Close();
885 }
886 }
887 this.Recordings = recordings;
888 }
889 catch (Exception ex)
890 {
891 gLog.Error.WriteLine(ex.ToString());
892 }
893 }
894
895 public void RemoveOldGBPVRPrograms(List<SQLLITE.IPROGRAMME> programs)
896 {
897 gLog.Info.WriteLine("Removing {0} gbpvr programs.", programs.Count);
898 int ChunkSize = 1024;
899 var ChunkList = programs.Chunk<IPROGRAMME>(ChunkSize);
900 double total = programs.Count;
901 double index = 0;
902 double progress = 0;
903 Stopwatch st1 = new Stopwatch();
904 st1.Start();
905 foreach (var p in ChunkList)
906 {
907 progress = 100.0 * (index / total);
908 if (!RemoveProgramDatabaseEntry(p))
909 {
910 gLog.Error.WriteLine("Failed to remove one or more program(s)");
911 }
912 gLog.ReportProgress(this, new ReportProgressEventArgs((int)progress, string.Format("Removing old gbpvr programs ({0} of {1}) {2:00}%", index, total, (int)progress)));
913 index += (double)p.Count();
914 }
915 gLog.ReportProgress(this, new ReportProgressEventArgs((int)progress, string.Format("Removing old gbpvr programs ({0} of {1}) {2:00}%", index, total, (int)progress)));
916 st1.Stop();
917 gLog.Warn.WriteLine(" operation took: {0:0.00000} seconds overall", st1.Elapsed.TotalSeconds);
918 }
919 public void UpdateGBPVRPrograms(List<IOldNewProgram> programs)
920 {
921 gLog.Info.WriteLine("Updating {0} gbpvr programs.", programs.Count);
922 int ChunkSize = 4096;
923 var ChunkList = programs.Chunk<IOldNewProgram>(ChunkSize);
924
925 double total = programs.Count;
926 double index = 0;
927 double progress = 0;
928 Stopwatch st1 = new Stopwatch();
929 st1.Start();
930 foreach (var p in ChunkList)
931 {
932 progress = 100.0 * (index / total);
933 if (!UpdateProgramEntryDatabase(p))
934 {
935 gLog.Error.WriteLine("Failed to update one or more program(s)");
936 }
937 gLog.ReportProgress(this, new ReportProgressEventArgs((int)progress, string.Format("Updating gbpvr programs ({0} of {1}) {2:00}%", index, total, (int)progress)));
938 index += (double)p.Count();
939 }
940 gLog.ReportProgress(this, new ReportProgressEventArgs((int)progress, string.Format("Updating gbpvr programs ({0} of {1}) {2:00}%", index, total, (int)progress)));
941 st1.Stop();
942 gLog.Warn.WriteLine(" operation took: {0:0.00000} seconds overall", st1.Elapsed.TotalSeconds);
943 }
944
945 private bool RemoveAllProgramDatabaseEntries()
946 {
947 bool result = false;
948 try
949 {
950 using (SQLiteConnection con = CreateConnection())
951 {
952 try
953 {
954 //gLog.Verbose.Info.WriteLine("Removing old program with oid: '{0}'", old_program.oid);
955 con.Open();
956 string command_text = string.Format(@"DELETE FROM [{0}];", TABLES.PROGRAMME);
957 //gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
958 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
959 {
960 //cmd.Parameters.Add(new SQLiteParameter("oid", old_program.oid));
961 int rowsupdated = cmd.ExecuteNonQuery();
962 //gLog.Verbose.Info.WriteLine("Updated '{0}' rows", rowsupdated);
963 }
964 result = true;
965 }
966 catch (SQLiteException ex)
967 {
968 gLog.Error.WriteLine(ex.ToString());
969 result = false;
970 }
971 finally
972 {
973 con.Close();
974 }
975 }
976 }
977 catch (Exception ex)
978 {
979 gLog.Error.WriteLine(ex.ToString());
980 result = false;
981 }
982 return result;
983 }
984 private bool RemoveProgramDatabaseEntry(IEnumerable<IPROGRAMME> list)
985 {
986 bool result = false;
987 try
988 {
989 using (SQLiteConnection con = CreateConnection())
990 {
991 try
992 {
993 //gLog.Verbose.Info.WriteLine("Updating old program with oid: '{0}'", new_program.oid);
994 con.Open();
995 //string command_text = string.Format(@"UPDATE [{0}] SET [name]=@name,[sub_title]=@subtitle, WHERE [OID] = @oid", TABLES.PROGRAMME);
996 string command_text = string.Empty;
997 command_text = BuildGBPVRMultiDeleteCommand(list);
998 //gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
999 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
1000 {
1001 int rowsupdated = cmd.ExecuteNonQuery();
1002 //gLog.Verbose.Info.WriteLine("Updated '{0}' rows", rowsupdated);
1003 }
1004
1005 result = true;
1006 }
1007 catch (SQLiteException ex)
1008 {
1009 gLog.Error.WriteLine(ex.ToString());
1010 result = false;
1011 }
1012 finally
1013 {
1014 con.Close();
1015 }
1016 }
1017 }
1018 catch (Exception ex)
1019 {
1020 gLog.Error.WriteLine(ex.ToString());
1021 result = false;
1022 }
1023 return result;
1024 }
1025 private bool UpdateProgramEntryDatabase(IEnumerable<IOldNewProgram> list)
1026 {
1027 bool result = false;
1028 try
1029 {
1030 using (SQLiteConnection con = CreateConnection())
1031 {
1032 try
1033 {
1034 //gLog.Verbose.Info.WriteLine("Updating old program with oid: '{0}'", new_program.oid);
1035 con.Open();
1036 //string command_text = string.Format(@"UPDATE [{0}] SET [name]=@name,[sub_title]=@subtitle, WHERE [OID] = @oid", TABLES.PROGRAMME);
1037 string command_text = string.Empty;
1038 command_text = BuildGBPVRMultiUpdateCommand(list);
1039 //gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
1040 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
1041 {
1042 int rowsupdated = cmd.ExecuteNonQuery();
1043 //gLog.Verbose.Info.WriteLine("Updated '{0}' rows", rowsupdated);
1044 }
1045
1046 result = true;
1047 }
1048 catch (SQLiteException ex)
1049 {
1050 gLog.Error.WriteLine(ex.ToString());
1051 result = false;
1052 }
1053 finally
1054 {
1055 con.Close();
1056 }
1057 }
1058 }
1059 catch (Exception ex)
1060 {
1061 gLog.Error.WriteLine(ex.ToString());
1062 result = false;
1063 }
1064 return result;
1065 }
1066 private bool InsertProgramEntryDatabase(IEnumerable<IPROGRAMME> list)
1067 {
1068 bool result = false;
1069 try
1070 {
1071 using (SQLiteConnection con = CreateConnection())
1072 {
1073 try
1074 {
1075 //gLog.Verbose.Info.WriteLine("Updating old program with oid: '{0}'", new_program.oid);
1076 con.Open();
1077 //string command_text = string.Format(@"UPDATE [{0}] SET [name]=@name,[sub_title]=@subtitle, WHERE [OID] = @oid", TABLES.PROGRAMME);
1078 string command_text = string.Empty;
1079 command_text = BuildGBPVRMultiInsertCommand(list);
1080 //gLog.Verbose.Debug.WriteLine("Executing Command: '{0}'", command_text);
1081 using (SQLiteCommand cmd = new SQLiteCommand(command_text, con))
1082 {
1083 int rowsupdated = cmd.ExecuteNonQuery();
1084 //gLog.Verbose.Info.WriteLine("Updated '{0}' rows", rowsupdated);
1085 }
1086
1087 result = true;
1088 }
1089 catch (SQLiteException ex)
1090 {
1091 gLog.Error.WriteLine(ex.ToString());
1092 result = false;
1093 }
1094 finally
1095 {
1096 con.Close();
1097 }
1098 }
1099 }
1100 catch (Exception ex)
1101 {
1102 gLog.Error.WriteLine(ex.ToString());
1103 result = false;
1104 }
1105 return result;
1106 }
1107
1108 #region Multi-Delete Command Support
1109 private string BuildGBPVRMultiDeleteCommand(IEnumerable<IPROGRAMME> list)
1110 {
1111 StringBuilder builder = new StringBuilder();
1112 /*
1113 insert into table1 (field1,field2) values (value1,value2);
1114 insert into table1 (field1,field2) values (value1,value2);
1115 insert into table1 (field1,field2) values (value1,value2);
1116 insert into table1 (field1,field2) values (value1,value2)
1117 */
1118 builder.AppendLine("begin transaction;");
1119 foreach (var t in list)
1120 {
1121 builder.AppendLine(BuildGBPVRSingleDeleteCommand(t));
1122 }
1123 builder.AppendLine("end transaction;");
1124 return builder.ToString();
1125 }
1126 private string BuildGBPVRSingleDeleteCommand(IPROGRAMME program)
1127 {
1128 StringBuilder builder = new StringBuilder();
1129 builder.AppendFormat("delete from {0} where oid={1};", TABLES.PROGRAMME, program.oid);
1130 return builder.ToString();
1131 }
1132 #endregion
1133 #region Multi-Update Command Support
1134 private string BuildGBPVRMultiUpdateCommand(IEnumerable<IOldNewProgram> list)
1135 {
1136 StringBuilder builder = new StringBuilder();
1137 /*
1138 insert into table1 (field1,field2) values (value1,value2);
1139 insert into table1 (field1,field2) values (value1,value2);
1140 insert into table1 (field1,field2) values (value1,value2);
1141 insert into table1 (field1,field2) values (value1,value2)
1142 */
1143 builder.AppendLine("begin transaction;");
1144 foreach (var t in list)
1145 {
1146 if (!t.OldProgram.Equals(t.NewProgram))
1147 {
1148 // only update the entry if it is different
1149 builder.AppendLine(BuildGBPVRSingleUpdateCommand(t.NewProgram));
1150 }
1151 }
1152 builder.AppendLine("end transaction;");
1153 return builder.ToString();
1154 }
1155 private string BuildGBPVRSingleUpdateCommand(IPROGRAMME program)
1156 {
1157 StringBuilder builder = new StringBuilder();
1158 builder.AppendFormat("update {0} SET ", TABLES.PROGRAMME);
1159 builder.AppendFormat("name=\"{0}\", ", program.name);
1160 builder.AppendFormat("sub_title=\"{0}\", ", program.sub_title);
1161 builder.AppendFormat("description=\"{0}\", ", program.description);
1162 builder.AppendFormat("start_time='{0}', ", program.start_time.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
1163 builder.AppendFormat("end_time='{0}', ", program.end_time.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
1164 builder.AppendFormat("channel_oid={0}, ", program.channel_oid);
1165 builder.AppendFormat("unique_identifier=\"{0}\", ", program.unique_identifier);
1166 builder.AppendFormat("rating=\"{0}\" ", program.rating);
1167 builder.AppendFormat("where oid={0};", program.oid);
1168 return builder.ToString();
1169 }
1170 #endregion
1171 #region Multi-Insert Command Support
1172 private string BuildGBPVRMultiInsertCommand(IEnumerable<IPROGRAMME> list)
1173 {
1174 StringBuilder builder = new StringBuilder();
1175 /*
1176 insert into table1 (field1,field2) values (value1,value2);
1177 insert into table1 (field1,field2) values (value1,value2);
1178 insert into table1 (field1,field2) values (value1,value2);
1179 insert into table1 (field1,field2) values (value1,value2)
1180 */
1181 builder.AppendLine("begin transaction;");
1182 foreach (var t in list)
1183 {
1184 builder.AppendLine(BuildGBPVRSingleInsertCommand(t));
1185 }
1186 builder.AppendLine("end transaction;");
1187 return builder.ToString();
1188 }
1189
1190 private string BuildGBPVRSingleInsertCommand(IPROGRAMME program)
1191 {
1192 StringBuilder builder = new StringBuilder();
1193 builder.AppendFormat("insert into {0} (oid,name,sub_title,description,start_time,end_time,channel_oid,unique_identifier,rating) values (", TABLES.PROGRAMME);
1194 builder.AppendFormat("{0},",program.oid);
1195 builder.AppendFormat("\"{0}\",", program.name);
1196 builder.AppendFormat("\"{0}\",", program.sub_title);
1197 builder.AppendFormat("\"{0}\",", program.description);
1198 builder.AppendFormat("'{0}',", program.start_time.ToString("yyyy/MM/dd HH:mm:ss.fffffff"));
1199 builder.AppendFormat("'{0}',", program.end_time.ToString("yyyy/MM/dd HH:mm:ss.fffffff"));
1200 builder.AppendFormat("{0},", program.channel_oid);
1201 builder.AppendFormat("\"{0}\",", program.unique_identifier);
1202 builder.AppendFormat("\"{0}\");", program.rating);
1203 return builder.ToString();
1204 }
1205 #endregion
1206
1207 }
1208 }

  ViewVC Help
Powered by ViewVC 1.1.22