private void InitChannels()
    {
      listViewChannels.Clear();
      listViewChannels.BeginUpdate();
      try
      {
        SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof (Channel));
        if (checkBoxGuideChannels.Checked)
        {
          sb.AddConstraint(Operator.Equals, "visibleInGuide", 1);
        }
        sb.AddConstraint(Operator.Equals, "isTv", 1);
        sb.AddOrderByField(true, "sortOrder");
        sb.AddOrderByField(true, "displayName");
        SqlStatement stmt = sb.GetStatement(true);
        IList<Channel> channels = ObjectFactory.GetCollection<Channel>(stmt.Execute());

        for (int i = 0; i < channels.Count; i++)
        {
          // TODO: add imagelist with channel logos from MP :)
          ListViewItem curItem = new ListViewItem(channels[i].DisplayName);
          curItem.Tag = channels[i];
          listViewChannels.Items.Add(curItem);
        }
      }
      finally
      {
        listViewChannels.EndUpdate();
      }
      mpButtonOk.Enabled = (listViewChannels.Items.Count > 0);
    }
    public void OnActivated()
    {
      try
      {
        Application.DoEvents();

        Cursor.Current = Cursors.WaitCursor;

        UpdateMenuAndTabs();

        listView1.Items.Clear();
        SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (GroupMap));

        sb.AddConstraint(Operator.Equals, "idGroup", _channelGroup.IdGroup);
        sb.AddOrderByField(true, "sortOrder");

        SqlStatement stmt = sb.GetStatement(true);

        IList<GroupMap> maps = ObjectFactory.GetCollection<GroupMap>(stmt.Execute());

        foreach (GroupMap map in maps)
        {
          Channel channel = map.ReferencedChannel();
          if (!channel.IsTv)
          {
            continue;
          }
          listView1.Items.Add(CreateItemForChannel(channel, map));
        }
        bool isAllChannelsGroup = (_channelGroup.GroupName == TvConstants.TvGroupNames.AllChannels);
        removeChannelFromGroup.Enabled = !isAllChannelsGroup;
        mpButtonDel.Enabled = !isAllChannelsGroup;

        if (_channelGroup.GroupName != TvConstants.TvGroupNames.AllChannels)
        {
          labelPinCode.Visible = true;
          textBoxPinCode.Visible = true;
          textBoxPinCode.Text = _channelGroup.PinCode;
        }

      }
      catch (Exception exp)
      {
        Log.Error("OnActivated error: {0}", exp.Message);
      }
      finally
      {
        Cursor.Current = Cursors.Default;
      }
    }
 public List<WebProgram> GetEPGForChannel(string idChannel,string startTime,string endTime)
 {
     List<WebProgram> infos = new List<WebProgram>();
       if (!ConnectToDatabase())
     return infos;
       DateTime dtStart; DateTime dtEnd;
       if (!DateTime.TryParse(startTime,out dtStart))
     return infos;
       if (!DateTime.TryParse(endTime, out dtEnd))
     return infos;
       IFormatProvider mmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
       try
       {
     SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof(Program));
     sb.AddConstraint(Operator.Equals, "idChannel", Int32.Parse(idChannel));
     sb.AddConstraint(String.Format("startTime>='{0}'", dtStart.ToString(GetDateTimeString(), mmddFormat)));
     sb.AddConstraint(String.Format("endTime<='{0}'", dtEnd.ToString(GetDateTimeString(), mmddFormat)));
     sb.AddOrderByField(true, "startTime");
     SqlStatement stmt = sb.GetStatement(true);
     IList programs = ObjectFactory.GetCollection(typeof(Program), stmt.Execute());
     if (programs != null && programs.Count > 0)
     {
       foreach (Program prog in programs)
     infos.Add(new WebProgram(prog));
     }
       }
       catch (Exception)
       {
       }
       return infos;
 }
예제 #4
0
        public List<Program> GetEPGForChannel(string idChannel, DateTime startTime, DateTime endTime)
        {
            IFormatProvider mmddFormat = new CultureInfo(String.Empty, false);
            //List<Program> infos = new List<Program>();

            try
            {
                SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof(Program));
                sb.AddConstraint(Operator.Equals, "idChannel", Int32.Parse(idChannel));
                if (startTime >= DateTime.Now)
                {
                    DateTime thisMorning = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                    sb.AddConstraint(String.Format("startTime>='{0}'", thisMorning.ToString(GetDateTimeString(), mmddFormat)));
                }
                else
                {
                    sb.AddConstraint(String.Format("startTime>='{0}'", startTime.ToString(GetDateTimeString(), mmddFormat)));
                }
                if (endTime>DateTime.Now)
                {
                    sb.AddConstraint(String.Format("endTime<='{0}'", endTime.ToString(GetDateTimeString(), mmddFormat)));
                }
                sb.AddOrderByField(true, "startTime");
                SqlStatement stmt = sb.GetStatement(true);
                IList programs = ObjectFactory.GetCollection(typeof(Program), stmt.Execute());
                return (List<Program>) programs;
            }
            catch(Exception e)
            {
                Console.WriteLine("Error while obtaining the EPG for channel " + idChannel + ": " + e.Message);
                Log.Debug("TVServerKodi: Error while obtaining the EPG for channel " + idChannel + ": " + e.Message);
            }
            return null;
        }
예제 #5
0
    protected override void OnPageLoad()
    {
      Log.Debug("zaposd pageload");
      // following line should stay. Problems with OSD not
      // appearing are already fixed elsewhere
      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
      sb.AddConstraint(Operator.Equals, "istv", 1);
      sb.AddOrderByField(true, "sortOrder");
      SqlStatement stmt = sb.GetStatement(true);
      ObjectFactory.GetCollection(typeof (Channel), stmt.Execute());

      AllocResources();
      // if (g_application.m_pPlayer) g_application.m_pPlayer.ShowOSD(false);
      ResetAllControls(); // make sure the controls are positioned relevant to the OSD Y offset
      m_bNeedRefresh = false;
      m_dateTime = DateTime.Now;
      channelNr = GetChannelNumber();
      channelName = GetChannelName();
      idChannel = GetIdChannel();
      SetCurrentChannelLogo();
      base.OnPageLoad();

      GUIPropertyManager.SetProperty("#currentmodule", GUILocalizeStrings.Get(100000 + GetID));
    }
예제 #6
0
 public DateTime GetNewestProgramForChannel(int idChannel)
 {
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Program));
   sb.AddConstraint(Operator.Equals, "idChannel", idChannel);
   sb.AddOrderByField(false, "startTime");
   sb.SetRowLimit(1);
   SqlStatement stmt = sb.GetStatement(true);
   IList<Program> progs = ObjectFactory.GetCollection<Program>(stmt.Execute());
   return progs.Count > 0 ? progs[0].StartTime : DateTime.MinValue;
 }
예제 #7
0
 public IList<Card> ListAllEnabledCardsOrderedByPriority()
 {
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Card));
   sb.AddConstraint("enabled=1");
   sb.AddOrderByField(false, "priority");
   SqlStatement stmt = sb.GetStatement(true);
   return ObjectFactory.GetCollection<Card>(stmt.Execute());
 }
예제 #8
0
    public override bool OnMessage(GUIMessage message)
    {
      switch (message.Message)
      {
        case GUIMessage.MessageType.GUI_MSG_WINDOW_DEINIT: // fired when OSD is hidden
          {
            //if (g_application.m_pPlayer) g_application.m_pPlayer.ShowOSD(true);
            // following line should stay. Problems with OSD not
            // appearing are already fixed elsewhere
            //for (int i = (int)Controls.Panel1; i < (int)Controls.Panel2; i++)
            //{
            //  HideControl(GetID, i);
            //}
            Dispose();
            GUIPropertyManager.SetProperty("#currentmodule", GUIWindowManager.GetWindow(message.Param1).GetModuleName());
            return true;
          }


        case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT: // fired when OSD is shown
          {
            // following line should stay. Problems with OSD not
            // appearing are already fixed elsewhere
            SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
            sb.AddConstraint(Operator.Equals, "istv", 1);
            sb.AddOrderByField(true, "sortOrder");
            SqlStatement stmt = sb.GetStatement(true);
            listTvChannels = ObjectFactory.GetCollection(typeof (Channel), stmt.Execute());
            GUIPropertyManager.SetProperty("#currentmodule", GetModuleName());
            previousProgram = null;
            AllocResources();
            // if (g_application.m_pPlayer) g_application.m_pPlayer.ShowOSD(false);
            ResetAllControls(); // make sure the controls are positioned relevant to the OSD Y offset
            isSubMenuVisible = false;
            m_iActiveMenuButtonID = 0;
            m_iActiveMenu = 0;
            m_bNeedRefresh = false;
            m_dateTime = DateTime.Now;
            Reset();
            FocusControl(GetID, (int)Controls.OSD_PLAY, 0); // set focus to play button by default when window is shown
            ShowPrograms();
            QueueAnimation(AnimationType.WindowOpen);
            for (int i = (int)Controls.Panel1; i < (int)Controls.Panel2; i++)
            {
              ShowControl(GetID, i);
            }
            if (g_Player.Paused)
            {
              ToggleButton((int)Controls.OSD_PLAY, true);
              // make sure play button is down (so it shows the pause symbol)
            }
            else
            {
              ToggleButton((int)Controls.OSD_PLAY, false); // make sure play button is up (so it shows the play symbol)
            }
            m_delayInterval = MediaPortal.Player.Subtitles.SubEngine.GetInstance().DelayInterval;
            if (m_delayInterval > 0)
              m_subtitleDelay = MediaPortal.Player.Subtitles.SubEngine.GetInstance().Delay / m_delayInterval;
            m_delayIntervalAudio = PostProcessingEngine.GetInstance().AudioDelayInterval;
            if (m_delayIntervalAudio > 0)
              m_audioDelay = PostProcessingEngine.GetInstance().AudioDelay / m_delayIntervalAudio;

            g_Player.UpdateMediaInfoProperties();
            GUIPropertyManager.SetProperty("#TV.View.HasTeletext", TVHome.Card.HasTeletext.ToString());

            MediaPortal.Player.VideoStreamFormat videoFormat = g_Player.GetVideoFormat();

            GUIPropertyManager.SetProperty("#Play.Current.TSBitRate",
             ((float)MediaPortal.Player.g_Player.GetVideoFormat().bitrate / 1024 / 1024).ToString("0.00", CultureInfo.InvariantCulture));

            GUIPropertyManager.SetProperty("#Play.Current.VideoFormat.RawResolution",
              videoFormat.width.ToString() + "x" + videoFormat.height.ToString());

            GUIPropertyManager.SetProperty("#TV.TuningDetails.FreeToAir", string.Empty);

            Channel chan = TVHome.Navigator.Channel;
            if (chan != null)
            {
              IList<TuningDetail> details = chan.ReferringTuningDetail();
              if (details.Count > 0)
              {
                TuningDetail detail = null;
                switch (TVHome.Card.Type)
                {
                  case TvLibrary.Interfaces.CardType.Analog:
                    foreach (TuningDetail t in details)
                    {
                      if (t.ChannelType == 0)
                        detail = t;
                    }
                    break;
                  case TvLibrary.Interfaces.CardType.Atsc:
                    foreach (TuningDetail t in details)
                    {
                      if (t.ChannelType == 1)
                        detail = t;
                    }
                    break;
                  case TvLibrary.Interfaces.CardType.DvbC:
                    foreach (TuningDetail t in details)
                    {
                      if (t.ChannelType == 2)
                        detail = t;
                    }
                    break;
                  case TvLibrary.Interfaces.CardType.DvbS:
                    foreach (TuningDetail t in details)
                    {
                      if (t.ChannelType == 3)
                        detail = t;
                    }
                    break;
                  case TvLibrary.Interfaces.CardType.DvbT:
                    foreach (TuningDetail t in details)
                    {
                      if (t.ChannelType == 4)
                        detail = t;
                    }
                    break;
                  default:
                    detail = details[0];
                    break;
                }
                GUIPropertyManager.SetProperty("#TV.TuningDetails.FreeToAir", detail.FreeToAir.ToString());
              }
            }
          }
          return true;

        case GUIMessage.MessageType.GUI_MSG_SETFOCUS:
          goto case GUIMessage.MessageType.GUI_MSG_LOSTFOCUS;

        case GUIMessage.MessageType.GUI_MSG_LOSTFOCUS:
          {
            if (message.SenderControlId == 13)
            {
              return true;
            }
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_CLICKED:
          {
            int iControl = message.SenderControlId; // get the ID of the control sending us a message

            if (iControl == btnChannelUp.GetID)
            {
              OnNextChannel();
            }

            if (iControl == btnChannelDown.GetID)
            {
              OnPreviousChannel();
            }

            if (!g_Player.IsTVRecording)
            {
              if (iControl == btnPreviousProgram.GetID)
              {
                Program prog = GetChannel().GetProgramAt(m_dateTime);
                if (prog != null)
                {
                  prog =
                    GetChannel().GetProgramAt(
                      prog.StartTime.Subtract(new TimeSpan(0, 1, 0)));
                  if (prog != null)
                  {
                    m_dateTime = prog.StartTime.AddMinutes(1);
                  }
                }
                ShowPrograms();
              }
              if (iControl == btnNextProgram.GetID)
              {
                Program prog = GetChannel().GetProgramAt(m_dateTime);
                if (prog != null)
                {
                  prog = GetChannel().GetProgramAt(prog.EndTime.AddMinutes(+1));
                  if (prog != null)
                  {
                    m_dateTime = prog.StartTime.AddMinutes(1);
                  }
                }
                ShowPrograms();
              }
            }

            if (iControl >= (int)Controls.OSD_VOLUMESLIDER)
              // one of the settings (sub menu) controls is sending us a message
            {
              Handle_ControlSetting(iControl, message.Param1);
            }

            if (iControl == (int)Controls.OSD_PAUSE)
            {
              if (g_Player.Paused)
              {
                ToggleButton((int)Controls.OSD_PLAY, true);
                // make sure play button is down (so it shows the pause symbol)                
                ToggleButton((int)Controls.OSD_FFWD, false); // pop the button back to it's up state
                ToggleButton((int)Controls.OSD_REWIND, false); // pop the button back to it's up state
              }
              else
              {
                ToggleButton((int)Controls.OSD_PLAY, false);
                // make sure play button is up (so it shows the play symbol)
                if (g_Player.Speed < 1) // are we not playing back at normal speed
                {
                  ToggleButton((int)Controls.OSD_REWIND, true); // make sure out button is in the down position
                  ToggleButton((int)Controls.OSD_FFWD, false); // pop the button back to it's up state
                }
                else
                {
                  ToggleButton((int)Controls.OSD_REWIND, false); // pop the button back to it's up state
                  if (g_Player.Speed == 1)
                  {
                    ToggleButton((int)Controls.OSD_FFWD, false); // pop the button back to it's up state
                  }
                }
              }
            }

            if (iControl == (int)Controls.OSD_PLAY)
            {
              //TODO
              int iSpeed = g_Player.Speed;
              if (iSpeed != 1) // we're in ffwd or rewind mode
              {
                g_Player.Speed = 1; // drop back to single speed
                ToggleButton((int)Controls.OSD_REWIND, false); // pop all the relevant
                ToggleButton((int)Controls.OSD_FFWD, false); // buttons back to
                ToggleButton((int)Controls.OSD_PLAY, false); // their up state
              }
              else
              {
                g_Player.Pause(); // Pause/Un-Pause playback
                if (g_Player.Paused)
                {
                  ToggleButton((int)Controls.OSD_PLAY, true);
                  // make sure play button is down (so it shows the pause symbol)
                }
                else
                {
                  ToggleButton((int)Controls.OSD_PLAY, false);
                  // make sure play button is up (so it shows the play symbol)
                }
              }
            }

            if (iControl == (int)Controls.OSD_STOP)
            {
              if (isSubMenuVisible) // sub menu currently active ?
              {
                FocusControl(GetID, m_iActiveMenuButtonID, 0); // set focus to last menu button
                ToggleSubMenu(0, m_iActiveMenu); // hide the currently active sub-menu
              }
              //g_application.m_guiWindowFullScreen.m_bOSDVisible = false;	// toggle the OSD off so parent window can de-init
              Log.Debug("TVOSD:stop");
              if (TVHome.Card.IsRecording)
              {
                int id = TVHome.Card.RecordingScheduleId;
                if (id > 0)
                {
                  TVHome.TvServer.StopRecordingSchedule(id);
                }
              }
              //GUIWindowManager.ShowPreviousWindow();							// go back to the previous window
            }

            if (iControl == (int)Controls.OSD_REWIND)
            {
              if (g_Player.Paused)
              {
                g_Player.Pause(); // Unpause playback
              }

              if (g_Player.Speed < 1) // are we not playing back at normal speed
              {
                ToggleButton((int)Controls.OSD_REWIND, true); // make sure out button is in the down position
                ToggleButton((int)Controls.OSD_FFWD, false); // pop the button back to it's up state
              }
              else
              {
                ToggleButton((int)Controls.OSD_REWIND, false); // pop the button back to it's up state
                if (g_Player.Speed == 1)
                {
                  ToggleButton((int)Controls.OSD_FFWD, false); // pop the button back to it's up state
                }
              }
            }

            if (iControl == (int)Controls.OSD_FFWD)
            {
              if (g_Player.Paused)
              {
                g_Player.Pause(); // Unpause playback
              }

              if (g_Player.Speed > 1) // are we not playing back at normal speed
              {
                ToggleButton((int)Controls.OSD_FFWD, true); // make sure out button is in the down position
                ToggleButton((int)Controls.OSD_REWIND, false); // pop the button back to it's up state
              }
              else
              {
                ToggleButton((int)Controls.OSD_FFWD, false); // pop the button back to it's up state
                if (g_Player.Speed == 1)
                {
                  ToggleButton((int)Controls.OSD_REWIND, false); // pop the button back to it's up state
                }
              }
            }

            if (iControl == (int)Controls.OSD_SKIPBWD)
            {
              if (_immediateSeekIsRelative)
              {
                g_Player.SeekRelativePercentage(-_immediateSeekValue);
              }
              else
              {
                g_Player.SeekRelative(-_immediateSeekValue);
              }
              ToggleButton((int)Controls.OSD_SKIPBWD, false); // pop the button back to it's up state
            }

            if (iControl == (int)Controls.OSD_SKIPFWD)
            {
              if (_immediateSeekIsRelative)
              {
                g_Player.SeekRelativePercentage(_immediateSeekValue);
              }
              else
              {
                g_Player.SeekRelative(_immediateSeekValue);
              }
              ToggleButton((int)Controls.OSD_SKIPFWD, false); // pop the button back to it's up state
            }

            if (iControl == (int)Controls.OSD_MUTE)
            {
              ToggleSubMenu(iControl, (int)Controls.OSD_SUBMENU_BG_VOL); // hide or show the sub-menu
              if (isSubMenuVisible) // is sub menu on?
              {
                int iValue = g_Player.Volume;
                GUISliderControl pSlider = GetControl((int)Controls.OSD_VOLUMESLIDER) as GUISliderControl;
                if (null != pSlider)
                {
                  pSlider.Percentage = iValue; // Update our volume slider accordingly ...
                }
                ShowControl(GetID, (int)Controls.OSD_VOLUMESLIDER); // show the volume control
                ShowControl(GetID, (int)Controls.OSD_VOLUMESLIDER_LABEL);
                FocusControl(GetID, (int)Controls.OSD_VOLUMESLIDER, 0); // set focus to it
              }
              else // sub menu is off
              {
                FocusControl(GetID, (int)Controls.OSD_MUTE, 0); // set focus to the mute button
              }
            }

            if (iControl == (int)Controls.OSD_SUBTITLES)
            {
              ToggleSubMenu(iControl, (int)Controls.OSD_SUBMENU_BG_SUBTITLES); // hide or show the sub-menu
              if (isSubMenuVisible)
              {
                // set the controls values
                GUISliderControl pControl = (GUISliderControl)GetControl((int)Controls.OSD_SUBTITLE_DELAY);
                pControl.SpinType = GUISpinControl.SpinType.SPIN_CONTROL_TYPE_FLOAT;
                pControl.FloatInterval = 1;
                pControl.SetRange(-10, 10);
                SetSliderValue(-10, 10, m_subtitleDelay, (int)Controls.OSD_SUBTITLE_DELAY);
                SetCheckmarkValue(g_Player.EnableSubtitle, (int)Controls.OSD_SUBTITLE_ONOFF);
                // show the controls on this sub menu
                ShowControl(GetID, (int)Controls.OSD_SUBTITLE_DELAY);
                ShowControl(GetID, (int)Controls.OSD_SUBTITLE_DELAY_LABEL);
                ShowControl(GetID, (int)Controls.OSD_SUBTITLE_ONOFF);
                ShowControl(GetID, (int)Controls.OSD_SUBTITLE_LIST);

                FocusControl(GetID, (int)Controls.OSD_SUBTITLE_DELAY, 0);
                // set focus to the first control in our group
                PopulateSubTitles(); // populate the list control with subtitles for this video
              }
            }

            if (iControl == (int)Controls.OSD_BOOKMARKS)
            {
              //not used
            }

            if (iControl == (int)Controls.OSD_VIDEO)
            {
              ToggleSubMenu(iControl, (int)Controls.OSD_SUBMENU_BG_VIDEO); // hide or show the sub-menu
              if (isSubMenuVisible) // is sub menu on?
              {
                // set the controls values
                float fPercent = (float)(100 * (g_Player.CurrentPosition / g_Player.Duration));
                SetSliderValue(0.0f, 100.0f, (float)fPercent, (int)Controls.OSD_VIDEOPOS);

                bool hasPostProc = g_Player.HasPostprocessing;
                if (hasPostProc)
                {
                  IPostProcessingEngine engine = PostProcessingEngine.GetInstance();
                  SetCheckmarkValue(engine.EnablePostProcess, (int)Controls.OSD_VIDEO_POSTPROC_DEBLOCK_ONOFF);
                  SetCheckmarkValue(engine.EnableResize, (int)Controls.OSD_VIDEO_POSTPROC_RESIZE_ONOFF);
                  SetCheckmarkValue(engine.EnableCrop, (int)Controls.OSD_VIDEO_POSTPROC_CROP_ONOFF);
                  SetCheckmarkValue(engine.EnableDeinterlace, (int)Controls.OSD_VIDEO_POSTPROC_DEINTERLACE_ONOFF);
                  UpdatePostProcessing();
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_DEBLOCK_ONOFF);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_RESIZE_ONOFF);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_CROP_ONOFF);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_DEINTERLACE_ONOFF);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_CROP_VERTICAL);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_CROP_HORIZONTAL);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_CROP_VERTICAL_LABEL);
                  ShowControl(GetID, (int)Controls.OSD_VIDEO_POSTPROC_CROP_HORIZONTAL_LABEL);
                }

                //SetCheckmarkValue(g_stSettings.m_bNonInterleaved, Controls.OSD_NONINTERLEAVED);
                //SetCheckmarkValue(g_stSettings.m_bNoCache, Controls.OSD_NOCACHE);
                //SetCheckmarkValue(g_stSettings.m_bFrameRateConversions, Controls.OSD_ADJFRAMERATE);

                UpdateGammaContrastBrightness();
                // show the controls on this sub menu
                ShowControl(GetID, (int)Controls.OSD_VIDEOPOS);
                ShowControl(GetID, (int)Controls.OSD_VIDEOPOS_LABEL);
                ShowControl(GetID, (int)Controls.OSD_NONINTERLEAVED);
                ShowControl(GetID, (int)Controls.OSD_NOCACHE);
                ShowControl(GetID, (int)Controls.OSD_ADJFRAMERATE);
                ShowControl(GetID, (int)Controls.OSD_SATURATIONLABEL);
                ShowControl(GetID, (int)Controls.OSD_SATURATION);
                ShowControl(GetID, (int)Controls.OSD_SHARPNESSLABEL);
                ShowControl(GetID, (int)Controls.OSD_SHARPNESS);
                ShowControl(GetID, (int)Controls.OSD_BRIGHTNESS);
                ShowControl(GetID, (int)Controls.OSD_BRIGHTNESSLABEL);
                ShowControl(GetID, (int)Controls.OSD_CONTRAST);
                ShowControl(GetID, (int)Controls.OSD_CONTRASTLABEL);
                ShowControl(GetID, (int)Controls.OSD_GAMMA);
                ShowControl(GetID, (int)Controls.OSD_GAMMALABEL);
                FocusControl(GetID, (int)Controls.OSD_VIDEOPOS, 0); // set focus to the first control in our group
              }
            }

            if (iControl == (int)Controls.OSD_AUDIO)
            {
              ToggleSubMenu(iControl, (int)Controls.OSD_SUBMENU_BG_AUDIO); // hide or show the sub-menu
              if (isSubMenuVisible) // is sub menu on?
              {
                int iValue = g_Player.Volume;
                GUISliderControl pSlider = GetControl((int)Controls.OSD_AUDIOVOLUMESLIDER) as GUISliderControl;
                if (null != pSlider)
                {
                  pSlider.Percentage = iValue; // Update our volume slider accordingly ...
                }

                // set the controls values
                GUISliderControl pControl = (GUISliderControl)GetControl((int)Controls.OSD_AVDELAY);
                pControl.SpinType = GUISpinControl.SpinType.SPIN_CONTROL_TYPE_FLOAT;
                pControl.SetRange(-20, 20);
                SetSliderValue(-20, 20, m_audioDelay, (int)Controls.OSD_AVDELAY);

                bool hasPostProc = g_Player.HasPostprocessing;
                if (hasPostProc)
                {
                  GUIPropertyManager.SetProperty("#TvOSD.AudioVideoDelayPossible", "true");
                  pControl.FloatInterval = 1;
                }
                else
                { 
                  GUIPropertyManager.SetProperty("#TvOSD.AudioVideoDelayPossible", "false");
                  pControl.FloatValue = 0;
                  m_audioDelay = 0;
                  pControl.FloatInterval = 0;
                }

                // show the controls on this sub menu
                ShowControl(GetID, (int)Controls.OSD_AVDELAY);
                ShowControl(GetID, (int)Controls.OSD_AVDELAY_LABEL);
                ShowControl(GetID, (int)Controls.OSD_AUDIOSTREAM_LIST);
                ShowControl(GetID, (int)Controls.OSD_AUDIOVOLUMESLIDER);
                ShowControl(GetID, (int)Controls.OSD_AUDIOVOLUMESLIDER_LABEL);

                FocusControl(GetID, (int)Controls.OSD_AVDELAY, 0); // set focus to the first control in our group
                PopulateAudioStreams(); // populate the list control with audio streams for this video
              }
            }

            return true;
          }
      }
      return base.OnMessage(message);
    }
        public Event[] RetrieveLast(int numberOfEvents)
        {
            SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(Event));
            sb.SetRowLimit(numberOfEvents);
            sb.AddOrderByField(false, "date");
            sb.AddConstraint(Operator.LessThanOrEquals, "date", DateTime.Now);

            SqlStatement stmt = sb.GetStatement(true);

            IList events = ObjectFactory.GetCollection(typeof(Event), stmt.Execute());

            List<Event> events_result = new List<Event>();
            foreach (Event e in events)
                events_result.Add(e);

            return events_result.ToArray();
        }
예제 #10
0
    /// <summary>
    /// Get a list of GroupMap referring to the current entity.
    /// </summary>
    public IList<RadioGroupMap> ReferringRadioGroupMap()
    {
      //select * from 'foreigntable'
      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (RadioGroupMap));

      // where foreigntable.foreignkey = ourprimarykey
      sb.AddConstraint(Operator.Equals, "idGroup", idGroup);
      sb.AddOrderByField("SortOrder");

      // passing true indicates that we'd like a list of elements, i.e. that no primary key
      // constraints from the type being retrieved should be added to the statement
      SqlStatement stmt = sb.GetStatement(true);

      // execute the statement/query and create a collection of User instances from the result set
      return ObjectFactory.GetCollection<RadioGroupMap>(stmt.Execute());

      // TODO In the end, a GentleList should be returned instead of an arraylist
      //return new GentleList( typeof(GroupMap), this );
    }
예제 #11
0
    private void LoadDirectory()
    {
      GUIControl.ClearControl(GetID, listPriorities.GetID);
      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Schedule));
      sb.AddOrderByField(false, "priority");
      SqlStatement stmt = sb.GetStatement(true);
      IList itemlist = ObjectFactory.GetCollection(typeof (Schedule), stmt.Execute());

      int total = 0;
      foreach (Schedule rec in itemlist)
      {
        if (rec.IsSerieIsCanceled(rec.StartTime, rec.IdChannel))
        {
          continue;
        }
        GUIListItem item = new GUIListItem();
        item.Label = String.Format("{0}.{1}", total, rec.ProgramName);
        item.TVTag = rec;
        string strLogo = Utils.GetCoverArt(Thumbs.TVChannel, rec.ReferencedChannel().DisplayName);
        if (string.IsNullOrEmpty(strLogo))                      
        {
          strLogo = "defaultVideoBig.png";
        }
        TvServer server = new TvServer();
        VirtualCard card;
        if (server.IsRecordingSchedule(rec.IdSchedule, out card))
        {
          if (rec.ScheduleType != (int)ScheduleRecordingType.Once)
          {
            item.PinImage = Thumbs.TvRecordingSeriesIcon;
          }
          else
          {
            item.PinImage = Thumbs.TvRecordingIcon;
          }
        }
        else if (rec.ReferringConflicts().Count > 0)
        {
          item.PinImage = Thumbs.TvConflictRecordingIcon;
        }
        item.ThumbnailImage = strLogo;
        item.IconImageBig = strLogo;
        item.IconImage = strLogo;
        listPriorities.Add(item);
        total++;
      }

      //set object count label
      GUIPropertyManager.SetProperty("#itemcount", Utils.GetObjectCountLabel(total));

      GUIControl.SelectItemControl(GetID, listPriorities.GetID, m_iSelectedItem);
    }
예제 #12
0
    private void buttonRefresh_Click(object sender, EventArgs e)
    {
      String name = null;


      try
      {
        textBoxAction.Text = "Loading";
        this.Refresh();

        Log.Debug("Loading all channels from the tvguide[s]");
        // used for partial matches
        TstDictionary guideChannels = new TstDictionary();

        Dictionary<string, Channel> guideChannelsExternald = new Dictionary<string, Channel>();

        List<Channel> lstTvGuideChannels = readChannelsFromTVGuide();

        if (lstTvGuideChannels == null)
          return;

        // convert to Dictionary
        foreach (Channel ch in lstTvGuideChannels)
        {
          string tName = ch.DisplayName.Replace(" ", "").ToLowerInvariant();
          if (!guideChannels.ContainsKey(tName))
            guideChannels.Add(tName, ch);

          // used to make sure that the available mapping is used by default
          if (ch.ExternalId != null && !ch.ExternalId.Trim().Equals(""))
          {
            // need to check this because we can have channels with multiple display-names 
            // and they're currently handles as one channel/display-name.
            // only in the mapping procedure of course
            if (!guideChannelsExternald.ContainsKey(ch.ExternalId))
              guideChannelsExternald.Add(ch.ExternalId, ch);
          }
        }

        Log.Debug("Loading all channels from the database");

        CBChannelGroup chGroup = (CBChannelGroup)comboBoxGroup.SelectedItem;

        IList<Channel> channels;

        bool loadRadio = checkBoxLoadRadio.Checked;

        if (chGroup != null && chGroup.idGroup != -1)
        {
          SqlBuilder sb1 = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof (Channel));
          SqlStatement stmt1 = sb1.GetStatement(true);
          SqlStatement ManualJoinSQL = new SqlStatement(stmt1.StatementType, stmt1.Command,
                                                        String.Format(
                                                          "select c.* from Channel c join GroupMap g on c.idChannel=g.idChannel where " +
                                                          (loadRadio ? "" : " c.isTv = 1 and ") +
                                                          " g.idGroup = '{0}' order by g.sortOrder", chGroup.idGroup),
                                                        typeof (Channel));
          channels = ObjectFactory.GetCollection<Channel>(ManualJoinSQL.Execute());
        }
        else
        {
          SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
          sb.AddOrderByField(true, "sortOrder");
          if (!loadRadio)
            sb.AddConstraint(" isTv = 1");
          SqlStatement stmt = sb.GetStatement(true);
          channels = ObjectFactory.GetCollection<Channel>(stmt.Execute());
        }

        progressBar1.Minimum = 0;
        progressBar1.Maximum = channels.Count;
        progressBar1.Value = 0;

        dataGridChannelMappings.Rows.Clear();

        int row = 0;

        if (channels.Count == 0)
        {
          MessageBox.Show("No tv-channels available to map");
          return;
        }
        // add as many rows in the datagrid as there are channels
        dataGridChannelMappings.Rows.Add(channels.Count);

        DataGridViewRowCollection rows = dataGridChannelMappings.Rows;

        // go through each channel and try to find a matching channel
        // 1: matching display-name (non case-sensitive)
        // 2: partial search on the first word. The first match will be selected in the dropdown

        foreach (Channel ch in channels)
        {
          Boolean alreadyMapped = false;
          DataGridViewRow gridRow = rows[row++];

          DataGridViewTextBoxCell idCell = (DataGridViewTextBoxCell)gridRow.Cells["Id"];
          DataGridViewTextBoxCell channelCell = (DataGridViewTextBoxCell)gridRow.Cells["tuningChannel"];
          DataGridViewTextBoxCell providerCell = (DataGridViewTextBoxCell)gridRow.Cells["tuningChannel"];
          DataGridViewCheckBoxCell showInGuideCell = (DataGridViewCheckBoxCell)gridRow.Cells["ShowInGuide"];

          channelCell.Value = ch.DisplayName;
          idCell.Value = ch.IdChannel;
          showInGuideCell.Value = ch.VisibleInGuide;

          DataGridViewComboBoxCell guideChannelComboBox = (DataGridViewComboBoxCell)gridRow.Cells["guideChannel"];

          // always add a empty item as the first option
          // these channels will not be updated when saving
          guideChannelComboBox.Items.Add("");

          // Start by checking if there's an available mapping for this channel
          Channel matchingGuideChannel = null;

          if (guideChannelsExternald.ContainsKey(ch.ExternalId))
          {
            matchingGuideChannel = guideChannelsExternald[ch.ExternalId];
            alreadyMapped = true;
          }
          // no externalid mapping available, try using the name
          if (matchingGuideChannel == null)
          {
            string tName = ch.DisplayName.Replace(" ", "").ToLowerInvariant();
            if (guideChannels.ContainsKey(tName))
              matchingGuideChannel = (Channel)guideChannels[tName];
          }

          Boolean exactMatch = false;
          Boolean partialMatch = false;

          if (!alreadyMapped)
          {
            if (matchingGuideChannel != null)
            {
              exactMatch = true;
            }
            else
            {
              // No name mapping found

              // do a partial search, default off
              if (checkBoxPartialMatch.Checked)
              {
                // do a search using the first word(s) (skipping the last) of the channelname
                name = ch.DisplayName.Trim();
                int spaceIdx = name.LastIndexOf(" ");
                if (spaceIdx > 0)
                {
                  name = name.Substring(0, spaceIdx).Trim();
                }
                else
                {
                  // only one word so we'll do a partial match on the first 3 letters
                  if (name.Length > 3)
                    name = name.Substring(0, 3);
                }

                try
                {
                  // Note: the partial match code doesn't work as described by the author
                  // so we'll use PrefixMatch method (created by a codeproject user)
                  ICollection partialMatches = guideChannels.PrefixMatch(name.Replace(" ", "").ToLowerInvariant());

                  if (partialMatches != null && partialMatches.Count > 0)
                  {
                    IEnumerator pmE = partialMatches.GetEnumerator();
                    pmE.MoveNext();
                    matchingGuideChannel = (Channel)guideChannels[(string)pmE.Current];
                    partialMatch = true;
                  }
                }
                catch (Exception ex)
                {
                  Log.Error("Error while searching for matching guide channel :" + ex.Message);
                }
              }
            }
          }
          // add the channels 
          // set the first matching channel in the search above as the selected

          Boolean gotMatch = false;

          string ALREADY_MAPPED = "Already mapped (got external id)";
          string EXACT_MATCH = "Exact match";
          string PARTIAL_MATCH = "Partial match";
          string NO_MATCH = "No match";

          DataGridViewCell cell = gridRow.Cells["matchType"];

          foreach (DictionaryEntry de in guideChannels)
          {
            Channel guideChannel = (Channel)de.Value;

            String itemText = guideChannel.DisplayName + " (" + guideChannel.ExternalId + ")";

            guideChannelComboBox.Items.Add(itemText);

            if (!gotMatch && matchingGuideChannel != null)
            {
              if (guideChannel.DisplayName.ToLowerInvariant().Equals(matchingGuideChannel.DisplayName.ToLowerInvariant()))
              {
                // set the matchtype row color according to the type of match(already mapped,exact, partial, none)
                if (alreadyMapped)
                {
                  cell.Style.BackColor = Color.White;
                  cell.ToolTipText = ALREADY_MAPPED;
                  // hack so that we can order the grid by mappingtype
                  cell.Value = "";
                }
                else if (exactMatch)
                {
                  cell.Style.BackColor = Color.Green;
                  cell.ToolTipText = EXACT_MATCH;
                  cell.Value = "  ";
                }
                else if (partialMatch)
                {
                  cell.Style.BackColor = Color.Yellow;
                  cell.ToolTipText = PARTIAL_MATCH;
                  cell.Value = "   ";
                }

                guideChannelComboBox.Value = itemText;
                guideChannelComboBox.Tag = ch.ExternalId;

                gotMatch = true;
              }
            }
          }
          if (!gotMatch)
          {
            cell.Style.BackColor = Color.Red;
            cell.ToolTipText = NO_MATCH;
            cell.Value = "    ";
          }
          progressBar1.Value++;
        }
        textBoxAction.Text = "Finished";
      }
      catch (Exception ex)
      {
        Log.Error("Failed loading channels/mappings : channel {0} erro {1} ", name, ex.Message);
        Log.Error(ex.StackTrace);
        textBoxAction.Text = "Error";
      }
    }
예제 #13
0
 /// <summary>
 /// Static method to retrieve all instances that are stored in the database in one call
 /// </summary>
 public static IList<RadioChannelGroup> ListAll()
 {
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (RadioChannelGroup));
   sb.AddOrderByField(true, "sortOrder");
   SqlStatement stmt = sb.GetStatement(true);
   return ObjectFactory.GetCollection<RadioChannelGroup>(stmt.Execute());
 }
예제 #14
0
 /// <summary>
 /// Get a list of ChannelGroup referring to the current entity.
 /// </summary>
 public IList<GroupMap> ReferringChannelGroup()
 {
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (KeywordMap));
   sb.AddConstraint(Operator.Equals, "idKeyword", idKeyword);
   sb.AddOrderByField("SortOrder");
   SqlStatement stmt = sb.GetStatement(true);
   List<GroupMap> returnList = new List<GroupMap>();
   IList<KeywordMap> list = ObjectFactory.GetCollection<KeywordMap>(stmt.Execute());
   foreach (KeywordMap map in list)
   {
     ChannelGroup group = map.ReferencedChannelGroup();
     returnList.InsertRange(0, group.ReferringGroupMap());
   }
   return returnList;
 }
예제 #15
0
 /// <summary>
 /// Get a list of Timespan referring to the current entity.
 /// </summary>
 public IList<Timespan> ReferringTimespan()
 {
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Timespan));
   sb.AddConstraint(Operator.Equals, "idKeyword", idKeyword);
   sb.AddOrderByField("SortOrder");
   SqlStatement stmt = sb.GetStatement(true);
   return ObjectFactory.GetCollection<Timespan>(stmt.Execute());
 }
예제 #16
0
    /// <summary>
    /// Get all channels from the database
    /// </summary>
    private void RefreshAllChannels()
    {
      Cursor.Current = Cursors.WaitCursor;
      IList<Card> dbsCards = Card.ListAll();
      _cards = new Dictionary<int, CardType>();
      foreach (Card card in dbsCards)
      {
        _cards[card.IdCard] = RemoteControl.Instance.Type(card.IdCard);
      }

      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
      sb.AddConstraint(Operator.Equals, "isTv", true);
      sb.AddOrderByField(true, "sortOrder");
      SqlStatement stmt = sb.GetStatement(true);
      _allChannels = ObjectFactory.GetCollection<Channel>(stmt.Execute());
      tabControl1.TabPages[0].Text = string.Format("Channels ({0})", _allChannels.Count);

      _lvChannelHandler = new ChannelListViewHandler(mpListView1, _allChannels, _cards, txtFilterString, ChannelType.Tv);
      _lvChannelHandler.FilterListView("");
    }
 public List<WebProgram> GetTodayEPGForChannel(int idChannel)
 {
     IFormatProvider mmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
       List<WebProgram> infos = new List<WebProgram>();
       if (!ConnectToDatabase())
     return infos;
       SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof(Program));
       sb.AddConstraint(Operator.Equals, "idChannel", idChannel);
       DateTime thisMorning = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
       sb.AddConstraint(String.Format("startTime>='{0}'", thisMorning.ToString(GetDateTimeString(), mmddFormat)));
       sb.AddOrderByField(true, "startTime");
       SqlStatement stmt = sb.GetStatement(true);
       IList programs = ObjectFactory.GetCollection(typeof(Program), stmt.Execute());
       if (programs != null && programs.Count > 0)
       {
     foreach (Program prog in programs)
       infos.Add(new WebProgram(prog));
       }
       return infos;
 }
예제 #18
0
    public void ReLoad()
    {
      //System.Diagnostics.Debugger.Launch();
      try
      {
        SetupDatabaseConnection();
        Log.Info("get channels from database");
        SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
        sb.AddConstraint(Operator.Equals, "isTv", 1);
        sb.AddOrderByField(true, "sortOrder");
        SqlStatement stmt = sb.GetStatement(true);
        channels = ObjectFactory.GetCollection(typeof (Channel), stmt.Execute());
        Log.Info("found:{0} tv channels", channels.Count);
        TvNotifyManager.OnNotifiesChanged();
        m_groups.Clear();

        TvBusinessLayer layer = new TvBusinessLayer();
        RadioChannelGroup allRadioChannelsGroup =
          layer.GetRadioChannelGroupByName(TvConstants.RadioGroupNames.AllChannels);
        IList<Channel> radioChannels = layer.GetAllRadioChannels();
        if (radioChannels != null)
        {
          if (radioChannels.Count > allRadioChannelsGroup.ReferringRadioGroupMap().Count)
          {
            foreach (Channel radioChannel in radioChannels)
            {
              layer.AddChannelToRadioGroup(radioChannel, allRadioChannelsGroup);
            }
          }
        }
        Log.Info("Done.");

        Log.Info("get all groups from database");
        sb = new SqlBuilder(StatementType.Select, typeof (ChannelGroup));
        sb.AddOrderByField(true, "groupName");
        stmt = sb.GetStatement(true);
        IList<ChannelGroup> groups = ObjectFactory.GetCollection<ChannelGroup>(stmt.Execute());
        IList<GroupMap> allgroupMaps = GroupMap.ListAll();

        bool hideAllChannelsGroup = false;
        using (
          Settings xmlreader =
            new MPSettings())
        {
          hideAllChannelsGroup = xmlreader.GetValueAsBool("mytv", "hideAllChannelsGroup", false);
        }


        foreach (ChannelGroup group in groups)
        {
          if (group.GroupName == TvConstants.TvGroupNames.AllChannels)
          {
            foreach (Channel channel in channels)
            {
              if (channel.IsTv == false)
              {
                continue;
              }
              bool groupContainsChannel = false;
              foreach (GroupMap map in allgroupMaps)
              {
                if (map.IdGroup != group.IdGroup)
                {
                  continue;
                }
                if (map.IdChannel == channel.IdChannel)
                {
                  groupContainsChannel = true;
                  break;
                }
              }
              if (!groupContainsChannel)
              {
                layer.AddChannelToGroup(channel, TvConstants.TvGroupNames.AllChannels);
              }
            }
            break;
          }
        }

        groups = ChannelGroup.ListAll();
        foreach (ChannelGroup group in groups)
        {
          //group.GroupMaps.ApplySort(new GroupMap.Comparer(), false);
          if (hideAllChannelsGroup && group.GroupName.Equals(TvConstants.TvGroupNames.AllChannels) && groups.Count > 1)
          {
            continue;
          }
          m_groups.Add(group);
        }
        Log.Info("loaded {0} tv groups", m_groups.Count);

        //TVHome.Connected = true;
      }
      catch (Exception ex)
      {
        Log.Error("TVHome: Error in Reload");
        Log.Error(ex);
        //TVHome.Connected = false;
      }
    }
 public List<WebProgram> SearchEPG(string show)
 {
     List<WebProgram> infos = new List<WebProgram>();
       if (!ConnectToDatabase())
     return infos;
       try
       {
     SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof(Program));
     sb.AddConstraint(Operator.Like, "title", show );
     sb.AddOrderByField(true, "startTime");
     SqlStatement stmt = sb.GetStatement(true);
     IList programs = ObjectFactory.GetCollection(typeof(Program), stmt.Execute());
     if (programs != null && programs.Count > 0)
     {
       foreach (Program prog in programs)
     infos.Add(new WebProgram(prog));
     }
       }
       catch (Exception)
       {
       }
       return infos;
 }
예제 #20
0
    public override void OnSectionActivated()
    {
      mpListView1.BeginUpdate();
      try
      {
        LoadLanguages();
        TvBusinessLayer layer = new TvBusinessLayer();
        Setting setting = layer.GetSetting("epgRadioStoreOnlySelected");
        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.IsRadio == 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 = 2;
          }
          else if (hasScrambled)
          {
            imageIndex = 1;
          }
          else
          {
            imageIndex = 0;
          }

          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();
      }
    }
        /// <summary>
        /// Update the Program in the database if it exists or add if it is new.
        /// </summary>
        /// <param name="mpProgram">The Program to add to the database</param>
        protected void UpdateProgram(Program mpProgram)
        {
            IFormatProvider mmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
             SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof(Program));
             // startTime < MyEndTime AND endTime > MyStartTime
             // OR ==
             string sqlW1 = String.Format("(StartTime < '{0}' and EndTime > '{1}')", mpProgram.EndTime.ToString(tvLayer.GetDateTimeString(), mmddFormat), mpProgram.StartTime.ToString(tvLayer.GetDateTimeString(), mmddFormat));
             string sqlW2 = String.Format("(StartTime = '{0}' and EndTime = '{1}')", mpProgram.StartTime.ToString(tvLayer.GetDateTimeString(), mmddFormat), mpProgram.EndTime.ToString(tvLayer.GetDateTimeString(), mmddFormat));

             sb.AddConstraint(Operator.Equals, "idChannel", mpProgram.IdChannel);
             sb.AddConstraint(string.Format("({0} or {1}) ", sqlW1, sqlW2));
             sb.AddOrderByField(true, "starttime");

             SqlStatement stmt = sb.GetStatement(true);
             IList progList = ObjectFactory.GetCollection(typeof(Program), stmt.Execute());

             if (progList.Count > 0)
             {
            bool bMatch = false;
            foreach (Program prog in progList)
            {
               if (!bMatch && prog.StartTime == mpProgram.StartTime && prog.EndTime == mpProgram.EndTime && prog.Title == mpProgram.Title)
               {
                  //update - but only allow one match
                  bMatch = true;
                  prog.Classification  = mpProgram.Classification;
                  prog.Description     = mpProgram.Description;
                  prog.EpisodeNum      = mpProgram.EpisodeNum;
                  prog.Genre           = mpProgram.Genre;
                  prog.OriginalAirDate = mpProgram.OriginalAirDate;
                  prog.SeriesNum       = mpProgram.SeriesNum;
                  prog.StarRating      = mpProgram.StarRating;
                  prog.Title           = mpProgram.Title;
                  prog.EpisodeName     = mpProgram.EpisodeName;
                  prog.Persist();
               }
               else
                  prog.Delete();
            }
            if (!bMatch)
               mpProgram.Persist();
             }
             else
             {
            mpProgram.Persist();
             }
        }
예제 #22
0
    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();
      }
    }
예제 #23
0
    private void comboBoxGroups_SelectedIndexChanged(object sender, EventArgs e)
    {
      ComboBoxExItem idItem = (ComboBoxExItem)comboBoxGroups.Items[comboBoxGroups.SelectedIndex];
      mpComboBoxChannels.Items.Clear();
      if (idItem.Id == -1)
      {
        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)
        {
          if (ch.IsTv == false) continue;
          bool hasFta = false;
          bool hasScrambled = false;
          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;
          }
          ComboBoxExItem item = new ComboBoxExItem(ch.DisplayName, imageIndex, ch.IdChannel);

          mpComboBoxChannels.Items.Add(item);
        }
      }
      else
      {
        ChannelGroup group = ChannelGroup.Retrieve(idItem.Id);
        IList<GroupMap> maps = group.ReferringGroupMap();
        foreach (GroupMap map in maps)
        {
          Channel ch = map.ReferencedChannel();
          if (ch.IsTv == false) continue;
          bool hasFta = false;
          bool hasScrambled = false;
          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;
          }
          ComboBoxExItem item = new ComboBoxExItem(ch.DisplayName, imageIndex, ch.IdChannel);
          mpComboBoxChannels.Items.Add(item);
        }
      }
      if (mpComboBoxChannels.Items.Count > 0)
        mpComboBoxChannels.SelectedIndex = 0;
    }
예제 #24
0
    public bool Import(string fileName, bool deleteBeforeImport, bool showProgress)
    {
      //System.Diagnostics.Debugger.Launch();
      _errorMessage = "";
      if (_isImporting == true)
      {
        _errorMessage = "already importing...";
        return false;
      }
      _isImporting = true;

      bool result = false;
      XmlTextReader xmlReader = null;


      // remove old programs
      _status.Status = "Removing old programs";
      _status.Channels = 0;
      _status.Programs = 0;
      _status.StartTime = DateTime.Now;
      _status.EndTime = new DateTime(1971, 11, 6);
      if (showProgress && ShowProgress != null) ShowProgress(_status);

      layer.RemoveOldPrograms();

      /*
      // for each channel, get the last program's time
      Dictionary<int, DateTime> lastProgramForChannel = new Dictionary<int, DateTime>();
      IList channels = Channel.ListAll();
      foreach (Channel ch in channels)
      {
        SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(TvDatabase.Program));
        sb.AddConstraint(Operator.Equals, "idChannel", ch.IdChannel);
        sb.AddOrderByField(false, "starttime");
        sb.SetRowLimit(1);
        SqlStatement stmt = sb.GetStatement(true);
        IList programsInDbs = ObjectFactory.GetCollection(typeof(TvDatabase.Program), stmt.Execute());

        DateTime lastProgram = DateTime.MinValue;
        if (programsInDbs.Count > 0)
        {
          TvDatabase.IProgram p = (TvDatabase.Program)programsInDbs[0];
          lastProgram = p.EndTime;
        }
        lastProgramForChannel[ch.IdChannel] = lastProgram;
      }*/

      //TVDatabase.SupressEvents = true;
      bool useTimeZone = layer.GetSetting("xmlTvUseTimeZone", "false").Value == "true";
      int hours = Int32.Parse(layer.GetSetting("xmlTvTimeZoneHours", "0").Value);
      int mins = Int32.Parse(layer.GetSetting("xmlTvTimeZoneMins", "0").Value);
      int timeZoneCorrection = hours * 60 + mins;

      ArrayList Programs = new ArrayList();
      Dictionary<int, ChannelPrograms> dChannelPrograms = new Dictionary<int, ChannelPrograms>();
      try
      {
        Log.WriteFile("xmltv import {0}", fileName);

        //
        // Make sure the file exists before we try to do any processing
        //
        if (File.Exists(fileName))
        {
          _status.Status = "Loading channel list";
          _status.Channels = 0;
          _status.Programs = 0;
          _status.StartTime = DateTime.Now;
          _status.EndTime = new DateTime(1971, 11, 6);
          if (showProgress && ShowProgress != null) ShowProgress(_status);

          Dictionary<int, Channel> guideChannels = new Dictionary<int, Channel>();

          IList<Channel> allChannels = Channel.ListAll();

          int iChannel = 0;

          xmlReader = new XmlTextReader(fileName);

          #region import non-mapped channels by their display-name

          if (xmlReader.ReadToDescendant("tv"))
          {
            // get the first channel
            if (xmlReader.ReadToDescendant("channel"))
            {
              do
              {
                String id = xmlReader.GetAttribute("id");
                if (id == null || id.Length == 0)
                {
                  Log.Error("  channel#{0} doesnt contain an id", iChannel);
                }
                else
                {
                  String displayName = null;

                  XmlReader xmlChannel = xmlReader.ReadSubtree();
                  xmlChannel.ReadStartElement(); // read channel
                  // now, xmlChannel is positioned on the first sub-element of <channel>
                  while (!xmlChannel.EOF)
                  {
                    if (xmlChannel.NodeType == XmlNodeType.Element)
                    {
                      switch (xmlChannel.Name)
                      {
                        case "display-name":
                        case "Display-Name":
                          if (displayName == null) displayName = xmlChannel.ReadString();
                          else xmlChannel.Skip();
                          break;
                          // could read more stuff here, like icon...
                        default:
                          // unknown, skip entire node
                          xmlChannel.Skip();
                          break;
                      }
                    }
                    else
                      xmlChannel.Read();
                  }
                  if (xmlChannel != null)
                  {
                    xmlChannel.Close();
                    xmlChannel = null;
                  }

                  if (displayName == null || displayName.Length == 0)
                  {
                    Log.Error("  channel#{0} xmlid:{1} doesnt contain an displayname", iChannel, id);
                  }
                  else
                  {
                    Channel chan = null;

                    // a guide channel can be mapped to multiple tvchannels
                    foreach (Channel ch in allChannels)
                    {
                      if (ch.ExternalId == id)
                      {
                        chan = ch;
                        chan.ExternalId = id;
                      }

                      if (chan == null)
                      {
                        // no mapping found, ignore channel
                        continue;
                      }

                      ChannelPrograms newProgChan = new ChannelPrograms();
                      newProgChan.Name = chan.DisplayName;
                      newProgChan.ExternalId = chan.ExternalId;
                      Programs.Add(newProgChan);

                      Log.WriteFile("  channel#{0} xmlid:{1} name:{2} dbsid:{3}", iChannel, chan.ExternalId,
                                    chan.DisplayName, chan.IdChannel);
                      if (!guideChannels.ContainsKey(chan.IdChannel))
                      {
                        guideChannels.Add(chan.IdChannel, chan);
                        dChannelPrograms.Add(chan.IdChannel, newProgChan);
                      }
                    }

                    _status.Channels++;
                    if (showProgress && ShowProgress != null) ShowProgress(_status);
                  }
                }
                iChannel++;
                // get the next channel
              } while (xmlReader.ReadToNextSibling("channel"));
            }
          }

          //xmlReader.Close();

          #endregion

          SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
          sb.AddOrderByField(true, "externalId");
          sb.AddConstraint("externalId IS NOT null");
          sb.AddConstraint(Operator.NotEquals, "externalId", "");

          SqlStatement stmt = sb.GetStatement(true);
          allChannels = ObjectFactory.GetCollection<Channel>(stmt.Execute());
          if (allChannels.Count == 0)
          {
            _isImporting = false;
            if (xmlReader != null)
            {
              xmlReader.Close();
              xmlReader = null;
            }

            return true;
          }

          ///////////////////////////////////////////////////////////////////////////
          /*  design:
           * 1. create a Dictionary<string,Channel> using the externalid as the key,
           *    add all channels to this Dictionary 
           *    Note: channel -> guidechannel is a one-to-many relationship. 
           * 2. Read all programs from the xml file
           * 3. Create a program for each mapped channel
           */
          ///////////////////////////////////////////////////////////////////////////
          Dictionary<string, List<Channel>> allChannelMappingsByExternalId = new Dictionary<string, List<Channel>>();

          string previousExternalId = null;
          // one-to-many so we need a collection of channels for each externalId
          List<Channel> eidMappedChannels = new List<Channel>();

          for (int i = 0; i < allChannels.Count; i++)
          {
            Channel ch = (Channel)allChannels[i];

            if (previousExternalId == null)
            {
              eidMappedChannels.Add(ch);
              previousExternalId = ch.ExternalId;
            }
            else if (ch.ExternalId == previousExternalId)
            {
              eidMappedChannels.Add(ch);
            }
            else
            {
              // got all channels for this externalId. Add the mappings
              allChannelMappingsByExternalId.Add(previousExternalId, eidMappedChannels);
              // new externalid, create a new List & add the channel to the new List
              eidMappedChannels = new List<Channel>();
              eidMappedChannels.Add(ch);
              previousExternalId = ch.ExternalId;
            }

            if (i == allChannels.Count - 1)
            {
              allChannelMappingsByExternalId.Add(previousExternalId, eidMappedChannels);
            }
          }

          int programIndex = 0;
          _status.Status = "Loading TV programs";
          if (showProgress && ShowProgress != null) ShowProgress(_status);

          Log.Debug("xmltvimport: Reading TV programs");
          if (xmlReader != null)
          {
            xmlReader.Close();
            xmlReader = null;
          }
          xmlReader = new XmlTextReader(fileName);
          if (xmlReader.ReadToDescendant("tv"))
          {
            // get the first programme
            if (xmlReader.ReadToDescendant("programme"))
            {
              #region read programme node

              do
              {
                ChannelPrograms channelPrograms = new ChannelPrograms();

                String nodeStart = xmlReader.GetAttribute("start");
                String nodeStop = xmlReader.GetAttribute("stop");
                String nodeChannel = xmlReader.GetAttribute("channel");

                String nodeTitle = null;
                String nodeCategory = null;
                String nodeDescription = null;
                String nodeEpisode = null;
                String nodeRepeat = null;
                String nodeEpisodeNum = null;
                String nodeEpisodeNumSystem = null;
                String nodeDate = null;
                String nodeStarRating = null;
                String nodeClassification = null;

                XmlReader xmlProg = xmlReader.ReadSubtree();
                xmlProg.ReadStartElement(); // read programme
                // now, xmlProg is positioned on the first sub-element of <programme>
                while (!xmlProg.EOF)
                {
                  if (xmlProg.NodeType == XmlNodeType.Element)
                  {
                    switch (xmlProg.Name)
                    {
                      case "title":
                        if (nodeTitle == null) nodeTitle = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "category":
                        if (nodeCategory == null) nodeCategory = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "desc":
                        if (nodeDescription == null) nodeDescription = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "sub-title":
                        if (nodeEpisode == null) nodeEpisode = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "previously-shown":
                        if (nodeRepeat == null) nodeRepeat = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "episode-num":
                        if (xmlProg.GetAttribute("system").Equals("xmltv_ns")) 
                        {
                            nodeEpisodeNumSystem = xmlProg.GetAttribute("system");
                            nodeEpisodeNum = xmlProg.ReadString();
                        }
                        else if (nodeEpisodeNum == null && xmlProg.GetAttribute("system").Equals("onscreen"))
                        {
                          nodeEpisodeNumSystem = xmlProg.GetAttribute("system");
                          nodeEpisodeNum = xmlProg.ReadString();
                        }
                        else xmlProg.Skip();
                        break;
                      case "date":
                        if (nodeDate == null) nodeDate = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "star-rating":
                        if (nodeStarRating == null) nodeStarRating = xmlProg.ReadInnerXml();
                        else xmlProg.Skip();
                        break;
                      case "rating":
                        if (nodeClassification == null) nodeClassification = xmlProg.ReadInnerXml();
                        else xmlProg.Skip();
                        break;
                      default:
                        // unknown, skip entire node
                        xmlProg.Skip();
                        break;
                    }
                  }
                  else
                    xmlProg.Read();
                }
                if (xmlProg != null)
                {
                  xmlProg.Close();
                  xmlProg = null;
                }

                #endregion

                #region verify/convert values (programme)

                if (nodeStart != null && nodeChannel != null && nodeTitle != null &&
                    nodeStart.Length > 0 && nodeChannel.Length > 0 && nodeTitle.Length > 0)
                {
                  string description = "";
                  string category = "-";
                  string serEpNum = "";
                  string date = "";
                  string seriesNum = "";
                  string episodeNum = "";
                  string episodeName = "";
                  string episodePart = "";
                  int starRating = -1;
                  string classification = "";

                  string title = ConvertHTMLToAnsi(nodeTitle);

                  long startDate = 0;
                  if (nodeStart.Length >= 14)
                  {
                    if (Char.IsDigit(nodeStart[12]) && Char.IsDigit(nodeStart[13]))
                      startDate = Int64.Parse(nodeStart.Substring(0, 14)); //20040331222000
                    else
                      startDate = 100 * Int64.Parse(nodeStart.Substring(0, 12)); //200403312220
                  }
                  else if (nodeStart.Length >= 12)
                  {
                    startDate = 100 * Int64.Parse(nodeStart.Substring(0, 12)); //200403312220
                  }

                  long stopDate = startDate;
                  if (nodeStop != null)
                  {
                    if (nodeStop.Length >= 14)
                    {
                      if (Char.IsDigit(nodeStop[12]) && Char.IsDigit(nodeStop[13]))
                        stopDate = Int64.Parse(nodeStop.Substring(0, 14)); //20040331222000
                      else
                        stopDate = 100 * Int64.Parse(nodeStop.Substring(0, 12)); //200403312220
                    }
                    else if (nodeStop.Length >= 12)
                    {
                      stopDate = 100 * Int64.Parse(nodeStop.Substring(0, 12)); //200403312220
                    }
                  }

                  startDate = CorrectIllegalDateTime(startDate);
                  stopDate = CorrectIllegalDateTime(stopDate);
                  string timeZoneStart = "";
                  string timeZoneEnd = "";
                  if (nodeStart.Length > 14)
                  {
                    timeZoneStart = nodeStart.Substring(14);
                    timeZoneStart = timeZoneStart.Trim();
                    timeZoneEnd = timeZoneStart;
                  }
                  if (nodeStop != null)
                  {
                    if (nodeStop.Length > 14)
                    {
                      timeZoneEnd = nodeStop.Substring(14);
                      timeZoneEnd = timeZoneEnd.Trim();
                    }
                  }

                  //
                  // add time correction
                  //

                  // correct program starttime
                  DateTime dateTimeStart = longtodate(startDate);
                  dateTimeStart = dateTimeStart.AddMinutes(timeZoneCorrection);

                  if (useTimeZone)
                  {
                    int off = GetTimeOffset(timeZoneStart);
                    int h = off / 100; // 220 -> 2,  -220 -> -2
                    int m = off - (h * 100); // 220 -> 20, -220 -> -20

                    dateTimeStart = dateTimeStart.AddHours(-h);
                    dateTimeStart = dateTimeStart.AddMinutes(-m);
                    dateTimeStart = dateTimeStart.ToLocalTime();
                  }
                  startDate = datetolong(dateTimeStart);

                  if (nodeStop != null)
                  {
                    // correct program endtime
                    DateTime dateTimeEnd = longtodate(stopDate);
                    dateTimeEnd = dateTimeEnd.AddMinutes(timeZoneCorrection);

                    if (useTimeZone)
                    {
                      int off = GetTimeOffset(timeZoneEnd);
                      int h = off / 100; // 220 -> 2,  -220 -> -2
                      int m = off - (h * 100); // 220 -> 20, -220 -> -20

                      dateTimeEnd = dateTimeEnd.AddHours(-h);
                      dateTimeEnd = dateTimeEnd.AddMinutes(-m);
                      dateTimeEnd = dateTimeEnd.ToLocalTime();
                    }
                    stopDate = datetolong(dateTimeEnd);
                  }
                  else stopDate = startDate;

                  //int channelId = -1;
                  //string channelName = "";

                  if (nodeCategory != null)
                    category = nodeCategory;

                  if (nodeDescription != null)
                  {
                    description = ConvertHTMLToAnsi(nodeDescription);
                  }
                  if (nodeEpisode != null)
                  {
                    episodeName = ConvertHTMLToAnsi(nodeEpisode);
                    if (title.Length == 0)
                      title = nodeEpisode;
                  }

                  if (nodeEpisodeNum != null)
                  {
                    if (nodeEpisodeNumSystem != null)
                    {
                      // http://xml.coverpages.org/XMLTV-DTD-20021210.html
                      if (nodeEpisodeNumSystem == "xmltv_ns")
                      {
                        serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum.Replace(" ", ""));
                        int dot1 = serEpNum.IndexOf(".", 0);
                        int dot2 = serEpNum.IndexOf(".", dot1 + 1);
                        seriesNum = serEpNum.Substring(0, dot1);
                        episodeNum = serEpNum.Substring(dot1 + 1, dot2 - (dot1 + 1));
                        episodePart = serEpNum.Substring(dot2 + 1, serEpNum.Length - (dot2 + 1));
                        //xmltv_ns is theorically zero-based number will be increased by one
                        seriesNum = CorrectEpisodeNum(seriesNum, 1);
                        episodeNum = CorrectEpisodeNum(episodeNum, 1);
                        episodePart = CorrectEpisodeNum(episodePart, 1);
                      }
                      else if (nodeEpisodeNumSystem == "onscreen")
                      {
                        // example: 'Episode #FFEE' 
                        serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum);
                        int num1 = serEpNum.IndexOf("#", 0);
                        if (num1 > 0)
                        {
                          episodeNum = CorrectEpisodeNum(serEpNum.Substring(num1, serEpNum.Length - num1), 0);
                        }
                        else
                        {
                          if (serEpNum.IndexOf(":", 0) > 0)
                          {
                            episodeNum = CorrectEpisodeNum(serEpNum, 0);
                          }
                          else
                          {
                            Regex regEpisode = new Regex("(?<episode>\\d*)\\D*(?<series>\\d*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
                            Match m = regEpisode.Match(serEpNum);
                            if (m.Success)
                            {
                              episodeNum = CorrectEpisodeNum(m.Groups["episode"].Value, 0);
                              seriesNum = CorrectEpisodeNum(m.Groups["series"].Value, 0);
                            }
                            else
                            {
                              episodeNum = CorrectEpisodeNum(serEpNum, 0);
                            }
                          }
                        }
                      }
                    }
                    else
                      // fixing mantis bug 1486: XMLTV import doesn't take episode number from TVGuide.xml made by WebEPG 
                    {
                      // example: '5' like WebEPG is creating
                      serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum.Replace(" ", ""));
                      episodeNum = CorrectEpisodeNum(serEpNum, 0);
                    }
                  }

                  if (nodeDate != null)
                  {
                    date = nodeDate;
                  }

                  if (nodeStarRating != null)
                  {
                    starRating = ParseStarRating(nodeStarRating);
                  }

                  if (nodeClassification != null)
                  {
                    classification = nodeClassification;
                  }

                  if (showProgress && ShowProgress != null && (_status.Programs % 100) == 0) ShowProgress(_status);

                  #endregion

                  #region create a program for every mapped channel

                  List<Channel> mappedChannels;

                  if (allChannelMappingsByExternalId.ContainsKey(nodeChannel))
                  {
                    mappedChannels = allChannelMappingsByExternalId[nodeChannel];
                    if (mappedChannels != null && mappedChannels.Count > 0)
                    {
                      foreach (Channel chan in mappedChannels)
                      {
                        // get the channel program
                        channelPrograms = dChannelPrograms[chan.IdChannel];

                        if (chan.IdChannel < 0)
                        {
                          continue;
                        }

                        title = title.Replace("\r\n", " ");
                        title = title.Replace("\n\r", " ");
                        title = title.Replace("\r", " ");
                        title = title.Replace("\n", " ");
                        title = title.Replace("  ", " ");

                        description = description.Replace("\r\n", " ");
                        description = description.Replace("\n\r", " ");
                        description = description.Replace("\r", " ");
                        description = description.Replace("\n", " ");
                        description = description.Replace("  ", " ");

                        episodeName = episodeName.Replace("\r\n", " ");
                        episodeName = episodeName.Replace("\n\r", " ");
                        episodeName = episodeName.Replace("\r", " ");
                        episodeName = episodeName.Replace("\n", " ");
                        episodeName = episodeName.Replace("  ", " ");

                        Program prog = new Program(chan.IdChannel, longtodate(startDate), longtodate(stopDate), title,
                                                   description, category, Program.ProgramState.None,
                                                   System.Data.SqlTypes.SqlDateTime.MinValue.Value, seriesNum,
                                                   episodeNum, episodeName, episodePart, starRating, classification, -1);
                        channelPrograms.programs.Add(prog);
                        programIndex++;
                        //prog.Description = ConvertHTMLToAnsi(strDescription);
                        //prog.StartTime = iStart;
                        //prog.EndTime = iStop;
                        //prog.Title = ConvertHTMLToAnsi(strTitle);
                        //prog.Genre = ConvertHTMLToAnsi(strCategory);
                        //prog.Channel = ConvertHTMLToAnsi(strChannelName);
                        //prog.Date = strDate;
                        //prog.Episode = ConvertHTMLToAnsi(strEpisode);
                        //prog.Repeat = ConvertHTMLToAnsi(strRepeat);
                        //prog.SeriesNum = ConvertHTMLToAnsi(strSeriesNum);
                        //prog.EpisodeNum = ConvertHTMLToAnsi(strEpisodeNum);
                        //prog.EpisodePart = ConvertHTMLToAnsi(strEpisodePart);
                        //prog.StarRating = ConvertHTMLToAnsi(strStarRating);
                        //prog.Classification = ConvertHTMLToAnsi(strClasification);
                        _status.Programs++;
                      }
                    }
                  }
                }
                // get the next programme
              } while (xmlReader.ReadToNextSibling("programme"));
              //if (xmlReader != null) xmlReader.Close();

              #endregion

              #region sort & remove invalid programs. Save all valid programs

              Log.Debug("xmltvimport: Sorting TV programs");

              _status.Programs = 0;
              _status.Status = "Sorting TV programs";
              if (showProgress && ShowProgress != null) ShowProgress(_status);
              DateTime dtStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);
              //dtStartDate=dtStartDate.AddDays(-4);

              foreach (ChannelPrograms progChan in Programs)
              {
                // empty, skip it
                if (progChan.programs.Count == 0) continue;

                progChan.programs.Sort();
                progChan.programs.AlreadySorted = true;
                progChan.programs.FixEndTimes();
                progChan.programs.RemoveOverlappingPrograms(); // be sure that we do not have any overlapping

                // get the id of the channel, just get the IdChannel of the first program
                int idChannel = progChan.programs[0].IdChannel;

                if (!deleteBeforeImport)
                {
                  // retrieve all programs for this channel
                  SqlBuilder sb2 = new SqlBuilder(StatementType.Select, typeof (Program));
                  sb2.AddConstraint(Operator.Equals, "idChannel", idChannel);
                  sb2.AddOrderByField(false, "starttime");
                  SqlStatement stmt2 = sb2.GetStatement(true);
                  ProgramList dbPrograms = new ProgramList();
                  ObjectFactory.GetCollection<Program>(stmt2.Execute(), dbPrograms);
                  progChan.programs.RemoveOverlappingPrograms(dbPrograms, true);
                }

                for (int i = 0; i < progChan.programs.Count; ++i)
                {
                  Program prog = progChan.programs[i];
                  // don't import programs which have already ended...
                  if (prog.EndTime <= dtStartDate)
                  {
                    progChan.programs.RemoveAt(i);
                    i--;
                    continue;
                  }

                  DateTime start = prog.StartTime;
                  DateTime end = prog.EndTime;
                  DateTime airDate = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
                  try
                  {
                    airDate = prog.OriginalAirDate;
                    if (airDate > System.Data.SqlTypes.SqlDateTime.MinValue.Value &&
                        airDate < System.Data.SqlTypes.SqlDateTime.MaxValue.Value)
                      prog.OriginalAirDate = airDate;
                  }
                  catch (Exception)
                  {
                    Log.Info("XMLTVImport: Invalid year for OnAirDate - {0}", prog.OriginalAirDate);
                  }

                  if (prog.StartTime < _status.StartTime)
                    _status.StartTime = prog.StartTime;
                  if (prog.EndTime > _status.EndTime)
                    _status.EndTime = prog.EndTime;
                  _status.Programs++;
                  if (showProgress && ShowProgress != null && (_status.Programs % 100) == 0) ShowProgress(_status);
                }
                Log.Info("XMLTVImport: Inserting {0} programs for {1}", progChan.programs.Count.ToString(),
                         progChan.Name);
                layer.InsertPrograms(progChan.programs,
                                     deleteBeforeImport
                                       ? DeleteBeforeImportOption.OverlappingPrograms
                                       : DeleteBeforeImportOption.None, ThreadPriority.BelowNormal);
              }
            }

            #endregion

            //TVDatabase.RemoveOverlappingPrograms();

            //TVDatabase.SupressEvents = false;
            if (programIndex > 0)
            {
              _errorMessage = "File imported successfully";
              result = true;
            }
            else
              _errorMessage = "No programs found";
          }
        }
        else
        {
          _errorMessage = "No xmltv file found";
          _status.Status = _errorMessage;
          Log.Error("xmltv data file was not found");
        }
      }
      catch (Exception ex)
      {
        _errorMessage = String.Format("Invalid XML file:{0}", ex.Message);
        _status.Status = String.Format("invalid XML file:{0}", ex.Message);
        Log.Error("XML tv import error loading {0} err:{1} \n {2}", fileName, ex.Message, ex.StackTrace);

        //TVDatabase.RollbackTransaction();
      }

      Programs.Clear();
      Programs = null;

      _isImporting = false;
      //      TVDatabase.SupressEvents = false;
      if (xmlReader != null)
      {
        xmlReader.Close();
        xmlReader = null;
      }
      return result;
    }
예제 #25
0
    public IList<Program> GetPrograms(Channel channel, DateTime startTime)
    {
      //The DateTime.MinValue is lower than the min datetime value of the database
      if (startTime == DateTime.MinValue)
      {
        startTime = startTime.AddYears(1900);
      }
      IFormatProvider mmddFormat = new CultureInfo(String.Empty, false);
      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Program));

      sb.AddConstraint(Operator.Equals, "idChannel", channel.IdChannel);
      sb.AddConstraint(String.Format("startTime>='{0}'", startTime.ToString(GetDateTimeString(), mmddFormat)));
      sb.AddOrderByField(true, "startTime");

      SqlStatement stmt = sb.GetStatement(true);
      return ObjectFactory.GetCollection<Program>(stmt.Execute());
    }
예제 #26
0
    private void getTvServerChannels()
    {
      CBChannelGroup chGroup = (CBChannelGroup)GroupComboBox.SelectedItem;

      IList<Channel> Channels;
      if (chGroup != null && chGroup.idGroup != -1)
      {
        SqlBuilder sb1 = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof (Channel));
        SqlStatement stmt1 = sb1.GetStatement(true);
        SqlStatement ManualJoinSQL = new SqlStatement(stmt1.StatementType, stmt1.Command,
                                                      String.Format(
                                                        "select c.* from Channel c join {0}GroupMap g on c.idChannel=g.idChannel where c.{1} = 1 and g.idGroup = '{2}' order by g.sortOrder",
                                                        IsTvMapping ? "" : "Radio", IsTvMapping ? "isTv" : "isRadio",
                                                        chGroup.idGroup), typeof (Channel));
        Channels = ObjectFactory.GetCollection<Channel>(ManualJoinSQL.Execute());
      }
      else
      {
        SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
        sb.AddOrderByField(true, "sortOrder");
        if (IsTvMapping)
        {
          sb.AddConstraint("isTv = 1");
        }
        else
        {
          sb.AddConstraint("isRadio = 1");
        }
        SqlStatement stmt = sb.GetStatement(true);
        Channels = ObjectFactory.GetCollection<Channel>(stmt.Execute());
      }

      foreach (Channel chan in Channels)
      {
        if (!_channelMapping.ContainsKey(chan.DisplayName))
        {
          ChannelMap channel = new ChannelMap();
          channel.displayName = chan.DisplayName;
          _channelMapping.Add(chan.DisplayName, channel);
        }
      }
    }
예제 #27
0
    public IList<Program> GetProgramsByTitle(Channel channel, DateTime startTime, DateTime endTime, string title)
    {
      IFormatProvider mmddFormat = new CultureInfo(String.Empty, false);
      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Program));

      string sub1 = String.Format("(EndTime > '{0}' and EndTime < '{1}')",
                                  startTime.ToString(GetDateTimeString(), mmddFormat),
                                  endTime.ToString(GetDateTimeString(), mmddFormat));
      string sub2 = String.Format("(StartTime >= '{0}' and StartTime <= '{1}')",
                                  startTime.ToString(GetDateTimeString(), mmddFormat),
                                  endTime.ToString(GetDateTimeString(), mmddFormat));
      string sub3 = String.Format("(StartTime <= '{0}' and EndTime >= '{1}')",
                                  startTime.ToString(GetDateTimeString(), mmddFormat),
                                  endTime.ToString(GetDateTimeString(), mmddFormat));

      sb.AddConstraint(Operator.Equals, "idChannel", channel.IdChannel);
      sb.AddConstraint(string.Format("({0} or {1} or {2}) ", sub1, sub2, sub3));
      sb.AddConstraint(Operator.Equals, "title", title);
      sb.AddOrderByField(true, "starttime");

      SqlStatement stmt = sb.GetStatement(true);
      return ObjectFactory.GetCollection<Program>(stmt.Execute());
    }
예제 #28
0
 public Program GetProgramAt(DateTime date, string title)
 {
   //IFormatProvider mmddFormat = new CultureInfo(String.Empty, false);
   //DateTime startTime = DateTime.Now;
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Program));
   sb.AddConstraint(Operator.Equals, "Title", title);
   sb.AddConstraint(Operator.Equals, "idChannel", IdChannel);
   sb.AddConstraint(Operator.GreaterThan, "endTime", date);
   sb.AddConstraint(Operator.LessThanOrEquals, "startTime", date);
   sb.AddOrderByField(true, "startTime");
   sb.SetRowLimit(1);
   SqlStatement stmt = sb.GetStatement(true);
   IList<Program> programs = ObjectFactory.GetCollection<Program>(stmt.Execute());
   if (programs.Count == 0)
   {
     return null;
   }
   return programs[0];
 }
예제 #29
0
 public IList<SoftwareEncoder> GetSofwareEncodersAudio()
 {
   SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (SoftwareEncoder));
   sb.AddConstraint(Operator.Equals, "type", 1);
   sb.AddOrderByField(true, "priority");
   SqlStatement stmt = sb.GetStatement(true);
   return ObjectFactory.GetCollection<SoftwareEncoder>(stmt.Execute());
 }
예제 #30
0
    private void UpdateNowAndNext()
    {
      if (_currentProgram != null)
      {
        if (DateTime.Now >= _currentProgram.StartTime && DateTime.Now <= _currentProgram.EndTime)
        {
          return;
        }
      }

      _currentProgram = null;
      _nextProgram = null;

      DateTime date = DateTime.Now;
      SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Program));
      sb.AddConstraint(Operator.Equals, "idChannel", IdChannel);
      sb.AddConstraint(Operator.GreaterThanOrEquals, "endTime", date);
      sb.AddOrderByField(true, "startTime");
      sb.SetRowLimit(2);
      SqlStatement stmt = sb.GetStatement(true);
      IList<Program> programs = ObjectFactory.GetCollection<Program>(stmt.Execute());
      if (programs.Count == 0)
      {
        return;
      }
      _currentProgram = programs[0];
      if (_currentProgram.StartTime >= date)
      {
        _nextProgram = _currentProgram;
        _currentProgram = null;
      }
      else
      {
        if (programs.Count == 2)
        {
          _nextProgram = programs[1];
        }
      }
    }