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

Diff of /trunk/GBPVRProgramDatabaseFixer/Program.cs

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 154 by william, Thu Mar 14 16:56:05 2013 UTC revision 241 by william, Sun Mar 17 10:40:09 2013 UTC
# Line 2  Line 2 
2  using System;  using System;
3  using System.Collections.Generic;  using System.Collections.Generic;
4  using System.Text;  using System.Text;
5    using System.Linq;
6  using Enterprise.Logging;  using Enterprise.Logging;
7  using System.Windows.Forms;  using System.Windows.Forms;
8  using System.Diagnostics;  using System.Diagnostics;
9  using System.IO;  using System.IO;
10  using libxmltv.Core;  using libxmltv.Core;
11    using libxmltv.Interfaces;
12    using libxmltv;
13    using GBPVR.Public;
14    using GBPVR.Backend.Common;
15  namespace GBPVRProgramDatabaseFixer  namespace GBPVRProgramDatabaseFixer
16  {  {
17      class Program      class Program
18      {      {
19            const long MAX_LOG_FILESIZE_IN_BYTES = 250000; //250kb max
20            static void TruncateLogFile(FileInfo log_file)
21            {
22                if (!log_file.Exists)
23                {
24                    gLog.CreateLog(log_file.FullName, false, LogLevel.kLogLevel_All);
25                }
26                else
27                {
28                    if (log_file.Length > MAX_LOG_FILESIZE_IN_BYTES)
29                    {
30                        string match = string.Format("{0}.*", log_file.Name);
31                        var files = Directory.GetFiles(log_file.Directory.FullName, match).ToList();
32                        files.RemoveAt(0);
33                        files.TrimExcess();
34                        int count = files.Count;
35                        if (log_file.Exists)
36                        {
37                            File.Copy(log_file.FullName, string.Format("{0}.{1}", log_file.FullName, count));
38                        }
39                        gLog.CreateLog(log_file.FullName, true, LogLevel.kLogLevel_All);
40                    }
41                    else
42                    {
43                        gLog.CreateLog(log_file.FullName, false, LogLevel.kLogLevel_All);
44                    }
45                }
46            }
47    
48            static ISQLLITE sqlite;
49          static string XMLTV_FILE = "";          static string XMLTV_FILE = "";
50          static string GBPVR_DATABASE = "";          static string GBPVR_DATABASE = "";
51    
52            //static bool LOADING_XMLTV_FILE = false;
53          static bool XMLTV_INSTANCE_CREATED = false;          static bool XMLTV_INSTANCE_CREATED = false;
54            //static int LAST_REPORTED_XMLTV_PROGRESS = 0;
55    
         static int LAST_REPORTED_XMLTV_PROGRESS =0;  
56    
57          static FileInfo fi_XMLTVFILE;          //static bool LOADING_GBPVR_DATABASE = false;
58            static bool SQLLIST_INSTANCE_CREATED = false;
59            //static int LAST_REPORTED_SQLLITE_PROGRESS = 0;
60    
61            //static int LAST_REPORTED_PROGRESS = 0;
62    
63            static FileInfo fi_XMLTVFILE;
64            static FileInfo fi_GBPVRDATABASE;
65          static void CreateLog()          static void CreateLog()
66          {          {
67              string log_path = Application.StartupPath;              string log_path = Application.StartupPath;
68              string log_filename = string.Format("{0}.log", typeof(Program).Assembly.GetName().Name);              string log_filename = string.Format("{0}.log", typeof(Program).Assembly.GetName().Name);
69              gLog.CreateLog(string.Format(@"{0}\{1}", log_path, log_filename), false, LogLevel.kLogLevel_All);              FileInfo log_file = new FileInfo(string.Format(@"{0}\{1}", log_path, log_filename));
70                TruncateLogFile(log_file);
71  #if DEBUG  #if DEBUG
72              LogLevel gLevel = gLog.LogLevel;              LogLevel gLevel = gLog.LogLevel;
73              gLevel |= LogLevel.kLogLevel_VerboseDebug;              gLevel |= LogLevel.kLogLevel_VerboseDebug;
# Line 78  namespace GBPVRProgramDatabaseFixer Line 121  namespace GBPVRProgramDatabaseFixer
121              }              }
122    
123              LoadXMLTVFile();              LoadXMLTVFile();
124                LoadGBPVRDatabase();
125                PerformDatabaseProcessing();
126          }          }
127    
128          static void gLog_ReportProgress(object sender, ReportProgressEventArgs e)          static void ConsoleOverwritePreviosLine(string format, params object[] args)
129          {          {
130              if (LAST_REPORTED_XMLTV_PROGRESS != e.Progress)              Console.WriteLine(format,args);
131                Console.SetCursorPosition(0, Console.CursorTop - 1);
132            }
133    
134            static void gLog_ReportProgress(object sender, ReportProgressEventArgs e)
135            {
136                object k = e.UserState; // we will assum that is a status message
137                if (k == null) // assume we do not have a user status message (ie: is only a progress message)
138                {
139                    if (sender == null) { ConsoleOverwritePreviosLine("Progress: {0} ", e.Progress); }
140                    else { ConsoleOverwritePreviosLine("{0}: Progress: {1:00}%", sender.GetType().Name, e.Progress); }
141                }
142                else // assume we have a user status message
143              {              {
144                  Console.WriteLine("XMLTV: {0} Loading: {1:00}%", fi_XMLTVFILE.Name, e.Progress);                  if (sender == null) { ConsoleOverwritePreviosLine("{0} ", k.ToString()); }
145                  LAST_REPORTED_XMLTV_PROGRESS = e.Progress;                  else { ConsoleOverwritePreviosLine("{0}: {1}", sender.GetType().Name, k.ToString()); }
146              }              }
147          }          }
148          static void LoadXMLTVFile()          static void LoadXMLTVFile()
149          {          {
150                //LOADING_XMLTV_FILE = true;
151              if (string.IsNullOrEmpty(XMLTV_FILE))              if (string.IsNullOrEmpty(XMLTV_FILE))
152              {              {
153                  gLog.Error.WriteLine("XMLTV File is either a null or empty string.");                  gLog.Error.WriteLine("XMLTV File is either a null or empty string.");
154                    //LOADING_XMLTV_FILE = false;
155                  return;                  return;
156              }              }
157              fi_XMLTVFILE = new FileInfo(XMLTV_FILE);              fi_XMLTVFILE = new FileInfo(XMLTV_FILE);
158              if (!fi_XMLTVFILE.Exists)              if (!fi_XMLTVFILE.Exists)
159              {              {
160                  gLog.Error.WriteLine("Could not find XMLTV File: {0}", fi_XMLTVFILE.FullName);                  gLog.Error.WriteLine("Could not find XMLTV File: {0}", fi_XMLTVFILE.FullName);
161                    //LOADING_XMLTV_FILE = false;
162                  return;                  return;
163              }              }
164    
165              XMLTV.Create(fi_XMLTVFILE.FullName, new EventHandler<EventArgs>(XMLTV_OnInstanceCreated));              XMLTV.Create(fi_XMLTVFILE.FullName, new EventHandler<EventArgs>(XMLTV_OnInstanceCreated));
166              while (!XMLTV_INSTANCE_CREATED) { Application.DoEvents(); }              while (!XMLTV_INSTANCE_CREATED) { Application.DoEvents(); }
167                //LOADING_XMLTV_FILE = false;
168          }          }
   
169          static void XMLTV_OnInstanceCreated(object sender, EventArgs e) { XMLTV_INSTANCE_CREATED = true; }          static void XMLTV_OnInstanceCreated(object sender, EventArgs e) { XMLTV_INSTANCE_CREATED = true; }
170    
171            static void LoadGBPVRDatabase()
172            {
173                //LOADING_GBPVR_DATABASE = true;
174                if (string.IsNullOrEmpty(GBPVR_DATABASE))
175                {
176                    gLog.Error.WriteLine("GBPVR Datbase is either a null or empty string.");
177                    //LOADING_GBPVR_DATABASE = false;
178                    return;
179                }
180                fi_GBPVRDATABASE = new FileInfo(GBPVR_DATABASE);
181                if (!fi_GBPVRDATABASE.Exists)
182                {
183                    gLog.Error.WriteLine("Could not find GBPVR Database: {0}", fi_GBPVRDATABASE.FullName);
184                    //LOADING_GBPVR_DATABASE = false;
185                    return;
186                }
187                sqlite = SQLLITE.Create(fi_GBPVRDATABASE.FullName, new EventHandler<EventArgs>(SQLLITE_OnInstanceCreated));
188                while (!SQLLIST_INSTANCE_CREATED) { Application.DoEvents(); }
189                //LOADING_GBPVR_DATABASE = false;
190            }
191            static void SQLLITE_OnInstanceCreated(object sender, EventArgs e) { SQLLIST_INSTANCE_CREATED = true; }
192    
193            static void PerformDatabaseProcessing()
194            {
195                var sqllite_channels = sqlite.Channels;
196                var sqllite_recordings = sqlite.Recordings;
197                var sqllite_programs = sqlite.Programs;
198                Type datatype;
199                var xmlt_raw_program_data = (IProgramDefinitionList)XMLTV.CreateBindingSourceFromData(XMLTV.GetPrograms(), out datatype);
200                var xmltv_programs = xmlt_raw_program_data.ToList().OrderBy(p => DateTime.Parse(p.Start)).ToList();
201                var sqllite_programs_startdate_range = sqlite.GetProgramsDateRange(sqllite_programs);
202                var xmltv_programs_startdate_range = GetXMLTVProgramStartDateRange(xmltv_programs);
203                var gbpvr_invalid_programs = new List<SQLLITE.IPROGRAMME>();
204                var gbpvr_valid_programs = sqlite.FixGBPVRProgramsDatabase(sqllite_programs, xmltv_programs, out gbpvr_invalid_programs);    
205                sqlite.RemoveOldGBPVRPrograms(gbpvr_invalid_programs);
206                sqlite.UpdateGBPVRPrograms(gbpvr_valid_programs);
207    
208                sqllite_programs.Clear();
209                gbpvr_valid_programs.ForEach(s=>sqllite_programs.Add(s.NewProgram));
210    
211                CheckScheduledRecordingsForDiscrepancies(sqllite_recordings,sqllite_programs);
212            }
213    
214            static IDateTimeRange GetXMLTVProgramStartDateRange(List<libxmltv.Interfaces.IProgramDefinition> programs)
215            {
216                IDateTimeRange range = DateTimeRange.Create();
217                var list = new List<libxmltv.Interfaces.IProgramDefinition>(programs.ToArray());
218                DateTime first = new DateTime();
219                DateTime last = new DateTime();
220                first = DateTime.Parse(list.OrderBy(s => DateTime.Parse(s.Start)).ToList().First().Start);
221                last = DateTime.Parse(list.OrderBy(s => DateTime.Parse(s.Start)).ToList().Last().Start);
222                gLog.Verbose.Debug.WriteLine("\tFirst: {0} = ({1})", first.ToString("yyyy/MM/dd HH:mm:ss.fffffff"), first.ToDateTimeString());
223                gLog.Verbose.Debug.WriteLine("\tLast: {0} = ({1})", last.ToString("yyyy/MM/dd HH:mm:ss.fffffff"), last.ToDateTimeString());
224                range = DateTimeRange.Create(first, last);
225                return range;
226            }
227    
228            static void CheckScheduledRecordingsForDiscrepancies(List<SQLLITE.IRECORDING_SCHEDULE> recordings, List<SQLLITE.IPROGRAMME> programs)
229            {
230                List<SQLLITE.IRECORDING_SCHEDULE> recordings_to_delete = new List<SQLLITE.IRECORDING_SCHEDULE>();
231                //List<SQLLITE.IRECORDING_SCHEDULE> deleted_recordings = new List<SQLLITE.IRECORDING_SCHEDULE>();
232                //List<SQLLITE.IRECORDING_SCHEDULE> reocurring_recordings = new List<SQLLITE.IRECORDING_SCHEDULE>();
233    
234    
235                //reocurring_recordings = recordings.FindAll(s => s.recording_type != (long)RecordingType.TYPE_RECORD_ONCE).ToList();
236    
237                foreach (var recording in recordings)
238                {
239                    RecordingStatus status = (RecordingStatus)recording.status;
240                    RecordingType type = (RecordingType)recording.recording_type;
241                    if (type == RecordingType.TYPE_RECORD_SEASON)
242                    {
243                        continue; // ignore TYPE_RECORD_SEASON
244                    }
245                    if (status != RecordingStatus.STATUS_PENDING)
246                    {
247                        continue; // ignore any status except STATUS_PENDING
248                    }
249                    if (recording.recording_group == 0 && recording.programme_oid == 0)
250                    {
251                        continue; // ignore manual recordings
252                    }
253                    // verify data for this recording
254                    var recording_oid = recording.oid;
255                    var programme_oid = recording.programme_oid;
256                    var filename = recording.filename;
257                    var manual_start_time = recording.manual_start_time;
258                    var manual_end_time = recording.manual_end_time;
259                    var manual_channel_oid = recording.manual_channel_oid;
260    
261                    // lookup program by oid
262                    var entry = programs.Find(s => s.oid == programme_oid);
263                    if (entry == null)
264                    {
265                        gLog.Warn.WriteLine("Unable to find program with oid: '{0}' for recording with oid: '{1}' -- assuming it should be deleted", programme_oid, recording_oid);
266                        //throw new NullReferenceException(string.Format("Unable to find program with oid: '{0}' for recording with oid: '{1}'", programme_oid, recording_oid));
267                        //deleted_recordings.Add(recording);
268                    }
269                    else
270                    {
271                        recordings_to_delete.Add(recording);        
272                    }
273                }
274                recordings_to_delete.TrimExcess();
275                if (recordings_to_delete.Count > 0)
276                {
277                    gLog.Info.WriteLine("Found {0} recordings to delete.", recordings_to_delete.Count);
278                    sqlite.DeleteGBPVRScheduledRecordings(recordings_to_delete);
279                }
280    
281                try
282                {
283    
284                    // taken from: Config.EpgUpdateProgress.method_1()
285                    Zap2itEpgReader.smethod_0();
286                    GClass4.smethod_0().method_14();
287    
288                }
289                catch (Exception ex)
290                {
291                    gLog.Error.WriteLine(ex.ToString());
292                }
293            }
294      }      }
295  }  }

Legend:
Removed from v.154  
changed lines
  Added in v.241

  ViewVC Help
Powered by ViewVC 1.1.22