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

Contents of /trunk/GBPVRProgramDatabaseFixer/Program.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 251 - (show annotations) (download)
Sat Mar 30 04:46:15 2013 UTC (6 years, 5 months ago) by william
File size: 13643 byte(s)

1 #define OVERRIDE_COMMANDLINE_ARGUMENTS // when defined will override supplied commandline args
2 //#define ENABLE_SCHEDULDED_RECORDINGS_FIXUP // when defined will enable calls to CheckScheduledRecordingsForDiscrepancies
3
4 using System;
5 using System.Collections.Generic;
6 using System.Text;
7 using System.Linq;
8 using Enterprise.Logging;
9 using System.Windows.Forms;
10 using System.Diagnostics;
11 using System.IO;
12 using libxmltv.Core;
13 using libxmltv.Interfaces;
14 using libxmltv;
15 using GBPVR.Backend.Common;
16 namespace GBPVRProgramDatabaseFixer
17 {
18 class Program
19 {
20 const long MAX_LOG_FILESIZE_IN_BYTES = 250000; //250kb max
21 static void TruncateLogFile(FileInfo log_file)
22 {
23 if (!log_file.Exists)
24 {
25 gLog.CreateLog(log_file.FullName, false, LogLevel.kLogLevel_All);
26 }
27 else
28 {
29 if (log_file.Length > MAX_LOG_FILESIZE_IN_BYTES)
30 {
31 string match = string.Format("{0}.*", log_file.Name);
32 var files = Directory.GetFiles(log_file.Directory.FullName, match).ToList();
33 files.RemoveAt(0);
34 files.TrimExcess();
35 int count = files.Count;
36 if (log_file.Exists)
37 {
38 File.Copy(log_file.FullName, string.Format("{0}.{1}", log_file.FullName, count));
39 }
40 gLog.CreateLog(log_file.FullName, true, LogLevel.kLogLevel_All);
41 }
42 else
43 {
44 gLog.CreateLog(log_file.FullName, false, LogLevel.kLogLevel_All);
45 }
46 }
47 }
48
49 static ISQLLITE sqlite;
50 static string XMLTV_FILE = "";
51 static string GBPVR_DATABASE = "";
52
53 //static bool LOADING_XMLTV_FILE = false;
54 static bool XMLTV_INSTANCE_CREATED = false;
55 //static int LAST_REPORTED_XMLTV_PROGRESS = 0;
56
57
58 //static bool LOADING_GBPVR_DATABASE = false;
59 static bool SQLLIST_INSTANCE_CREATED = false;
60 //static int LAST_REPORTED_SQLLITE_PROGRESS = 0;
61
62 //static int LAST_REPORTED_PROGRESS = 0;
63
64 static FileInfo fi_XMLTVFILE;
65 static FileInfo fi_GBPVRDATABASE;
66 static void CreateLog()
67 {
68 string log_path = Application.StartupPath;
69 string log_filename = string.Format("{0}.log", typeof(Program).Assembly.GetName().Name);
70 FileInfo log_file = new FileInfo(string.Format(@"{0}\{1}", log_path, log_filename));
71 TruncateLogFile(log_file);
72 #if DEBUG
73 LogLevel gLevel = gLog.LogLevel;
74 gLevel |= LogLevel.kLogLevel_VerboseDebug;
75 gLevel |= LogLevel.kLogLevel_Debug;
76 gLog.SetLogLevel(gLevel);
77 #else
78 LogLevel gLevel = LogLevel.kLogLevel_Default; // set the default log level: Info, Warn, Error, Debug
79 // it is OK for kLogLevel_Debug to be set in Release mode ... must of the chatty messages are from kLogLevel_VerboseDebug
80 gLevel &= ~LogLevel.kLogLevel_Debug; // ensure this is not set, ever in release mode
81 gLevel &= ~LogLevel.kLogLevel_VerboseDebug; // ensure this is not set, ever in release mode
82 gLog.SetLogLevel(gLevel);
83 #endif
84 gLog.ReportProgressEvent += new EventHandler<ReportProgressEventArgs>(gLog_ReportProgress);
85 }
86
87 [Conditional("OVERRIDE_COMMANDLINE_ARGUMENTS")]
88 static void CreateDebugCommandlineArgs(ref List<string> cargs)
89 {
90 cargs = new List<string>();
91 cargs.Add(string.Format("--xmltv_file=\"{0}\"", @"c:\EPG Guide\Guide\tvguide.xml"));
92 cargs.Add(string.Format("--gbprv_db=\"{0}\"", @"c:\Program Files (x86)\Devnz\GBPVR\gbpvr.db3"));
93 }
94
95 static List<string> CreateCommandlineArgs(string[] args)
96 {
97 List<string> cargs = new List<string>(args);
98 CreateDebugCommandlineArgs(ref cargs);
99 return cargs;
100 }
101
102 static void Main(string[] args)
103 {
104 CreateLog();
105 var cargs = CreateCommandlineArgs(args);
106 foreach (var carg in cargs)
107 {
108 if (carg.ToLower().Contains("--xmltv_file="))
109 {
110 XMLTV_FILE = carg.Replace("--xmltv_file=", "").Replace("\"","");
111 gLog.Info.WriteLine("XMLTV FILE: '{0}'", XMLTV_FILE);
112 }
113 else if (carg.ToLower().Contains("--gbprv_db="))
114 {
115 GBPVR_DATABASE = carg.Replace("--gbprv_db=", "").Replace("\"", "");
116 gLog.Info.WriteLine("GBPVR DATABASE: '{0}'", GBPVR_DATABASE);
117 }
118 else
119 {
120 gLog.Warn.WriteLine("Unknown commandline option: {0}", carg);
121 }
122 }
123
124 LoadXMLTVFile();
125 LoadGBPVRDatabase();
126 PerformDatabaseProcessing();
127 }
128
129 static void ConsoleOverwritePreviosLine(string format, params object[] args)
130 {
131 Console.WriteLine(format,args);
132 Console.SetCursorPosition(0, Console.CursorTop - 1);
133 }
134
135 static void gLog_ReportProgress(object sender, ReportProgressEventArgs e)
136 {
137 object k = e.UserState; // we will assum that is a status message
138 if (k == null) // assume we do not have a user status message (ie: is only a progress message)
139 {
140 if (sender == null) { ConsoleOverwritePreviosLine("Progress: {0} ", e.Progress); }
141 else { ConsoleOverwritePreviosLine("{0}: Progress: {1:00}%", sender.GetType().Name, e.Progress); }
142 }
143 else // assume we have a user status message
144 {
145 if (sender == null) { ConsoleOverwritePreviosLine("{0} ", k.ToString()); }
146 else { ConsoleOverwritePreviosLine("{0}: {1}", sender.GetType().Name, k.ToString()); }
147 }
148 }
149 static void LoadXMLTVFile()
150 {
151 //LOADING_XMLTV_FILE = true;
152 if (string.IsNullOrEmpty(XMLTV_FILE))
153 {
154 gLog.Error.WriteLine("XMLTV File is either a null or empty string.");
155 //LOADING_XMLTV_FILE = false;
156 return;
157 }
158 fi_XMLTVFILE = new FileInfo(XMLTV_FILE);
159 if (!fi_XMLTVFILE.Exists)
160 {
161 gLog.Error.WriteLine("Could not find XMLTV File: {0}", fi_XMLTVFILE.FullName);
162 //LOADING_XMLTV_FILE = false;
163 return;
164 }
165
166 XMLTV.Create(fi_XMLTVFILE.FullName, new EventHandler<EventArgs>(XMLTV_OnInstanceCreated));
167 while (!XMLTV_INSTANCE_CREATED) { Application.DoEvents(); }
168 //LOADING_XMLTV_FILE = false;
169 }
170 static void XMLTV_OnInstanceCreated(object sender, EventArgs e) { XMLTV_INSTANCE_CREATED = true; }
171
172 static void LoadGBPVRDatabase()
173 {
174 //LOADING_GBPVR_DATABASE = true;
175 if (string.IsNullOrEmpty(GBPVR_DATABASE))
176 {
177 gLog.Error.WriteLine("GBPVR Datbase is either a null or empty string.");
178 //LOADING_GBPVR_DATABASE = false;
179 return;
180 }
181 fi_GBPVRDATABASE = new FileInfo(GBPVR_DATABASE);
182 if (!fi_GBPVRDATABASE.Exists)
183 {
184 gLog.Error.WriteLine("Could not find GBPVR Database: {0}", fi_GBPVRDATABASE.FullName);
185 //LOADING_GBPVR_DATABASE = false;
186 return;
187 }
188 sqlite = SQLLITE.Create(fi_GBPVRDATABASE.FullName, new EventHandler<EventArgs>(SQLLITE_OnInstanceCreated));
189 while (!SQLLIST_INSTANCE_CREATED) { Application.DoEvents(); }
190 //LOADING_GBPVR_DATABASE = false;
191 }
192 static void SQLLITE_OnInstanceCreated(object sender, EventArgs e) { SQLLIST_INSTANCE_CREATED = true; }
193
194 static void PerformDatabaseProcessing()
195 {
196 var sqllite_channels = sqlite.Channels;
197 var sqllite_recordings = sqlite.Recordings;
198 var sqllite_programs = sqlite.Programs;
199 Type datatype;
200 var xmlt_raw_program_data = (IProgramDefinitionList)XMLTV.CreateBindingSourceFromData(XMLTV.GetPrograms(), out datatype);
201 var xmltv_programs = xmlt_raw_program_data.ToList().OrderBy(p => DateTime.Parse(p.Start)).ToList();
202 var sqllite_programs_startdate_range = sqlite.GetProgramsDateRange(sqllite_programs);
203 var xmltv_programs_startdate_range = GetXMLTVProgramStartDateRange(xmltv_programs);
204 var gbpvr_invalid_programs = new List<SQLLITE.IPROGRAMME>();
205 var gbpvr_valid_programs = sqlite.FixGBPVRProgramsDatabase(sqllite_programs, xmltv_programs, out gbpvr_invalid_programs);
206 sqlite.RemoveOldGBPVRPrograms(gbpvr_invalid_programs);
207 sqlite.UpdateGBPVRPrograms(gbpvr_valid_programs);
208
209 sqllite_programs.Clear();
210 gbpvr_valid_programs.ForEach(s=>sqllite_programs.Add(s.NewProgram));
211
212 CheckScheduledRecordingsForDiscrepancies(sqllite_recordings,sqllite_programs);
213 }
214
215 static IDateTimeRange GetXMLTVProgramStartDateRange(List<libxmltv.Interfaces.IProgramDefinition> programs)
216 {
217 IDateTimeRange range = DateTimeRange.Create();
218 var list = new List<libxmltv.Interfaces.IProgramDefinition>(programs.ToArray());
219 DateTime first = new DateTime();
220 DateTime last = new DateTime();
221 first = DateTime.Parse(list.OrderBy(s => DateTime.Parse(s.Start)).ToList().First().Start);
222 last = DateTime.Parse(list.OrderBy(s => DateTime.Parse(s.Start)).ToList().Last().Start);
223 gLog.Verbose.Debug.WriteLine("\tFirst: {0} = ({1})", first.ToString("yyyy/MM/dd HH:mm:ss.fffffff"), first.ToDateTimeString());
224 gLog.Verbose.Debug.WriteLine("\tLast: {0} = ({1})", last.ToString("yyyy/MM/dd HH:mm:ss.fffffff"), last.ToDateTimeString());
225 range = DateTimeRange.Create(first, last);
226 return range;
227 }
228
229 static void CheckScheduledRecordingsForDiscrepancies(List<SQLLITE.IRECORDING_SCHEDULE> recordings, List<SQLLITE.IPROGRAMME> programs)
230 {
231 #if !ENABLE_SCHEDULDED_RECORDINGS_FIXUP
232 gLog.Warn.WriteLine("WANRING: Checking scheduled recordings for errors (and then deleting them) has been disabled.");
233 #else
234 List<SQLLITE.IRECORDING_SCHEDULE> recordings_to_delete = new List<SQLLITE.IRECORDING_SCHEDULE>();
235 foreach (var recording in recordings)
236 {
237 RecordingStatus status = (RecordingStatus)recording.status;
238 RecordingType type = (RecordingType)recording.recording_type;
239
240 // ignore any recording whose type is not: RecordingType.TYPE_RECORD_ONCE
241 if (type != RecordingType.TYPE_RECORD_ONCE) { continue; }
242 // ignore any recording whose status is not: RecordingStatus.STATUS_PENDING and not: RecordingStatus.STATUS_IN_PROGRESS
243 if (status != RecordingStatus.STATUS_PENDING && status != RecordingStatus.STATUS_IN_PROGRESS) { continue; }
244 // only fix recordings that have a recording group greater than 0 (zero)
245 if (recording.recording_group == 0) { continue; }
246 // verify data for this recording
247 var recording_oid = recording.oid;
248 var programme_oid = recording.programme_oid;
249 var filename = recording.filename;
250 var manual_start_time = recording.manual_start_time;
251 var manual_end_time = recording.manual_end_time;
252 var manual_channel_oid = recording.manual_channel_oid;
253
254 // lookup program by oid
255 var entry = programs.Find(s => s.oid == programme_oid);
256 if (entry == null)
257 {
258 gLog.Warn.WriteLine("Unable to find program with oid: '{0}' for recording with oid: '{1}' -- assuming it should be deleted", programme_oid, recording_oid);
259 //throw new NullReferenceException(string.Format("Unable to find program with oid: '{0}' for recording with oid: '{1}'", programme_oid, recording_oid));
260 //deleted_recordings.Add(recording);
261 }
262 else
263 {
264 recordings_to_delete.Add(recording);
265 }
266 }
267 recordings_to_delete.TrimExcess();
268 if (recordings_to_delete.Count > 0)
269 {
270 gLog.Info.WriteLine("Found {0} recordings to delete.", recordings_to_delete.Count);
271 sqlite.DeleteGBPVRScheduledRecordings(recordings_to_delete);
272 }
273 try
274 {
275
276 // taken from: Config.EpgUpdateProgress.method_1()
277 //Zap2itEpgReader.smethod_0();
278 //GClass4.smethod_0().method_14();
279 Zap2itEpgReader.x9a6781c43845a63b();
280 x396614b3dae3b1da.x479a7b07c9d5bd70().xf03e555cf1814572();
281 }
282 catch (Exception ex)
283 {
284 gLog.Error.WriteLine(ex.ToString());
285 }
286 #endif
287 }
288 }
289 }

  ViewVC Help
Powered by ViewVC 1.1.22