/// <summary> /// Read the share configuration data. /// </summary> /// <returns>true if share monitoring is enabled.</returns> private bool LoadSharesToMonitor() { try { _sharesToMonitor.Clear(); TvBusinessLayer layer = new TvBusinessLayer(); // Load share monitoring configuration for standby prevention if (Convert.ToBoolean(layer.GetSetting("PreventStandybyWhenSharesInUse", "false").Value)) { Setting setting = layer.GetSetting("PreventStandybyWhenSpecificSharesInUse", ""); string[] shares = setting.Value.Split(';'); foreach (string share in shares) { string[] shareItem = share.Split(','); if ((shareItem.Length.Equals(3)) && ((shareItem[0].Trim().Length > 0) || (shareItem[1].Trim().Length > 0) || (shareItem[2].Trim().Length > 0))) { _sharesToMonitor.Add(new ShareMonitor(shareItem[0], shareItem[1], shareItem[2])); } } Log.Debug("{0}: Share monitoring is enabled.", HandlerName); return(true); } } catch (Exception ex) { Log.Error("{0}: Error >{1}< loading shares to monitor", HandlerName, ex.Message); } Log.Debug("{0}: Share monitoring is disabled.", HandlerName); return(false); }
private void UpdateDescription() { Schedule rec = new Schedule(-1, "", Schedule.MinSchedule, Schedule.MinSchedule); TvBusinessLayer layer = new TvBusinessLayer(); rec.PreRecordInterval = Int32.Parse(layer.GetSetting("preRecordInterval", "5").Value); rec.PostRecordInterval = Int32.Parse(layer.GetSetting("postRecordInterval", "5").Value); SetProperties(rec); GUIListItem pItem = GetItem(GetSelectedItemNo()); if (pItem == null) { return; } rec = pItem.TVTag as Schedule; if (rec == null) { return; } Program prog = rec.ReferencedChannel().GetProgramAt(rec.StartTime.AddMinutes(1)); SetProperties(rec, prog); }
/// <summary> /// Thread to perform reboot /// </summary> private void RebootThread() { TvBusinessLayer layer = new TvBusinessLayer(); EPGWakeupConfig config = new EPGWakeupConfig((layer.GetSetting("PowerSchedulerRebootConfig", String.Empty).Value)); Log.Debug("RebootHandler: Reboot schedule {0:00}:{1:00} is due", config.Hour, config.Minutes); // Start external command RunExternalCommand("reboot"); // Trigger reboot Log.Info("RebootHandler: Reboot system"); IPowerScheduler ps = GlobalServiceProvider.Instance.Get <IPowerScheduler>(); ps.SuspendSystem("RebootHandler", (int)RestartOptions.Reboot, false); }
private void LoadRemoteCodes() { try { using ( FileStream fs = new FileStream(String.Format(@"{0}\ServerBlaster.dat", PathManager.GetDataPath), FileMode.Open, FileAccess.Read)) { BinaryFormatter bf = new BinaryFormatter(); _packetCollection = bf.Deserialize(fs) as Hashtable; if (_packetCollection != null) { foreach (string buttonName in _packetCollection.Keys) { Log.WriteFile("ServerBlaster.LoadRemoteCodes: Packet '{0}' ({1} bytes)", buttonName, ((byte[])_packetCollection[buttonName]).Length); } } } } catch (Exception e) { Log.WriteFile("ServerBlaster.LoadRemoteCodes: {0}", e.Message); } try { TvBusinessLayer layer = new TvBusinessLayer(); _sendSelect = (layer.GetSetting("SrvBlasterSendSelect", "False").Value == "True"); _sleepTime = 100; //xmlreader.GetValueAsInt("ServerBlaster", "delay", 100); _sendPort = 1; //xmlreader.GetValueAsInt("ServerBlaster", "forceport", 1); _blaster1Card = Convert.ToInt16(layer.GetSetting("SrvBlaster1Card", "0").Value); _blaster2Card = Convert.ToInt16(layer.GetSetting("SrvBlaster2Card", "0").Value); _deviceType = Convert.ToInt16(layer.GetSetting("SrvBlasterType", "0").Value); _deviceSpeed = Convert.ToInt16(layer.GetSetting("SrvBlasterSpeed", "0").Value); _advandeLogging = (layer.GetSetting("SrvBlasterLog", "False").Value == "True"); _sendPort = Math.Max(1, Math.Min(2, _sendPort)); Log.WriteFile("ServerBlaster.LoadRemoteCodes: Default port {0}", _sendPort); Log.WriteFile("ServerBlaster.RemoteType {0}", _deviceType); Log.WriteFile("ServerBlaster.DeviceSpeed {0}", _deviceSpeed); Log.WriteFile("ServerBlaster.Blaster1Card {0}", _blaster1Card); Log.WriteFile("ServerBlaster.Blaster2Card {0}", _blaster2Card); Log.WriteFile("ServerBlaster.Type {0}", _deviceType); Log.WriteFile("ServerBlaster.AdvancedLogging {0}", _advandeLogging); Log.WriteFile("ServerBlaster.SendSelect {0}", _sendSelect); } catch (Exception e) { Log.WriteFile("ServerBlaster.LoadRemoteCodes: {0}", e.Message); } return; }
public override void OnSectionDeActivated() { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("PTVGDebugMode", "false"); if (debug.Checked) { setting.Value = "true"; } else { setting.Value = "false"; } setting.Persist(); base.OnSectionDeActivated(); }
private void UpdateDriveInfo(bool save) { if (comboBoxDrive.SelectedItem == null) { return; } string drive = (string)comboBoxDrive.SelectedItem; ulong freeSpace = Utils.GetFreeDiskSpace(drive); long totalSpace = Utils.GetDiskSize(drive); labelFreeDiskspace.Text = Utils.GetSize((long)freeSpace); labelTotalDiskSpace.Text = Utils.GetSize(totalSpace); if (labelTotalDiskSpace.Text == "0") { labelTotalDiskSpace.Text = "Not available - WMI service not available"; } if (save) { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("freediskspace" + drive[0]); if (mpNumericTextBoxDiskQuota.Value < 500) { mpNumericTextBoxDiskQuota.Value = 500; } long quota = mpNumericTextBoxDiskQuota.Value * 1024; setting.Value = quota.ToString(); setting.Persist(); } else { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("freediskspace" + drive[0]); try { long quota = Int64.Parse(setting.Value); mpNumericTextBoxDiskQuota.Value = (int)quota / 1024; } catch (Exception) { mpNumericTextBoxDiskQuota.Value = 0; } if (mpNumericTextBoxDiskQuota.Value < 500) { mpNumericTextBoxDiskQuota.Value = 500; } } }
private void LoadLanguages() { _loaded = true; mpListView2.BeginUpdate(); try { mpListView2.Items.Clear(); TvLibrary.Epg.Languages languages = new TvLibrary.Epg.Languages(); List <String> codes = languages.GetLanguageCodes(); List <String> list = languages.GetLanguages(); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("epgLanguages"); string values = ""; for (int j = 0; j < list.Count; j++) { ListViewItem item = new ListViewItem(new string[] { list[j], codes[j] }); mpListView2.Items.Add(item); item.Tag = codes[j]; if (setting.Value == "") { values += item.Tag; values += ","; } else { if (setting.Value.IndexOf((string)item.Tag) >= 0) { item.Checked = true; } } } mpListView2.Sort(); if (setting.Value == "") { setting.Value = values; setting.Persist(); //DatabaseManager.Instance.SaveChanges(); } } finally { mpListView2.EndUpdate(); } }
/// <summary> /// Returns whether a schedule is due, and the EPG should run now. /// </summary> /// <returns></returns> private bool ShouldRunNow() { TvBusinessLayer layer = new TvBusinessLayer(); EPGWakeupConfig config = new EPGWakeupConfig((layer.GetSetting("PowerSchedulerEPGWakeupConfig", String.Empty).Value)); // Check if this day is configured for EPG and there was no EPG grabbing yet DateTime now = DateTime.Now; if (ShouldRun(config.Days, now.DayOfWeek) && config.LastRun.Date < now.Date) { // Check if schedule is due if (now >= new DateTime(now.Year, now.Month, now.Day, config.Hour, config.Minutes, 0)) { return(true); } } return(false); }
private static bool OutOfDiskSpace(string drive) { TvBusinessLayer layer = new TvBusinessLayer(); ulong minimiumFreeDiskSpace; string quotaText = layer.GetSetting("freediskspace" + drive[0], "51200").Value; try { minimiumFreeDiskSpace = (ulong)Int32.Parse(quotaText); } catch (Exception e) { Log.Error("DiskManagement: Exception at parsing freediskspace ({0}) to drive {1}", quotaText, drive); Log.Error(e.ToString()); //no setting for this drive: quitting return(false); } if (minimiumFreeDiskSpace <= 51200) // 50MB { minimiumFreeDiskSpace = 51200; } // Kilobytes to Bytes minimiumFreeDiskSpace *= 1024; if (minimiumFreeDiskSpace <= 0) { return(false); } ulong freeDiskSpace = Utils.GetFreeDiskSpace(drive); if (freeDiskSpace > minimiumFreeDiskSpace) { return(false); } Log.Info("DiskManagement: Drive {0} is out of free space!", drive); Log.Info("DiskManagement: Has: {0} Minimum Set: {1}", freeDiskSpace.ToString(), minimiumFreeDiskSpace.ToString()); return(true); }
public void ReloadConfig() { _layer = new TvBusinessLayer(); _titleTemplate = _layer.GetSetting("epgTitleTemplate", "%TITLE%").Value; _descriptionTemplate = _layer.GetSetting("epgDescriptionTemplate", "%DESCRIPTION%").Value; _epgLanguages = _layer.GetSetting("epgLanguages").Value; Setting setting = _layer.GetSetting("epgStoreOnlySelected"); _storeOnlySelectedChannels = (setting.Value == "yes"); Setting settingRadio = _layer.GetSetting("epgRadioStoreOnlySelected"); _storeOnlySelectedChannelsRadio = (settingRadio.Value == "yes"); Setting s = _layer.GetSetting("timeoutEPGRefresh", "240"); if (Int32.TryParse(s.Value, out _epgReGrabAfter) == false) { _epgReGrabAfter = 240; } _alwaysFillHoles = (_layer.GetSetting("generalEPGAlwaysFillHoles", "no").Value == "yes"); _alwaysReplace = (_layer.GetSetting("generalEPGAlwaysReplace", "no").Value == "yes"); }
protected ITvSubChannel _subchannel; // the active sub channel to record protected TimeShifterBase(ITvCardHandler cardHandler) { _eventAudio.Reset(); _eventVideo.Reset(); var layer = new TvBusinessLayer(); _waitForTimeshifting = Int32.Parse(layer.GetSetting("timeshiftWaitForTimeshifting", "15").Value); if (_cardHandler != null && _cardHandler.Tuner != null) { _cardHandler.Tuner.OnAfterCancelTuneEvent += Tuner_OnAfterCancelTuneEvent; } if (_cardHandler != null && _cardHandler.Tuner != null) { _cardHandler.Tuner.OnAfterCancelTuneEvent += new CardTuner.OnAfterCancelTuneDelegate(Tuner_OnAfterCancelTuneEvent); } }
/// <summary> /// ctor /// </summary> public TvCardCollection(IEpgEvents epgEvents) { Log.Log.WriteFile("----------------------------"); _epgEvents = epgEvents; // Logic here to delay detection of cards // Ideally this should occur after standby event. TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("delayCardDetect", "0"); int delayDetect = Convert.ToInt32(setting.Value); if (delayDetect >= 1) { Log.Log.WriteFile("Detecting Cards in {0} seconds", delayDetect); System.Threading.Thread.Sleep(delayDetect * 1000); } Log.Log.WriteFile("Detecting Cards"); _cards = new List <ITVCard>(); DetectCards(); }
public override void OnSectionActivated() { _cards = Card.ListAll(); base.OnSectionActivated(); mpGroupBox1.Visible = false; RemoteControl.Instance.EpgGrabberEnabled = true; comboBoxGroups.Items.Clear(); IList <ChannelGroup> groups = ChannelGroup.ListAll(); foreach (ChannelGroup group in groups) { comboBoxGroups.Items.Add(new ComboBoxExItem(group.GroupName, -1, group.IdGroup)); } if (comboBoxGroups.Items.Count == 0) { comboBoxGroups.Items.Add(new ComboBoxExItem("(no groups defined)", -1, -1)); } comboBoxGroups.SelectedIndex = 0; timer1.Enabled = true; mpListView1.Items.Clear(); buttonRestart.Visible = false; mpButtonRec.Enabled = false; TvBusinessLayer layer = new TvBusinessLayer(); if (layer.GetSetting("idleEPGGrabberEnabled", "yes").Value != "yes") { mpButtonReGrabEpg.Enabled = false; } _channelNames = new Dictionary <int, string>(); IList <Channel> channels = Channel.ListAll(); foreach (Channel ch in channels) { _channelNames.Add(ch.IdChannel, ch.DisplayName); } }
private void linkLabelLanguageNone_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { mpListView2.BeginUpdate(); try { for (int i = 0; i < mpListView2.Items.Count; ++i) { mpListView2.Items[i].Checked = false; } TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("epgLanguages"); setting.Value = ","; Log.WriteFile("tvsetup:epggrabber:none: epglang={0}", setting.Value); setting.Persist(); } finally { mpListView2.EndUpdate(); } }
/// <summary> /// Initializes a new instance of the <see cref="TvCardDvbSS2"/> class. /// </summary> /// <param name="epgEvents">The EPG events interface.</param> /// <param name="device">The device.</param> public TvCardDvbSS2(IEpgEvents epgEvents, DsDevice device) : base(epgEvents, device) { _useDISEqCMotor = false; TvBusinessLayer layer = new TvBusinessLayer(); Card card = layer.GetCardByDevicePath(device.DevicePath); if (card != null) { Setting setting = layer.GetSetting("dvbs" + card.IdCard + "motorEnabled", "no"); if (setting.Value == "yes") { _useDISEqCMotor = true; } } _conditionalAccess = new ConditionalAccess(null, null, null, this); _ptrDisEqc = Marshal.AllocCoTaskMem(20); _disEqcMotor = new DiSEqCMotor(this); GetTunerCapabilities(); }
private void OnSystemDeviceConnectedOrDisconnected(object sender, EventArrivedEventArgs e) { // Often several events will be triggered within a very short period of // time when a device is added/removed. We only want to check for new // devices once. Also, the first event may occur before the device is // ready, so we apply the device detection delay here. if ((DateTime.Now - _previousSystemDeviceChange).TotalMilliseconds < 10000) { return; } _previousSystemDeviceChange = DateTime.Now; TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("delayCardDetect", "0"); int delayDetect = Convert.ToInt32(setting.Value); if (delayDetect >= 1) { Thread.Sleep(delayDetect * 1000); } DetectBdaWdmDevices(); }
public override void OnSectionDeActivated() { Log.Info("TV3BlasterPlugin: Configuration deactivated"); TV3BlasterPlugin.HandleMessage -= ReceivedMessage; TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("TV3BlasterPlugin_ServerHost"); setting.Value = TV3BlasterPlugin.ServerHost; setting.Persist(); //TV3BlasterPlugin.LoadExternalConfigs(); TV3BlasterPlugin.StopClient(); TV3BlasterPlugin.InConfiguration = false; base.OnSectionDeActivated(); }
private void buttonExport_Click(object sender, EventArgs e) { TvBusinessLayer layer = new TvBusinessLayer(); string folder = layer.GetSetting("xmlTv", XmlTvImporter.DefaultOutputFolder).Value; string selFolder = textBoxFolder.Text; // use the folder set in the gui if it doesn't match the one set in the database // these might be different since it isn't saved until the user clicks ok or // moves to another part of the gui if (!folder.Equals(selFolder)) { folder = selFolder.Trim(); } if (System.IO.Directory.Exists(folder)) { saveFileExport.InitialDirectory = folder; } saveFileExport.ShowDialog(); }
public override void SaveSettings() { if (false == _loaded) { return; } TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("epgLanguages"); setting.Value = ","; for (int i = 0; i < mpListView2.Items.Count; ++i) { if (mpListView2.Items[i].Checked) { string code = (string)mpListView2.Items[i].Tag; setting.Value += code; setting.Value += ","; } } setting.Persist(); base.SaveSettings(); }
/// <summary> /// Returns whether a schedule is due, and the EPG should run now. /// </summary> /// <returns></returns> private bool ShouldRunNow() { TvBusinessLayer layer = new TvBusinessLayer(); EPGWakeupConfig config = new EPGWakeupConfig(layer.GetSetting("webepgSchedule", String.Empty).Value); // check if schedule is due // check if we've already run today if (config.LastRun.Day != DateTime.Now.Day) { // check if we should run today if (ShouldRun(config.Days, DateTime.Now.DayOfWeek)) { // check if schedule is due DateTime now = DateTime.Now; if (now.Hour > config.Hour || (now.Hour == config.Hour && now.Minute >= config.Minutes)) { return(true); } } } return(false); }
/// <summary> /// This method checks the diskspace on each harddisk /// if the diskspace used by recordings exceeds the disk quota set on the drive /// then this method will delete recordings until the disk quota is not exceeded anymore /// </summary> /// <remarks>Note, this method will run once every 15 minutes /// </remarks> private static void CheckFreeDiskSpace() { //check diskspace every 15 minutes... TvBusinessLayer layer = new TvBusinessLayer(); if (!(layer.GetSetting("diskQuotaEnabled", "False").Value == "True")) { //Disk Quota Management disabled: quitting return; } Log.Write("DiskManagement: checking free disk space"); //first get all drives.. List <string> drives = GetDisks(); // next check diskspace on each drive. foreach (string drive in drives) { CheckDriveFreeDiskSpace(drive); } }
public override void OnSectionActivated() { TvBusinessLayer layer = new TvBusinessLayer(); comboBoxType.SelectedIndex = Convert.ToInt16(layer.GetSetting("SrvBlasterType", "0").Value); comboBoxSpeed.SelectedIndex = Convert.ToInt16(layer.GetSetting("SrvBlasterSpeed", "0").Value); comboBoxBlaster1.Items.Clear(); comboBoxBlaster2.Items.Clear(); comboBoxBlaster1.Items.Add("None"); comboBoxBlaster2.Items.Add("None"); for (int i = 0; i < layer.Cards.Count; ++i) { Card card = layer.Cards[i]; comboBoxBlaster1.Items.Add(card.Name); comboBoxBlaster2.Items.Add(card.Name); } Log.WriteFile("CB1Size {0}, CB2Size {1}, BT1 {2}, BT2 {3}", comboBoxBlaster1.Items.Count, comboBoxBlaster1.Items.Count, Convert.ToInt16(layer.GetSetting("SrvBlaster1Card", "0").Value), Convert.ToInt16(layer.GetSetting("SrvBlaster2Card", "0").Value)); comboBoxBlaster1.SelectedIndex = Convert.ToInt16(layer.GetSetting("SrvBlaster1Card", "0").Value); comboBoxBlaster2.SelectedIndex = Convert.ToInt16(layer.GetSetting("SrvBlaster2Card", "0").Value); checkBoxExtLog.Checked = (layer.GetSetting("SrvBlasterLog").Value == "True"); checkSendSelect.Checked = (layer.GetSetting("SrvBlasterSendSelect").Value == "True"); }
public override void LoadSettings() { TvBusinessLayer layer = new TvBusinessLayer(); numericUpDownMinFiles.Value = ValueSanityCheck( Convert.ToDecimal(layer.GetSetting("timeshiftMinFiles", "6").Value), 3, 100); numericUpDownMaxFiles.Value = ValueSanityCheck(Convert.ToDecimal(layer.GetSetting("timeshiftMaxFiles", "20").Value), 3, 100); numericUpDownMaxFileSize.Value = ValueSanityCheck(Convert.ToDecimal(layer.GetSetting("timeshiftMaxFileSize", "256").Value), 20, 1024); numericUpDownWaitUnscrambled.Value = ValueSanityCheck(Convert.ToDecimal(layer.GetSetting("timeshiftWaitForUnscrambled", "5").Value), 1, 30); numericUpDownWaitTimeshifting.Value = ValueSanityCheck(Convert.ToDecimal(layer.GetSetting("timeshiftWaitForTimeshifting", "15").Value), 1, 30); numericUpDownMaxFreeCardsToTry.Value = ValueSanityCheck( Convert.ToDecimal(layer.GetSetting("timeshiftMaxFreeCardsToTry", "0").Value), 0, 100); }
/// <summary> /// action: standby, wakeup, epg /// </summary> /// <param name="action"></param> public void RunExternalCommand(String action) { TvBusinessLayer layer = new TvBusinessLayer(); String cmd = layer.GetSetting("PowerSchedulerEPGCommand", String.Empty).Value; if (cmd.Equals(String.Empty)) { return; } using (Process p = new Process()) { ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = cmd; psi.UseShellExecute = true; psi.WindowStyle = ProcessWindowStyle.Minimized; psi.Arguments = action; psi.ErrorDialog = false; if (Environment.OSVersion.Version.Major >= 6) { psi.Verb = "runas"; } p.StartInfo = psi; Log.Debug("EpgGrabbingHandler: Starting external command: {0} {1}", p.StartInfo.FileName, p.StartInfo.Arguments); try { p.Start(); p.WaitForExit(); } catch (Exception ex) { Log.Error("EpgGrabbingHandler: Exception in RunExternalCommand: {0}", ex.Message); Log.Info("EpgGrabbingHandler: Exception in RunExternalCommand: {0}", ex.Message); } Log.Debug("EpgGrabbingHandler: External command finished"); } }
/// <summary> /// Reads previous settings and assign them to controls /// </summary> private void SetDefaults() { TvBusinessLayer layer = new TvBusinessLayer(); int index = Math.Max(Int32.Parse(layer.GetSetting("dvbt" + _cardNumber + "Country", "0").Value), 0); // limit to >= 0 if (index < mpComboBoxCountry.Items.Count) { mpComboBoxCountry.SelectedIndex = index; } index = Math.Max(Int32.Parse(layer.GetSetting("dvbt" + _cardNumber + "Region", "0").Value), 0); // limit to >= 0 if (index < mpComboBoxRegion.Items.Count) { mpComboBoxRegion.SelectedIndex = index; } textBoxFreq.Text = layer.GetSetting("dvbt" + _cardNumber + "Freq", "306000").Value; textBoxBandwidth.Text = layer.GetSetting("dvbt" + _cardNumber + "Bandwidth", "8").Value; checkBoxCreateGroups.Checked = (layer.GetSetting("dvbt" + _cardNumber + "creategroups", "false").Value == "true"); checkBoxCreateSignalGroup.Checked = (layer.GetSetting("dvbt" + _cardNumber + "createsignalgroup", "false").Value == "true"); }
public DateTime EPGUpdateBeforeSchedule(DateTime _nextEpgTime) { Logdebug("EPGUpdateBeforeSchedule() _nextEpgTime="+_nextEpgTime.ToString()); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; setting = layer.GetSetting("TvWishList_CheckEPGScheduleMinutes","00"); bool EPGBeforeSchedule = false; Boolean.TryParse(setting.Value, out EPGBeforeSchedule); setting = layer.GetSetting("TvWishList_SlowCPU","true"); _useRecordingFlag = false; Boolean.TryParse(setting.Value, out _useRecordingFlag); if (EPGBeforeSchedule) { string minutes = layer.GetSetting("TvWishList_BeforeEPGMinutes", "00").Value; Logdebug("tvserver minutes =" + minutes); double minutenumber = 0; try { minutenumber = Convert.ToDouble(minutes); } catch (Exception exc) { Log.Error("Error: Could not convert EPG minutes " + minutenumber + " into number - setting to 00"); Log.Error("Exception message was:\n" + exc.Message + "\n"); minutenumber = 0; } //get next schedule start DateTime firstStartTime = DateTime.Now.AddYears(100); //always in the future Log.Debug("firstStartTime ="+firstStartTime.ToString()); Boolean found = false; foreach (Schedule myschedule in Schedule.ListAll()) { DateTime newStartTime = myschedule.StartTime.AddMinutes(minutenumber * (-1.0)); newStartTime = newStartTime.AddMinutes(myschedule.PreRecordInterval * (-1.0)); Log.Debug("Schedule ProgramName=" + myschedule.ProgramName); Log.Debug("newStartTime="+newStartTime.ToString()); if ((newStartTime > DateTime.Now) && (newStartTime < firstStartTime) ) { firstStartTime = newStartTime; found = true; Logdebug("New minimum schedule time found = "+newStartTime.ToString()); } } //update next epg time if ((found) && (firstStartTime < _nextEpgTime)) { _runEPGScript = true; //run script before next EPG check _nextEpgTime = firstStartTime; Logdebug("updating with new schedule start time nextEPGtime=" + _nextEpgTime.ToString()); //store data, because check needs to be done after each recording setting = layer.GetSetting("TvWishList_NextEpgDate", "2999-01-01"); setting.Value = _NextEpgTime.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Logdebug("Next epg checking date set to " + setting.Value); setting.Persist(); } } Logdebug("EPGUpdateBeforeSchedule() completed _nextEpgTime=" + _nextEpgTime.ToString()); return _nextEpgTime; }
public bool LockTvWishList(string pluginName) { bool BUSY = false; TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; Log.Debug("LockTvWishList: Trying to lock Tvwishes by " + pluginName); for (int i = 0; i < 5; i++) //5 retries { setting = layer.GetSetting("TvWishList_BUSY", "false"); try { BUSY = Convert.ToBoolean(setting.Value); } catch { BUSY = true; Log.Debug("Could not convert TvWishList_BUSY - setting BUSY to true", (int)LogSetting.ERROR); } if (BUSY == false) break; Thread.Sleep(1000); //retry every second } if (BUSY == true) { Log.Debug("BUSY=true - other process is running", (int)LogSetting.DEBUG); setting = layer.GetSetting("TvWishList_TimeStampLock", "1999-12-31 11:59:00"); DateTime lockTime = DateTime.ParseExact(setting.Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); DateTime checkTime = lockTime.AddHours(1.0); //ignore existing lock after 1 hour Log.Debug("lockTime=" + lockTime.ToString()); Log.Debug("checkTime=" + checkTime.ToString()); Log.Debug("DateTime.Now=" + DateTime.Now.ToString()); setting = layer.GetSetting("TvWishList_LockingPluginname", "Not Defined"); Log.Debug("TvWishList_LockingPluginname=" + setting.Value); if ((setting.Value.Contains(pluginName))&&(setting.Value.Contains(Environment.MachineName)) ) { Log.Error("Locking data because plugin and host are the same - data were locked by " + setting.Value); } else if (DateTime.Now < checkTime) {// data are locked return return false; } else //data lock is too old - ignore { Log.Error("Locking data because timestamp is expired - data were locked by " + setting.Value); } } //set BUSY = true setting = layer.GetSetting("TvWishList_BUSY", "true"); setting.Value = "true"; setting.Persist(); //tell plugin setting = layer.GetSetting("TvWishList_LockingPluginname", "Not Defined"); setting.Value = Environment.MachineName + ":" + pluginName + ":" + DateTime.Now.ToString() + " by version " + TvWishVersion(); _LockingPluginname = setting.Value; Log.Debug("TvWishList has been locked by " + _LockingPluginname, (int)LogSetting.DEBUG); setting.Persist(); //tell timestamp setting = layer.GetSetting("TvWishList_TimeStampLock", "1999-12-31 11:59:00"); setting.Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); setting.Persist(); return true; }
private void TestTvWishList() { LogDebug("EPG watching started", (int)LogSetting.DEBUG); try { MySaveSettings(); } catch (Exception ex) { LogDebug("Fatal Error: Failed to save settings - exception message is\n" + ex.Message, (int)LogSetting.ERROR); } try { //***************************************************** //unlock TvWishList myTvWishes.UnLockTvWishList(); //***************************************************** //run processing epgwatchclass.SearchEPG(false); //Email & Record } catch (Exception exc) { LogDebug("Parsing EPG data failed with exception message:", (int)LogSetting.ERROR); LogDebug(exc.Message, (int)LogSetting.ERROR); // Reset BUSY Flag TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; //set BUSY = false setting = layer.GetSetting("TvWishList_BUSY", "false"); setting.Value = "false"; setting.Persist(); labelupdate("Parsing EPG data failed - Check the log file", PipeCommands.Error); } try { //***************************************************** //Lock TvWishList with timeout error bool success = false; int seconds = 60; for (int i = 0; i < seconds / 10; i++) { success = myTvWishes.LockTvWishList("TvWishList Setup"); if (success) break; System.Threading.Thread.Sleep(10000); //sleep 10s to wait for BUSY=false LogDebug("Waiting for old jobs " + (seconds - i * 10).ToString() + "s to finish", (int)LogSetting.DEBUG); } if (success == false) { LogDebug("Timeout Error: TvWishList did not finish old jobs - reboot your computer ", (int)LogSetting.DEBUG); MessageBox.Show(lng.TranslateString("Timeout Error: TvWishList did not finish old jobs - try to close the plugin again or reboot ", 002)); LoadSettingError = true; } else { MyLoadSettings(); } } catch (Exception ex) { LogDebug("Fatal Error: Failed to load settings - exception message is\n" + ex.Message, (int)LogSetting.ERROR); LogDebug("Trying to resave settings to data base", (int)LogSetting.ERROR); try { MySaveSettings(); LogDebug("Saving settings succeeded", (int)LogSetting.ERROR); } catch { LogDebug("Fatal Error: Faileed to save settings", (int)LogSetting.ERROR); } } BUSY = false; }
public void MySaveSettings() { Log.Debug("MySaveSettings()"); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; if (LoadSettingError == true) { LogDebug("No data saved because of loadsetting error", (int)LogSetting.ERROR); return; } //TV User Folder setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND"); setting.Value = TV_USER_FOLDER; setting.Persist(); //checkboxes setting = layer.GetSetting("TvWishList_Debug", "false"); if (checkBoxDebug.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_SkipDeleted", "false"); if (checkBoxSkipDeleted.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_EmailReply", "true"); if (checkBoxemailreply.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_Schedule", "true"); if (checkBoxschedule.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_ScheduleConflicts", "false"); if (checkBoxscheduleconflicts.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_EmailOnlyNew", "true"); if (checkBoxEmailOnlynew.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_DeleteTimeChanges", "true"); if (checkBoxDeleteChangedEPG.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_SlowCPU", "true"); if (checkBoxSlowCPU.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_FilterEmail", "true"); if (checkBoxFilterEmail.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_FilterRecord", "false"); if (checkBoxFilterRecord.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_FilterConflicts", "true"); if (checkBoxFilterConflicts.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_DescendingSort", "true"); if (checkBoxdescendingSort.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_Easy", "true"); if (radioButtonEasy.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_Expert", "false"); if (radioButtonExpert.Checked == true) setting.Value = "true"; else setting.Value = "false"; setting.Persist(); //textboxes setting = layer.GetSetting("TvWishList_Sort", "Start"); setting.Value = SortCriteriaReverseTranslation(comboBoxSortCriteria.Text); setting.Persist(); setting = layer.GetSetting("TvWishList_DateTimeFormat", "{1:00}/{2:00} at {3:00}:{4:00}"); setting.Value = textBoxDateTimeFormat.Text; setting.Persist(); myTvWishes.save_longsetting(textBoxEmailFormat.Text, "TvWishList_EmailFormat"); setting = layer.GetSetting("TvWishList_EpgMarker", ""); setting.Value = textBoxEpgMark.Text; setting.Persist(); setting = layer.GetSetting("TvWishList_UserName", ""); setting.Value = trimstring(TextBoxUserName.Text); setting.Persist(); if (TextBoxPassword.Text !=TextBoxPassword2.Text) { MessageBox.Show(lng.TranslateString("Error: Your password does not match and is reset - please enter password again",023),lng.TranslateString("Error: Passwords Do Not Match",4305)); TextBoxPassword.Text=""; TextBoxPassword2.Text=""; } setting = layer.GetSetting("TvWishList_Password", ""); setting.Value = trimstring(TextBoxPassword.Text); setting.Persist(); if (textBoxSmtpEmailAdress.Text == "") { textBoxSmtpEmailAdress.Text = TextBoxUserName.Text; } setting = layer.GetSetting("TvWishList_SmtpEmailAddress", ""); setting.Value = trimstring(textBoxSmtpEmailAdress.Text); setting.Persist(); setting = layer.GetSetting("TvWishList_TestReceiver", ""); setting.Value = trimstring(TextBoxTestReceiver.Text); setting.Persist(); //arrays try { try { providerupdate(0); //store last settings as first provider defaults } catch {//ignore errors LogDebug("Last user settings could not be stored", (int)LogSetting.ERROR); } for (int i=0; i< listBoxProvider2.Items.Count; i++) //last settings are stored at position 0 for custom provider { setting = layer.GetSetting("TvWishList_Providers_"+i.ToString(), ";;;"); //LogDebug("provider_"+i.ToString()+" = "+providers[i]); setting.Value = providers[i]; if (setting.Value == null) { setting.Value = ";;;"; } setting.Persist(); } } catch (Exception ex) { LogDebug("Failed to write Provider ListBox to data base - exception message is\n" + ex.Message, (int)LogSetting.ERROR); } //maxfound //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxmaxfound, "", 1, 1000000000, "Max Found"); setting = layer.GetSetting("TvWishList_MaxFound", "100"); setting.Value = comboBoxmaxfound.Text; setting.Persist(); setting = layer.GetSetting("TvWishList_DeleteExpiration", "12"); setting.Value = comboBoxDeleteExpiration.Text; setting.Persist(); setting = layer.GetSetting("TvWishList_ChannelGroups", "Any"); setting.Value = comboBoxGroups.Text; setting.Persist(); setting = layer.GetSetting("TvWishList_LanguageFile", "strings_en.xml"); setting.Value = ReverseLanguageFileTranslation(comboBoxLanguage.Text); setting.Persist(); //saving messages //update message.tvwishid if tvwish has been deleted or is unknown Log.Debug("tv setup window before updating messages: TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString()); for (int i = mymessage.ListAllTvMessages().Count - 1; i >= 0; i--) { xmlmessage onemessage = mymessage.GetTvMessageAtIndex(i); //Log.Debug("onemessage.tvwishid="+onemessage.tvwishid); TvWish mywish = myTvWishes.RetrieveById(onemessage.tvwishid); if ((mywish == null)&&(onemessage.tvwishid!="-1")) //allow -1 for general conflicts { Log.Debug("deleting " + onemessage.title + " at " + onemessage.start.ToString() + " ID: " + onemessage.tvwishid); mymessage.DeleteTvMessageAt(i); } /*if ((mywish == null) && (mymessage.tvwishid != "-1")) { Log.Debug("Changing for " + mymessage.title + " at " + mymessage.start.ToString() + " from " + mymessage.tvwishid + " to -1"); mymessage.tvwishid = "-1"; mymessages.TvMessages[i] = mymessage; }*/ } Log.Debug("tv setup window after updating messages: TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString()); string dataString = mymessage.writexmlfile(false); //write xml file to string myTvWishes.save_longsetting(dataString, "TvWishList_ListViewMessages"); //listview data string listviewstring = ""; myTvWishes.Clear(); //convert dataGridView1 to tvwishes for (int i=0;i<dataGridView1.Rows.Count-1;i++) { try //add new default row to enable automated upgrades for new formats with more items { TvWish mywish = myTvWishes.DefaultData(); Log.Debug("i="+i.ToString()); Log.Debug("dataGridView1.RowCount=" + dataGridView1.RowCount.ToString()); Log.Debug("dataGridView1.ColumnCount=" + dataGridView1.ColumnCount.ToString()); try { mywish.active = dataGridView1[(int)TvWishEntries.active, i].Value.ToString(); } catch { } try{ mywish.skip = dataGridView1[(int)TvWishEntries.skip, i].Value.ToString(); } catch { } try{ mywish.includeRecordings = dataGridView1[(int)TvWishEntries.includerecordings, i].Value.ToString(); } catch { } try { mywish.searchfor = dataGridView1[(int)TvWishEntries.searchfor, i].Value.ToString(); } catch { } try { mywish.matchtype = dataGridView1[(int)TvWishEntries.matchtype, i].Value.ToString(); } catch { } try { mywish.group = dataGridView1[(int)TvWishEntries.group, i].Value.ToString(); } catch { } try { mywish.recordtype = dataGridView1[(int)TvWishEntries.recordtype, i].Value.ToString(); } catch { } try { mywish.action = dataGridView1[(int)TvWishEntries.action, i].Value.ToString(); } catch { } try { mywish.exclude = dataGridView1[(int)TvWishEntries.exclude, i].Value.ToString(); } catch { } try { mywish.prerecord = dataGridView1[(int)TvWishEntries.prerecord, i].Value.ToString(); } catch { } try { mywish.postrecord = dataGridView1[(int)TvWishEntries.postrecord, i].Value.ToString(); } catch { } try { mywish.episodename = dataGridView1[(int)TvWishEntries.episodename, i].Value.ToString(); } catch { } try { mywish.episodepart = dataGridView1[(int)TvWishEntries.episodepart, i].Value.ToString(); } catch { } try { mywish.episodenumber = dataGridView1[(int)TvWishEntries.episodenumber, i].Value.ToString(); } catch { } try { mywish.seriesnumber = dataGridView1[(int)TvWishEntries.seriesnumber, i].Value.ToString(); } catch { } try { mywish.keepepisodes = dataGridView1[(int)TvWishEntries.keepepisodes, i].Value.ToString(); } catch { } try { mywish.keepuntil = dataGridView1[(int)TvWishEntries.keepuntil, i].Value.ToString(); } catch { } try { mywish.recommendedcard = dataGridView1[(int)TvWishEntries.recommendedcard, i].Value.ToString(); } catch { } try { mywish.priority = dataGridView1[(int)TvWishEntries.priority, i].Value.ToString(); } catch { } try { mywish.aftertime = dataGridView1[(int)TvWishEntries.aftertime, i].Value.ToString(); } catch { } try { mywish.beforetime = dataGridView1[(int)TvWishEntries.beforetime, i].Value.ToString(); } catch { } try { mywish.afterdays = dataGridView1[(int)TvWishEntries.afterdays, i].Value.ToString(); } catch { } try { mywish.beforedays = dataGridView1[(int)TvWishEntries.beforedays, i].Value.ToString(); } catch { } try { mywish.channel = dataGridView1[(int)TvWishEntries.channel, i].Value.ToString(); } catch { } try { mywish.name = dataGridView1[(int)TvWishEntries.name, i].Value.ToString(); } catch { } try { mywish.useFolderName = dataGridView1[(int)TvWishEntries.useFolderName, i].Value.ToString(); } catch { } try { mywish.withinNextHours = dataGridView1[(int)TvWishEntries.withinNextHours, i].Value.ToString(); } catch { } try { mywish.episodecriteria = dataGridView1[(int)TvWishEntries.episodecriteria, i].Value.ToString(); } catch { } try { mywish.preferredgroup = dataGridView1[(int)TvWishEntries.preferredgroup, i].Value.ToString(); } catch { } //add tvwishid try { mywish.tvwishid = dataGridView1[(int)TvWishEntries.tvwishid, i].Value.ToString(); //decrease MaxTvWishId because new defaultwish id was not used - otherwise tvwishid would be increased during each save action myTvWishes.MaxTvWishId--; } catch { } myTvWishes.Add(mywish); Log.Debug("Tv wish added"); } catch (Exception exc) { LogDebug("Reading row failed with message \n" + exc.Message, (int)LogSetting.ERROR); } LogDebug("Tvwish finished", (int)LogSetting.DEBUG); } //End all rows in datagridview // save to string (includes backtransformation from language) listviewstring = myTvWishes.SaveToStringNoChecking(); Log.Debug("savesettings: after language translation listviewstring=" + listviewstring); //check data listviewstring = myTvWishes.CheckString(listviewstring); Log.Debug("savesettings: after checking listviewstring=" + listviewstring); myTvWishes.save_longsetting(listviewstring, "TvWishList_ListView"); //must be after listviewstring! LogDebug("SaveSetings: MaxTvWishId=" + myTvWishes.MaxTvWishId.ToString(), (int)LogSetting.DEBUG); setting = layer.GetSetting("TvWishList_MaxTvWishId", "0"); setting.Value = myTvWishes.MaxTvWishId.ToString(); setting.Persist(); //integer values setting = layer.GetSetting("TvWishList_ProviderSelected", "0"); int j = listBoxProvider2.SelectedIndex; setting.Value = j.ToString(); //select actual item in listbox setting.Persist(); //comboboxes setting = layer.GetSetting("TvWishList_WaitComSkipMinutes", "60"); try { int i = Convert.ToInt32(comboBoxComSkipWaitMinutes.Text); } catch { comboBoxComSkipWaitMinutes.Text = "60"; } setting.Value = comboBoxComSkipWaitMinutes.Text; setting.Persist(); // check comboboxes before saving //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxdays, "D2" , 1, 14, "Days"); //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxhours, "D2", 0, 23, "Hours"); //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxminutes, "D2", 0, 59, "Minutes"); //calculate new epg checking data // get old epg checking data string old_epg_check = ""; setting = layer.GetSetting("TvWishList_CheckEpgDays", "07"); old_epg_check += "days"+setting.Value; setting = layer.GetSetting("TvWishList_CheckEpgHours", "06"); old_epg_check += "hours"+setting.Value; setting = layer.GetSetting("TvWishList_CheckEpgMinutes", "00"); LogDebug("old epg checking data minutes=" + setting.Value, (int)LogSetting.DEBUG); old_epg_check += "minutes"+setting.Value; setting = layer.GetSetting("TvWishList_Monday", "false"); old_epg_check += "Monday" + setting.Value; setting = layer.GetSetting("TvWishList_Tuesday", "false"); old_epg_check += "Tuesday" + setting.Value; setting = layer.GetSetting("TvWishList_Wednesday", "false"); old_epg_check += "Wednesday" + setting.Value; setting = layer.GetSetting("TvWishList_Thursday", "false"); old_epg_check += "Thursday" + setting.Value; setting = layer.GetSetting("TvWishList_Friday", "false"); old_epg_check += "Friday" + setting.Value; setting = layer.GetSetting("TvWishList_Saturday", "false"); old_epg_check += "Saturday" + setting.Value; setting = layer.GetSetting("TvWishList_Sunday", "false"); old_epg_check += "Sunday" + setting.Value; setting = layer.GetSetting("TvWishList_Every", "false"); old_epg_check += "Every" + setting.Value; setting = layer.GetSetting("TvWishList_CheckEPGScheduleMinutes", "false"); old_epg_check += "CheckEPGScheduleMinutes" + setting.Value; setting = layer.GetSetting("TvWishList_BeforeEPGMinutes", "00"); old_epg_check += "BeforeEPGMinutes" + setting.Value; string new_epg_check = ""; if ((checkBoxMon.Checked == false) && (checkBoxTue.Checked == false) && (checkBoxWed.Checked == false) && (checkBoxThur.Checked == false) && (checkBoxFri.Checked == false) && (checkBoxSat.Checked == false) && (checkBoxSun.Checked == false) && (checkBoxEvery.Checked == false)) { checkBoxEvery.Checked = true; LogDebug("no information about checking days - using every " + comboBoxdays.Text + " days", (int)LogSetting.INFO); } setting = layer.GetSetting("TvWishList_CheckEpgDays", "07"); setting.Value = comboBoxdays.Text; new_epg_check += "days" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_CheckEpgHours", "06"); setting.Value = comboBoxhours.Text; new_epg_check += "hours" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_CheckEpgMinutes", "00"); setting.Value = comboBoxminutes.Text; LogDebug("new_epg_check minutes=" + setting.Value, (int)LogSetting.DEBUG); new_epg_check += "minutes" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Monday", "false"); if (checkBoxMon.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Monday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Tuesday", "false"); if (checkBoxTue.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Tuesday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Wednesday", "false"); if (checkBoxWed.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Wednesday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Thursday", "false"); if (checkBoxThur.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Thursday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Friday", "false"); if (checkBoxFri.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Friday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Saturday", "false"); if (checkBoxSat.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Saturday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Sunday", "false"); if (checkBoxSun.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Sunday" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_Every", "false"); if (checkBoxEvery.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "Every" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_CheckEPGScheduleMinutes", "false"); if (checkBoxScheduleMinutes.Checked == true) setting.Value = "true"; else setting.Value = "false"; new_epg_check += "CheckEPGScheduleMinutes" + setting.Value; setting.Persist(); setting = layer.GetSetting("TvWishList_BeforeEPGMinutes", "00"); setting.Value = comboBoxScheduleMinutes.Text; new_epg_check += "BeforeEPGMinutes" + setting.Value; setting.Persist(); LogDebug("old_epg_check=" + old_epg_check, (int)LogSetting.DEBUG); LogDebug("new_epg_check=" + new_epg_check, (int)LogSetting.DEBUG); //update tv service if a new value is set if (old_epg_check != new_epg_check) { string nextEpgFileWatcherFile = TV_USER_FOLDER + @"\TvWishList\NextEPGCheck.txt"; LogDebug("Writing Filewatcher file " + nextEpgFileWatcherFile, (int)LogSetting.DEBUG); //writing file try { File.WriteAllText(nextEpgFileWatcherFile, "NextEPGCheckUpdate"); } catch (Exception exc) { LogDebug("Error in writing epg time file " + nextEpgFileWatcherFile, (int)LogSetting.ERROR); LogDebug(exc.Message, (int)LogSetting.ERROR); } } }
/// <summary> /// Loads the settings. /// </summary> private static void LoadSettings() { TvBusinessLayer layer = new TvBusinessLayer(); ServerHost = layer.GetSetting("TV3BlasterPlugin_ServerHost", "localhost").Value; }
public bool SearchEPG(bool view_only_mode) { Log.Info("[TvWishList]:SearchEPG started with view_only_mode=" + view_only_mode.ToString(), (int)LogSetting.DEBUG); VIEW_ONLY_MODE = view_only_mode; myTvWishes = new TvWishProcessing(); // load globals from data base TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; /* //Debug only Log.Debug("Debug Schedules:"); foreach (Schedule myschedule in Schedule.ListAll()) { outputscheduletoresponse(myschedule, (int)LogSetting.DEBUG); } //end debug */ lng.ReadLanguageFile(); Log.Debug("language file read"); try { setting = layer.GetSetting("TvWishList_Debug", "false"); if (BoolConversion(setting.Value,false)) { DEBUG = true; } else { DEBUG = false; } Log.DebugValue = DEBUG; //TV User Folder setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND"); TV_USER_FOLDER = setting.Value; /*// delete later - no more needed filewatchermessages = TV_USER_FOLDER + @"\TvWishList\filewatchermessages.txt"; if (File.Exists(filewatchermessages) == true) { File.Delete(filewatchermessages); LogDebug("Deleting file " + filewatchermessages, (int)LogSetting.DEBUG); }*/ } catch { string languagetext = lng.TranslateString("Fatal error - check the log file",24 ); labelmessage(languagetext, PipeCommands.Error); LogDebug("Could not read from TV database", (int)LogSetting.ERROR); return false; } //***************************************************** //Lock TvWishList with timeout error bool success = false; int seconds = 60; Log.Debug("Lock TvWishList EpgSearch"); for (int i = 0; i < seconds / 10; i++) { success = myTvWishes.LockTvWishList("TvWishList EpgSearch"); if (success) break; System.Threading.Thread.Sleep(10000); //sleep 10s to wait for BUSY=false string languagetext = lng.TranslateString("Waiting for old jobs {0}s to finish", 1, (seconds - i * 10).ToString()); Log.Debug(languagetext, (int)LogSetting.DEBUG); labelmessage(languagetext, PipeCommands.StartEpg); } if (success == false) { string languagetext = lng.TranslateString("Error: TvWishList did not finish old jobs - reboot your computer", 2); LogDebug(languagetext, (int)LogSetting.ERROR); labelmessage(languagetext, PipeCommands.Error); return false; } try { string languagetext = lng.TranslateString("Reading data settings", 3); LogDebug(languagetext, (int)LogSetting.DEBUG); labelmessage(languagetext, PipeCommands.StartEpg); //checkboxes Log.Debug("Reading Settings"); setting = layer.GetSetting("TvWishList_SkipDeleted", "false"); if (BoolConversion(setting.Value, false)) _skipDeleted = true; else _skipDeleted = false; setting = layer.GetSetting("TvWishList_EmailReply", "true"); if (BoolConversion(setting.Value, true)) _emailreply = true; else _emailreply = false; setting = layer.GetSetting("TvWishList_Schedule", "true"); if (BoolConversion(setting.Value, true)) _automaticrecording = true; else _automaticrecording = false; setting = layer.GetSetting("TvWishList_ScheduleConflicts", "false"); if (BoolConversion(setting.Value, false)) _scheduleconflicts = true; else _scheduleconflicts = false; setting = layer.GetSetting("TvWishList_EmailOnlyNew", "true"); if (BoolConversion(setting.Value, true)) _emailonlynew = true; else _emailonlynew = false; setting = layer.GetSetting("TvWishList_DeleteTimeChanges", "true"); if (BoolConversion(setting.Value, true)) _DeleteTimeChanges = true; else _DeleteTimeChanges = false; setting = layer.GetSetting("TvWishList_FilterEmail", "true"); if (BoolConversion(setting.Value, true)) _filter_email = true; else _filter_email = false; setting = layer.GetSetting("TvWishList_FilterRecord", "true"); if (BoolConversion(setting.Value, true)) _filter_scheduled = true; else _filter_scheduled = false; setting = layer.GetSetting("TvWishList_FilterConflicts", "true"); if (BoolConversion(setting.Value, true)) _filter_conflicts = true; else _filter_conflicts = false; setting = layer.GetSetting("TvWishList_DescendingSort", "false"); if (BoolConversion(setting.Value, true)) _descendingsort = true; else _descendingsort = false; //textboxes string Emailformat = myTvWishes.loadlongsettings("TvWishList_EmailFormat"); if (Emailformat == string.Empty) { Emailformat = lng.TranslateString(Emailformat, 90); } Emailformat = Emailformat.Replace(@"\n", "\n"); Emailformat = Emailformat.Replace("<br>", "\n"); Emailformat = Emailformat.Replace("<BR>", "\n"); string myEmailformat=Emailformat.ToString().Replace('{', '_'); myEmailformat=myEmailformat.ToString().Replace('}', '_'); LogDebug("Emailformat :" + myEmailformat, (int)LogSetting.DEBUG); //datetimeformat setting = layer.GetSetting("TvWishList_DateTimeFormat", ""); string DateTimeFormat = setting.Value.ToString(); if (DateTimeFormat == string.Empty) { DateTimeFormat = lng.TranslateString("{1:00}/{2:00} at {3:00}:{4:00}", 91); } string myDateformat = DateTimeFormat.ToString().Replace('{', '_'); myDateformat = myDateformat.ToString().Replace('}', '_'); LogDebug("DateTimeFormat=" + myDateformat, (int)LogSetting.DEBUG); //initialize messages string messagedata = ""; mymessage = new XmlMessages(DateTimeFormat, Emailformat, DEBUG); languagetext = lng.TranslateString("Loading Messages", 4); Log.Debug(languagetext); labelmessage(languagetext, PipeCommands.StartEpg); if (VIEW_ONLY_MODE == true) { messagedata = ""; //start with a clean message list for viewonlymode } else { //mymessage.filename = TV_USER_FOLDER + @"\TvWishList\Messages.xml"; messagedata = myTvWishes.loadlongsettings("TvWishList_ListViewMessages"); } mymessage.readxmlfile(messagedata, false); Log.Debug("mymessage.TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString()); //mymessage.logmessages(); //DEBUG ONLY setting = layer.GetSetting("TvWishList_Sort", "Start"); string sortstring = setting.Value; if (sortstring == "Title") _sort = (int)XmlMessages.Sorting.Title; else if (sortstring == "Start") _sort = (int)XmlMessages.Sorting.Start; else if (sortstring == "Created") _sort = (int)XmlMessages.Sorting.Created; else if (sortstring == "Genre") _sort = (int)XmlMessages.Sorting.Genre; else if (sortstring == "Classification") _sort = (int)XmlMessages.Sorting.Classification; else if (sortstring == "ParentalRating") _sort = (int)XmlMessages.Sorting.ParentalRating; else if (sortstring == "StarRating") _sort = (int)XmlMessages.Sorting.StarRating; else if (sortstring == "Type") _sort = (int)XmlMessages.Sorting.Type; else if (sortstring == "Message") _sort = (int)XmlMessages.Sorting.Message; else if (sortstring == "SearchString") _sort = (int)XmlMessages.Sorting.SearchString; else if (sortstring == "EpisodeName") _sort = (int)XmlMessages.Sorting.EpisodeName; else if (sortstring == "EpisodeNum") _sort = (int)XmlMessages.Sorting.EpisodeNum; else if (sortstring == "EpisodeNumber") _sort = (int)XmlMessages.Sorting.EpisodeNumber; else if (sortstring == "EpisodePart") _sort = (int)XmlMessages.Sorting.EpisodePart; //EPG marker setting = layer.GetSetting("TvWishList_EpgMarker", ""); _EpgMarker = setting.Value; /*if (_EpgMarker.Contains(@"|")) { EpgMarkerExpression = true; } else { EpgMarkerExpression = false; }*/ //textboxes setting = layer.GetSetting("TvWishList_UserName", ""); _TextBoxUserName = setting.Value; setting = layer.GetSetting("TvWishList_Password", ""); _TextBoxPassword = setting.Value; setting = layer.GetSetting("TvWishList_TestReceiver", ""); s_receiver = setting.Value; setting = layer.GetSetting("TvWishList_SmtpEmailAddress", ""); _TextBoxSmtpEmailAddress = setting.Value; //providerdata setting = layer.GetSetting("TvWishList_Providers_0", "_Last Setting;;0;False"); string[] tokenarray = setting.Value.Split(';'); if (tokenarray.Length != 4) { LogDebug("Provider array has invalid number of elements: " + tokenarray.Length.ToString(), (int)LogSetting.ERROR); } else { try { _TextBoxSmtpServer = tokenarray[1]; _numericUpDownSmtpPort = Convert.ToInt32(tokenarray[2]); _checkBoxSSL = Convert.ToBoolean(tokenarray[3]); } catch (Exception ex) { LogDebug("Failed converting provider data with exception: " + ex.Message, (int)LogSetting.ERROR); languagetext = lng.TranslateString("Fatal error - check the log file", 24); labelmessage(languagetext, PipeCommands.StartEpg); //do not stop - do not flag as error Thread.Sleep(ErrorWaitTime); } } //maxfound setting = layer.GetSetting("TvWishList_MaxFound", "100"); try { MAXFOUND = Convert.ToInt32(setting.Value); } catch { LogDebug("Max Found could not be converted to number resetting to 100", (int)LogSetting.DEBUG); MAXFOUND = 100; languagetext = lng.TranslateString("Fatal error - check the log file", 24); labelmessage(languagetext, PipeCommands.StartEpg); //do not stop - do not flag as error Thread.Sleep(ErrorWaitTime); } setting = layer.GetSetting("TvWishList_MaxTvWishId", "0"); int maxTvWishId = 0; int.TryParse(setting.Value, out maxTvWishId); myTvWishes.MaxTvWishId = maxTvWishId; Log.Debug("EpgClass: MaxTvWishId=" + myTvWishes.MaxTvWishId.ToString(), (int)LogSetting.DEBUG); //deleteExpiration in months int deleteExpiration = 12; setting = layer.GetSetting("TvWishList_DeleteExpiration", "12"); try { deleteExpiration = Convert.ToInt32(setting.Value); } catch { LogDebug("Delete Expiration could not be converted to number resetting to 12", (int)LogSetting.ERROR); deleteExpiration = 12; languagetext = lng.TranslateString("Fatal error - check the log file", 24); labelmessage(languagetext, PipeCommands.StartEpg); //do not stop - do not flag as error Thread.Sleep(ErrorWaitTime); } //listviewdata setting = layer.GetSetting("TvWishList_ColumnSeparator", ";"); TV_WISH_COLUMN_SEPARATOR = setting.Value[0]; //default pre and post record from general recording settings setting = layer.GetSetting("preRecordInterval", "5"); string prerecord = setting.Value; setting = layer.GetSetting("postRecordInterval", "5"); string postrecord = setting.Value; myTvWishes.TvServerSettings(prerecord, postrecord, ChannelGroup.ListAll(), RadioChannelGroup.ListAll(), Channel.ListAll(), Card.ListAll(), TV_WISH_COLUMN_SEPARATOR); languagetext = lng.TranslateString("Loading Tv wishes", 5); Log.Debug(languagetext); labelmessage(languagetext, PipeCommands.StartEpg); string listviewdata = ""; if (VIEW_ONLY_MODE == true) { listviewdata = myTvWishes.loadlongsettings("TvWishList_OnlyView"); //never change setting name must match to MP plugin and later savelongsetting } else { listviewdata = myTvWishes.loadlongsettings("TvWishList_ListView"); } Log.Debug("listviewdata=" + listviewdata, (int)LogSetting.DEBUG); myTvWishes.Clear(); myTvWishes.LoadFromString(listviewdata, true); RESPONSE = ""; //conflictprograms.Clear(); //update messages before conflict checking of EPG data Log.Debug("after reading messages: TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString()); mymessage.updatemessages(deleteExpiration); Log.Debug("after update messages: TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString()); //Debug for foxbenw issue Log.Debug("Outputting all schedules before schedule processing"); foreach (Schedule oneschedule in Schedule.ListAll()) { mymessage.outputscheduletoresponse(oneschedule, (int)LogSetting.DEBUG); } Log.Debug("End of Outputting all schedules before schedule processing"); //#if (MP11RC || MP12) #if (TV11 || TV12) // check for conflicts between epg data and schedules (only for 1.1 final lor later) foreach (Schedule oneschedule in Schedule.ListAll()) { LogDebug("Schedule=" + oneschedule.ProgramName, (int)LogSetting.DEBUG); LogDebug("Schedule Start Time: " + oneschedule.StartTime.ToString(), (int)LogSetting.DEBUG); LogDebug("Schedule End Time: " + oneschedule.EndTime.ToString(), (int)LogSetting.DEBUG); LogDebug("Schedule Channel: " + oneschedule.IdChannel.ToString(), (int)LogSetting.DEBUG); LogDebug("Schedule ID: " + oneschedule.IdSchedule.ToString(), (int)LogSetting.DEBUG); bool EpgTimeChanged = false; Program testprogram = null; Schedule testschedule = oneschedule; try { testprogram = Program.RetrieveByTitleTimesAndChannel(oneschedule.ProgramName, oneschedule.StartTime, oneschedule.EndTime, oneschedule.IdChannel); } catch { testprogram = null; } if (_DeleteTimeChanges == true) { // check for valid EPG entry if (testprogram == null) { // check for changed time on same channel IList<Program> alternativeprograms = null; alternativeprograms = Program.RetrieveEveryTimeOnThisChannel(oneschedule.ProgramName, oneschedule.IdChannel); if (alternativeprograms != null) { // search for closest program to original start time double minimumdifferenz = 10000000.0; //start with largest value > 4 weeks Program minprogram = null; foreach (Program altprogram in alternativeprograms) { LogDebug("Alternate EPG=" + altprogram.Title, (int)LogSetting.DEBUG); LogDebug("Alternate Start Time: " + altprogram.StartTime.ToString(), (int)LogSetting.DEBUG); LogDebug("Alternate End Time: " + altprogram.EndTime.ToString(), (int)LogSetting.DEBUG); double totalminutes = (altprogram.StartTime - oneschedule.StartTime).TotalMinutes; if (totalminutes < 0) totalminutes = totalminutes * (-1); LogDebug("Differenz to Schedule totalminutes=" + totalminutes.ToString(), (int)LogSetting.DEBUG); // int differenz = oneschedule.StartTime.Subtract(altprogram.StartTime).Minutes; //DateTime.Compare(oneschedule.StartTime, altprogram.StartTime); if (totalminutes < minimumdifferenz) { minimumdifferenz = totalminutes; minprogram = altprogram; } } LogDebug("Minimum Differenz to Schedule = " + minimumdifferenz.ToString(), (int)LogSetting.DEBUG); if (minprogram != null) { //alternative program found Schedule schedule = layer.AddSchedule(minprogram.IdChannel, minprogram.Title, minprogram.StartTime, minprogram.EndTime, 0); schedule.PreRecordInterval = oneschedule.PreRecordInterval; schedule.PostRecordInterval = oneschedule.PostRecordInterval; schedule.ScheduleType = oneschedule.ScheduleType; schedule.Series = oneschedule.Series; schedule.KeepDate = oneschedule.KeepDate; schedule.KeepMethod = oneschedule.KeepMethod; schedule.RecommendedCard = oneschedule.RecommendedCard; schedule.Priority = oneschedule.Priority; schedule.Persist(); LogDebug("", (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); message = lng.TranslateString("Schedule {0} had no valid EPG data but could be corrected", 50, oneschedule.ProgramName); LogDebug("Scheduled New= " + schedule.ProgramName, (int)LogSetting.INFO); LogDebug("New Start Time= " + schedule.StartTime.ToString(), (int)LogSetting.INFO); LogDebug("New End Time= " + schedule.EndTime.ToString(), (int)LogSetting.INFO); LogDebug("Deleted= " + oneschedule.ProgramName, (int)LogSetting.INFO); LogDebug("Old Start Time= " + oneschedule.StartTime.ToString(), (int)LogSetting.INFO); LogDebug("OLd End Time= " + oneschedule.EndTime.ToString(), (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); EpgTimeChanged = true; //new // try to change schedule messages if they exist from old data try { int k; k = mymessage.GetTvMessageBySchedule(oneschedule,MessageType.Scheduled); LogDebug("try to change schedule message: k="+k.ToString(), (int)LogSetting.DEBUG); xmlmessage scheduledmessage = mymessage.GetTvMessageAtIndex(k); LogDebug("schedule message retrieved", (int)LogSetting.DEBUG); bool ok = mymessage.addmessage(schedule, scheduledmessage.message, MessageType.Scheduled, scheduledmessage.searchstring, (int)XmlMessages.MessageEvents.SCHEDULE_FOUND, scheduledmessage.tvwishid, string.Empty); LogDebug("ok=" + ok.ToString(), (int)LogSetting.DEBUG); if (ok) mymessage.DeleteTvMessageAt(k); /* updatedmessage.start = schedule.StartTime; updatedmessage.end = schedule.EndTime; mymessage.ReplaceTvMessageAtIndex(k, updatedmessage);*/ LogDebug("new schedule message has been added", (int)LogSetting.DEBUG); } catch { LogDebug("schedule message could not be found", (int)LogSetting.DEBUG); } //add new email message if it did exist try { int k; k = mymessage.GetTvMessageBySchedule(oneschedule, MessageType.Emailed); LogDebug("try to change email message: k=" + k.ToString(), (int)LogSetting.DEBUG); xmlmessage emailmessage = mymessage.GetTvMessageAtIndex(k); LogDebug("email message retrieved", (int)LogSetting.DEBUG); bool ok = mymessage.addmessage(schedule, emailmessage.message, MessageType.Emailed, emailmessage.searchstring, (int)XmlMessages.MessageEvents.EMAIL_FOUND, emailmessage.tvwishid, string.Empty); LogDebug("ok=" + ok.ToString(), (int)LogSetting.DEBUG); if (ok) mymessage.DeleteTvMessageAt(k); LogDebug("new email message has been added", (int)LogSetting.DEBUG); } catch { LogDebug("Email message could not be found", (int)LogSetting.DEBUG); } //end new change Log.Debug("Deleting schedule "+oneschedule.ProgramName+" with id="+oneschedule.IdSchedule.ToString()); oneschedule.Delete(); //delete old schedule if possible mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.NO_VALID_EPG, "-1", string.Empty); //reassign testprogram and testschedule testprogram = minprogram; testschedule = schedule; } else { LogDebug("", (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); message = lng.TranslateString("Schedule {0} has no valid EPG data - check your schedules for conflicts",51,oneschedule.ProgramName); LogDebug(message, (int)LogSetting.INFO); LogDebug("Schedule start date = " + oneschedule.StartTime.ToString() + "\n", (int)LogSetting.INFO); LogDebug("Schedule end date= " + oneschedule.EndTime.ToString() + "\n\n", (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.NO_VALID_EPG, "-1", string.Empty); } } else //no alternative program does exist - email warning { LogDebug("", (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); message = lng.TranslateString("Schedule {0} has no valid EPG data - check your schedules for conflicts",52,oneschedule.ProgramName); LogDebug(message, (int)LogSetting.INFO); LogDebug( "Schedule start date = " + oneschedule.StartTime.ToString() + "\n", (int)LogSetting.INFO); LogDebug("Schedule end date= " + oneschedule.EndTime.ToString() + "\n\n", (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.NO_VALID_EPG, "-1", string.Empty); //do not use -1 bug!!! } }// else: Schedule does match to EPG data - check next schedule }//end epg changes //try to reschedule if episode or description epg data and message have been changed, but only if tvwish still exists int i; try { i = mymessage.GetTvMessageBySchedule(testschedule,MessageType.Scheduled); // new bugfix: must be type scheduled } catch { i = -1; } Log.Debug("message index i=" + i.ToString()); if ((i >= 0) && (testprogram != null))//scheduled message does exist for schedule and program does exist for schedule { try { xmlmessage testmessage = mymessage.GetTvMessageAtIndex(i); Log.Debug("retriefed testmessage.title=" + testmessage.title); //get tvwish (which can cause exception for unvalid entries) TvWish mytestwish = myTvWishes.RetrieveById(testmessage.tvwishid); Log.Debug("retrieved mytestwish.name=" + mytestwish.name); bool ok = episodeManagementEmptyString(testprogram.Description, testmessage.description, testprogram.EpisodePart, testmessage.EpisodePart, testprogram.EpisodeName, testmessage.EpisodeName, testprogram.SeriesNum, testmessage.SeriesNum, testprogram.EpisodeNum, testmessage.EpisodeNum, mytestwish.b_episodecriteria_d, mytestwish.b_episodecriteria_n, mytestwish.b_episodecriteria_c); if ((ok == false) || (EpgTimeChanged))//epg episode data or epg time did change //new: always try to reschedule if epg time changed because simultanous change of EPG data cannot be tracked { //conflict message testmessage.type = MessageType.Conflict.ToString(); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); message = lng.TranslateString("Epg data did change for Episode/Description or EPG Time changed- deleting current schedule and trying to reschedule",53); LogDebug(message, (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); testmessage.message = message; mymessage.ReplaceTvMessageAtIndex(i, testmessage); //delete schedule Log.Debug("Deleting testschedule " + testschedule.ProgramName + " with id=" + testschedule.IdSchedule.ToString()); testschedule.Delete(); if (mytestwish.b_active == false) {//need to run now again for inactive tvwish mytestwish.b_active = true; Log.Debug("Setting Tvwish active and running sql query"); //search for schedules SqlQueryPrograms(ref mytestwish, i); mytestwish.b_active = false; myTvWishes.ReplaceAtIndex(i, mytestwish); } } } catch //ignore errors { } }//end of episode changes } //end all schedules #endif //Debug for foxbenw issue Log.Debug("Outputting all schedules before tvwish processing"); foreach (Schedule oneschedule in Schedule.ListAll()) { mymessage.outputscheduletoresponse(oneschedule, (int)LogSetting.DEBUG); } Log.Debug("End of Outputting all schedules before tvwish processing"); // start processing all TvWishes TvWish mywish = null; for (int i = 0; i < myTvWishes.ListAll().Count; i++) { mywish = myTvWishes.GetAtIndex(i); if (DEBUG) { Log.Debug("Before Query:"); myTvWishes.DebugTvWish(mywish); } if ((mywish.name == "") && (mywish.searchfor == "") && (mywish.episodename == "") && (mywish.episodenumber == "") && (mywish.episodepart == "")) { Log.Debug("Skipping tvwish with id=" + mywish.tvwishid.ToString()); continue; } languagetext = lng.TranslateString("Searching for {0}", 6,mywish.name); labelmessage(languagetext, PipeCommands.StartEpg); //remove leading and ending spaces of tv wish Log.Debug("(before removing spaces: mywish.searchfor="+mywish.searchfor); if (mywish.searchfor.Length > 0) { while (mywish.searchfor[0] == ' ') { mywish.searchfor = mywish.searchfor.Substring(1, mywish.searchfor.Length - 1); if (mywish.searchfor.Length == 0) break; } while (mywish.searchfor[mywish.searchfor.Length - 1] == ' ') { mywish.searchfor = mywish.searchfor.Substring(0, mywish.searchfor.Length - 1); if (mywish.searchfor.Length == 0) break; } } Log.Debug("(after removing spaces: mywish.searchfor=" + mywish.searchfor); //search for recordings and add messages only in email mode DateTime start = DateTime.Now; //DEBUG PERFORMANCE if (VIEW_ONLY_MODE == false) //recording first to identify existing recordings SqlQueryRecordings(mywish, i); DateTime end = DateTime.Now; //DEBUG PERFORMANCE Log.Debug("SQL query recordings time=" + end.Subtract(start).TotalSeconds.ToString()); //DEBUG PERFORMANCE //search for schedules start = DateTime.Now; //DEBUG PERFORMANCE SqlQueryPrograms(ref mywish, i); end = DateTime.Now; //DEBUG PERFORMANCE Log.Debug("SQL query programs time=" + end.Subtract(start).TotalSeconds.ToString()); //DEBUG PERFORMANCE myTvWishes.ReplaceAtIndex(i, mywish); /* if (DEBUG) { Log.Debug("After Query:"); myTvWishes.DebugTvWish(mywish); }*/ } //end all Tvwishes //check for remaining schedule conflicts #if(TV11 || TV12) //only for 1.1 final IList<Schedule> allschedules = Schedule.ListAll(); IList<Card> cards = Card.ListAll(); // initialize conflicting schedules and assign all existing schedules to cards List<Schedule> conflicts = new List<Schedule>(); if (cards.Count != 0) { //LogDebug("GetConflictingSchedules: Cards.Count =" + cards.Count.ToString(), (int)LogSetting.DEBUG); #if (!MPTV2) List<Schedule>[] cardSchedules = new List<Schedule>[cards.Count]; for (int i = 0; i < cards.Count; i++) { cardSchedules[i] = new List<Schedule>(); } Schedule overlappingSchedule = null; #endif bool ok = false; Log.Debug("allschedules.count=" + allschedules.Count.ToString()); foreach (Schedule oneschedule in allschedules) { #if (MPTV2) if (Schedule.GetConflictingSchedules(oneschedule).Count > 0) { ok = false; } else { ok = true; } Log.Debug("ok="+ok.ToString()); /* Mediaportal.TV.Server.TVDatabase.Entities.Schedule onerawschedule = ServiceAgents.Instance.ScheduleServiceAgent.GetSchedule(oneschedule.IdSchedule); List<Mediaportal.TV.Server.TVDatabase.Entities.Schedule> notViewableSchedules = new List<Mediaportal.TV.Server.TVDatabase.Entities.Schedule>(); ServiceAgents.Instance.ScheduleServiceAgent.GetConflictingSchedules(onerawschedule, out notViewableSchedules); try { if (notViewableSchedules.Count > 0) { ok = false; } else { ok = true; } } catch { ok = false; }*/ #elif(TV110) //mylayer.GetConflictingSchedules(schedule, out conflictingSchedules, out notViewableSchedules); IList<Schedule> local_conflicts = GetConflictingSchedules(oneschedule); try { if (local_conflicts.Count > 0) ok = false; else ok = true; } catch { ok = false; } #else ok = AssignSchedulesToCard(oneschedule, cardSchedules, out overlappingSchedule, DEBUG); //overlappingSchedule not used #endif if (ok == false)//conflict exists { LogDebug("", (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); message = lng.TranslateString("Schedule conflict must be manually resolved",54); LogDebug(message, (int)LogSetting.INFO); LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); outputscheduletoresponse(oneschedule, (int)LogSetting.INFO); LogDebug("", (int)LogSetting.INFO); mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.MANUAL_CONFLICT, "-1", string.Empty); //Bug -1 } } } #endif //enable html email format if ((mymessage.EmailFormat.StartsWith("USE_HTML")) && (mymessage.EmailFormat.Length > 7)) { mymessage.EmailFormat = mymessage.EmailFormat.Substring(8); HtmlFormat = true; } else { HtmlFormat = false; } //Send all reply mails //update messages was done at the beginning mymessage.sortmessages(_sort, _descendingsort); mymessage.filtermessages(_filter_email, false, _filter_conflicts, _filter_scheduled, false, false, false); // old: mymessage.filtermessages(_filter_email,_filter_scheduled,_filter_conflicts,false,false,false); RESPONSE = mymessage.emailmessages(_emailonlynew); //store modified listviewdata and messages back //update counters before saving data myTvWishes.UpdateCounters(mymessage.ListAllTvMessages()); //log messages mymessage.logmessages(); string listviewstring = myTvWishes.SaveToString(); //mymessage.logmessages(); //DEBUGONLY string dataString = mymessage.writexmlfile(false); //write xml file to string //LogDebug("Updated listview string: \n" + listviewstring, (int)LogSetting.DEBUG); if (VIEW_ONLY_MODE == true) { myTvWishes.save_longsetting(listviewstring, "TvWishList_OnlyView"); //do never modify keywords must match MP plugin myTvWishes.save_longsetting(dataString, "TvWishList_OnlyViewMessages"); } else { myTvWishes.save_longsetting(listviewstring, "TvWishList_ListView"); //do never modify keywords must match MP plugin myTvWishes.save_longsetting(dataString, "TvWishList_ListViewMessages"); } Log.Debug("RESPONSE="+RESPONSE); if ((_emailreply == true) && (RESPONSE != "") && (VIEW_ONLY_MODE == false)) { languagetext = lng.TranslateString("Sending email to {0}", 7, s_receiver); LogDebug(languagetext, (int)LogSetting.DEBUG); labelmessage(languagetext, PipeCommands.StartEpg); // build the email message /* LogDebug("_TextBoxSmtpServer " + _TextBoxSmtpServer, (int)LogSetting.DEBUG); LogDebug("_TextBoxUserName " + _TextBoxUserName, (int)LogSetting.DEBUG); LogDebug("_TextBoxPassword " + _TextBoxPassword, (int)LogSetting.DEBUG); LogDebug("_numericUpDownSmtpPort " + _numericUpDownSmtpPort.ToString(), (int)LogSetting.DEBUG); LogDebug("_checkBoxSSL " + _checkBoxSSL.ToString(), (int)LogSetting.DEBUG);*/ if (_TextBoxSmtpServer == "") { LogDebug("Error: No Smtp Server defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: No Smtp Server defined", 8); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } /* if ((_TextBoxUserName == "") && (_useCredentials)) { LogDebug("Error: No user name defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: No user name defined", 9); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } if ((_TextBoxPassword == "")&& (_useCredentials)) { LogDebug("Error: No password defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: No password defined", 10); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; }*/ if (_TextBoxSmtpEmailAddress == "") { _TextBoxSmtpEmailAddress = _TextBoxUserName; } if (s_receiver == "") { LogDebug("Error: No receiver emailaddress defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: No receiver emailaddress defined", 11); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } //load last settings and store it in providerstring [0] setting = layer.GetSetting("TvWishList_Providers_0", "_Last Setting;;0;False;False;;0;False"); string[] array = setting.Value.Split(";".ToCharArray()); if (array.Length != 4) { LogDebug("TvWishList Error: Invalid provider string: " + setting.Value + "\n Count is " + array.Length, (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: Invalid provider settings", 12); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } string ServerAddress = array[1]; if (ServerAddress == "") { LogDebug("Server address not specified - aborting email check", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: Server address not specified", 13); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } //wait for internet connection bool InternetConnected = false; for (int i = 1; i < 30; i++) //wait up to 300s and check every 10s { System.Threading.Thread.Sleep(10000); //sleep 10s to wait for internet connection after standby //check for existing ip address try { IPHostEntry hostIP = Dns.GetHostEntry(ServerAddress); IPAddress[] addr = hostIP.AddressList; LogDebug("POP3 Server exists", (int)LogSetting.DEBUG); InternetConnected = true; break; } catch {//continue loop LogDebug("Waiting for internet connection in iteration " + i.ToString(), (int)LogSetting.DEBUG); } } if (InternetConnected == false) { LogDebug("Failed to get internet connection", (int)LogSetting.DEBUG); languagetext = lng.TranslateString("Error: Failed to get internet connection to POP3 server", 14); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } int smtpport = 0; try { smtpport = Convert.ToInt32(_numericUpDownSmtpPort); } catch { smtpport = 0; } if (smtpport == 0) { LogDebug("Error: No smtp port defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: No smtp port defined", 15); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } LogDebug("_TextBoxSmtpServer:" + _TextBoxSmtpServer, (int)LogSetting.DEBUG); LogDebug("smtpport:" + smtpport, (int)LogSetting.DEBUG); LogDebug("_checkBoxSSL:" + _checkBoxSSL.ToString(), (int)LogSetting.DEBUG); LogDebug("_TextBoxUserName:"******"_TextBoxSmtpEmailAddress:" + _TextBoxSmtpEmailAddress, (int)LogSetting.DEBUG); SendTvServerEmail sendobject = new SendTvServerEmail(_TextBoxSmtpServer, smtpport, _checkBoxSSL, _TextBoxUserName, _TextBoxPassword, _TextBoxSmtpEmailAddress); sendobject.Debug = DEBUG; sendobject.HtmlFormat = HtmlFormat; LogDebug("Send reply mail to " + s_receiver + " at " + DateTime.Now.ToString(), (int)LogSetting.DEBUG); LogDebug("Subject:" + s_subject, (int)LogSetting.DEBUG); LogDebug(RESPONSE, (int)LogSetting.DEBUG); LogDebug("End of mail", (int)LogSetting.DEBUG); bool ok = sendobject.SendNewEmail(s_receiver, s_subject, RESPONSE); if (ok == true) { LogDebug("Sending return emails completed", (int)LogSetting.DEBUG); //System.Threading.Thread.Sleep(2000); //wait 2s languagetext = lng.TranslateString("Sending return emails completed", 16); labelmessage(languagetext, PipeCommands.StartEpg); } else { if (_TextBoxUserName == string.Empty) { LogDebug("Sending return emails failed - check the username", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: Sending return emails failed - check the username", 17); labelmessage(languagetext, PipeCommands.Error); } else if (_TextBoxPassword == string.Empty) { LogDebug("Sending return emails failed - check the password", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: Sending return emails failed - check the password", 18); labelmessage(languagetext, PipeCommands.Error); } else { LogDebug("Sending return emails failed", (int)LogSetting.ERROR); languagetext = lng.TranslateString("Error: Sending return emails failed", 19); labelmessage(languagetext, PipeCommands.Error); } SearchEpgExit(); //includes setting BUSY = false; return false; } } //System.Threading.Thread.Sleep(2000); //wait 2s languagetext = lng.TranslateString("Ready", 20); labelmessage(languagetext, PipeCommands.Ready); Log.Info("SearchEPG ended successfully"); } catch (Exception exc) { Log.Error("Error:Exception in SearchEPG: "+exc.Message); string languagetext = lng.TranslateString("Fatal error - check the log file",24 ); labelmessage(languagetext, PipeCommands.Error); SearchEpgExit(); //includes setting BUSY = false; return false; } SearchEpgExit(); //includes setting BUSY = false; return true; }
private void mpComboBoxCard_SelectedIndexChanged(object sender, EventArgs e) { //DatabaseManager.Instance.SaveChanges(); mpListViewChannels.BeginUpdate(); mpListViewMapped.BeginUpdate(); try { mpListViewMapped.Items.Clear(); mpListViewChannels.Items.Clear(); SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(Channel)); sb.AddOrderByField(true, "sortOrder"); SqlStatement stmt = sb.GetStatement(true); IList <Channel> channels = ObjectFactory.GetCollection <Channel>(stmt.Execute()); Card card = ((CardInfo)mpComboBoxCard.SelectedItem).Card; IList <ChannelMap> maps = card.ReferringChannelMap(); // get cardtype, dvb, analogue etc. CardType cardType = RemoteControl.Instance.Type(card.IdCard); //Card card = Card.Retrieve(card.IdCard); TvBusinessLayer layer = new TvBusinessLayer(); bool enableDVBS2 = (layer.GetSetting("dvbs" + card.IdCard + "enabledvbs2", "false").Value == "true"); List <ListViewItem> items = new List <ListViewItem>(); foreach (ChannelMap map in maps) { Channel channel = null; try { channel = map.ReferencedChannel(); } catch (Exception) {} if (channel == null) { continue; } if (channel.IsTv == false) { continue; } List <TuningDetail> tuningDetails = GetTuningDetailsByCardType(channel, cardType, enableDVBS2); bool foundValidTuningDetail = tuningDetails.Count > 0; if (foundValidTuningDetail) { int imageIndex = GetImageIndex(tuningDetails); string displayName = channel.DisplayName; if (map.EpgOnly) { displayName = channel.DisplayName + " (EPG Only)"; } ListViewItem item = new ListViewItem(displayName, imageIndex); item.Tag = map; items.Add(item); foreach (Channel ch in channels) { if (ch.IdChannel == channel.IdChannel) { //No risk of concurrent modification so remove it directly. channels.Remove(ch); break; } } } else { map.Delete(); } } mpListViewMapped.Items.AddRange(items.ToArray()); items = new List <ListViewItem>(); foreach (Channel channel in channels) { if (channel.IsTv == false) { continue; } List <TuningDetail> tuningDetails = GetTuningDetailsByCardType(channel, cardType, enableDVBS2); // only add channel that is tuneable on the device selected. bool foundValidTuningDetail = tuningDetails.Count > 0; if (foundValidTuningDetail) { int imageIndex = GetImageIndex(tuningDetails); ListViewItem item = new ListViewItem(channel.DisplayName, imageIndex); item.Tag = channel; items.Add(item); } } mpListViewChannels.Items.AddRange(items.ToArray()); mpListViewChannels.Sort(); } finally { mpListViewChannels.EndUpdate(); mpListViewMapped.EndUpdate(); } }
private void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) { try { Logdebug("SystemEvents_PowerModeChanged =" + e.Mode.ToString()); if (e.Mode == PowerModes.Suspend) { Logdebug("SystemEvents Suspend"); if (receivethread != null) { try { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; setting = layer.GetSetting("TvWishList_NextEpgDate", DateTime.Now.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture)); setting.Value = _PreviousEpgTime.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Logdebug("TvWishList_NextEpgDate=" + setting.Value); setting.Persist(); } catch (Exception exc) { Log.Error("Error in writing old epg time"); Log.Error(exc.Message); } Log.Error("Aborting receive thread because of system standby event"); receivethread.Abort(); //resetting next epg date _NextEpgTime = _PreviousEpgTime; Logdebug("TVSERVER TvWishList: Setting NextEpgTime =" + _NextEpgTime.ToString()); /* //writing file try { string[] all_lines = new string[] { _PreviousEpgTime.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture) }; File.WriteAllLines(TV_USER_FOLDER + @"\TvWishList\NextEPG.txt", all_lines); } catch (Exception exc) { Logdebug("Error in writing old epg time file"); Log.Error("Error in writing old epg time file"); Log.Debug(exc.Message); Log.Error(exc.Message); }*/ } } else if (e.Mode == PowerModes.Resume) { Logdebug("SystemEvents Resume"); } else if (e.Mode == PowerModes.StatusChange) { Logdebug("SystemEvents Status Change"); } } catch (Exception exc) { Log.Error("SystemEvents_PowerModeChanged failed with exception message:"); Log.Error(exc.Message); } }
public void epgwatch() { try { Logdebug("Epg watching started"); //get new updated value for next epg check TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; // get DEBUG setting = layer.GetSetting("TvWishList_Debug", "false"); DEBUG = false; Boolean.TryParse(setting.Value, out DEBUG); Log.DebugValue = DEBUG; _NextEpgTime = NextEpgTime(); Log.Debug("epgwatch(): _NextEpgTime=" + _NextEpgTime.ToString()); //////////////////////////////////////////////// //start epgprocessing here if (epgwatchclass == null) { Log.Error("EpgParser could not be initiated - aborting operation"); return; } else { try { epgwatchclass.SearchEPG(false); //Email & Record } catch (Exception exc) { Log.Error("Parsing EPG data failed with exception message:"); Log.Error(exc.Message); // Reset BUSY Flag after exception //set BUSY = false setting = layer.GetSetting("TvWishList_BUSY", "false"); setting.Value = "false"; setting.Persist(); } } } catch (Exception exc) { Log.Error("epgwatch failed with exception message:"); Log.Error(exc.Message); } }
private void ProcessFileRenaming() { if (_ProcessFileRenamingRunning == true) { Log.Debug("Old ProcessFileRenaming is running - returning thread"); return; } _ProcessFileRenamingRunning = true; string filename = TV_USER_FOLDER + @"\TvWishList\" + FileRenameXML; Logdebug("Starting ProcessFileRenaming - file=" + filename); //process file renaming from xml file if (File.Exists(filename) == false) { Logdebug("Could not find jobfile " + filename); _ProcessFileRenamingRunning = false; return; } TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; //wait for comskip to finish setting = layer.GetSetting("TvWishList_WaitComSkipMinutes", "60"); try { int i = Convert.ToInt32(setting.Value); ComSkipMaxWait = i; } catch { ComSkipMaxWait = 60; } Log.Debug("ComSkipMaxWait=" + ComSkipMaxWait.ToString()); System.Threading.Thread.Sleep(10000);//sleep 10s Process[] sprocs1 = Process.GetProcessesByName(ProcessName1); if (sprocs1.Length > 0) { sprocs1[0].WaitForExit(60000 * ComSkipMaxWait); //wait 60s * ComSkipMaxWait if (sprocs1[0].HasExited) { Log.Debug("Process " + ProcessName1 + " has been finished"); } else { Log.Error("Process " + ProcessName1 + " did not finish"); } } else { Log.Debug("Process " + ProcessName1 + " does not exist"); } System.Threading.Thread.Sleep(10000);//sleep 10s Process[] sprocs2 = Process.GetProcessesByName(ProcessName2); if (sprocs2.Length > 0) { sprocs2[0].WaitForExit(60000 * ComSkipMaxWait); //wait 60s * MaxWait if (sprocs2[0].HasExited) { Log.Debug("Process " + ProcessName2 + " has been finished"); } else { Log.Error("Process " + ProcessName2 + " did not finish"); } } else { Log.Debug("Process " + ProcessName2 + " does not exist"); } System.Threading.Thread.Sleep(10000);//sleep 10s Log.Debug("read xml file"); //read xml file XmlDocument renamexmldoc = new XmlDocument(); try { renamexmldoc.Load(filename); XmlNode root = renamexmldoc.DocumentElement; XmlNodeList nodealljobs = renamexmldoc.SelectNodes("/AllJobs/Job"); Log.Debug("Reading Nodes"); #if(TV100) IList allrecordings = Recording.ListAll(); #elif(TV101) IList<Recording> allrecordings = Recording.ListAll(); #elif((TV11)||(TV12)) IList<Recording> allrecordings = Recording.ListAll(); #endif foreach (XmlNode nodejob in nodealljobs) { //get xml node string programname = nodejob.Attributes["ScheduleName"].Value; Log.Debug("programname=" + programname); string folder = nodejob.Attributes["Folder"].Value; Log.Debug("folder=" + folder); DateTime startTime = DateTime.ParseExact(nodejob.Attributes["Start"].Value, "yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture); Logdebug("startTime =" + startTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture)); DateTime endTime = DateTime.ParseExact(nodejob.Attributes["End"].Value, "yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture); Logdebug("endTime =" + endTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture)); int channelid = -1; int.TryParse(nodejob.Attributes["idChannel"].Value, out channelid); Logdebug("channelid =" + channelid.ToString()); bool nodeExists = true; //search all my recordings for match foreach (Recording myrecording in allrecordings) { if (myrecording.StartTime == myrecording.EndTime) {//during recording the start time will be equal to the end time and text all in capitol letters - in that case ignore and wait till recording is finished - schedule does exist in parallel during recording continue; } string myrecording_startstring = myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture); DateTime myrecording_start = DateTime.ParseExact(myrecording_startstring, "yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture); //Logdebug("myrecording_startTime =" + myrecording_start.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture)); string myrecording_endstring = myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture); DateTime myrecording_end = DateTime.ParseExact(myrecording_endstring, "yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture); //Logdebug("myrecording_endTime =" + myrecording_end.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture)); if ((startTime == myrecording_start) && (endTime == myrecording_end) && (channelid == myrecording.IdChannel) && (File.Exists(myrecording.FileName) == true)) { //xml list entry has been recorded and matches start, end time and channel id Logdebug("Recording matched for " + programname); //rename filenames and update recording with new location string directory = System.IO.Path.GetDirectoryName(myrecording.FileName); //valid directory string filenameNoExtension = System.IO.Path.GetFileNameWithoutExtension(myrecording.FileName); //valid filename without extension char[] invalidPathChars = Path.GetInvalidPathChars(); for (int i = 0; i < invalidPathChars.Length; i++) { folder = folder.Replace(invalidPathChars[i], '_'); //valid subdirectory name after replacement } string newname = directory + @"\" + folder + @"\" + filenameNoExtension + ".ts"; if (Directory.Exists(directory + @"\" + folder) == false) { Log.Debug("Creating directory " + directory + @"\" + folder); Directory.CreateDirectory(directory + @"\" + folder); } if (File.Exists(newname) == false) { Logdebug("Moving " + myrecording.FileName + " to " + newname); File.Move(myrecording.FileName, newname); String xmlfilename = myrecording.FileName.Substring(0, myrecording.FileName.Length - 2) + "xml"; //substitute .ts by .xml if (File.Exists(xmlfilename) == true) { String newxmlfilename = directory + @"\" + folder + @"\" + filenameNoExtension + ".xml"; //bug in older version File.Move(xmlfilename, newxmlfilename); Logdebug("Moving " + xmlfilename + " to " + newxmlfilename); } //update recording file name myrecording.FileName = newname; myrecording.Persist(); //move other comskip files as well string[] morefiles = Directory.GetFiles(directory, filenameNoExtension + "*"); foreach (string singlefile in morefiles) { string shortname=System.IO.Path.GetFileName(singlefile); string newfilename = directory + @"\" + folder + @"\" + shortname; if (File.Exists(newfilename) == false) { Logdebug("Moving " + singlefile + " to " + newfilename); File.Move(singlefile, newfilename); } else { Log.Error("file " + singlefile + " does exist already - will not move file"); } } //removing node after successful completion root.RemoveChild(nodejob); Logdebug("Removing childnode after successful renaming for " + programname); nodeExists = false; } else { Log.Error("file " + newname + " does exist already - will not move file"); } break; } }//end all recordings endTime = endTime.AddDays(1.0); //add one day to make sure recordings are completed including postprocessing if ((DateTime.Now > endTime)&&(nodeExists)) { root.RemoveChild(nodejob); Logdebug("Removing childnode due to timeout for " + programname); } } renamexmldoc.Save(filename); if (root.HasChildNodes == false) { File.Delete(filename); Log.Debug("Deleting xml file as there are no entries"); } } catch (Exception ee) { Log.Error("ProcessFileRenaming failed with exception message:"); Log.Error(ee.Message); } Log.Debug("ProcessFileRenaming completed"); _ProcessFileRenamingRunning = false; }
private void LoadFromTvServer() {//load TvwishlistFolder and file namesfrom TvServer TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; setting = layer.GetSetting("TvWishList_MachineName", "NONE"); HostComputer = setting.Value; //load Tvserver Version setting = layer.GetSetting("TvWishList_TvServerVersion", "0.0.0.0"); TvVersion = setting.Value; /*//TV_PROGRAM_FOLDER setting = layer.GetSetting("TvWishList_TV_PROGRAM_FOLDER", "NOT_DEFINED"); TV_PROGRAM_FOLDER = setting.Value;*/ }
public bool save_longsetting(string mystring, string mysetting) { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; int STRINGLIMIT = 4000; //is 4096 string limit for settings - split if larger // tell TvWishCreator setting = layer.GetSetting("TvWishList_TvWishDataCreator", "0.0.0.0"); if (setting.Value != _DataLoadedBy) { Log.Error("Fatal data consistency error: Data have been loaded by " + _DataLoadedBy + " and were overwritten by " + setting.Value+" will overwrite again!"); } setting.Value = _LockingPluginname;//new data created now _DataLoadedBy = _LockingPluginname; setting.Persist(); // tell TvWish Version setting = layer.GetSetting("TvWishList_TvWishVersion", "0.0.0.0"); setting.Value = TvWishVersion(); setting.Persist(); #if (MP2) //send pipe command for speeding up savesettings string response = string.Empty; string command = Main_GUI.PipeCommands.RemoveLongSetting.ToString() + mysetting + ":10"; Log.Debug("command=" + command); for (int i = 1; i < 120; i++) { response = PipeClient.Instance.RunSingleCommand(command); if (response == PluginGuiLocalizeStrings.Get(1200)) //Waiting for old process to finish { Log.Debug("Waiting for old process to finish"); Thread.Sleep(1000); } else { break; } } Log.Debug("Server response=" + response); if (response.StartsWith("Error") ) {//error occured Log.Error("Error in pipecommand response="+response); } #elif(MPTV2) //Log.Debug("TvWishListSetup.Setup=" + TvWishListSetup.Setup.ToString()); Log.Debug("TvSetup = " + TvSetup.ToString()); if (TvSetup) {// Command comes from setup form as TvWishList setup is activated //send pipe command for speeding up savesettings string response = string.Empty; string command = PipeCommands.RemoveLongSetting.ToString() + mysetting + ":10"; Log.Debug("command=" + command); for (int i = 1; i < 120; i++) { response = PipeClient.Instance.RunSingleCommand(command); if (response == PluginGuiLocalizeStrings.Get(1200)) //Waiting for old process to finish { Log.Debug("Waiting for old process to finish"); Thread.Sleep(1000); } else { break; } } Log.Debug("Server response=" + response); if (response.StartsWith("Error")) {//error occured Log.Error("Error in pipecommand response=" + response); } } else //command comes from tvserver as TvWishList setup is deactivated { Setting.DeleteSettings(mysetting); } #else //cleanup work for (int i = 1; i < 1000; i++) { setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_"); Log.Debug("save_longsetting setting=" + setting.Value); if (setting.Value == "_DOES_NOT_EXIST_") { setting.Remove(); break; } else { string value = setting.Value; setting.Remove(); //if (value == string.Empty) was needed for MP2 only before pipecommand // break; //will be cleaned up later by tv server } } #endif // split string if too large !!! Limit of 4096 characters in tv server try { if (mystring.Length > STRINGLIMIT) { string partial_string = mystring.Substring(0, STRINGLIMIT); setting = layer.GetSetting(mysetting, ""); setting.Value = partial_string; //LogDebug("partial string " + mysetting + " =" + partial_string, (int)LogSetting.DEBUG); setting.Persist(); int ctr = 1; while (ctr * STRINGLIMIT <= mystring.Length) { if ((ctr + 1) * STRINGLIMIT < mystring.Length) { partial_string = mystring.Substring(ctr * STRINGLIMIT, STRINGLIMIT); setting = layer.GetSetting(mysetting + "_" + ctr.ToString("D3"), ""); setting.Value = partial_string; //LogDebug("partial string " + mysetting + "_" + ctr.ToString("D3") + " =" + partial_string, (int)LogSetting.DEBUG); setting.Persist(); } else { partial_string = mystring.Substring(ctr * STRINGLIMIT, mystring.Length - ctr * STRINGLIMIT); setting = layer.GetSetting(mysetting + "_" + ctr.ToString("D3"), ""); setting.Value = partial_string; //LogDebug("partial listviewstring " + mysetting + "_" + ctr.ToString("D3") + " =" + partial_string, (int)LogSetting.DEBUG); setting.Persist(); ctr++; setting = layer.GetSetting(mysetting + "_" + ctr.ToString("D3"), ""); setting.Value = ""; setting.Persist(); } ctr++; if (ctr > 999) { Log.Debug("!!!!!!!!!!!!!!!!!!!! Fatal Error: Too many data entries - skipping data", (int)LogSetting.ERROR); break; } } } else //do not split string - small enough { setting = layer.GetSetting(mysetting, ""); setting.Value = mystring; setting.Persist(); int ctr = 1; //LogDebug("string " + mysetting + "=" + mystring, (int)LogSetting.DEBUG); setting = layer.GetSetting(mysetting + "_" + ctr.ToString("D3"), ""); //needed for detecting in loadlongsettings setting.Value = ""; setting.Persist(); } return true; } catch (Exception exc) { Log.Debug("Adding long setting failed with message \n" + exc.Message, (int)LogSetting.ERROR); return false; } }
public string loadlongsettings(string name) { //splits long setting strings in multiple parts TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; // tell TvWishCreator setting = layer.GetSetting("TvWishList_TvWishDataCreator", "0.0.0.0"); _DataLoadedBy = setting.Value; //LogDebug("Longsetting TvWishList_ListView", (int)LogSetting.DEBUG); string stringdata = layer.GetSetting(name, "").Value; //LogDebug("listviewdata TvWishList_ListView=" + listviewdata, (int)LogSetting.DEBUG); int count = 1; string partial = layer.GetSetting(name + "_" + count.ToString("D3"), "").Value; //LogDebug("partial " + "TvWishList_ListView_" + count.ToString("D3") + "=" + partial, (int)LogSetting.DEBUG); while (partial != "") { stringdata += partial; count++; partial = layer.GetSetting(name + "_" + count.ToString("D3"), "").Value; //LogDebug("partial " + name + "_" + count.ToString("D3") + "=" + partial, (int)LogSetting.DEBUG); } //LogDebug("Merged" + "TvWishList_ListView Length =" + listviewdata.Length.ToString(), (int)LogSetting.DEBUG); //LogDebug("Merged" + "TvWishList_ListView =" + listviewdata, (int)LogSetting.DEBUG); return stringdata; }
public override void OnSectionActivated() { //set Debug flag first TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; setting = layer.GetSetting("TvWishList_Debug", "false"); DEBUG = false; Boolean.TryParse(setting.Value, out DEBUG); checkBoxDebug.Checked = DEBUG; Log.DebugValue = DEBUG; //turn on setup flag _setup = true; LogDebug("TvWishList: Configuration activated", (int)LogSetting.DEBUG); if (epgwatchclass != null) { epgwatchclass.newlabelmessage += new setuplabelmessage(labelupdate); } #if (MPTV2) if (tvSetupPipeClient != null) { tvSetupPipeClient.newlabelmessage += new setupPipeLabelMessage(labelupdate); } #endif //dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded); // set actual groups from TV server DataGridViewComboBoxColumn mygroupcomboxcolumn = dataGridView1.Columns[3] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn mypreferredgroupcomboxcolumn = dataGridView1.Columns[34] as DataGridViewComboBoxColumn; //LogDebug("2) Group Item Count=" + mygroupcomboxcolumn.Items.Count.ToString(), (int)LogSetting.DEBUG); if (mygroupcomboxcolumn.Items.Count == 1) { foreach (ChannelGroup channelgroup in ChannelGroup.ListAll()) { if (channelgroup.GroupName != "All Channels") { mygroupcomboxcolumn.Items.AddRange(new object[] { channelgroup.GroupName }); mypreferredgroupcomboxcolumn.Items.AddRange(new object[] { channelgroup.GroupName }); } } foreach (RadioChannelGroup radiochannelgroup in RadioChannelGroup.ListAll()) { if (radiochannelgroup.GroupName != "All Channels") { mygroupcomboxcolumn.Items.AddRange(new object[] { radiochannelgroup.GroupName }); mypreferredgroupcomboxcolumn.Items.AddRange(new object[] { radiochannelgroup.GroupName }); } } } //channel group drop box at the bottom of the GUI if (comboBoxGroups.Items.Count == 1) { foreach (ChannelGroup channelgroup in ChannelGroup.ListAll()) { if (channelgroup.GroupName != "All Channels") { comboBoxGroups.Items.AddRange(new object[] { channelgroup.GroupName }); } } foreach (RadioChannelGroup radiochannelgroup in RadioChannelGroup.ListAll()) { if (radiochannelgroup.GroupName != "All Channels") { comboBoxGroups.Items.AddRange(new object[] { radiochannelgroup.GroupName }); } } } //LogDebug("3)After Group Item Count=" + mygroupcomboxcolumn.Items.Count.ToString(), (int)LogSetting.DEBUG); //dataGridView1.Columns.RemoveAt(3); //dataGridView1.Columns.Insert(3, mygroupcomboxcolumn); //set tv cards #if(TV100) IList cards = Card.ListAll(); #elif(TV101) IList<Card> cards = Card.ListAll(); #elif(TV11) IList<Card> cards = Card.ListAll(); #elif(TV12) IList<Card> cards = Card.ListAll(); #endif DataGridViewComboBoxColumn mycomboxcolumn = dataGridView1.Columns[16] as DataGridViewComboBoxColumn; //LogDebug("Card Item Count=" + mycomboxcolumn.Items.Count.ToString(), (int)LogSetting.DEBUG); if (mycomboxcolumn.Items.Count == 1) { foreach (Card card in cards) { mycomboxcolumn.Items.AddRange(new object[] { card.IdCard.ToString() }); } } SetupLanguages(); //must come before loadsettings try { //***************************************************** //Lock TvWishList with timeout error bool success = false; //int seconds = 60; success = myTvWishes.LockTvWishList("TvWishList Setup"); if (!success) { setting = layer.GetSetting("TvWishList_LockingPluginname", "Not Defined"); MessageBox.Show(lng.TranslateString("Waiting for old jobs to finish from\n" + setting.Value + "\nTry again later\nIf jobs do not finish you have to reboot or manually stop the Tvserver", 250, setting.Value), lng.TranslateString("Closing Tv Configuration",251)); Log.Debug("Waiting for old jobs to finish from\n" + setting.Value + "\nTry again later\nIf jobs do not finish you have to reboot or manually stop the Tvserver"); Application.Exit(); //application is not closing immediately!! return; } MyLoadSettings(); //enable SetupTV process filewatcher loop after locking string filename = TV_USER_FOLDER + @"\TvWishList\SetupTvStarted.txt"; Log.Debug("trying to create file "+filename); if (!File.Exists(filename)) { try { File.WriteAllText(filename, "SetupTvStarted"); Log.Debug("file created"); } catch (Exception ex) { LogDebug("Fatal Error: Failed to delete file " + filename + " - exception message is\n" + ex.Message, (int)LogSetting.ERROR); } } } catch (Exception ex) { LogDebug("Fatal Error: Failed to load settings - exception message is\n" + ex.Message, (int)LogSetting.ERROR); LogDebug("Trying to resave settings to data base", (int)LogSetting.ERROR); try { MySaveSettings(); LogDebug("Saving settings succeeded", (int)LogSetting.ERROR); } catch { LogDebug("Fatal Error: Faileed to save settings", (int)LogSetting.ERROR); } } //language file drop box Log.Debug("start comboBoxLanguage.Items.Count="+comboBoxLanguage.Items.Count.ToString()); comboBoxLanguage.Items.Clear(); string languageFolder = TV_USER_FOLDER + @"\TvWishList\Languages"; if (Directory.Exists(languageFolder) == false) { Log.Error("language folder " + languageFolder + " does not exist"); comboBoxLanguage.Items.Add("Error: No Language files found"); } else { try { DirectoryInfo dirinfo = new DirectoryInfo(languageFolder); FileInfo[] allfiles = dirinfo.GetFiles("string*.xml"); ReverseLanguageFileTranslator_File = new string[allfiles.Length]; ReverseLanguageFileTranslator_Language = new string[allfiles.Length]; int ctr = 0; foreach (FileInfo myfileinfo in allfiles) { ReverseLanguageFileTranslator_File[ctr] = myfileinfo.Name; ReverseLanguageFileTranslator_Language[ctr] = LanguageFileTranslation(myfileinfo.Name); comboBoxLanguage.Items.Add(ReverseLanguageFileTranslator_Language[ctr]); ctr++; } } catch (Exception exc) { Log.Error("ProcessFolder Exception: " + exc.Message); } } Log.Debug("end comboBoxLanguage.Items.Count=" + comboBoxLanguage.Items.Count.ToString()); base.OnSectionActivated(); }
public bool ReadLanguageFile() { Log.Debug("ReadLanguageFile started"); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_DEFINED"); string TV_USER_FOLDER; TV_USER_FOLDER = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND").Value; if ((File.Exists(TV_USER_FOLDER + @"\TvService.exe") == true) || (Directory.Exists(TV_USER_FOLDER) == false)) { //autodetect paths InstallPaths instpaths = new InstallPaths(); //define new instance for folder detection #if (MPTV2) //Native MP2 Tv server instpaths.GetInstallPathsMP2(); TV_USER_FOLDER = instpaths.TV2_USER_FOLDER; #else instpaths.GetInstallPaths(); TV_USER_FOLDER = instpaths.TV_USER_FOLDER; #endif Log.Debug("TV server user folder detected at " + TV_USER_FOLDER); if ((File.Exists(TV_USER_FOLDER + @"\TvService.exe") == true) || (Directory.Exists(TV_USER_FOLDER) == false)) { Log.Error(@" TV server user folder does not exist - using C:\MediaPortal\TvWishList"); Log.Debug(@" TV server user folder does not exist - using C:\MediaPortal\TvWishList"); TV_USER_FOLDER = @"C:\MediaPortal"; if (Directory.Exists(TV_USER_FOLDER) == false) Directory.CreateDirectory(TV_USER_FOLDER + @"\TvWishList"); } else {//store found TV_USER_FOLDER setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND"); setting.Value = TV_USER_FOLDER; setting.Persist(); } } if (Directory.Exists(setting.Value) == false) { Log.Error("Error: TV User Folder is not defined - cannot use language file"); return false; } string foldername = setting.Value + @"\TvWishList\Languages\"; setting = layer.GetSetting("TvWishList_LanguageFile", "strings_en.xml"); string filename = foldername + setting.Value; if (File.Exists(filename) == false) { Log.Error("Could not find language file " + filename); filename = foldername + "strings_en.xml"; Log.Error("Switching to English default language file " + filename); } Log.Debug("Language file is " + filename); try { //read inputfile string[] inputlines = File.ReadAllLines(filename); Log.Debug(inputlines.Length.ToString()+" Lines read"); int minimum = 0; int maximum = 0; int offset = 0; int offsetMinimum = 0; int offsetMaximum = 0; //process each line foreach (string line in inputlines) { string myline = line.Replace("\t", string.Empty); //replace tab //global replacements if ((myline.Contains("<!-- TVSERVER VECTORSIZE="))||(myline.Contains("<!--TVSERVER VECTORSIZE="))) { myline = myline.Replace("<!-- TVSERVER VECTORSIZE=", string.Empty); myline = myline.Replace("<!--TVSERVER VECTORSIZE=", string.Empty); myline = myline.Replace("-->", string.Empty); int size = 0; int.TryParse(myline, out size); Log.Debug("size = " + size.ToString()); Language = new string[size]; for (int i = 0; i < size; i++) { Language[i] = String.Empty; } //define at least true and false try { Language[4000] = "true"; Language[4001] = "false"; } catch //do nothing { Log.Error("Error in default initialization of true and false"); } } else if ((myline.Contains("<!-- TVSERVER USE FROM=")) || (myline.Contains("<!--TVSERVER USE FROM=")) ) { myline = myline.Replace("<!-- TVSERVER USE FROM=", string.Empty); myline = myline.Replace("<!--TVSERVER USE FROM=", string.Empty); myline = myline.Replace("-->", string.Empty); myline = myline.Replace("OFFSET_FROM=", "\n"); //order is important myline = myline.Replace("OFFSET_TO=", "\n"); myline = myline.Replace("TO=", "\n"); //myline = myline.Replace("OFFSET=", "\n"); string[] tokenarray = myline.Split('\n'); if (tokenarray.Length != 4) { Log.Error("Invalid tv server command " + line.Replace("{","_") + " - cannot use language files"); return false; } minimum = 0; int.TryParse(tokenarray[0], out minimum); Log.Debug(" new minimum=" + minimum.ToString()); maximum = 0; int.TryParse(tokenarray[1], out maximum); Log.Debug(" new maximum=" + maximum.ToString()); offsetMinimum = 0; int.TryParse(tokenarray[2], out offsetMinimum); Log.Debug(" new offsetMinimum=" + offsetMinimum.ToString()); offsetMaximum = 0; int.TryParse(tokenarray[3], out offsetMaximum); Log.Debug(" new offsetMaximum=" + offsetMaximum.ToString()); offset = minimum - offsetMinimum; Log.Debug(" new offset=" + offset.ToString()); } else if (myline.Contains("<String id=\"")) // <String id="1107">Mehr</String> { try { //remove leading spaces int leadingSpaces = 0; for (int i = 0; i < myline.Length; i++) { if (myline[i] == ' ') { leadingSpaces++; } else { break; } } //textoutput("leadingSpaces=" + leadingSpaces.ToString()); myline = myline.Substring(leadingSpaces, myline.Length - leadingSpaces);//remove leading spaces //remove trailing spaces int trailingSpaces = 0; for (int i = myline.Length - 1; i >= 0; i--) { if (myline[i] == ' ') { trailingSpaces++; } else { break; } } //textoutput("trailingSpaces=" + trailingSpaces.ToString()); myline = myline.Substring(0, myline.Length - trailingSpaces); myline = myline.Substring(12, myline.Length - 12); //remove beginning comment and <String id=" //now extract the numbers till the next " int digits = 0; for (int i = 0; i < myline.Length; i++) { if (myline[i] == '"') { break; } else { digits++; } } //Log.Debug("digits=" + digits.ToString()); string digitString = myline.Substring(0, digits); //Log.Debug("digitString=" + digitString); if (myline.Length >= digits) myline = myline.Substring(digits, myline.Length - digits); myline = myline.Replace("\">", ""); //remove ending myline = myline.Replace("</String>", ""); //remove ending string valueString = myline; //Debug //string output = valueString.Replace("{", "_"); //output = output.Replace("}", "_"); //Log.Debug("output ="+output); int number = 0; int.TryParse(digitString, out number); //Log.Debug("number=" + number.ToString()); if ((number >= minimum) && (number <= maximum)) { number = number - offset; Language[number] = valueString; //Debug //string output2 = Language[number].Replace("{", "_"); //output2 = output2.Replace("}", "_"); //Log.Debug("language[" + number.ToString() + "]=" + output2); } } catch (Exception exc) { string output = line.Replace("{", "_"); output = output.Replace("}", "_"); Log.Error("Error: could not read string " + output + " Exception was " + exc.Message); } }//end expression }//end foreach line } catch (Exception exc) { Log.Error("Error: could not read language file " + filename + " Exception was " + exc.Message); return false; } Log.Debug("Language file read"); return true; }
/// <summary> /// call this function before using an encoder to check /// whether it is possible to use it /// </summary> /// <param name="device">the encoder device</param> /// <param name="dbEncoder">the preferences for dealing with the encoder</param> /// <returns><c>true</c> if the encoder can be used, otherwise <c>false</c></returns> public bool Add(DsDevice device, SoftwareEncoder dbEncoder) { if (device == null) { return(false); } int reuseLimit = Convert.ToInt32(_layer.GetSetting("softwareEncoderReuseLimit", "0").Value); lock (_encodersInUse) { DsDevice key = null; foreach (DsDevice dev in _encodersInUse.Keys) { if (dev.Name == device.Name && device.Mon.IsEqual(dev.Mon) == 0 && dev.DevicePath == device.DevicePath) { Log.Log.WriteFile("analog: compressor {0} is in use, checking reuse limit...", dev.Name); key = dev; break; } } // Encoder not yet used -> always okay to use. if (key == null) { Log.Log.WriteFile("analog: compressor {0} is usable", device.Name); _encodersInUse.Add(device, 1); return(true); } // Encoder not yet in DB -> assume reusable. if (dbEncoder == null) { Log.Log.WriteFile("analog: unrecognised compressor, assuming usable"); _encodersInUse[key]++; return(true); } // If the encoder is reusable then check // the existing usage against the cap. if (dbEncoder.Reusable) { if (reuseLimit <= 0 || _encodersInUse[key] < reuseLimit) { Log.Log.WriteFile("analog: reusable compressor, usage under limit (usage: {0}, limit: {1})", _encodersInUse[key], reuseLimit == 0 ? "[unlimited]" : reuseLimit.ToString()); _encodersInUse[key]++; return(true); } else { Log.Log.WriteFile("analog: reusable compressor, usage already at limit (usage: {0}, limit: {1})", _encodersInUse[key], reuseLimit); return(false); } } } // If we get to here then the encoder isn't reusable // and it is in use, which means the limit has already // been reached. The encoder wouldn't be in _encodersInUse // if it wasn't in use... Log.Log.WriteFile("analog: non-reusable compressor, already used"); return(false); }
private void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e) { try { Logdebug("SystemEvents_SessionEnded =" + e.Reason.ToString()); if (receivethread != null) { try { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; setting = layer.GetSetting("TvWishList_NextEpgDate", DateTime.Now.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture)); setting.Value = _PreviousEpgTime.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Logdebug("TvWishList_NextEpgDate=" + setting.Value); setting.Persist(); } catch (Exception exc) { Logdebug("Error in writing old epg time"); Log.Error("Error in writing old epg time"); Log.Debug(exc.Message); Log.Error(exc.Message); } Logdebug("Aborting receive thread because of shutdown or logoff event"); Log.Error("Aborting receive thread because of shutdown or logoff event"); receivethread.Abort(); //resetting next epg date _NextEpgTime = _PreviousEpgTime; Logdebug("TVSERVER TvWishList: Setting NextEpgTime =" + _NextEpgTime.ToString()); } } catch (Exception exc) { Log.Debug("SystemEvents_SessionEnded failed with exception message:"); Log.Error("SystemEvents_SessionEnded failed with exception message:"); Log.Debug(exc.Message); Log.Error(exc.Message); } }
private void ServerThreadRoutine(object data) { string defaultTimeOutValuestring = TimeOutValuestring; TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; while (PipeServerActive) { try { var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,System.Security.AccessControl.AccessControlType.Allow); var sec = new PipeSecurity(); sec.AddAccessRule(rule); #if (MPTV2) string pipeName = "MP2TvWishListPipe"; #else string pipeName = "TvWishListPipe"; #endif pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec); //only 1 thread for pipe int threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect Logdebug("TvServer: Waiting for client to connect"); PipeServerBusy = false; pipeServer.WaitForConnection(); ServerMessage = string.Empty; Logdebug("Client connected on pipe server thread."); PipeServerBusy = true; ; // Read the request from the client. Once the client has // written to the pipe its security token will be available. //pipeServer.ReadTimeout = 5000; //timeout not supported for async streams StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. MessageFromClient = ss.ReadString(); //receive message from client first //labelreceivedTextServer.Text = messagefromclient; Logdebug("***** CLIENTMESSAGE=" + MessageFromClient); //******************************* //commandinterpretation //******************************* if (MessageFromClient == PipeCommands.RequestTvVersion.ToString()) { string response = PipeCommands.RequestTvVersion.ToString() + "=" + this.Version; Logdebug("sending response " + response); ss.WriteString(response); } else if (MessageFromClient.StartsWith(PipeCommands.StartEpg.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } Logdebug("Starting EPG Search from pipe command"); Thread StartEPGsearchThread = new Thread(StartEPGsearchCommand); StartEPGsearchThread.Start(); while ((ServerMessage.StartsWith(PipeCommands.Ready.ToString())==false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false)) { ServerTimeOutCounter = new Thread(ServerTimeOutError); ServerTimeOutCounter.Start(); while ((NewServerMessage == false) || (ServerMessage==string.Empty)) { Thread.Sleep(500); Logdebug("waiting for new servermessage (ServerMessage="+ServerMessage); } Logdebug("Sending Servermessage=" + ServerMessage); ss.WriteString(ServerMessage); //send response messages until done ServerTimeOutCounter.Abort(); NewServerMessage = false; } TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.Error_TimeOut.ToString()) == true) { TimeOutValuestring = MessageFromClient.Replace(PipeCommands.Error_TimeOut.ToString(), string.Empty); Logdebug("new TimeOutValuestring="+TimeOutValuestring); ss.WriteString(TimeOutValuestring); } else if (MessageFromClient.StartsWith(PipeCommands.ExportTvWishes.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Log.Debug("Changed TimeOutValuestring=" + TimeOutValuestring); } if (MessageFromClient.Contains("VIEWONLY=TRUE") == true) { ServerMessage = ExportTvWishes(true); } else //Email & Record Mode { ServerMessage = ExportTvWishes(false); } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.ImportTvWishes.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } if (MessageFromClient.Contains("VIEWONLY=TRUE") == true) { ServerMessage = ImportTvWishes(true); } else //Email & Record Mode { ServerMessage = ImportTvWishes(false); } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.RemoveSetting.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } string tag = tokens[0].Replace(PipeCommands.RemoveSetting.ToString(), string.Empty); setting = layer.GetSetting(tag, string.Empty); if (setting != null) { setting.Remove(); ServerMessage = "Setting " + tag + " removed"; Logdebug("Setting " + tag + " removed"); } else { ServerMessage = "Setting " + tag + " could not be removed"; Logdebug("Eror: Setting " + tag + " could not be removed"); } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.RemoveRecording.ToString()) == true) {//string command = Main_GUI.PipeCommands.RemoveRecording.ToString() + this.IdRecording.ToString() + ":10"; defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } string idRecordingString = tokens[0].Replace(PipeCommands.RemoveRecording.ToString(), string.Empty); try { int idRecording = -1; int.TryParse(idRecordingString, out idRecording); Logdebug("idRecording=" + idRecording.ToString()); Recording myrecording = Recording.Retrieve(idRecording); Logdebug("idRecording=" + myrecording.Title.ToString()); myrecording.Delete(); Logdebug("Recording deleted"); ServerMessage = "Recording deleted"; } catch (Exception exc) { Logdebug("no recording found for idRecordingString = " + idRecordingString); Logdebug("exception is " + exc.Message); ServerMessage = "Error: Recording could not be deleted check the tvserver log file"; } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.RemoveLongSetting.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } //processing string mysetting = string.Empty; try { //cleanup work mysetting = tokens[0].Replace(PipeCommands.RemoveLongSetting.ToString(), string.Empty); Log.Debug("mysetting=" + mysetting); for (int i = 1; i < 1000; i++) { setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_"); Log.Debug("save_longsetting setting=" + setting.Value); if (setting.Value == "_DOES_NOT_EXIST_") { setting.Remove(); break; } else { string value = setting.Value; setting.Remove(); } } ServerMessage = "Long setting could be removed"; } catch (Exception exc) { Logdebug("Longsetting could not be removed for mysetting= " + mysetting); Logdebug("exception is " + exc.Message); ServerMessage = "Error: Long setting could not be removed - check the tvserver log file"; } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } #if (MPTV2) else if (MessageFromClient.StartsWith(PipeCommands.WriteSetting.ToString()) == true) { string tag = MessageFromClient.Replace(PipeCommands.WriteSetting.ToString(), string.Empty); string[] tags = tag.Split('\n'); ServiceAgents.Instance.SettingServiceAgent.SaveValue(tags[0], tags[1]); ServerMessage = "SUCCESS"; ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadSetting.ToString()) == true) { string tag = MessageFromClient.Replace(PipeCommands.ReadSetting.ToString(), string.Empty); Log.Debug("tag="+tag); string value = ServiceAgents.Instance.SettingServiceAgent.GetValue(tag, string.Empty); Log.Debug("value=" + value); ServerMessage = value; ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllCards.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } ServerMessage = string.Empty; foreach (Card mycard in Card.ListAll()) { ServerMessage += mycard.IdCard.ToString() + "\n" + mycard.Name + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelsByGroup.ToString()) == true) { string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllChannelsByGroup.ToString(), string.Empty); Log.Debug("groupIdString="+groupIdString); int groupId = -1; int.TryParse(groupIdString, out groupId); Log.Debug("groupId=" + groupId.ToString()); ServerMessage = string.Empty; foreach (Channel mychannel in Channel.ListAllByGroup(groupId)) { ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n"; } Log.Debug("Groupchannels=" + ServerMessage); //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannels.ToString()) == true)//must be after ReadAllChannelsByGroup { ServerMessage = string.Empty; foreach (Channel mychannel in Channel.ListAll()) { ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelsByGroup.ToString()) == true) { string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllRadioChannelsByGroup.ToString(), string.Empty); Log.Debug("radiogroupIdString=" + groupIdString); int groupId = -1; int.TryParse(groupIdString, out groupId); Log.Debug("radiogroupId=" + groupId.ToString()); ServerMessage = string.Empty; foreach (RadioChannel myradiochannel in RadioChannel.ListAllByGroup(groupId)) { ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n"; } Log.Debug("radioGroupchannels=" + ServerMessage); //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannels.ToString()) == true)//must be after ReadAllRadioChannelsByGroup { ServerMessage = string.Empty; foreach (RadioChannel myradiochannel in RadioChannel.ListAll()) { ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelGroups.ToString()) == true) { ServerMessage = string.Empty; foreach (ChannelGroup mygroup in ChannelGroup.ListAll()) { ServerMessage += mygroup.Id.ToString() + "\n" + mygroup.GroupName + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelGroups.ToString()) == true) { ServerMessage = string.Empty; foreach (RadioChannelGroup myradiogroup in RadioChannelGroup.ListAll()) { ServerMessage += myradiogroup.Id.ToString() + "\n" + myradiogroup.GroupName + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRecordings.ToString()) == true) { ServerMessage = string.Empty; foreach (Recording myrecording in Recording.ListAll()) { ServerMessage += myrecording.IdRecording.ToString() + "\n" + myrecording.Title + "\n"+myrecording.FileName + "\n" + myrecording.IdChannel.ToString() + "\n" + myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllSchedules.ToString()) == true) { ServerMessage = string.Empty; foreach (Schedule myschedule in Schedule.ListAll()) { ServerMessage += myschedule.IdSchedule.ToString() + "\n" + myschedule.ProgramName + "\n" + myschedule.IdChannel.ToString() + "\n" + myschedule.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myschedule.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myschedule.ScheduleType.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" + myschedule.PostRecordInterval.ToString() + "\n" + myschedule.MaxAirings.ToString() + "\n" + myschedule.KeepDate.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myschedule.KeepMethod.ToString() + "\n" + myschedule.Priority.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" + myschedule.Series.ToString() + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ScheduleDelete.ToString()) == true) { string scheduleIdString = MessageFromClient.Replace(PipeCommands.ScheduleDelete.ToString(), string.Empty); Log.Debug("scheduleIdString=" + scheduleIdString); int scheduleId = -1; int.TryParse(scheduleIdString, out scheduleId); Log.Debug("scheduleId=" + scheduleId.ToString()); Schedule.Delete(scheduleId); //65000 max chars ss.WriteString("Deleted"); } else if (MessageFromClient.StartsWith(PipeCommands.ScheduleNew.ToString()) == true) { string schedule = MessageFromClient.Replace(PipeCommands.ScheduleNew.ToString(), string.Empty); string[] scheduletags = schedule.Split('\n'); int idChannel = -1; int.TryParse(scheduletags[1], out idChannel); DateTime start = DateTime.ParseExact(scheduletags[2], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); DateTime end = DateTime.ParseExact(scheduletags[3], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Schedule myschedule = new Schedule(idChannel, scheduletags[0], start, end); myschedule.Persist(); ServerMessage = "SUCCESS"; ss.WriteString(ServerMessage); } #endif else //Unknown command { Logdebug("sending response " + PipeCommands.UnknownCommand.ToString()); ss.WriteString(PipeCommands.UnknownCommand.ToString()); } } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Log.Error("ServerThread ERROR: " + e.Message); } catch (Exception e) { Log.Error("ServerThread ERROR: " + e.Message); } if (pipeServer != null) { if (pipeServer.IsConnected) pipeServer.Disconnect(); pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; } Logdebug("Connection closed"); } Logdebug("Pipe Server Thread Completed"); }
public void Start(IController controller) #endif { try { Log.Info("TvWishList started"); SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged); SystemEvents.SessionEnded += new SessionEndedEventHandler(SystemEvents_SessionEnded); events = GlobalServiceProvider.Instance.Get<ITvServerEvent>(); events.OnTvServerEvent += new TvServerEventHandler(events_OnTvServerEvent); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; //set BUSY = false setting = layer.GetSetting("TvWishList_BUSY", "false"); setting.Value = "false"; setting.Persist(); setting = layer.GetSetting("TvWishList_Debug", "false"); Log.Info("setting DEBUG MODE = " + setting.Value); DEBUG = false; Boolean.TryParse(setting.Value, out DEBUG); Log.DebugValue = DEBUG; Log.Info("DEBUG MODE = " + DEBUG.ToString()); //unlock pluginversion setting = layer.GetSetting("TvWishList_LockingPluginname", "NONE"); setting.Value = "NONE"; setting.Persist(); //write Tv version setting = layer.GetSetting("TvWishList_TvServerVersion", "0.0.0.0"); setting.Value = Version; setting.Persist(); Log.Debug("TvVersion = "+Version); //is host name stored in database for TvWishListMP? setting = layer.GetSetting("TvWishList_MachineName", "NONE"); Log.Debug("TvServer Machine Name="+setting.Value); if (setting.Value != System.Environment.MachineName.ToString()) { setting.Value = System.Environment.MachineName.ToString(); setting.Persist(); Log.Debug("Overwriting TvServer Machine Name To " + setting.Value); } //save pipename for Tvserver2 setting = layer.GetSetting("TvWishList_PipeName", "NONE"); Log.Debug("TvWishList_PipeName=" + setting.Value); #if (MPTV2) setting.Value = "MP2TvWishListPipe"; #else setting.Value = "TvWishListPipe"; #endif setting.Persist(); TV_USER_FOLDER = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND").Value; if ((File.Exists(TV_USER_FOLDER + @"\TvService.exe") == true) || (Directory.Exists(TV_USER_FOLDER) == false)) { //autodetect paths InstallPaths instpaths = new InstallPaths(); //define new instance for folder detection #if (MPTV2) //Native MP2 Tv server instpaths.GetInstallPathsMP2(); TV_USER_FOLDER = instpaths.TV2_USER_FOLDER; #else instpaths.GetInstallPaths(); TV_USER_FOLDER = instpaths.TV_USER_FOLDER; #endif Logdebug("TV server user folder detected at " + TV_USER_FOLDER); if ((File.Exists(TV_USER_FOLDER + @"\TvService.exe") == true) || (Directory.Exists(TV_USER_FOLDER) == false)) { Log.Error(@" TV server user folder does not exist - using C:\MediaPortal\TvWishList"); Logdebug(@" TV server user folder does not exist - using C:\MediaPortal\TvWishList"); TV_USER_FOLDER = @"C:\MediaPortal"; if (Directory.Exists(TV_USER_FOLDER) == false) Directory.CreateDirectory(TV_USER_FOLDER + @"\TvWishList"); } else {//store found TV_USER_FOLDER setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND"); setting.Value = TV_USER_FOLDER; setting.Persist(); } } _RecordingFlagTime = DateTime.Now.AddHours(1.0); //add 1 hour to give time for setup _NextEpgTime = DateTime.Now.AddHours(1.0); //add 1 hour to give time for setup setting = layer.GetSetting("TvWishList_NextEpgDate", _NextEpgTime.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture)); try { _NextEpgTime = DateTime.ParseExact(setting.Value, "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); } catch (Exception exc) { Log.Error("NextEpgDate reading failed with exception: " + exc.Message); } Log.Debug("Start(IController controller): _NextEpgTime=" + _NextEpgTime.ToString()); /* // lock next time for receive mail for upcoming startups if Tvserver is being restarted after each standby setting = layer.GetSetting("TvWishList_SetEpgTime", "false"); setting.Value = "false"; setting.Persist();*/ epgwatchclass = new EpgParser(); if (epgwatchclass == null) { Log.Error("EpgParser could not be initiated - aborting operation"); return; } else { epgwatchclass.newlabelmessage += new setuplabelmessage(SendServerPipeMessage); Logdebug("EpgParser initiated"); } //start pollingthread runpolling = true; System.Threading.Thread th = new System.Threading.Thread(startpolling); th.IsBackground = true; th.Start(); Logdebug("Polling thread starting"); /* // activate filewatcher for active command try { filewatcherstartepg = TV_USER_FOLDER + @"\TvWishList\StartEPGsearch.txt"; if (File.Exists(filewatcherstartepg) == true) { File.Delete(filewatcherstartepg); } filewatcherfinishedepg = TV_USER_FOLDER + @"\TvWishList\FinishedEPGsearch.txt"; if (File.Exists(filewatcherfinishedepg) == true) { File.Delete(filewatcherfinishedepg); } FileInfo myfileinfo = new FileInfo(filewatcherstartepg); StartEPGsearch.Path = myfileinfo.DirectoryName; StartEPGsearch.Created += new FileSystemEventHandler(StartEPGsearchFilewatcher); StartEPGsearch.Filter = myfileinfo.Name; StartEPGsearch.EnableRaisingEvents = true; Logdebug("file watcher StartEPGsearch enabled"); } catch (Exception ex) { Log.Error("Error in starting StartEPGsearch File watcher: Exception message was " + ex.Message); return; }*/ // activate filewatcher for setupTvStarted try { filewatcherSetupTvStarted = TV_USER_FOLDER + @"\TvWishList\SetupTvStarted.txt"; if (File.Exists(filewatcherSetupTvStarted) == true) { File.Delete(filewatcherSetupTvStarted); } FileInfo myfileinfo = new FileInfo(filewatcherSetupTvStarted); SetupTvStarted.Path = myfileinfo.DirectoryName; SetupTvStarted.Created += new FileSystemEventHandler(SetupTvStartedFilewatcher); SetupTvStarted.Filter = myfileinfo.Name; SetupTvStarted.EnableRaisingEvents = true; Logdebug("file watcher SetupTvStarted enabled"); } catch (Exception ex) { Log.Error("Error in starting SetupTvStarted File watcher: Exception message was " + ex.Message); return; } // activate filewatcher for NextEpgCheck try { filewatcherNextEpgCheck = TV_USER_FOLDER + @"\TvWishList\NextEpgCheck.txt"; if (File.Exists(filewatcherNextEpgCheck) == true) { File.Delete(filewatcherNextEpgCheck); } FileInfo myfileinfo = new FileInfo(filewatcherNextEpgCheck); NextEpgCheck.Path = myfileinfo.DirectoryName; NextEpgCheck.Created += new FileSystemEventHandler(NextEpgCheckFilewatcher); NextEpgCheck.Filter = myfileinfo.Name; NextEpgCheck.EnableRaisingEvents = true; Logdebug("file watcher NextEpgCheck enabled"); } catch (Exception ex) { Log.Error("Error in starting NextEpgCheck File watcher: Exception message was " + ex.Message); return; } //startpipeserver and listen for commands StartServer(); } catch (Exception ex) { Log.Debug("Error in starting TvWishList: Exception message was " + ex.Message); return; } Log.Debug("TvWishList start completed"); }
public override void LoadSettings() { Setting setting; setting = _layer.GetSetting("PowerSchedulerShutdownActive", "false"); checkBox1.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("PowerSchedulerIdleTimeout", "5"); numericUpDown1.Value = Convert.ToDecimal(setting.Value); setting = _layer.GetSetting("PowerSchedulerStandbyAllowedStart", "0"); numUpDownStandbyAllowedStartHour.Value = Convert.ToDecimal(setting.Value); setting = _layer.GetSetting("PowerSchedulerStandbyAllowedEnd", "24"); numUpDownStandbyAllowedEndHour.Value = Convert.ToDecimal(setting.Value); setting = _layer.GetSetting("PowerSchedulerWakeupActive", "false"); checkBox2.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("PowerSchedulerShutdownMode", "2"); comboBox1.SelectedIndex = Convert.ToInt32(setting.Value); setting = _layer.GetSetting("PowerSchedulerForceShutdown", "false"); checkBox3.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("PowerSchedulerExtensiveLogging", "false"); checkBox4.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("PowerSchedulerPreWakeupTime", "60"); numericUpDown2.Value = Convert.ToDecimal(setting.Value); setting = _layer.GetSetting("PowerSchedulerPreNoShutdownTime", "300"); numericUpDown4.Value = Convert.ToDecimal(setting.Value); setting = _layer.GetSetting("PowerSchedulerCheckInterval", "60"); numericUpDown3.Value = Convert.ToDecimal(setting.Value); setting = _layer.GetSetting("PowerSchedulerReinitializeController", "false"); checkBox5.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("PowerSchedulerCommand", string.Empty); textBox2.Text = setting.Value; setting = _layer.GetSetting("PreventStandbyWhenGrabbingEPG", "false"); checkBox6.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("WakeupSystemForEPGGrabbing", "false"); checkBox7.Checked = Convert.ToBoolean(setting.Value); EPGWakeupConfig config = new EPGWakeupConfig(_layer.GetSetting("EPGWakeupConfig", String.Empty).Value); foreach (EPGGrabDays day in config.Days) { switch (day) { case EPGGrabDays.Monday: checkBox8.Checked = true; break; case EPGGrabDays.Tuesday: checkBox9.Checked = true; break; case EPGGrabDays.Wednesday: checkBox10.Checked = true; break; case EPGGrabDays.Thursday: checkBox11.Checked = true; break; case EPGGrabDays.Friday: checkBox12.Checked = true; break; case EPGGrabDays.Saturday: checkBox13.Checked = true; break; case EPGGrabDays.Sunday: checkBox14.Checked = true; break; } } string hFormat, mFormat; if (config.Hour < 10) { hFormat = "0{0}"; } else { hFormat = "{0}"; } if (config.Minutes < 10) { mFormat = "0{0}"; } else { mFormat = "{0}"; } maskedTextBox1.Text = String.Format(hFormat, config.Hour) + ":" + String.Format(mFormat, config.Minutes); setting = _layer.GetSetting("PowerSchedulerEpgCommand", String.Empty); tbEpgCmd.Text = setting.Value; setting = _layer.GetSetting("PowerSchedulerProcesses", "SetupTv, Configuration"); textBox1.Text = setting.Value; // Load share monitoring configuration for standby prevention setting = _layer.GetSetting("PreventStandybyWhenSharesInUse", "true"); shareMonitoring.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("PreventStandybyWhenSpecificSharesInUse", ""); inhibitStandbyShares.Rows.Clear(); string[] shares = setting.Value.Split(';'); foreach (string share in shares) { string[] shareItem = share.Split(','); if ((shareItem.Length.Equals(3)) && ((shareItem[0].Trim().Length > 0) || (shareItem[1].Trim().Length > 0) || (shareItem[2].Trim().Length > 0))) { inhibitStandbyShares.Rows.Add(shareItem); } } setting = _layer.GetSetting("NetworkMonitorEnabled", "false"); checkBox15.Checked = Convert.ToBoolean(setting.Value); setting = _layer.GetSetting("NetworkMonitorIdleLimit", "2"); numericUpDown5.Value = Convert.ToDecimal(setting.Value); }
public void StartEPGsearchCommand() { try { Logdebug("Started StartEPGsearchCommand"); //disable filewatcher //StartEPGsearch.EnableRaisingEvents = false; //File.Delete(filewatcherstartepg); use this file as a check for other processes //get new updated value for next epg check TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; // get DEBUG setting = layer.GetSetting("TvWishList_Debug", "false"); DEBUG = false; Boolean.TryParse(setting.Value, out DEBUG); Log.DebugValue = DEBUG; //////////////////////////////////////////////// //start epgprocessing here if (epgwatchclass == null) { Logdebug("EpgParser could not be initiated - aborting operation"); Log.Error("EpgParser could not be initiated - aborting operation"); return; } else { try { if (MessageFromClient.Contains("VIEWONLY=TRUE") == true) { epgwatchclass.SearchEPG(true); } else //Email & Record Mode { epgwatchclass.SearchEPG(false); } } catch (Exception exc) { Log.Error("Parsing EPG data failed with exception message:"); Log.Error(exc.Message); // Reset BUSY Flag after exception //set BUSY = false setting = layer.GetSetting("TvWishList_BUSY", "false"); setting.Value = "false"; setting.Persist(); } } Log.Debug("epgwatchcommand completed "); //must end with "ready or "error" if ((ServerMessage.StartsWith(PipeCommands.Ready.ToString()) == false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false)) { string errortext = "Epgwatch did end without error and not ready"; Logdebug(errortext); SendServerPipeMessage(errortext, PipeCommands.Error); } //enable filewatcher //StartEPGsearch.EnableRaisingEvents = true; } catch (Exception exc) { Log.Error("filewatcher epgwatch failed with exception message:"); Log.Error(exc.Message); } }
public override void OnSectionActivated() { mpListView1.BeginUpdate(); try { LoadLanguages(); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("epgStoreOnlySelected"); mpCheckBoxStoreOnlySelected.Checked = (setting.Value == "yes"); Dictionary <string, CardType> cards = new Dictionary <string, CardType>(); IList <Card> dbsCards = Card.ListAll(); foreach (Card card in dbsCards) { cards[card.DevicePath] = RemoteControl.Instance.Type(card.IdCard); } base.OnSectionActivated(); mpListView1.Items.Clear(); SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(Channel)); sb.AddOrderByField(true, "sortOrder"); SqlStatement stmt = sb.GetStatement(true); IList <Channel> channels = ObjectFactory.GetCollection <Channel>(stmt.Execute()); foreach (Channel ch in channels) { bool analog = false; bool dvbc = false; bool dvbt = false; bool dvbs = false; bool atsc = false; bool dvbip = false; bool hasFta = false; bool hasScrambled = false; if (ch.IsTv == false) { continue; } if (ch.IsWebstream()) { continue; } IList <TuningDetail> tuningDetails = ch.ReferringTuningDetail(); foreach (TuningDetail detail in tuningDetails) { if (detail.FreeToAir) { hasFta = true; } if (!detail.FreeToAir) { hasScrambled = true; } } int imageIndex; if (hasFta && hasScrambled) { imageIndex = 5; } else if (hasScrambled) { imageIndex = 4; } else { imageIndex = 3; } ListViewItem item = mpListView1.Items.Add(ch.DisplayName, imageIndex); foreach (ChannelMap map in ch.ReferringChannelMap()) { if (cards.ContainsKey(map.ReferencedCard().DevicePath)) { CardType type = cards[map.ReferencedCard().DevicePath]; switch (type) { case CardType.Analog: analog = true; break; case CardType.DvbC: dvbc = true; break; case CardType.DvbT: dvbt = true; break; case CardType.DvbS: dvbs = true; break; case CardType.Atsc: atsc = true; break; case CardType.DvbIP: dvbip = true; break; } } } string line = ""; if (analog) { line += "Analog"; } if (dvbc) { if (line != "") { line += ","; } line += "DVB-C"; } if (dvbt) { if (line != "") { line += ","; } line += "DVB-T"; } if (dvbs) { if (line != "") { line += ","; } line += "DVB-S"; } if (atsc) { if (line != "") { line += ","; } line += "ATSC"; } if (dvbip) { if (line != "") { line += ","; } line += "DVB-IP"; } item.SubItems.Add(line); item.Checked = ch.GrabEpg; item.Tag = ch; } } finally { mpListView1.EndUpdate(); } }
public void SetupTvStartedFilewatcher(object sender, FileSystemEventArgs e) { Logdebug("SetupTvStartedFilewatcher"); //disable filewatcher SetupTvStarted.EnableRaisingEvents = false; /* //debug only foreach (Mediaportal.TV.Server.TVDatabase.Entities.Schedule allschedule in Mediaportal.TV.Server.TVDatabase.TVBusinessLayer.ScheduleManagement.ListAllSchedules()) { List<Mediaportal.TV.Server.TVDatabase.Entities.Schedule> notViewableSchedules = new List<Mediaportal.TV.Server.TVDatabase.Entities.Schedule>(); IList<Mediaportal.TV.Server.TVDatabase.Entities.Schedule> mylist = Mediaportal.TV.Server.TVDatabase.TVBusinessLayer.ScheduleManagementhuha.GetConflictingSchedules(allschedule, out notViewableSchedules); Log.Debug("*****************************************************************"); Log.Debug("***********************allschedule=" + allschedule.ProgramName + " s=" + allschedule.StartTime.ToString() + " ch=" + allschedule.IdChannel.ToString()); Log.Debug("mylist.Count="+mylist.Count.ToString()); foreach (Mediaportal.TV.Server.TVDatabase.Entities.Schedule test in mylist) { Log.Debug("mylistSchedules = " + test.ProgramName + " id=" + test.IdSchedule.ToString() + " start=" + test.StartTime.ToString() + " end=" + test.EndTime.ToString() + " channel=" + test.IdChannel); } Log.Debug("notViewableSchedules.Count="+notViewableSchedules.Count.ToString()); Log.Debug("*****************************************************************"); foreach (Mediaportal.TV.Server.TVDatabase.Entities.Schedule test in notViewableSchedules) { Log.Debug("notViewableSchedules = " + test.ProgramName + " id=" + test.IdSchedule.ToString() + " start=" + test.StartTime.ToString() + " end=" + test.EndTime.ToString() + " channel=" + test.IdChannel); } Log.Debug(""); } //end debug */ //Thread.Sleep(2000); //wait for storing data Process[] allnamedprocesses; do { System.Threading.Thread.Sleep(1000); //sleep 1s allnamedprocesses = Process.GetProcessesByName("SetupTv"); Log.Debug("allnamedprocesses.Length=" + allnamedprocesses.Length.ToString()); } while ((allnamedprocesses.Length > 0) && (File.Exists(filewatcherSetupTvStarted))); //SetupTv completed or TvWishList deactivated TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; //unlock data setting = layer.GetSetting("TvWishList_LockingPluginname", "NONE"); setting.Value = "NONE"; setting.Persist(); if (File.Exists(filewatcherSetupTvStarted) == true) { File.Delete(filewatcherSetupTvStarted); } setting = layer.GetSetting("TvWishList_BUSY", "false"); setting.Value = "false"; setting.Persist(); Logdebug("SetupTvStartedFilewatcher completed busy=false, unlocked"); //enable filewatcher SetupTvStarted.EnableRaisingEvents = true; }
public void SetupLanguages() { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; //check for installation folders first setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND"); TV_USER_FOLDER = setting.Value; Log.Debug("a) TV_USER_FOLDER=" + TV_USER_FOLDER); if ((File.Exists(TV_USER_FOLDER + @"\TvService.exe") == true) || (Directory.Exists(TV_USER_FOLDER) == false)) { //autodetect paths #if (MPTV2) //Native MP2 Tv server instpaths.GetInstallPathsMP2(); TV_USER_FOLDER = instpaths.ask_TV2_USER(); #else instpaths.GetInstallPaths(); TV_USER_FOLDER = instpaths.ask_TV_USER(); #endif LogDebug("TV server user folder detected at " + TV_USER_FOLDER, (int)LogSetting.DEBUG); if ((File.Exists(TV_USER_FOLDER + @"\TvService.exe") == true) || (Directory.Exists(TV_USER_FOLDER) == false)) { LogDebug(@" TV server user folder does not exist - using C:\MediaPortal", (int)LogSetting.ERROR); TV_USER_FOLDER = @"C:\MediaPortal"; if (Directory.Exists(TV_USER_FOLDER) == false) Directory.CreateDirectory(TV_USER_FOLDER + @"\TvWishList"); } } setting.Value = TV_USER_FOLDER; setting.Persist();//write setting during initialization Log.Debug("TV_USER_FOLDER=" + TV_USER_FOLDER); //checkboxes setting = layer.GetSetting("TvWishList_Debug", "false"); DEBUG = false; Boolean.TryParse(setting.Value, out DEBUG); checkBoxDebug.Checked = DEBUG; Log.DebugValue = DEBUG; LogDebug("Loadsettings Debug set", (int)LogSetting.DEBUG); if (lng.ReadLanguageFile() == false) return; tabControl1.TabPages[0].Text = lng.TranslateString("Main", 100); radioButtonEasy.Text = lng.TranslateString("Easy", 101); radioButtonExpert.Text = lng.TranslateString("Expert", 102); buttonUp.Text = lng.TranslateString("Up", 103); buttonDown.Text = lng.TranslateString("Down", 104); buttonDelete.Text = lng.TranslateString("Delete", 105); buttonCancel.Text = lng.TranslateString("Cancel", 106); buttonDefault.Text = lng.TranslateString("Default", 107); buttonhelp.Text = lng.TranslateString("Help", 108); checkBoxDebug.Text = lng.TranslateString("Debugmodus", 109); linkLabel1.Text = lng.TranslateString("Home Page", 110); buttonallactive.Text = lng.TranslateString("All Active", 111); buttonallinactive.Text = lng.TranslateString("All Inactive", 112); buttonSkipAll.Text = lng.TranslateString("Skip All", 113); buttonSkipNone.Text = lng.TranslateString("Skip None", 114); label11.Text = lng.TranslateString("Channel Filter", 115); tabControl1.TabPages[1].Text = lng.TranslateString("Email", 130); groupBox2.Text = lng.TranslateString("Account", 131); label16.Text = lng.TranslateString("User Name", 132); label18.Text = lng.TranslateString("Password", 133); label1.Text = lng.TranslateString("Repeat Password", 134); label4.Text = lng.TranslateString("Email Address", 135); label2.Text = lng.TranslateString("only if different than user name", 136); buttontest.Text = lng.TranslateString("Search Now", 137); groupBox1.Text = lng.TranslateString("Address", 138); label14.Text = lng.TranslateString("Email Receiver", 139); buttonTestSend.Text = lng.TranslateString("Test Send Mail", 140); groupBox4.Text = lng.TranslateString("SMTP", 141); label13.Text = lng.TranslateString("Provider", 142); label8.Text = lng.TranslateString("Port", 143); label9.Text = lng.TranslateString("SMTP Server", 144); checkBoxSSL.Text = lng.TranslateString("SSL", 145); checkBoxemailreply.Text = lng.TranslateString("Enable Email Reply", 146); checkBoxEmailOnlynew.Text = lng.TranslateString("Email Only New", 147); labelstatus.Text = lng.TranslateString("Ready", 20); labelmainstatus.Text = lng.TranslateString("Ready", 20); tabControl1.TabPages[2].Text = lng.TranslateString("EPG", 193); groupBox3.Text = lng.TranslateString("Check EPG", 161); checkBoxMon.Text = lng.TranslateString("Monday", 162); checkBoxTue.Text = lng.TranslateString("Tuesday", 163); checkBoxWed.Text = lng.TranslateString("Wednesday", 164); checkBoxThur.Text = lng.TranslateString("Thursday", 165); checkBoxFri.Text = lng.TranslateString("Friday", 166); checkBoxSat.Text = lng.TranslateString("Saturday", 167); checkBoxSun.Text = lng.TranslateString("Sunday", 168); checkBoxEvery.Text = lng.TranslateString("Every", 169); label5.Text = lng.TranslateString("Days", 170); label7.Text = lng.TranslateString("Hours", 171); label10.Text = lng.TranslateString("Minutes", 172); label26.Text = lng.TranslateString("Minutes", 172); label6.Text = lng.TranslateString("At", 173); checkBoxScheduleMinutes.Text = lng.TranslateString("Check EPG", 174); label27.Text = lng.TranslateString("before each schedule", 175); label15.Text = lng.TranslateString("Next Tv Server Checking Date:", 176); groupBox6.Text = lng.TranslateString("Match Criteria for Repeated Movies and Episodes besides the title", 177); label12.Text = lng.TranslateString("EPG Repeater Mark in Title or Description", 178); groupBox5.Text = lng.TranslateString("Other Options", 179); checkBoxschedule.Text = lng.TranslateString("Automatic Recording", 180); checkBoxscheduleconflicts.Text = lng.TranslateString("Schedule Conflicts", 181); checkBoxDeleteChangedEPG.Text = lng.TranslateString("Delete Changed EPG", 182); checkBoxResetEmailFormat.Text = lng.TranslateString("Restore Default Values", 183); checkBoxSlowCPU.Text = lng.TranslateString("Slow CPU", 184); checkBoxSkipDeleted.Text = lng.TranslateString("Skip Deleted", 185); label17.Text = lng.TranslateString("Deleted Expiration:", 186); label19.Text = lng.TranslateString("Months", 187); label32.Text = lng.TranslateString("Max Schedules Per Wish", 188); label28.Text = lng.TranslateString("Minutes", 172); label20.Text = lng.TranslateString("ComSkip Wait Time", 192); tabControl1.TabPages[3].Text = lng.TranslateString("Settings", 160); tabControl1.TabPages[4].Text = lng.TranslateString("Formats", 200); label23.Text = lng.TranslateString("Expert users can define customized formats for sent emails", 205); label25.Text = lng.TranslateString("Date and Time Format", 201); //label20.Text = lng.TranslateString("Email Format", 202); label24.Text = lng.TranslateString("Language File", 203); label21.Text = lng.TranslateString("Sort Criteria", 204); checkBoxdescendingSort.Text = lng.TranslateString("Descending Sort", 206); label22.Text = lng.TranslateString("Filter Criteria", 207); checkBoxFilterEmail.Text = lng.TranslateString("Email", 208); checkBoxFilterRecord.Text = lng.TranslateString("Record", 209); checkBoxFilterConflicts.Text = lng.TranslateString("Conflicts", 210); checkBoxDeletemessageFile.Text = lng.TranslateString("Delete All Messages", 211); //Match Type 2600-2606 DataGridViewComboBoxColumn mygroupcomboxcolumn2 = dataGridView1.Columns[2] as DataGridViewComboBoxColumn; for (int i = 0; i <= 6; i++) { mygroupcomboxcolumn2.Items[i] = lng.Get(2600 + i); //Log.Debug(" mygroupcomboxcolumn2.Items["+i.ToString()+"]="+ mygroupcomboxcolumn2.Items[i].ToString()); } //Group DataGridViewComboBoxColumn mygroupcomboxcolumn3 = dataGridView1.Columns[3] as DataGridViewComboBoxColumn; mygroupcomboxcolumn3.Items[0] = lng.Get(4104); //"All Channels" //Record type 2650-2655 DataGridViewComboBoxColumn mygroupcomboxcolumn4 = dataGridView1.Columns[4] as DataGridViewComboBoxColumn; for (int i = 0; i <= 5; i++) { mygroupcomboxcolumn4.Items[i] = lng.Get(2650 + i); } //Action 2700-2702 // do not use view 2703! DataGridViewComboBoxColumn mygroupcomboxcolumn5 = dataGridView1.Columns[5] as DataGridViewComboBoxColumn; for (int i = 0; i <= 2; i++) { mygroupcomboxcolumn5.Items[i] = lng.Get(2700 + i); } //Recommendedcard Any DataGridViewComboBoxColumn mygroupcomboxcolumn16 = dataGridView1.Columns[16] as DataGridViewComboBoxColumn; mygroupcomboxcolumn16.Items[0] = lng.Get(4100); //Any //Days 2750-2756 DataGridViewComboBoxColumn mygroupcomboxcolumn20 = dataGridView1.Columns[20] as DataGridViewComboBoxColumn; mygroupcomboxcolumn20.Items[0] = lng.Get(4100); //Any for (int i = 0; i <= 6; i++) { mygroupcomboxcolumn20.Items[i+1] = lng.Get(2750 + i); } DataGridViewComboBoxColumn mygroupcomboxcolumn21 = dataGridView1.Columns[21] as DataGridViewComboBoxColumn; mygroupcomboxcolumn21.Items[0] = lng.Get(4100); //Any for (int i = 0; i <= 6; i++) { mygroupcomboxcolumn21.Items[i+1] = lng.Get(2750 + i); } //Channel DataGridViewComboBoxColumn mygroupcomboxcolumn22 = dataGridView1.Columns[22] as DataGridViewComboBoxColumn; mygroupcomboxcolumn22.Items[0] = lng.Get(4100); //Any //Use name Folder 2850-2853 DataGridViewComboBoxColumn mygroupcomboxcolumn25 = dataGridView1.Columns[25] as DataGridViewComboBoxColumn; for (int i = 0; i <= 3; i++) { mygroupcomboxcolumn25.Items[i] = lng.Get(2850 + i); } //Keep Until 2900-2906 --> not used a combobox in tv server //Change Episode Matching Criteria USE SHORT NAMES! DataGridViewComboBoxColumn mygroupcomboxcolumn33 = dataGridView1.Columns[33] as DataGridViewComboBoxColumn; mygroupcomboxcolumn33.Items[0] = lng.Get(3264);//bug do not use 4103, 3264 is used in tvWish.c for translation mygroupcomboxcolumn33.Items[1] = lng.Get(2960); mygroupcomboxcolumn33.Items[2] = lng.Get(2961); mygroupcomboxcolumn33.Items[3] = lng.Get(2962); mygroupcomboxcolumn33.Items[4] = lng.Get(2960) + "+" + lng.Get(2961); mygroupcomboxcolumn33.Items[5] = lng.Get(2960) + "+" + lng.Get(2962); mygroupcomboxcolumn33.Items[6] = lng.Get(2961) + "+" + lng.Get(2962); mygroupcomboxcolumn33.Items[7] = lng.Get(2960) + "+" + lng.Get(2961) + "+" + lng.Get(2962); /*Log.Debug("Episode Matching Criteria Items for Combobox"); Log.Debug(lng.Get(3264)); Log.Debug(lng.Get(2960)); Log.Debug(lng.Get(2961)); Log.Debug(lng.Get(2962)); Log.Debug(lng.Get(2960) + "+" + lng.Get(2961)); Log.Debug(lng.Get(2960) + "+" + lng.Get(2962)); Log.Debug(lng.Get(2961) + "+" + lng.Get(2962)); Log.Debug(lng.Get(2960) + "+" + lng.Get(2961) + "+" + lng.Get(2962)); Log.Debug("End Episode Matching Criteria Items for Combobox");*/ //PreferredGroup DataGridViewComboBoxColumn mygroupcomboxcolumn34 = dataGridView1.Columns[34] as DataGridViewComboBoxColumn; mygroupcomboxcolumn34.Items[0] = lng.Get(4104); //"All Channels" //Column Headers 2800-2835 dataGridView1.Columns[0].HeaderText = lng.TranslateString("Active", 2800); dataGridView1.Columns[1].HeaderText = lng.TranslateString("Search For", 2801); dataGridView1.Columns[2].HeaderText = lng.TranslateString("Match Type", 2802); dataGridView1.Columns[3].HeaderText = lng.TranslateString("Group", 2803); dataGridView1.Columns[4].HeaderText = lng.TranslateString("Record Type", 2804); dataGridView1.Columns[5].HeaderText = lng.TranslateString("Action", 2805); dataGridView1.Columns[6].HeaderText = lng.TranslateString("Exclude", 2806); dataGridView1.Columns[8].HeaderText = lng.TranslateString("Pre Recording Time", 2808); dataGridView1.Columns[9].HeaderText = lng.TranslateString("Post Recording Time", 2809); dataGridView1.Columns[10].HeaderText = lng.TranslateString("Episode Name", 2810); dataGridView1.Columns[11].HeaderText = lng.TranslateString("Episode Part", 2811); dataGridView1.Columns[12].HeaderText = lng.TranslateString("Episode Number", 2812); dataGridView1.Columns[13].HeaderText = lng.TranslateString("Series Number", 2813); dataGridView1.Columns[14].HeaderText = lng.TranslateString("Keep Episodes", 2814); dataGridView1.Columns[15].HeaderText = lng.TranslateString("Keep Until", 2815); dataGridView1.Columns[16].HeaderText = lng.TranslateString("Recommended Card", 2816); dataGridView1.Columns[17].HeaderText = lng.TranslateString("Priority", 2817); dataGridView1.Columns[18].HeaderText = lng.TranslateString("After Time", 2818); dataGridView1.Columns[19].HeaderText = lng.TranslateString("Before Time", 2819); dataGridView1.Columns[20].HeaderText = lng.TranslateString("After Day", 2820); dataGridView1.Columns[21].HeaderText = lng.TranslateString("Before Day", 2821); dataGridView1.Columns[22].HeaderText = lng.TranslateString("Channel", 2822); dataGridView1.Columns[23].HeaderText = lng.TranslateString("Skip", 2823); dataGridView1.Columns[24].HeaderText = lng.TranslateString("Name", 2824); dataGridView1.Columns[25].HeaderText = lng.TranslateString("Move Recordings to Folder", 2825); dataGridView1.Columns[26].HeaderText = lng.TranslateString("Show Only Within The Next Hour(s)", 2826); dataGridView1.Columns[33].HeaderText = lng.TranslateString("Change Episode Match Criteria", 2833); dataGridView1.Columns[34].HeaderText = lng.TranslateString("Preferred Channel Group", 2834); dataGridView1.Columns[35].HeaderText = lng.TranslateString("Including Recordings", 2835); //Tv Setup Format Column Box for (int i = 1; i <= 13; i++) { comboBoxSortCriteria.Items[i-1] = lng.Get(3200 + i); } comboBoxSortCriteria.Text = comboBoxSortCriteria.Items[0].ToString(); }
public DateTime NextEpgTime() { try { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; string hours = layer.GetSetting("TvWishList_CheckEpgHours", "06").Value; int hournumber = 0; try { hournumber = Convert.ToInt32(hours); } catch (Exception exc) { Log.Error("Error: Could not convert EPG hours " + hours + " into number - setting to 06"); Log.Error("Exception message was:\n" + exc.Message + "\n"); hournumber = 6; } string minutes = layer.GetSetting("TvWishList_CheckEpgMinutes", "00").Value; Logdebug("tvserver minutes =" + minutes); int minutenumber = 0; try { minutenumber = Convert.ToInt32(minutes); } catch (Exception exc) { Log.Error("Error: Could not convert EPG minutes " + minutenumber + " into number - setting to 00"); Log.Error("Exception message was:\n" + exc.Message + "\n"); minutenumber = 0; } if (layer.GetSetting("TvWishList_Every", "false").Value.ToLower() == "true") { //process every xx days string days = layer.GetSetting("TvWishList_CheckEpgDays", "07").Value; int daynumber = 7; try { daynumber = Convert.ToInt32(days); } catch (Exception exc) { Log.Error("Error: Could not convert EPG days " + days + " into number - setting to 07"); Log.Error("Exception message was:\n" + exc.Message + "\n"); daynumber = 7; } _NextEpgTime = _NextEpgTime.AddDays(daynumber); } else //process week days { // extract weekday bool Sunday = false; if (layer.GetSetting("TvWishList_Sunday", "false").Value.ToLower() == "true") { Sunday = true; Log.Debug("Sunday"); } bool Monday = false; if (layer.GetSetting("TvWishList_Monday", "false").Value.ToLower() == "true") { Monday = true; Log.Debug("Monday"); } bool Tuesday = false; if (layer.GetSetting("TvWishList_Tuesday", "false").Value.ToLower() == "true") { Tuesday = true; Log.Debug("Tuesday"); } bool Wednesday = false; if (layer.GetSetting("TvWishList_Wednesday", "false").Value.ToLower() == "true") { Wednesday = true; Log.Debug("Wednesday"); } bool Thursday = false; if (layer.GetSetting("TvWishList_Thursday", "false").Value.ToLower() == "true") { Thursday = true; Log.Debug("Thursday"); } bool Friday = false; if (layer.GetSetting("TvWishList_Friday", "false").Value.ToLower() == "true") { Friday = true; Log.Debug("Friday"); } bool Saturday = false; if (layer.GetSetting("TvWishList_Saturday", "false").Value.ToLower() == "true") { Saturday = true; Log.Debug("Saturday"); } string testdatestring = DateTime.Now.ToString("yyyy-MM-dd") + "_" + hournumber.ToString("D2") + ":" + minutenumber.ToString("D2"); DateTime testdate = DateTime.ParseExact(testdatestring, "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Logdebug("testdate=" + testdate.ToString()); int daynumber = 7; if (testdate > DateTime.Now) { daynumber = 0; } DayOfWeek weekday = _NextEpgTime.DayOfWeek; if (weekday == DayOfWeek.Sunday) { if (Monday) daynumber = 1; else if (Tuesday) daynumber = 2; else if (Wednesday) daynumber = 3; else if (Thursday) daynumber = 4; else if (Friday) daynumber = 5; else if (Saturday) daynumber = 6; } else if (weekday == DayOfWeek.Monday) { if (Tuesday) daynumber = 1; else if (Wednesday) daynumber = 2; else if (Thursday) daynumber = 3; else if (Friday) daynumber = 4; else if (Saturday) daynumber = 5; else if (Sunday) daynumber = 6; } else if (weekday == DayOfWeek.Tuesday) { if (Wednesday) daynumber = 1; else if (Thursday) daynumber = 2; else if (Friday) daynumber = 3; else if (Saturday) daynumber = 4; else if (Sunday) daynumber = 5; else if (Monday) daynumber = 6; } else if (weekday == DayOfWeek.Wednesday) { if (Thursday) daynumber = 1; else if (Friday) daynumber = 2; else if (Saturday) daynumber = 3; else if (Sunday) daynumber = 4; else if (Monday) daynumber = 5; else if (Tuesday) daynumber = 6; } else if (weekday == DayOfWeek.Thursday) { if (Friday) daynumber = 1; else if (Saturday) daynumber = 2; else if (Sunday) daynumber = 3; else if (Monday) daynumber = 4; else if (Tuesday) daynumber = 5; else if (Wednesday) daynumber = 6; } else if (weekday == DayOfWeek.Friday) { if (Saturday) daynumber = 1; else if (Sunday) daynumber = 2; else if (Monday) daynumber = 3; else if (Tuesday) daynumber = 4; else if (Wednesday) daynumber = 5; else if (Thursday) daynumber = 6; } else if (weekday == DayOfWeek.Saturday) { if (Sunday) daynumber = 1; else if (Monday) daynumber = 2; else if (Tuesday) daynumber = 3; else if (Wednesday) daynumber = 4; else if (Thursday) daynumber = 5; else if (Friday) daynumber = 6; } _PreviousEpgTime = _NextEpgTime; _NextEpgTime = _NextEpgTime.AddDays(daynumber); Log.Debug("_PreviousEpgTime=" + _PreviousEpgTime.ToString()); Log.Debug("_NextEpgTime=" + _NextEpgTime.ToString()); Log.Debug("daynumber=" + daynumber.ToString()); } string datestring = _NextEpgTime.ToString("yyyy-MM-dd"); datestring = datestring + "_" + hours + ":" + minutes; Logdebug("Next epg checking date set to datestring=" + datestring); _NextEpgTime = DateTime.ParseExact(datestring, "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); _NextEpgTime = EPGUpdateBeforeSchedule(_NextEpgTime); setting = layer.GetSetting("TvWishList_NextEpgDate","2999-01-01"); setting.Value = _NextEpgTime.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Logdebug("Next epg checking date set to " + setting.Value); setting.Persist(); } catch (Exception ex) { Log.Error("Error in starting setting next Epg date time: Exception message was " + ex.Message); } return _NextEpgTime; }
public void MyLoadSettings() { LogDebug("Loadsettings started", (int)LogSetting.DEBUG); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; try { setting = layer.GetSetting("TvWishList_SkipDeleted", "false"); if (BoolConversion(setting.Value,false)) checkBoxSkipDeleted.Checked = true; else checkBoxSkipDeleted.Checked = false; setting = layer.GetSetting("TvWishList_EmailReply", "true"); if (BoolConversion(setting.Value, true)) checkBoxemailreply.Checked = true; else checkBoxemailreply.Checked = false; setting = layer.GetSetting("TvWishList_Schedule", "true"); if (BoolConversion(setting.Value, true)) checkBoxschedule.Checked = true; else checkBoxschedule.Checked = false; setting = layer.GetSetting("TvWishList_ScheduleConflicts", "false"); if (BoolConversion(setting.Value, false)) checkBoxscheduleconflicts.Checked = true; else checkBoxscheduleconflicts.Checked = false; setting = layer.GetSetting("TvWishList_EmailOnlyNew", "true"); if (BoolConversion(setting.Value, true)) checkBoxEmailOnlynew.Checked = true; else checkBoxEmailOnlynew.Checked = false; setting = layer.GetSetting("TvWishList_SlowCPU", "true"); if (BoolConversion(setting.Value, true)) checkBoxSlowCPU.Checked = true; else checkBoxSlowCPU.Checked = false; setting = layer.GetSetting("TvWishList_Monday", "false"); if (BoolConversion(setting.Value, false)) checkBoxMon.Checked = true; else checkBoxMon.Checked = false; setting = layer.GetSetting("TvWishList_Tuesday", "false"); if (BoolConversion(setting.Value, false)) checkBoxTue.Checked = true; else checkBoxTue.Checked = false; setting = layer.GetSetting("TvWishList_Wednesday", "false"); if (BoolConversion(setting.Value, false)) checkBoxWed.Checked = true; else checkBoxWed.Checked = false; setting = layer.GetSetting("TvWishList_Thursday", "false"); if (BoolConversion(setting.Value, false)) checkBoxThur.Checked = true; else checkBoxThur.Checked = false; setting = layer.GetSetting("TvWishList_Friday", "false"); if (BoolConversion(setting.Value, false)) checkBoxFri.Checked = true; else checkBoxFri.Checked = false; setting = layer.GetSetting("TvWishList_Saturday", "false"); if (BoolConversion(setting.Value, false)) checkBoxSat.Checked = true; else checkBoxSat.Checked = false; setting = layer.GetSetting("TvWishList_Sunday", "false"); if (BoolConversion(setting.Value, false)) checkBoxSun.Checked = true; else checkBoxSun.Checked = false; setting = layer.GetSetting("TvWishList_Every", "false"); if (BoolConversion(setting.Value, false)) checkBoxEvery.Checked = true; else checkBoxEvery.Checked = false; setting = layer.GetSetting("TvWishList_DeleteTimeChanges", "false"); if (BoolConversion(setting.Value, false)) checkBoxDeleteChangedEPG.Checked = true; else checkBoxDeleteChangedEPG.Checked = false; setting = layer.GetSetting("TvWishList_FilterEmail", "true"); if (BoolConversion(setting.Value, true)) checkBoxFilterEmail.Checked = true; else checkBoxFilterEmail.Checked = false; setting = layer.GetSetting("TvWishList_FilterRecord", "false"); if (BoolConversion(setting.Value, false)) checkBoxFilterRecord.Checked = true; else checkBoxFilterRecord.Checked = false; setting = layer.GetSetting("TvWishList_FilterConflicts", "true"); if (BoolConversion(setting.Value, true)) checkBoxFilterConflicts.Checked = true; else checkBoxFilterConflicts.Checked = false; setting = layer.GetSetting("TvWishList_DescendingSort", "false"); if (BoolConversion(setting.Value, false)) checkBoxdescendingSort.Checked = true; else checkBoxdescendingSort.Checked = false; setting = layer.GetSetting("TvWishList_Easy", "true"); if (BoolConversion(setting.Value, true)) { radioButtonEasy.Checked = true; } setting = layer.GetSetting("TvWishList_Expert", "false"); if (BoolConversion(setting.Value, false)) { radioButtonExpert.Checked = true; } LogDebug("TvWishList_Expert=" + radioButtonExpert.Checked.ToString(), (int)LogSetting.DEBUG); setting = layer.GetSetting("TvWishList_DateTimeFormat", "{1:00}/{2:00} at {3:00}:{4:00}"); textBoxDateTimeFormat.Text = setting.Value; //LogDebug("TvWishList_DateTimeFormat=" + setting.Value, (int)LogSetting.DEBUG); textBoxEmailFormat.Text = myTvWishes.loadlongsettings("TvWishList_EmailFormat"); setting = layer.GetSetting("TvWishList_Sort", "Start"); Log.Debug("TvWishList_Sort=" + setting.Value); comboBoxSortCriteria.Text = SortCriteriaTranslation(setting.Value); setting = layer.GetSetting("TvWishList_EpgMarker", ""); textBoxEpgMark.Text = setting.Value; setting = layer.GetSetting("TvWishList_LanguageFile", "strings_en.xml"); comboBoxLanguage.Text = LanguageFileTranslation(setting.Value); Log.Debug("TvWishList_LanguageFile="+setting.Value); setting = layer.GetSetting("TvWishList_UserName", ""); TextBoxUserName.Text = setting.Value; setting = layer.GetSetting("TvWishList_Password", ""); TextBoxPassword.Text = setting.Value; TextBoxPassword2.Text = setting.Value; setting = layer.GetSetting("TvWishList_TestReceiver", ""); TextBoxTestReceiver.Text = setting.Value; setting = layer.GetSetting("TvWishList_SmtpEmailAddress", ""); textBoxSmtpEmailAdress.Text = setting.Value; if (textBoxSmtpEmailAdress.Text == "") { textBoxSmtpEmailAdress.Text = TextBoxUserName.Text; } //combobox setting = layer.GetSetting("TvWishList_WaitComSkipMinutes", "60"); try { int i = Convert.ToInt32(setting.Value); comboBoxComSkipWaitMinutes.Text = setting.Value; } catch { comboBoxComSkipWaitMinutes.Text = "60"; } setting = layer.GetSetting("TvWishList_CheckEpgDays", "07"); comboBoxdays.Text = setting.Value; //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxdays, "D2", 1, 14, "Days"); setting = layer.GetSetting("TvWishList_CheckEpgHours", "06"); comboBoxhours.Text = setting.Value; //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxhours, "D2", 0, 23, "Hours"); setting = layer.GetSetting("TvWishList_CheckEpgMinutes", "00"); comboBoxminutes.Text = setting.Value; //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxminutes, "D2", 0, 59, "Minutes"); setting = layer.GetSetting("TvWishList_BeforeEPGMinutes", "00"); comboBoxScheduleMinutes.Text = setting.Value; //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxScheduleMinutes, "D2", 0, 59, "Minutes"); setting = layer.GetSetting("TvWishList_CheckEPGScheduleMinutes", "false"); //Log.Debug("TvWishList_CheckEPGScheduleMinutes"+setting.Value); try { checkBoxScheduleMinutes.Checked = Convert.ToBoolean(setting.Value); } catch { checkBoxScheduleMinutes.Checked = false; } try { setting = layer.GetSetting("TvWishList_ChannelGroups", "Any"); comboBoxGroups.Text = setting.Value; } catch { comboBoxGroups.Text = "Any"; } //maxfound setting = layer.GetSetting("TvWishList_MaxFound", "100"); comboBoxmaxfound.Text = setting.Value; //checkcombotextbox(ref ComboBox mycombobox,string format,int min, int max, string fieldname); checkcombotextbox(ref comboBoxmaxfound, "", 1, 1000000000, "Max Found"); setting = layer.GetSetting("TvWishList_MaxTvWishId", "0"); int maxTvWishId = 0; int.TryParse(setting.Value, out maxTvWishId); myTvWishes.MaxTvWishId = maxTvWishId; LogDebug("LoadSettings: MaxTvWishId=" + myTvWishes.MaxTvWishId.ToString(), (int)LogSetting.DEBUG); setting = layer.GetSetting("TvWishList_DeleteExpiration", "12"); comboBoxDeleteExpiration.Text = setting.Value; //initialize messages string messagedata = ""; //mymessage = new XmlMessages(mymessage.date_time_format, mymessage.EmailFormat, DEBUG); messagedata = myTvWishes.loadlongsettings("TvWishList_ListViewMessages"); mymessage.readxmlfile(messagedata, false); Log.Debug(mymessage.ListAllTvMessages().Count.ToString()+" messages read"); setting = layer.GetSetting("TvWishList_ColumnSeparator", ";"); TV_WISH_COLUMN_SEPARATOR = setting.Value[0]; //default pre and post record from general recording settings setting = layer.GetSetting("preRecordInterval", "5"); PRERECORD = setting.Value; setting = layer.GetSetting("postRecordInterval", "5"); POSTRECORD = setting.Value; //initialize tvserver settings in TvWish for checking of channels myTvWishes.TvServerSettings(PRERECORD, POSTRECORD, ChannelGroup.ListAll(), RadioChannelGroup.ListAll(), Channel.ListAll(), Card.ListAll(), TV_WISH_COLUMN_SEPARATOR); //listviewdata //Log.Debug("Turnuing off eventhandler for adding rows"); //dataGridView1.RowsAdded -= new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded); DataGridViewComboBoxColumn channelfilter = dataGridView1.Columns[22] as DataGridViewComboBoxColumn; string addnames = ";"; for (int i = 0; i < channelfilter.Items.Count; i++) { addnames += channelfilter.Items[i] + ";" as String; } //convert defaultdata with language translation string[] columndata = (string[])myTvWishes.DefaultValues.Clone(); TvWish defaultwish = new TvWish(); defaultwish = myTvWishes.CreateTvWish(true, columndata); //Log.Debug("defaultwish with Languagetranslation"); myTvWishes.DebugTvWish(defaultwish); //define nullvalues for datagrid with language translation DataGridViewCheckBoxColumn active = dataGridView1.Columns[(int)TvWishEntries.active] as DataGridViewCheckBoxColumn; active.DefaultCellStyle.NullValue = defaultwish.b_active; DataGridViewCheckBoxColumn skip = dataGridView1.Columns[(int)TvWishEntries.skip] as DataGridViewCheckBoxColumn; skip.DefaultCellStyle.NullValue = defaultwish.b_skip; DataGridViewCheckBoxColumn includerecordings = dataGridView1.Columns[(int)TvWishEntries.includerecordings] as DataGridViewCheckBoxColumn; includerecordings.DefaultCellStyle.NullValue = defaultwish.b_includeRecordings; DataGridViewTextBoxColumn searchfor = dataGridView1.Columns[(int)TvWishEntries.searchfor] as DataGridViewTextBoxColumn; searchfor.DefaultCellStyle.NullValue = defaultwish.searchfor; DataGridViewComboBoxColumn matchtype = dataGridView1.Columns[(int)TvWishEntries.matchtype] as DataGridViewComboBoxColumn; matchtype.DefaultCellStyle.NullValue = defaultwish.matchtype; DataGridViewComboBoxColumn group = dataGridView1.Columns[(int)TvWishEntries.group] as DataGridViewComboBoxColumn; group.DefaultCellStyle.NullValue = defaultwish.group; DataGridViewComboBoxColumn recordtype = dataGridView1.Columns[(int)TvWishEntries.recordtype] as DataGridViewComboBoxColumn; recordtype.DefaultCellStyle.NullValue = defaultwish.recordtype; DataGridViewComboBoxColumn action = dataGridView1.Columns[(int)TvWishEntries.action] as DataGridViewComboBoxColumn; action.DefaultCellStyle.NullValue = defaultwish.action; DataGridViewTextBoxColumn exclude = dataGridView1.Columns[(int)TvWishEntries.exclude] as DataGridViewTextBoxColumn; exclude.DefaultCellStyle.NullValue = defaultwish.exclude; DataGridViewTextBoxColumn prerecord = dataGridView1.Columns[(int)TvWishEntries.prerecord] as DataGridViewTextBoxColumn; prerecord.DefaultCellStyle.NullValue = defaultwish.prerecord; DataGridViewTextBoxColumn postrecord = dataGridView1.Columns[(int)TvWishEntries.postrecord] as DataGridViewTextBoxColumn; postrecord.DefaultCellStyle.NullValue = defaultwish.postrecord; DataGridViewTextBoxColumn episodename = dataGridView1.Columns[(int)TvWishEntries.episodename] as DataGridViewTextBoxColumn; episodename.DefaultCellStyle.NullValue = defaultwish.episodename; DataGridViewTextBoxColumn episodepart = dataGridView1.Columns[(int)TvWishEntries.episodepart] as DataGridViewTextBoxColumn; episodepart.DefaultCellStyle.NullValue = defaultwish.episodepart; DataGridViewTextBoxColumn episodenumber = dataGridView1.Columns[(int)TvWishEntries.episodenumber] as DataGridViewTextBoxColumn; episodenumber.DefaultCellStyle.NullValue = defaultwish.episodenumber; DataGridViewTextBoxColumn seriesnumber = dataGridView1.Columns[(int)TvWishEntries.seriesnumber] as DataGridViewTextBoxColumn; seriesnumber.DefaultCellStyle.NullValue = defaultwish.seriesnumber; DataGridViewTextBoxColumn keepepisodes = dataGridView1.Columns[(int)TvWishEntries.keepepisodes] as DataGridViewTextBoxColumn; keepepisodes.DefaultCellStyle.NullValue = defaultwish.keepepisodes; DataGridViewTextBoxColumn keepuntil = dataGridView1.Columns[(int)TvWishEntries.keepuntil] as DataGridViewTextBoxColumn; keepuntil.DefaultCellStyle.NullValue = defaultwish.keepuntil; DataGridViewComboBoxColumn recommendedcard = dataGridView1.Columns[(int)TvWishEntries.recommendedcard] as DataGridViewComboBoxColumn; recommendedcard.DefaultCellStyle.NullValue = defaultwish.recommendedcard; DataGridViewComboBoxColumn priority = dataGridView1.Columns[(int)TvWishEntries.priority] as DataGridViewComboBoxColumn; priority.DefaultCellStyle.NullValue = defaultwish.priority; DataGridViewTextBoxColumn aftertime = dataGridView1.Columns[(int)TvWishEntries.aftertime] as DataGridViewTextBoxColumn; aftertime.DefaultCellStyle.NullValue = defaultwish.aftertime; DataGridViewTextBoxColumn beforetime = dataGridView1.Columns[(int)TvWishEntries.beforetime] as DataGridViewTextBoxColumn; beforetime.DefaultCellStyle.NullValue = defaultwish.beforetime; DataGridViewComboBoxColumn afterdays = dataGridView1.Columns[(int)TvWishEntries.afterdays] as DataGridViewComboBoxColumn; afterdays.DefaultCellStyle.NullValue = defaultwish.afterdays; DataGridViewComboBoxColumn beforedays = dataGridView1.Columns[(int)TvWishEntries.beforedays] as DataGridViewComboBoxColumn; beforedays.DefaultCellStyle.NullValue = defaultwish.beforedays; DataGridViewComboBoxColumn channel = dataGridView1.Columns[(int)TvWishEntries.channel] as DataGridViewComboBoxColumn; channel.DefaultCellStyle.NullValue = defaultwish.channel; DataGridViewTextBoxColumn name = dataGridView1.Columns[(int)TvWishEntries.name] as DataGridViewTextBoxColumn; name.DefaultCellStyle.NullValue = defaultwish.name; DataGridViewComboBoxColumn useFolderName = dataGridView1.Columns[(int)TvWishEntries.useFolderName] as DataGridViewComboBoxColumn; useFolderName.DefaultCellStyle.NullValue = defaultwish.useFolderName; DataGridViewTextBoxColumn withinNextHours = dataGridView1.Columns[(int)TvWishEntries.withinNextHours] as DataGridViewTextBoxColumn; withinNextHours.DefaultCellStyle.NullValue = defaultwish.withinNextHours; DataGridViewComboBoxColumn episodecriteria = dataGridView1.Columns[(int)TvWishEntries.episodecriteria] as DataGridViewComboBoxColumn; episodecriteria.DefaultCellStyle.NullValue = defaultwish.episodecriteria; DataGridViewComboBoxColumn preferredgroup = dataGridView1.Columns[(int)TvWishEntries.preferredgroup] as DataGridViewComboBoxColumn; preferredgroup.DefaultCellStyle.NullValue = defaultwish.preferredgroup; //load all tvwishes string listviewdata = myTvWishes.loadlongsettings("TvWishList_ListView"); LogDebug("liestview=" + listviewdata, (int)LogSetting.DEBUG); myTvWishes.LoadFromString(listviewdata, true); //needed for later checking in savesettings() //fill datagridview LogDebug("initial datagrid rowcount=" + dataGridView1.Rows.Count.ToString(), (int)LogSetting.DEBUG); int newrow = dataGridView1.Rows.Count - 1; if (newrow == 0) //fill only the first time, datagrid is being remembered { Log.Debug("myTvWishes.ListAll().Count="+myTvWishes.ListAll().Count.ToString()); foreach (TvWish mywish in myTvWishes.ListAll()) { newrow = dataGridView1.Rows.Count - 1; Log.Debug("searchfor" + mywish.searchfor); Log.Debug("newrow=" + newrow.ToString()); if (addnames.Contains(";" + mywish.channel + ";") == false)//add new channel names { channelfilter.Items.Add(mywish.channel); addnames += mywish.channel + ";"; //LogDebug("loadsetting addnames: " + addnames, (int)LogSetting.DEBUG); } LoadTvWishToDataGridRow(newrow, mywish); } Log.Debug(myTvWishes.ListAll().Count.ToString()+" Tvwishes added"); }//end fill datagrid updatechannelnames(); //dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded); //Log.Debug("Turnuing on eventhandler for adding rows"); //end listviewdata //load providervalues setdefaultproviders(false); //load last settings and store it in providerstring [0] setting = layer.GetSetting("TvWishList_Providers_0", "_Last Setting;;0;False"); providers[0] = setting.Value; //LogDebug("Load settings: provider_0=" + providers[0]); try { translateprovider(providers[0]); //restore last user settings providers[0] } catch { LogDebug("translateprovider(providers[0]= " + providers[0] + " failed", (int)LogSetting.DEBUG); } //labels DateTime NextEpgDate = DateTime.Now; setting = layer.GetSetting("TvWishList_NextEpgDate", DateTime.Now.ToString("yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture)); try { NextEpgDate = DateTime.ParseExact(setting.Value, "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); } catch (Exception exc) { LogDebug("NextEpgDate failed with exception: " + exc.Message, (int)LogSetting.ERROR); } Log.Debug("FormatConversion:"); string mydate = NextEpgDate.ToString(lng.TranslateString(@"MM/dd/yyyy", 189), System.Globalization.CultureInfo.InvariantCulture); Log.Debug("mydate=" + mydate); string mytime = NextEpgDate.ToString(lng.TranslateString(@"HH:mm", 190), System.Globalization.CultureInfo.InvariantCulture); Log.Debug("mytime=" + mytime); labelCheckingdate.Text = lng.TranslateString("{0} at {1}",191,mydate,mytime); Log.Debug("labelCheckingdate.Text" + labelCheckingdate.Text); //integer values setting = layer.GetSetting("TvWishList_ProviderSelected", "0"); int j = 0; int.TryParse(setting.Value, out j); if ((j < 0) || (j > listBoxProvider2.Items.Count)) { j = 0; } try { listBoxProvider2.SetSelected(0, true); //select custom item in listbox } catch (Exception exc) { LogDebug("listBoxProvider2.SetSelected failed with exception: " + exc.Message, (int)LogSetting.ERROR); } LogDebug("LoadSettings Completed", (int)LogSetting.DEBUG); LoadSettingError = false; } catch (Exception exc) { LogDebug("LoadSettings Error: Exception: "+exc.Message, (int)LogSetting.ERROR); LoadSettingError = true; } }
public bool UnLockTvWishList() { TvBusinessLayer layer = new TvBusinessLayer(); Setting setting; Log.Debug("UnLockTvWishList: Trying to unlock Tvwishes"); try { //tell pluginversion setting = layer.GetSetting("TvWishList_LockingPluginname", "NONE"); string owner=setting.Value; if (owner == _LockingPluginname) { setting.Value = "NONE"; _LockingPluginname = "NONE"; setting.Persist(); //create old timestamp setting = layer.GetSetting("TvWishList_TimeStampLock", "1999-12-31 11:59:00"); setting.Value = "1999-12-31 11:59:00"; setting.Persist(); //set BUSY = false setting = layer.GetSetting("TvWishList_BUSY", "false"); setting.Value = "false"; setting.Persist(); Log.Debug("TvWishList has been sucessfully unlocked by "+owner, (int)LogSetting.DEBUG); return true; } else { Log.Debug("TvWishList could not be unlocked - owner is " + setting.Value, (int)LogSetting.ERROR); return false; } } catch (Exception exc) { Log.Debug("TvWishList could not be unlocked - exception: "+exc.Message, (int)LogSetting.ERROR); return false; } }