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

  ViewVC Help
Powered by ViewVC 1.1.22