예제 #1
0
 /// <summary>
 /// Executes the specified param.
 /// </summary>
 /// <param name="param">The param.</param>
 /// <param name="result">The result.</param>
 /// <returns></returns>
 public OpResult Execute(string param)
 {
     OpResult opResult = new OpResult();
     opResult.StatusCode = OpStatusCode.Success;
     try
     {
         if (AddInModule.getMediaExperience() == null)
         {
             opResult.StatusCode = OpStatusCode.BadRequest;
             opResult.AppendFormat("No media playing");
         }
         else if (m_set)
         {
             TimeSpan position = TimeSpan.FromSeconds(double.Parse(param));
             AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position = position;
         }
         else
         {
             TimeSpan position = AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position;
             opResult.AppendFormat("Position={0}", position);
         }
     }
     catch (Exception ex)
     {
         opResult.StatusCode = OpStatusCode.Exception;
         opResult.AppendFormat(ex.Message);
     }
     return opResult;
 }
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                if (AddInHost.Current.MediaCenterEnvironment.MediaExperience == null)
                {
                    opResult.StatusCode = OpStatusCode.BadRequest;
                    opResult.AppendFormat("No media playing");
                }
                else
                {
                    foreach (KeyValuePair <string, object> entry in AddInHost.Current.MediaCenterEnvironment.MediaExperience.MediaMetadata)
                    {
                        opResult.AppendFormat("{0}={1}", entry.Key, entry.Value);
                    }
                    opResult.StatusCode = OpStatusCode.Ok;
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #3
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            opResult.StatusCode = OpStatusCode.Success;
            try
            {
                if (AddInHost.Current.MediaCenterEnvironment.MediaExperience == null)
                {
                    opResult.StatusCode = OpStatusCode.BadRequest;
                    opResult.AppendFormat("No media playing");
                }
                else if (m_set)
                {
                    TimeSpan position = TimeSpan.FromSeconds(double.Parse(param));
                    AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position = position;
                }
                else
                {
                    TimeSpan position = AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position;
                    opResult.AppendFormat("Position={0}", position);
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.AppendFormat(ex.Message);
            }
            return(opResult);
        }
예제 #4
0
 /// <summary>
 /// Executes the specified param.
 /// </summary>
 /// <param name="param">The param.</param>
 /// <returns></returns>
 public OpResult Execute(string param)
 {
     // Now try to read again
     OpResult opResult = new OpResult();
     try
     {
         if (AddInModule.getMediaExperience() == null)
         {
             opResult.StatusCode = OpStatusCode.BadRequest;
             opResult.AppendFormat("No media playing");
         }
         else
         {
             foreach (KeyValuePair<string, object> entry in AddInHost.Current.MediaCenterEnvironment.MediaExperience.MediaMetadata)
             {
                 opResult.AppendFormat("{0}={1}", entry.Key, entry.Value);
             }
             opResult.StatusCode = OpStatusCode.Ok;
         }
     }
     catch (Exception ex)
     {
         opResult.StatusCode = OpStatusCode.Exception;
         opResult.StatusText = ex.Message;
     }
     return opResult;
 }
예제 #5
0
        public OpResult showHelp(OpResult or)
        {
            or.AppendFormat("Currently defined templates:\r\n" + listTemplates());
            or.AppendFormat("Custom Formatting Notes:");
            or.AppendFormat("     All custom formats must be defined in the \"custom.template\" file");
            or.AppendFormat("     The \"custom.template\" file must be manually coppied to the ehome directory (usually C:\\Windows\\ehome)");
            or.AppendFormat("     The \"custom.template\" file contains notes / examples on formatting");

            return(or);
        }
예제 #6
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                if (AddInHost.Current.MediaCenterEnvironment.MediaExperience == null)
                {
                    if (m_set)
                    {
                        opResult.StatusCode = OpStatusCode.Ok;
                        opResult.AppendFormat("No media playing");
                    }
                    else
                    {
                        opResult.StatusCode = OpStatusCode.BadRequest;
                        opResult.AppendFormat("No media playing");
                    }
                }
                else if (m_set)
                {
                    PlayRateEnum playRate = (PlayRateEnum)Enum.Parse(typeof(PlayRateEnum), param, true);
                    if (playRate == PlayRateEnum.SkipForward)
                    {
                        AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.SkipForward();
                    }
                    else if (playRate == PlayRateEnum.SkipBack)
                    {
                        AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.SkipBack();
                    }
                    else
                    {
                        AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayRate = (Single)playRate;
                    }
                }
                else if (!m_state)
                {
                    int rate = (int)AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayRate;
                    opResult.AppendFormat("PlayRate={0}", Enum.GetNames(typeof(PlayRateEnum))[rate]);
                }
                else
                {
                    PlayState state = AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayState;
                    opResult.AppendFormat("PlayState={0}", Enum.GetName(typeof(PlayState), state));
                }
                opResult.StatusCode = OpStatusCode.Success;
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.AppendFormat(ex.Message);
            }
            return(opResult);
        }
예제 #7
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                Match match = m_regex.Match(param);
                if (match.Success)
                {
                    opResult.AppendFormat("response={0}", AddInHost.Current.MediaCenterEnvironment.Dialog(
                                              match.Groups["message"].Value,
                                              match.Groups["caption"].Value,
                                              DialogButtons.Ok,
                                              int.Parse(match.Groups["timeout"].Value),
                                              false).ToString());
                    opResult.StatusCode = OpStatusCode.Ok;
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #8
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                Match match = m_regex.Match(param);
                if (match.Success)
                {
                    string imagefile = match.Groups["imagepath"].Value.Replace("/", "\\");

                    // get latest image file from directory, notation example: @"c:\temp\test*.jpg"
                    if (imagefile.Contains("*"))
                    {
                        imagefile = GetFileInfo.GetNewestImage(imagefile);
                    }

                    opResult.AppendFormat("response={0}", AddInHost.Current.MediaCenterEnvironment.DialogNotification(
                                              match.Groups["message"].Value,
                                              new System.Collections.ArrayList(1),
                                              int.Parse(match.Groups["timeout"].Value),
                                              "file://" + imagefile
                                              ).ToString());
                    opResult.StatusCode = OpStatusCode.Ok;
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #9
0
        private bool templateOut(string template, OpResult or, int idx, double elapsed)
        {
            string tmp = "";

            if (!m_templates.ContainsKey(template))
            {
                return(false);
            }

            tmp = m_templates[template];
            tmp = tmp.Replace("%idx%", String.Format("{0}", idx));
            tmp = tmp.Replace("%elapsed_time%", String.Format("{0}", elapsed));
            tmp = tmp.Replace("\\r", "\r");
            tmp = tmp.Replace("\\n", "\n");
            tmp = tmp.Replace("\\t", "\t");
            tmp = tmp.Replace("{", "{{");
            tmp = tmp.Replace("}", "}}");
            tmp = the_state.replacer(tmp);
            if (tmp.TrimStart(' ').Length > 0)
            {
                or.AppendFormat(tmp);
            }

            return(true);
        }
예제 #10
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();
            try
            {
                Match match = m_regex.Match(param);
                if (match.Success)
                {
                    string imagefile = match.Groups["imagepath"].Value.Replace("/","\\");

                    // get latest image file from directory, notation example: @"c:\temp\test*.jpg"
                    if (imagefile.Contains("*"))
                    {
                        imagefile = GetFileInfo.GetNewestImage(imagefile);
                    }

                    opResult.AppendFormat("response={0}", AddInHost.Current.MediaCenterEnvironment.DialogNotification(
                        match.Groups["message"].Value,
                        new System.Collections.ArrayList(1),
                        int.Parse(match.Groups["timeout"].Value),
                        "file://" + imagefile
                        ).ToString());
                    opResult.StatusCode = OpStatusCode.Ok;
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }
예제 #11
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            opResult.StatusCode = OpStatusCode.BadRequest;
            opResult.AppendFormat("This command unavailable due to exception at load: {0}", err_text);
            return(opResult);
        }
예제 #12
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult(OpStatusCode.Success);

            try
            {
                if (param.Equals("Up", StringComparison.InvariantCultureIgnoreCase))
                {
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp();
                }
                else if (param.Equals("Down", StringComparison.InvariantCultureIgnoreCase))
                {
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown();
                }
                else if (param.Equals("Mute", StringComparison.InvariantCultureIgnoreCase))
                {
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute = true;
                }
                else if (param.Equals("UnMute", StringComparison.InvariantCultureIgnoreCase))
                {
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute = false;
                }
                else if (param.Equals("Get", StringComparison.InvariantCultureIgnoreCase))
                {
                    opResult.StatusCode = OpStatusCode.Ok;
                    opResult.AppendFormat("volume={0}", (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7));
                }
                else
                {
                    int desiredLevel = int.Parse(param);
                    if (desiredLevel > 50 || desiredLevel < 0)
                    {
                        opResult.StatusCode = OpStatusCode.BadRequest;
                        return(opResult);
                    }

                    int volume = (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7);
                    for (int level = volume; level > desiredLevel; level--)
                    {
                        AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown();
                    }

                    for (int level = volume; level < desiredLevel; level++)
                    {
                        AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp();
                    }
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #13
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            bool     bTemplate = true;
            OpResult opResult  = new OpResult();
            string   page_file = "";
            string   page      = "";

            opResult.StatusCode = OpStatusCode.Ok;
            try
            {
                if (param.IndexOf("-help") >= 0)
                {
                    opResult = showHelp(opResult);
                    return(opResult);
                }

                // Use custom format?
                if (!m_templates.ContainsKey(param))
                {
                    bTemplate = false;
                    page      = "Error: Template '" + param + "' not found!\r\n All available templates:\r\n";
                    page     += listTemplates();
                }
                else
                {
                    page_file = m_templates[param];
                }
                if (page_file.Length > 0)
                {
                    page = loadTemplateFile(page_file);
                }

                // Convert tags:
                if (bTemplate)
                {
                    Regex rTags = new Regex("%%(?<rex>.+?)%%");
                    Match match = rTags.Match(page);
                    while (match.Success)
                    {
                        string value = getRex(match.Groups["rex"].Value);
                        page  = page.Replace("%%" + match.Groups["rex"].Value + "%%", value);
                        match = match.NextMatch();
                    }
                }

                opResult.AppendFormat("{0}", page);
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #14
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            List <ScheduleEvent> events;
            StringBuilder        sb       = new StringBuilder();
            OpResult             opResult = new OpResult();

            if (m_eventSchedule == null)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = m_exception;
                return(opResult);
            }

            try
            {
                if (param.Equals("recorded", StringComparison.InvariantCultureIgnoreCase))
                {
                    events = m_eventSchedule.GetScheduleEvents(DateTime.MinValue, DateTime.MaxValue, ScheduleEventStates.HasOccurred) as List <ScheduleEvent>;
                }
                else if (param.Equals("recording", StringComparison.InvariantCultureIgnoreCase))
                {
                    events = m_eventSchedule.GetScheduleEvents(DateTime.MinValue, DateTime.MaxValue, ScheduleEventStates.IsOccurring) as List <ScheduleEvent>;
                }
                else if (param.Equals("scheduled", StringComparison.InvariantCultureIgnoreCase))
                {
                    events = m_eventSchedule.GetScheduleEvents(DateTime.Now, DateTime.Now.AddDays(7), ScheduleEventStates.WillOccur) as List <ScheduleEvent>;
                }
                else
                {
                    opResult.StatusCode = OpStatusCode.BadRequest;
                    return(opResult);
                }

                events.Sort(CompareScheduleEvents);
                foreach (ScheduleEvent item in events)
                {
                    opResult.AppendFormat("{0}={1} ({2}-{3})",
                                          item.Id, item.GetExtendedProperty("Title"),
                                          item.StartTime.ToLocalTime().ToString("g"),
                                          item.EndTime.ToLocalTime().ToShortTimeString()
                                          );
                }
                opResult.StatusCode = OpStatusCode.Ok;
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #15
0
 /// <summary>
 /// Executes the specified param.
 /// </summary>
 /// <param name="param">The param.</param>
 /// <param name="result">The result.</param>
 /// <returns></returns>
 public OpResult Execute(string param)
 {
     OpResult opResult = new OpResult();
     try
     {
         opResult.StatusCode = OpStatusCode.Ok;
         opResult.AppendFormat("version={0}", AddInHost.Current.MediaCenterEnvironment.Version.ToString());
     }
     catch (Exception ex)
     {
         opResult.StatusCode = OpStatusCode.Exception;
         opResult.StatusText = ex.Message;
     }
     return opResult;
 }
예제 #16
0
 /// <summary>
 /// Executes the specified param.
 /// </summary>
 /// <param name="param">The param.</param>
 /// <param name="result">The result.</param>
 /// <returns></returns>
 public OpResult Execute(string param)
 {
     OpResult opResult = new OpResult();
     try
     {
         opResult.StatusCode = OpStatusCode.Ok;
         opResult.AppendFormat("NIT={0}","Niewenhuijse IT, Nieuwdorp (www.niewenhuijse.nl)");
     }
     catch (Exception ex)
     {
         opResult.StatusCode = OpStatusCode.Exception;
         opResult.StatusText = ex.Message;
     }
     return opResult;
 }
예제 #17
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                opResult.StatusCode = OpStatusCode.Ok;
                opResult.AppendFormat("version={0}", AddInHost.Current.MediaCenterEnvironment.Version.ToString());
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #18
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                opResult.StatusCode = OpStatusCode.Ok;
                opResult.AppendFormat("NIT={0}", "Niewenhuijse IT, Nieuwdorp (www.niewenhuijse.nl)");
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #19
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                foreach (KeyValuePair <string, object> entry in AddInHost.Current.MediaCenterEnvironment.Capabilities)
                {
                    opResult.AppendFormat("{0}={1}", entry.Key, entry.Value);
                }
                opResult.StatusCode = OpStatusCode.Ok;
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #20
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                foreach (KeyValuePair<string, object> entry in AddInHost.Current.MediaCenterEnvironment.Capabilities)
                {
                    opResult.AppendFormat("{0}={1}", entry.Key, entry.Value);
                }
                opResult.StatusCode = OpStatusCode.Ok;
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }
예제 #21
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
                string version = fileVersionInfo.ProductVersion;

                opResult.StatusCode = OpStatusCode.Ok;
                opResult.AppendFormat("version={0}", version + " (" + AddInHost.Current.MediaCenterEnvironment.CpuClass + ")");
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }
예제 #22
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult(OpStatusCode.Success);
            try
            {
                if (param.Equals("Up", StringComparison.InvariantCultureIgnoreCase))
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp();
                else if (param.Equals("Down", StringComparison.InvariantCultureIgnoreCase))
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown();
                else if (param.Equals("Mute", StringComparison.InvariantCultureIgnoreCase))
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute = true;
                else if (param.Equals("UnMute", StringComparison.InvariantCultureIgnoreCase))
                    AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute = false;
                else if (param.Equals("Get", StringComparison.InvariantCultureIgnoreCase))
                {
                    opResult.StatusCode = OpStatusCode.Ok;
                    opResult.AppendFormat("volume={0}", (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7));
                }
                else
                {
                    int desiredLevel = int.Parse(param);
                    if (desiredLevel > 50 || desiredLevel < 0)
                    {
                        opResult.StatusCode = OpStatusCode.BadRequest;
                        return opResult;
                    }

                    int volume = (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7);
                    for (int level = volume; level > desiredLevel; level--)
                        AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown();

                    for (int level = volume; level < desiredLevel; level++)
                        AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp();
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }
예제 #23
0
        public OpResult listArtistsOnly(OpResult or, string filter)
        {
            WMPLib.IWMPMediaCollection2 collection = null;

            collection = (WMPLib.IWMPMediaCollection2)Player.mediaCollection;
            WMPLib.IWMPQuery            query   = collection.createQuery();
            WMPLib.IWMPStringCollection artists = null;

            if (filter.Length > 0)
            {
                query.addCondition("Artist", "Contains", filter);
            }
            artists = collection.getStringCollectionByQuery("Artist", query, "Audio", "", true);
            for (int j = 0; j < artists.count; j++)
            {
                or.AppendFormat("artist={0}", artists.Item(j));
            }

            return(or);
        }
예제 #24
0
 /// <summary>
 /// Executes the specified param.
 /// </summary>
 /// <param name="param">The param.</param>
 /// <param name="result">The result.</param>
 /// <returns></returns>
 public OpResult Execute(string param)
 {
     OpResult opResult = new OpResult();
     try
     {
         Match match = m_regex.Match(param);
         if (match.Success)
         {
             opResult.AppendFormat("response={0}", AddInHost.Current.MediaCenterEnvironment.Dialog(
                 match.Groups["message"].Value,
                 match.Groups["caption"].Value,
                 DialogButtons.Ok,
                 int.Parse(match.Groups["timeout"].Value),
                 false).ToString());
             opResult.StatusCode = OpStatusCode.Ok;
         }
     }
     catch (Exception ex)
     {
         opResult.StatusCode = OpStatusCode.Exception;
         opResult.StatusText = ex.Message;
     }
     return opResult;
 }
예제 #25
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                Match match = m_regex.Match(param);
                System.Collections.ArrayList buttonArray = new System.Collections.ArrayList();
                System.Collections.Hashtable buttonHT    = new System.Collections.Hashtable();

                int customButtonID = 100;

                if (match.Groups["buttoncodes"].Value.Length > 0)
                {
                    string[] buttons = match.Groups["buttoncodes"].Value.Split(';');

                    foreach (string button in buttons)
                    {
                        switch (button)
                        {
                        case "OK":
                            buttonArray.Add(1);
                            break;

                        case "Cancel":
                            buttonArray.Add(2);
                            break;

                        case "Yes":
                            buttonArray.Add(4);
                            break;

                        case "No":
                            buttonArray.Add(8);
                            break;

                        default:
                            buttonArray.Add(button);
                            buttonHT.Add(customButtonID.ToString(), button);
                            customButtonID++;
                            break;
                        }
                    }
                }

                if (match.Success)
                {
                    responseReceived = false;
                    dlg = new DialogClosedCallback(On_DialogResult);

                    string imagefile = match.Groups["imagepath"].Value.Replace("/", "\\");

                    // get latest image file from directory, notation example: @"c:\temp\test*.jpg"
                    if (imagefile.Contains("*"))
                    {
                        imagefile = GetFileInfo.GetNewestImage(imagefile);
                    }

                    AddInHost.Current.MediaCenterEnvironment.Dialog(
                        match.Groups["message"].Value
                        , match.Groups["caption"].Value
                        , buttonArray
                        , int.Parse(match.Groups["timeout"].Value)
                        , match.Groups["modal"].Value == "modal" ? true:false
                        , "file://" + imagefile
                        , dlg);

                    //wait for a response
                    while (!responseReceived)
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    string btnResult = "";

                    switch (m_dlgResult.ToString())
                    {
                    case "100":
                    case "101":
                    case "102":
                        btnResult = (string)buttonHT[m_dlgResult.ToString()];
                        break;

                    default:
                        btnResult = m_dlgResult.ToString();
                        break;
                    }

                    opResult.AppendFormat("response={0}", btnResult);

                    opResult.StatusCode = OpStatusCode.Success;
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #26
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();
            try
            {

                Match match = m_regex.Match(param);
                System.Collections.ArrayList buttonArray = new System.Collections.ArrayList();
                System.Collections.Hashtable buttonHT = new System.Collections.Hashtable();

                int customButtonID = 100;

                if (match.Groups["buttoncodes"].Value.Length > 0)
                {
                    string[] buttons = match.Groups["buttoncodes"].Value.Split(';');

                    foreach (string button in buttons)
                    {
                        switch (button)
                        {
                            case "OK":
                                buttonArray.Add(1);
                                break;
                            case "Cancel":
                                buttonArray.Add(2);
                                break;
                            case "Yes":
                                buttonArray.Add(4);
                                break;
                            case "No":
                                buttonArray.Add(8);
                                break;
                            default:
                                buttonArray.Add(button);
                                buttonHT.Add(customButtonID.ToString(),button);
                                customButtonID++;
                                break;
                        }
                    }
                }

                if (match.Success)
                {

                    responseReceived = false;
                    dlg = new DialogClosedCallback(On_DialogResult);

                    string imagefile = match.Groups["imagepath"].Value.Replace("/","\\");

                    // get latest image file from directory, notation example: @"c:\temp\test*.jpg"
                    if (imagefile.Contains("*"))
                    {
                        imagefile = GetFileInfo.GetNewestImage(imagefile);
                    }

                    AddInHost.Current.MediaCenterEnvironment.DialogNotification(
                        match.Groups["message"].Value
                        ,buttonArray
                        ,int.Parse(match.Groups["timeout"].Value)
                        ,"file://" + imagefile
                        ,dlg);

                    //wait for a response
                    while (!responseReceived)
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    string btnResult = "";

                    switch (m_dlgResult.ToString())
                    {
                        case "100":
                        case "101":
                        case "102":
                            btnResult = (string)buttonHT[m_dlgResult.ToString()];
                            break;
                        default:
                            btnResult = m_dlgResult.ToString();
                            break;

                    }

                    opResult.AppendFormat("response={0}", btnResult);

                    opResult.StatusCode = OpStatusCode.Ok;

                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }
예제 #27
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            //try
            //{
            Match match = m_regex.Match(param);

            if (match.Success)
            {

                //try
                //{
                //msgResult = msg.Execute(msgboxcmd);
                //}
                //catch (Exception ex)
                //{
                //EventLog.WriteEntry("VmcController Client AddIn", "Error in Announce: " + ex.ToString());
                //}

                //EventLog.WriteEntry("VmcController Client AddIn", "Past msgboxrich");
                //AddInHost.Current.MediaCenterEnvironment.Dialog("Doing the playback", "", DialogButtons.Ok, 5, true);

                //first show the message box
                //MsgBoxRichCmd msg = new MsgBoxRichCmd();
                //string msgboxcmd = "\"" + match.Groups["caption"].Value + "\" \"" + match.Groups["message"].Value + "\" " + match.Groups["timeout"].Value + " \"" + match.Groups["buttoncodes"].Value + "\" \"" + match.Groups["modal"].Value + "\" \"" + match.Groups["imagepath"].Value + "\"";

                Messenger msg = new Messenger("\"" + match.Groups["caption"].Value + "\" \"" + match.Groups["message"].Value + "\" " + match.Groups["timeout"].Value + " \"" + match.Groups["buttoncodes"].Value + "\" \"" + match.Groups["modal"].Value + "\" \"" + match.Groups["imagepath"].Value + "\"");
                //EventLog.WriteEntry("VmcController Client AddIn", "Executing msgboxrich: " + msgboxcmd);

                //OpResult msgResult;

                //AddInHost.Current.MediaCenterEnvironment.Dialog("Playback state: " + isPlaying.ToString(), "", DialogButtons.Ok, 5, true);
                //then if not playing, speak the message

                Thread t = new Thread(new ThreadStart(msg.ShowMessage));
                if (isPlaying() == true)
                {
                    t.Start();
                }
                else
                {
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Not playing. Proceeding", "", DialogButtons.Ok, 5, true);

                    FileInfo fi;
                    if (match.Groups["ssmltospeak"].Value.Length > 1)
                    {
                        fi = MakeAudioFile(match.Groups["ssmltospeak"].Value);
                    }
                    else
                    {
                        //AddInHost.Current.MediaCenterEnvironment.Dialog("Making the audio file from the message", "", DialogButtons.Ok, 5, true);
                        fi = MakeAudioFile(match.Groups["message"].Value);
                    }

                    //long fileDurationInMS = (fi.Length / 352000) * 1000;  //much older code

                    //long fileDurationInMS = ((fi.Length / 44100) * 1000)-3000;  //current code
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Duration: " + fileDurationInMS.ToString(), "", DialogButtons.Ok, 3, true);
                    /*
                    WMPLib.WindowsMediaPlayer Player = new WMPLib.WindowsMediaPlayer();
                    Player.settings.autoStart = true;
                    Player.URL = fi.FullName;

                    */

                    //show the message box
                    //msgResult = msg.Execute(msgboxcmd);

                    t.Start();
                    //ThreadPriority PreviousPriority = Thread.CurrentThread.Priority;
                    //Thread.CurrentThread.Priority = ThreadPriority.Highest;
                    WMPLib.WindowsMediaPlayer Player = new WMPLib.WindowsMediaPlayer();
                    Player.settings.playCount = 1;
                    Player.settings.setMode("loop", false);
                    Player.URL = fi.FullName;

                    //AddInHost.Current.MediaCenterEnvironment.PlayMedia(MediaType.Audio, fi.FullName, false);

                    //DateTime ExpectedEndTime = DateTime.Now.AddMilliseconds(fileDurationInMS);
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Now we're playing", "", DialogButtons.Ok, 5, true);
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Playstate: " + (AddInHost.Current.MediaCenterEnvironment.MediaExperience == null).ToString(), "", DialogButtons.Ok, 5, true);
                    //SendKeyCmd StopCmd = new SendKeyCmd('S', true, true, false);
                    //OpResult StopResult = null;

                    //while (AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Playing)

                    //wait for the required duration to elapse

                    //while (isPlaying() == true)
                    //{
                    //  if (DateTime.Compare(DateTime.Now,ExpectedEndTime) >= 0)
                    //{

                    //ensure it only plays once, regardless of shuffle/repeat state. Don't know why we have to keep sending the stop command
                    //probably something to do with timing
                    //while (AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Playing)
                    //{
                    //StopResult = StopCmd.Execute("");

                    //System.Windows.Forms.Application.DoEvents(); //ensures that the stop command is responded to
                    //System.Threading.Thread.Sleep(100);
                    //}
                    //break;
                    // }

                    // System.Threading.Thread.Sleep(100);
                    //}
                    //Thread.CurrentThread.Priority = PreviousPriority;
                    fi.Delete();

                }

                //opResult.AppendFormat(msgResult.StatusText);
                opResult.AppendFormat("Ok");
                opResult.StatusCode = OpStatusCode.Ok;
            }

            //}
            //catch (Exception ex)
            //{
            //    EventLog.WriteEntry("VmcController Client AddIn", ex.ToString());
            //    opResult.StatusCode = OpStatusCode.Exception;
            //    opResult.StatusText = ex.Message;
            //}
            return opResult;
        }
예제 #28
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param, NowPlayingList nowPlaying, MediaItem currentMedia)
        {
            OpResult opResult = new OpResult();
            opResult.StatusCode = OpStatusCode.Json;

            if (currentMedia != null)
            {
                opResult.ContentText = JsonConvert.SerializeObject(currentMedia, Formatting.Indented);
                return opResult;
            }
            else if (param.IndexOf("-help") >= 0)
            {
                opResult.StatusCode = OpStatusCode.Ok;
                opResult = showHelp(opResult);
                return opResult;
            }

            debug_last_action = "Execute: Start";
            bool should_enqueue = true;
            int size_x = 0;
            int size_y = 0;
            string create_playlist_name = null;
            string playlist_query = null;
            string template = "";
            string cache_fn = make_cache_fn(String.Format("{0}-{1}.txt", which_command, param));
            string cache_body = "";
            try
            {
                IWMPMediaCollection2 collection = (IWMPMediaCollection2)Player.mediaCollection;
                IWMPPlaylistCollection playlistCollection = (IWMPPlaylistCollection)Player.playlistCollection;

                int ver = Player.mediaCollection.getByAttribute("MediaType", "Audio").count;
                string cache_ver = String.Format("{0}", ver);
                cache_body = get_cached(cache_fn, cache_ver);
                if (cache_body.Length != 0 && create_playlist_name == null && playlist_query == null && !m_stats_only)
                {
                    opResult.ContentText = setCachedFlag(cache_body);
                    return opResult;
                }

                IWMPQuery query = collection.createQuery();
                IWMPPlaylistArray playlists = null;
                IWMPPlaylist mediaPlaylist = null;
                IWMPMedia media_item;

                ArrayList query_indexes = new ArrayList();

                Library metadata = new Library(m_stats_only);

                bool has_query = false;
                bool has_exact_query = false;

                string query_text = "";
                string query_type = "";

                debug_last_action = "Execution: Parsing params";

                request_params = HttpUtility.UrlEncode(param);

                if (param.Contains("create-playlist:"))
                {
                    create_playlist_name = param.Substring(param.IndexOf("create-playlist:") + "create-playlist:".Length);
                    create_playlist_name = trim_parameter(create_playlist_name);
                }

                if (param.Contains("exact-genre:"))
                {
                    string genre = param.Substring(param.IndexOf("exact-genre:") + "exact-genre:".Length);
                    genre = trim_parameter(genre);
                    query.addCondition("WM/Genre", "Equals", genre);
                    genre_filter = genre;
                    query_text = genre;
                    query_type = "Genre";
                    has_query = true;
                    has_exact_query = true;
                }
                else if (param.Contains("genre:*"))
                {
                    string genre = param.Substring(param.IndexOf("genre:*") + "genre:*".Length);
                    genre = trim_parameter(genre);
                    query.addCondition("WM/Genre", "BeginsWith", genre);
                    query.beginNextGroup();
                    query.addCondition("WM/Genre", "Contains", " " + genre);
                    genre_filter = genre;
                    query_text = genre;
                    query_type = "Genre";
                    has_query = true;
                }
                else if (param.Contains("genre:"))
                {
                    string genre = param.Substring(param.IndexOf("genre:") + "genre:".Length);
                    genre = trim_parameter(genre);
                    query.addCondition("WM/Genre", "BeginsWith", genre);
                    genre_filter = genre;
                    query_text = genre;
                    query_type = "Genre";
                    has_query = true;
                }

                if (param.Contains("exact-artist:"))
                {
                    string artist = param.Substring(param.IndexOf("exact-artist:") + "exact-artist:".Length);
                    artist = trim_parameter(artist);
                    query.addCondition("Author", "Equals", artist);
                    artist_filter = artist;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += artist;
                    query_type += "Artist";
                    has_query = true;
                    has_exact_query = true;
                }
                else if (param.Contains("exact-album-artist:"))
                {
                    string album_artist = param.Substring(param.IndexOf("exact-album-artist:") + "exact-album-artist:".Length);
                    album_artist = trim_parameter(album_artist);
                    query.addCondition("WM/AlbumArtist", "Equals", album_artist);
                    artist_filter = album_artist;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += album_artist;
                    query_type += "Album Artist";
                    has_query = true;
                    has_exact_query = true;
                }
                else if (param.Contains("album-artist:*"))
                {
                    string album_artist = param.Substring(param.IndexOf("album-artist:*") + "album-artist:*".Length);
                    album_artist = trim_parameter(album_artist);
                    query.addCondition("WM/AlbumArtist", "BeginsWith", album_artist);
                    query.beginNextGroup();
                    query.addCondition("WM/AlbumArtist", "Contains", " " + album_artist);
                    artist_filter = album_artist;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += album_artist;
                    query_type += "Album Artist";
                    has_query = true;
                }
                else if (param.Contains("album-artist:"))
                {
                    string album_artist = param.Substring(param.IndexOf("album-artist:") + "album-artist:".Length);
                    album_artist = trim_parameter(album_artist);
                    query.addCondition("WM/AlbumArtist", "BeginsWith", album_artist);
                    artist_filter = album_artist;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += album_artist;
                    query_type += "Album Artist";
                    has_query = true;
                }
                else if (param.Contains("artist:*"))
                {
                    string artist = param.Substring(param.IndexOf("artist:*") + "artist:*".Length);
                    artist = trim_parameter(artist);
                    query.addCondition("Author", "BeginsWith", artist);
                    query.beginNextGroup();
                    query.addCondition("Author", "Contains", " " + artist);
                    artist_filter = artist;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += artist;
                    query_type += "Artist";
                    has_query = true;
                }
                else if (param.Contains("artist:"))
                {
                    string artist = param.Substring(param.IndexOf("artist:") + "artist:".Length);
                    artist = trim_parameter(artist);
                    query.addCondition("Author", "BeginsWith", artist);
                    artist_filter = artist;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += artist;
                    query_type += "Artist";
                    has_query = true;
                }

                if (param.Contains("exact-album:"))
                {
                    string album = param.Substring(param.IndexOf("exact-album:") + "exact-album:".Length);
                    album = trim_parameter(album);
                    query.addCondition("WM/AlbumTitle", "Equals", album);
                    album_filter = album;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += album;
                    query_type += "Album";
                    has_query = true;
                    has_exact_query = true;
                }
                else if (param.Contains("album:"))
                {
                    string album = param.Substring(param.IndexOf("album:") + "album:".Length);
                    album = trim_parameter(album);
                    query.addCondition("WM/AlbumTitle", "BeginsWith", album);
                    album_filter = album;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += album;
                    query_type += "Album";
                    has_query = true;
                }

                //This is not for a query but rather for playing/enqueing exact songs
                if (param.Contains("exact-song:"))
                {
                    string song = param.Substring(param.IndexOf("exact-song:") + "exact-song:".Length);
                    song = trim_parameter(song);
                    song_filter = song;
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_text += song;
                    query_type += "Song";
                    has_exact_query = true;
                }

                if (param.Contains("exact-playlist:"))
                {
                    playlist_query = param.Substring(param.IndexOf("exact-playlist:") + "exact-playlist:".Length);
                    playlist_query = trim_parameter(playlist_query);
                }

                // Indexes specified?
                if (param.Contains("indexes:"))
                {
                    string indexes = param.Substring(param.IndexOf("indexes:") + "indexes:".Length);
                    if (indexes.IndexOf(" ") >= 0) indexes = indexes.Substring(0, indexes.IndexOf(" "));
                    string[] s_idx = indexes.Split(',');
                    foreach (string s in s_idx)
                    {
                        if (s.Length > 0) query_indexes.Add(Int16.Parse(s));
                    }
                    if (query_text.Length > 0)
                    {
                        query_text += ": ";
                        query_type += "/";
                    }
                    query_type += "Tracks";
                    has_query = true;
                }

                if (!has_query) query_type = query_text = "All";

                // Cover size specified?
                if (param.Contains("size-x:"))
                {
                    string tmp_size = param.Substring(param.IndexOf("size-x:") + "size-x:".Length);
                    if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                    size_x = Convert.ToInt32(tmp_size);
                }
                if (param.Contains("size-y:"))
                {
                    string tmp_size = param.Substring(param.IndexOf("size-y:") + "size-y:".Length);
                    if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                    size_y = Convert.ToInt32(tmp_size);
                }
                // Use Custom Template?
                if (param.Contains("template:"))
                {
                    template = param.Substring(param.IndexOf("template:") + "template:".Length);
                    if (template.IndexOf(" ") >= 0) template = template.Substring(0, template.IndexOf(" "));
                }

                if (which_command == PLAY) should_enqueue = false;

                switch (which_command)
                {
                    case CLEAR_CACHE:
                        opResult.StatusCode = OpStatusCode.Ok;
                        clear_cache();
                        return opResult;
                    case LIST_GENRES:
                        if (create_playlist_name != null)
                        {
                            IWMPPlaylist genre_playlist = collection.getPlaylistByQuery(query, "Audio", "WM/Genre", true);
                            add_to_playlist(opResult, has_query, genre_playlist, create_playlist_name);
                            opResult.StatusCode = OpStatusCode.Ok;
                        }
                        else
                        {
                            IWMPStringCollection genres;
                            if (has_query)
                            {
                                genres = collection.getStringCollectionByQuery("WM/Genre", query, "Audio", "WM/Genre", true);
                            }
                            else
                            {
                                genres = collection.getAttributeStringCollection("WM/Genre", "Audio");
                            }
                            if (genres != null && genres.count > 0)
                            {
                                result_count = 0;
                                for (int k = 0; k < genres.count; k++)
                                {
                                    string item = genres.Item(k);
                                    if (item != null && !item.Equals(""))
                                    {
                                        if (!m_stats_only) metadata.addGenre(item);
                                        else result_count++;
                                    }
                                }
                                opResult.ResultCount = result_count;
                                metadata.trimToSize();
                                opResult = serializeObject(opResult, metadata, cache_fn, cache_ver);
                            }
                            else
                            {
                                opResult.StatusCode = OpStatusCode.BadRequest;
                                opResult.StatusText = "No genres found!";
                            }
                        }
                        return opResult;
                    case LIST_ARTISTS:
                        if (create_playlist_name != null)
                        {
                            IWMPPlaylist artists_playlist = collection.getPlaylistByQuery(query, "Audio", "Author", true);
                            add_to_playlist(opResult, has_query, artists_playlist, create_playlist_name);
                            opResult.StatusCode = OpStatusCode.Ok;
                        }
                        else
                        {
                            IWMPStringCollection artists;
                            if (has_query)
                            {
                                artists = collection.getStringCollectionByQuery("Author", query, "Audio", "Author", true);
                            }
                            else
                            {
                                artists = collection.getAttributeStringCollection("Author", "Audio");
                            }
                            if (artists != null && artists.count > 0)
                            {
                                result_count = 0;
                                for (int k = 0; k < artists.count; k++)
                                {
                                    string item = artists.Item(k);
                                    if (item != null && !item.Equals(""))
                                    {
                                        if (!m_stats_only) metadata.addArtist(item);
                                        else result_count++;
                                    }
                                }
                                opResult.ResultCount = result_count;
                                metadata.trimToSize();
                                opResult = serializeObject(opResult, metadata, cache_fn, cache_ver);
                            }
                            else
                            {
                                opResult.StatusCode = OpStatusCode.BadRequest;
                                opResult.StatusText = "No artists found!";
                            }
                        }
                        return opResult;
                    case LIST_ALBUM_ARTISTS:
                        if (create_playlist_name != null)
                        {
                            IWMPPlaylist album_artists_playlist = collection.getPlaylistByQuery(query, "Audio", "WM/AlbumArtist", true);
                            add_to_playlist(opResult, has_query, album_artists_playlist, create_playlist_name);
                            opResult.StatusCode = OpStatusCode.Ok;
                        }
                        else
                        {
                            IWMPStringCollection album_artists;
                            if (has_query)
                            {
                                album_artists = collection.getStringCollectionByQuery("WM/AlbumArtist", query, "Audio", "WM/AlbumArtist", true);
                            }
                            else
                            {
                                album_artists = collection.getAttributeStringCollection("WM/AlbumArtist", "Audio");
                            }
                            if (album_artists != null && album_artists.count > 0)
                            {
                                result_count = 0;
                                for (int k = 0; k < album_artists.count; k++)
                                {
                                    string item = album_artists.Item(k);
                                    if (item != null && !item.Equals("") && !metadata.containsAlbumArtist(item))
                                    {
                                        if (!m_stats_only) metadata.addAlbumArtist(item);
                                        else result_count++;
                                    }
                                }
                                opResult.ResultCount = result_count;
                                metadata.trimToSize();
                                opResult = serializeObject(opResult, metadata, cache_fn, cache_ver);
                            }
                            else
                            {
                                opResult.StatusCode = OpStatusCode.BadRequest;
                                opResult.StatusText = "No album artists found!";
                            }
                        }
                        return opResult;
                    case LIST_ALBUMS:
                        if (create_playlist_name != null)
                        {
                            IWMPPlaylist albums_playlist = collection.getPlaylistByQuery(query, "Audio", "WM/AlbumTitle", true);
                            add_to_playlist(opResult, has_query, albums_playlist, create_playlist_name);
                            opResult.StatusCode = OpStatusCode.Ok;
                        }
                        else
                        {
                            IWMPStringCollection albums;
                            if (has_query)
                            {
                                albums = collection.getStringCollectionByQuery("WM/AlbumTitle", query, "Audio", "WM/AlbumTitle", true);
                            }
                            else
                            {
                                albums = collection.getAttributeStringCollection("WM/AlbumTitle", "Audio");
                            }
                            if (albums != null && albums.count > 0)
                            {
                                result_count = 0;
                                for (int k = 0; k < albums.count; k++)
                                {
                                    string item = albums.Item(k);
                                    if (item != null && !item.Equals(""))
                                    {
                                        if (!m_stats_only) metadata.addAlbum(new Album(item, collection.getByAlbum(item), m_stats_only));
                                        else result_count++;
                                    }
                                }
                                opResult.ResultCount = result_count;
                                metadata.trimToSize();
                                opResult = serializeObject(opResult, metadata, cache_fn, cache_ver);
                            }
                            else
                            {
                                opResult.StatusCode = OpStatusCode.BadRequest;
                                opResult.StatusText = "No albums found!";
                            }
                        }
                        return opResult;
                    case LIST_SONGS:
                        IWMPStringCollection songs;
                        if (has_query)
                        {
                            songs = collection.getStringCollectionByQuery("Title", query, "Audio", "Title", true);
                        }
                        else
                        {
                            songs = collection.getAttributeStringCollection("Title", "Audio");
                        }
                        if (songs != null && songs.count > 0)
                        {
                            for (int k = 0; k < songs.count; k++)
                            {
                                IWMPPlaylist playlist = collection.getByName(songs.Item(k));
                                if (playlist != null && playlist.count > 0)
                                {
                                    if (create_playlist_name != null)
                                    {
                                        add_to_playlist(opResult, has_query, playlist, create_playlist_name);
                                        opResult.StatusCode = OpStatusCode.Ok;
                                    }
                                    else
                                    {
                                        metadata.addSongs(playlist);
                                    }
                                }
                            }
                            if (create_playlist_name == null)
                            {
                                metadata.trimToSize();
                                opResult = serializeObject(opResult, metadata, cache_fn, cache_ver);
                            }
                        }
                        else
                        {
                            opResult.StatusCode = OpStatusCode.BadRequest;
                            opResult.StatusText = "No songs found!";
                        }
                        return opResult;
                    case LIST_PLAYLISTS:
                        result_count = 0;
                        playlists = getAllUserPlaylists(playlistCollection);
                        result_count = metadata.addPlaylists(playlistCollection, playlists);
                        metadata.trimToSize();
                        opResult.ResultCount = result_count;
                        opResult.ContentText = JsonConvert.SerializeObject(metadata, Formatting.Indented);
                        return opResult;
                    case LIST_RECENT:
                        if (param.Contains("count:"))
                        {
                            string scount = param.Substring(param.IndexOf("count:") + "count:".Length);
                            if (scount.IndexOf(" ") >= 0) scount = scount.Substring(0, scount.IndexOf(" "));
                            int count = Convert.ToInt32(scount);
                            list_recent(opResult, template, count);
                        }
                        else list_recent(opResult, template);
                        opResult.StatusCode = OpStatusCode.Ok;
                        return opResult;
                    case LIST_NOWPLAYING:
                        if (nowPlaying != null)
                        {
                            opResult.ContentText = JsonConvert.SerializeObject(nowPlaying, Formatting.Indented);
                        }
                        else
                        {
                            opResult.StatusCode = OpStatusCode.BadRequest;
                            opResult.StatusText = "Now playing is null!";
                        }
                        return opResult;
                    case DELETE_PLAYLIST:
                        if (playlist_query != null)
                        {
                            playlists = getUserPlaylistsByName(playlist_query, playlistCollection);
                            if (playlists.count > 0)
                            {
                                IWMPPlaylist mod_playlist = playlists.Item(0);
                                if (query_indexes.Count > 0)
                                {
                                    // Delete items indicated by indexes instead of deleting playlist
                                    for (int j = 0; j < query_indexes.Count; j++)
                                    {
                                        mod_playlist.removeItem(mod_playlist.get_Item((Int16)query_indexes[j]));
                                    }
                                    opResult.ContentText = "Items removed from playlist " + mod_playlist + ".";
                                }
                                else
                                {
                                    ((IWMPPlaylistCollection)Player.playlistCollection).remove(mod_playlist);
                                    opResult.ContentText = "Playlist " + mod_playlist + " deleted.";
                                }
                                opResult.StatusCode = OpStatusCode.Success;
                            }
                            else
                            {
                                opResult.StatusCode = OpStatusCode.BadRequest;
                                opResult.StatusText = "Playlist does not exist!";
                            }
                        }
                        else
                        {
                            opResult.StatusCode = OpStatusCode.BadRequest;
                            opResult.StatusText = "Must specify the exact playlist!";
                        }
                        return opResult;
                    case LIST_DETAILS:
                        // Get  query as a playlist
                        if (playlist_query != null)
                        {
                            //Return a specific playlist when music-list-details with exact-playlist is queried
                            playlists = getUserPlaylistsByName(playlist_query, playlistCollection);
                            if (playlists.count > 0)
                            {
                                Playlist aPlaylist = new Playlist(playlist_query);
                                mediaPlaylist = playlists.Item(0);
                                //Or return a playlist query
                                if (mediaPlaylist != null)
                                {
                                    aPlaylist.addItems(mediaPlaylist);
                                }
                                metadata.playlists.Add(aPlaylist);
                            }
                        }
                        else if (has_exact_query)
                        {
                            mediaPlaylist = getPlaylistFromExactQuery(query_text, query_type, collection);
                        }
                        else if (has_query)
                        {
                            string type = getSortAttributeFromQueryType(query_type);
                            mediaPlaylist = collection.getPlaylistByQuery(query, "Audio", type, true);
                        }

                        if (mediaPlaylist != null)
                        {
                            //Create playlist from query if supplied with playlist name
                            if (create_playlist_name != null)
                            {
                                add_to_playlist(opResult, has_query, mediaPlaylist, create_playlist_name);
                                return opResult;
                            }
                            else if (query_indexes.Count > 0)
                            {
                                for (int j = 0; j < query_indexes.Count; j++)
                                {
                                    media_item = mediaPlaylist.get_Item((Int16)query_indexes[j]);
                                    if (media_item != null)
                                    {
                                        metadata.addSong(media_item);
                                    }
                                }
                            }
                            else
                            {
                                if (query_type.Equals("Album"))
                                {
                                    Album album = new Album(query_text, m_stats_only);
                                    album.addTracks(mediaPlaylist);
                                    metadata.addAlbum(album);
                                }
                                else
                                {
                                    metadata.addSongs(mediaPlaylist);
                                }
                            }
                        }
                        else
                        {
                            if (logger != null)
                            {
                                logger.Write("Creating library metadata object");
                            }
                            //No query supplied so entire detailed library requested
                            //Parse all albums and return, no value album will be added as songs
                            IWMPStringCollection album_collection = collection.getAttributeStringCollection("WM/AlbumTitle", "Audio");
                            if (album_collection.count > 0)
                            {
                                result_count = 0;
                                for (int j = 0; j < album_collection.count; j++)
                                {
                                    if (album_collection.Item(j) != null)
                                    {
                                        //The collection seems to represent the abcense of an album as an "" string value
                                        IWMPPlaylist album_playlist = collection.getByAlbum(album_collection.Item(j));
                                        if (album_playlist != null)
                                        {
                                            if (!album_collection.Item(j).Equals(""))
                                            {
                                                Album album = new Album(album_collection.Item(j), m_stats_only);
                                                result_count += album.addTracks(album_playlist);
                                                metadata.addAlbum(album);
                                            }
                                            else
                                            {
                                                result_count += metadata.addSongs(album_playlist);
                                            }
                                        }
                                    }
                                }
                                metadata.trimToSize();
                            }
                        }
                        if (logger != null)
                        {
                            logger.Write("Starting serialization of metadata object.");
                        }
                        opResult.ResultCount = result_count;
                        opResult = serializeObject(opResult, metadata, cache_fn, cache_ver);
                        return opResult;
                    case PLAY:
                    case QUEUE:
                        if (has_exact_query)
                        {
                            mediaPlaylist = getPlaylistFromExactQuery(query_text, query_type, collection);
                        }
                        else if (has_query)
                        {
                            string type = getSortAttributeFromQueryType(query_type);
                            mediaPlaylist = collection.getPlaylistByQuery(query, "Audio", type, true);
                        }
                        else
                        {
                            mediaPlaylist = collection.getByAttribute("MediaType", "Audio");
                        }
                        //Play or enqueue
                        PlayMediaCmd pmc;
                        if (query_indexes.Count > 0)
                        {
                            result_count = query_indexes.Count;
                            for (int j = 0; j < query_indexes.Count; j++)
                            {
                                media_item = mediaPlaylist.get_Item(j);
                                if (media_item != null)
                                {
                                    query_text += ((j == 0) ? "" : ", ") + (Int16)query_indexes[j] + ". " + media_item.getItemInfo("Title");
                                }
                            }
                            pmc = new PlayMediaCmd(remotePlayer, mediaPlaylist, query_indexes, should_enqueue);
                        }
                        else
                        {
                            result_count = mediaPlaylist.count;
                            pmc = new PlayMediaCmd(remotePlayer, mediaPlaylist, should_enqueue);
                        }
                        opResult = pmc.Execute(null);

                        // Type, Artist, Album, Track, param, count
                        add_to_mrp(query_type, query_text, param, result_count); //Add to recent played list
                        return opResult;
                    case SERV_COVER:
                        if (has_exact_query)
                        {
                            mediaPlaylist = getPlaylistFromExactQuery(query_text, query_type, collection);
                        }
                        else if (has_query)
                        {
                            string type = getSortAttributeFromQueryType(query_type);
                            mediaPlaylist = collection.getPlaylistByQuery(query, "Audio", type, true);
                        }
                        else
                        {
                            mediaPlaylist = collection.getByAttribute("MediaType", "Audio");
                        }

                        try
                        {
                            if (query_indexes.Count > 0)
                            {
                                for (int j = 0; j < query_indexes.Count; j++)
                                {
                                    media_item = mediaPlaylist.get_Item((Int16)query_indexes[j]);
                                    if (media_item != null)
                                    {
                                        string album_path = findAlbumPath(media_item.sourceURL);
                                        photoCmd pc = new photoCmd(photoCmd.SERV_PHOTO);
                                        if (album_path.Length == 0) return pc.getPhoto(DEFAULT_IMAGE, "jpeg", size_x, size_y);
                                        else return pc.getPhoto(album_path, "jpeg", size_x, size_y);
                                    }
                                }
                            }
                            else
                            {
                                for (int j = 0; j < mediaPlaylist.count; j++)
                                {
                                    media_item = mediaPlaylist.get_Item(j);
                                    if (media_item != null)
                                    {
                                        string album_path = findAlbumPath(media_item.sourceURL);
                                        photoCmd pc = new photoCmd(photoCmd.SERV_PHOTO);
                                        if (album_path.Length == 0) return pc.getPhoto(DEFAULT_IMAGE, "jpeg", size_x, size_y);
                                        else return pc.getPhoto(album_path, "jpeg", size_x, size_y);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            opResult.StatusCode = OpStatusCode.Exception;
                            opResult.StatusText = ex.Message;
                        }
                        return opResult;
                }
            }
            catch (Exception ex)
            {
                opResult = new OpResult();
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
                opResult.AppendFormat("{0}", debug_last_action);
                opResult.AppendFormat("{0}", ex.Message);
            }

            debug_last_action = "Execute: End";

            return opResult;
        }
예제 #29
0
        public OpResult showHelp(OpResult or)
        {
            or.AppendFormat("list-artists [artist_name_filter] - lists all matching artists (Note very slow!)");
            or.AppendFormat("list-artist-songs <index#> - lists all songs for the specified artist");
            or.AppendFormat("list-artist-albums <index#> - lists all albums for the specified artist");
            or.AppendFormat("list-albums - lists all albums");
            or.AppendFormat("list-album-songs <index#> - lists all songs for the specified album");
            or.AppendFormat("list-all-custom [-custom#] - Uses the specified custom format against all audio items");
            or.AppendFormat("list-artist-custom [-custom#] <index#> - Uses the specified custom format for the specified artist");
            or.AppendFormat("list-album-custom [-custom#] <index#> - Uses the specified custom format for the specified album");
            or.AppendFormat("list-song-custom [-custom#] <index#> - Uses the specified custom format for the specified song");
            or.AppendFormat("play-audio-artist <index#> - plays all songs for the specified artist");
            or.AppendFormat("play-audio-album <index#> - plays all songs for the specified album");
            or.AppendFormat("play-audio-song <index#> - plays the specified song");
            or.AppendFormat("queueaudio-artist <index#> - Adds all songs for the specified artist to the queue");
            or.AppendFormat("queueaudio-album <index#> - Adds all songs for the specified album to the queue");
            or.AppendFormat("queueaudio-song <index#> - Adds the specified song to the queue");
            or.AppendFormat(" ");
            or.AppendFormat("Where:");
            or.AppendFormat("     artist_name_filter: a filter string (\"ab\" would only return artists starting with \"Ab\")");
            or.AppendFormat("          NOTE: Using an artist_name_filter is very slow! May take minutes to return with 10K tracks!!");
            or.AppendFormat("     custom#: a number > 100 which specifies a custom format in the artist.template file");
            or.AppendFormat("     index#: a track index (from the default \"list-xxx\" commands)");
            or.AppendFormat("          NOTE: Using the track index is very fast! Use the list-xxx commands to retrieve the indexes");
            or.AppendFormat(" ");
            or.AppendFormat("Parameter Notes:");
            or.AppendFormat("     The index number is just an index into the complete collection of songs and may change - it is not static!");
            or.AppendFormat("     Almost of the parameters can be used with any command - the above just shows the parameters that make sense.");
            or.AppendFormat(" ");
            or.AppendFormat("Custom Formatting Notes:");
            or.AppendFormat("     All custom formats must be defined in the \"artist.template\" file");
            or.AppendFormat("     The \"artist.template\" file must be manually coppied to the ehome directory (usually C:\\Windows\\ehome)");
            or.AppendFormat("     The \"artist.template\" file contains notes / examples on formatting");
            or.AppendFormat("     The built in formats may also be overwritten via the \"artist.template\" file");

            return(or);
        }
예제 #30
0
        private OpResult do_basic_list(OpResult or, WMPLib.IWMPStringCollection list, string list_type, string template, string default_template)
        {
            int result_count = list.count;
            or.AppendFormat("{0}", basic_replacer(getTemplate(template + ".H", ""), "", "", result_count, -1)); // Header
            string c_last = " ";
            for (int j = 0; j < list.count; j++)
            {
                string list_item = list.Item(j);
                if (list_item.Length > 0)
                {
                    string s_out = "";
                    if (first_letter(list_item) != c_last)
                    {
                        if (j > 0)
                        {
                            s_out = getTemplate(template + ".Alpha-", "");
                            s_out = basic_replacer(s_out, list_type, list.Item(j - 1), result_count, j);
                            s_out = basic_replacer(s_out, "letter", c_last, result_count, j);
                            if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Alpha-
                        }
                        c_last = first_letter(list_item);
                        s_out = getTemplate(template + ".Alpha+", "");
                        s_out = basic_replacer(s_out, list_type, list_item, result_count, j);
                        s_out = basic_replacer(s_out, "letter", c_last, result_count, j);
                        if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Alpha +
                    }
                    s_out = getTemplate(template + ".Entry", default_template);
                    s_out = basic_replacer(s_out, list_type, list_item, result_count, j);
                    s_out = basic_replacer(s_out, "letter", c_last, result_count, j);
                    s_out = do_conditional_replace(s_out, "all_filters", request_params);
                    s_out = do_conditional_replace(s_out, "genreFilter", genre_filter);
                    s_out = do_conditional_replace(s_out, "artistFilter", artist_filter);
                    s_out = do_conditional_replace(s_out, "albumFilter", album_filter);

                    //opResult.AppendFormat("artist={0}", artists.Item(j));
                    if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Entry
                }
            }
            if (result_count > 0) // Close the final alpha grouping
            {
                string s_out = getTemplate(template + ".Alpha-", "");
                s_out = basic_replacer(s_out, list_type, list.Item(result_count - 1), result_count, result_count);
                s_out = basic_replacer(s_out, "letter", c_last, result_count, result_count);
                if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Alpha-
            }
            return or;
        }
예제 #31
0
        private bool templateOut(string template, OpResult or, int idx, double elapsed)
        {
            string tmp = "";

            if (!m_templates.ContainsKey(template)) return false;

            tmp = m_templates[template];
            tmp = tmp.Replace("%idx%", String.Format("{0}", idx));
            tmp = tmp.Replace("%elapsed_time%", String.Format("{0}", elapsed));
            tmp = tmp.Replace("\\r", "\r");
            tmp = tmp.Replace("\\n", "\n");
            tmp = tmp.Replace("\\t", "\t");
            tmp = tmp.Replace("{", "{{");
            tmp = tmp.Replace("}", "}}");
            tmp = the_state.replacer(tmp);
            if (tmp.TrimStart(' ').Length > 0) or.AppendFormat(tmp);

            return true;
        }
예제 #32
0
        public OpResult show_stats(string template, HashSet<int> results)
        {
            OpResult op_return = new OpResult(OpStatusCode.Ok);
            string template_list = "";
            int pic_count = photo_media_play_list.count;

            if (results.Count > 0) pic_count = results.Count;

            string output_template = getTemplate(template + "+", DEFAULT_STATS_HEAD);
            output_template += getTemplate(template, DEFAULT_STATS_RESULT);
            output_template += getTemplate(template + "-", DEFAULT_STATS_FOOT);

            if (output_template.Length > 0)
            {
                output_template = file_includer(output_template);
                output_template = do_conditional_replace(output_template, "results_count", String.Format("{0}", pic_count));
                output_template = do_conditional_replace(output_template, "tag_count", String.Format("{0}", kw_count));
                output_template = do_conditional_replace(output_template, "start_date", String.Format("{0}", first_date.ToShortDateString()));
                output_template = do_conditional_replace(output_template, "end_date", String.Format("{0}", last_date.ToShortDateString()));
                output_template = do_conditional_replace(output_template, "filter_is_tagged", String.Format("{0}", param_is_tagged));
                output_template = do_conditional_replace(output_template, "filter_not_tagged", String.Format("{0}", param_not_tagged));
                output_template = do_conditional_replace(output_template, "filter_start_date", String.Format("{0}", param_start_date));
                output_template = do_conditional_replace(output_template, "filter_end_date", String.Format("{0}", param_end_date));
                if (output_template.IndexOf("%available_templates%") >= 0)
                {
                    foreach (KeyValuePair<string, string> t in m_templates)
                    {
                        if (!t.Key.EndsWith("+") && !t.Key.EndsWith("-"))
                        {
                            if (template_list.Length > 0) template_list += ", ";
                            template_list += t.Key;
                        }
                    }
                }
                /* get random image index in results if needed */
                if (output_template.Contains("%random_id%"))
                {
                    int random_index = new Random().Next(pic_count);
                    string random = "";

                    if (results.Count > 0)
                    {
                        HashSet<int>.Enumerator results_enum = results.GetEnumerator();
                        for (int i = 0; i < random_index; i++) results_enum.MoveNext();
                        random = "" + results_enum.Current;
                    }
                    else random = "" + random_index;
                    output_template = do_conditional_replace(output_template, "random_id", random);
                }
                output_template = do_conditional_replace(output_template, "available_templates", template_list);
                op_return.AppendFormat("{0}", output_template);
            }

            return op_return;
        }
예제 #33
0
        public OpResult showHelp(OpResult or)
        {
            or.AppendFormat("photo-list [<Parameter List>] - lists all matching photos");
            or.AppendFormat("photo-play [<Parameter List>] - plays all matching photos");
            or.AppendFormat("photo-queue [<Parameter List>] - adds all match photos to the current slideshow");
            or.AppendFormat("photo-serv [ids:<indexlist>] [size-x:width] [size-y:height] [size-long:height] [size-short:height] [random] - serves (via http) the first/random image");
            or.AppendFormat("photo-tag-list [<Parameter List>] - lists all tags from all matching photos");
            or.AppendFormat("photo-stats [<Parameter List>]- lists 'stats' from the querry (filters, matches, etc)");
            or.AppendFormat("photo-clear-cache - forces the cache to reset (otherwise only resets when the number of photos changes)");
            or.AppendFormat(" ");
            or.AppendFormat("<Parameter List>: [ids:<indexlist>] [is-tagged:<taglist>] [not-tagged:<taglist>] [start-date:m-d-yyyy] [end-date:m-d-yyyy] [page-limit:x] [page-start:x] [template:name");
            or.AppendFormat("     [ids:<indexlist>] - lists / plays / queues the specified images");
            or.AppendFormat("          <indexlist> is a list of indexes (numbers) separated by commas (no spaces)");
            or.AppendFormat("          Note that specifying image indexes overrides all filters");
            or.AppendFormat("     [is-tagged:<taglist>] - filter images by included tags - limits results to images having all specified tags");
            or.AppendFormat("     [not-tagged:<taglist>] - filter images by excluded tags - limits results to images having none of the tags");
            or.AppendFormat("          <taglist> is a list of one or more tags that are used to filter images. Multiple tags should be separated ");
            or.AppendFormat("               with a ';' - no spaces allowed (use '_' in multi-word tags)");
            or.AppendFormat("     [start-date:m-d-yyyy] - filter images by date - limit results to images taken on or after the specified date");
            or.AppendFormat("     [end-date:m-d-yyyy] - filter images by date - limit results to images taken on or before the specified date");
            or.AppendFormat("     [page-limit:<x>] - where <x> is a number - Limits results to the first <x> images (photo-list only)");
            or.AppendFormat("     [page-start:<y>] - where <y> is a number - Results start with the <y> matching image (photo-list only)");
            or.AppendFormat("     [template:<name>] - where <name> is a custom template in the \"photo.template\" file");
            or.AppendFormat("     [size-x:<width>] - Resizes the served image, where <width> is the max width of the served image");
            or.AppendFormat("     [size-y:<height>] - Resizes the served image, where <height> is the max height of the served image");
            or.AppendFormat("     [size-short:<size_in_pix>] - Resizes the served image, where <size_in_pix> is the shorter side of the served image");
            or.AppendFormat("     [size-long:<size_in_pix>] - Resizes the served image, where <size_in_pix> is the max long size of the served image");
            or.AppendFormat("     [random] - (photo-serv only) serves a random image from the results (else serves the first image)");
            or.AppendFormat(" ");
            or.AppendFormat("Filter Notes:");
            or.AppendFormat("     - Multiple filters can be used");
            or.AppendFormat("     - The 'page-limit' and 'page-start' paramters can be used to page results");
            or.AppendFormat("     - The start-date and end-date filters are based on the 'DateTaken' value in the image's metadata");
            or.AppendFormat("     - If image ids are used all other filters are ignored!");
            or.AppendFormat(" ");
            or.AppendFormat("Resizeing Notes:");
            or.AppendFormat("     - Conflicting sizing can be specified, but only the most restrictive size (resulting in smallest image) ");
            or.AppendFormat("       will be used - the photo's ratio is preserved");
            or.AppendFormat(" ");
            or.AppendFormat("Custom Formatting Notes:");
            or.AppendFormat("     All custom formats must be defined in the \"photo.template\" file");
            or.AppendFormat("     The \"photo.template\" file must be manually coppied to the ehome directory (usually C:\\Windows\\ehome)");
            or.AppendFormat("     The \"photo.template\" file contains notes / examples on formatting");

            return or;
        }
예제 #34
0
 public OpResult showHelp(OpResult or)
 {
     or.AppendFormat("music-list-artists [~filters~] [~custom-template~] - lists all matching artists");
     or.AppendFormat("music-list-album-artists [~filters~] [~custom-template~] - lists all matching album artists - See WARNING");
     or.AppendFormat("music-list-songs [~filters~] [~custom-template~] - lists all matching songs");
     or.AppendFormat("music-list-albums [~filters~] [~custom-template~] - lists all matching albums");
     or.AppendFormat("music-list-genres [~filters~] [~custom-template~] - lists all matching genres");
     or.AppendFormat("music-list-playlists - lists all playlists");
     or.AppendFormat("music-list-playing [~index~] - lists songs in the current playlist or set playback to a specified song if index is supplied");
     or.AppendFormat("music-list-current - returns a key value pair list of current media similarly to mediametadata command");
     or.AppendFormat("music-delete-playlist [~filters~] [~index-list~] - deletes playlist specified by playlist_filter or, if indexes are supplied, only deletes items at indexes in the specified playlist");
     or.AppendFormat("music-play [~filters~] [~index-list~] - plays all matching songs");
     or.AppendFormat("music-queue [~filters~] [~index-list~] - queues all matching songs");
     or.AppendFormat("music-shuffle - sets playback mode to shuffle");
     or.AppendFormat("music-cover [~filters~] [~index-list~] [size-x:width] [size-y:height] - serves the cover image (first match)");
     or.AppendFormat(" ");
     or.AppendFormat("Where:");
     or.AppendFormat("     [~filters~] is one or more of: [~artist-filter~] [~album-filter~] [~genre-filter~] ");
     or.AppendFormat("     [~playlist-name~] is optional, can be an existing playlist to update, and must be combined with another filter below.");
     or.AppendFormat("     [~artist-filter~] is one of:");
     or.AppendFormat("          artist:<text> - matches track artists that start with <text> (\"artist:ab\" would match artists \"ABBA\" and \"ABC\")");
     or.AppendFormat("          artist:*<text> - matches track artists that have any words that start with <text> (\"artist:*ab\" would match \"ABBA\" and \"The Abstracts\")");
     or.AppendFormat("          exact-artist:<text> - matches the track artist that exactly matches <text> (\"exact-artist:ab\" would only match an artist names \"Ab\")");
     or.AppendFormat("     [~album-filter~] is one of:");
     or.AppendFormat("          album:<text> - matches albums that start with <text> (\"album:ab\" would match the album \"ABBA Gold\" and \"Abbey Road\")");
     or.AppendFormat("          exact-album:<text> - matches the album exactly named <text> (\"exact-album:ab\" would only match an album named \"Ab\")");
     or.AppendFormat("     [~genre-filter~] is one of:");
     or.AppendFormat("          genre:<text> - matches genre that start with <text> (\"genre:ja\" would match the genre \"Jazz\")");
     or.AppendFormat("          genre:*<text> - matches genres that contain <text> (\"genre:*rock\" would match \"Rock\" and \"Alternative Rock\")");
     or.AppendFormat("          exact-genre:<text> - matches the genere exactly named <text> (\"exact-genre:ja\" would only match an genre named \"Ja\")");
     or.AppendFormat("     [~playlist-filter~] is only:");
     or.AppendFormat("          exact-playlist:<text> - matches playlist exactly named <text>");
     or.AppendFormat("     [~song-filter~] is only:");
     or.AppendFormat("          exact-song:<text> - matches song exactly named <text>");
     or.AppendFormat("     [~index~] is of the form:");
     or.AppendFormat("          index:idx1 - specifies only one song in the current playlist by index");
     or.AppendFormat("     [~index-list~] is of the form:");
     or.AppendFormat("          indexes:idx1,idx2... - specifies one or more specific songs returned by the filter");
     or.AppendFormat("               Where idx1,idx2... is a comma separated list with no spaces (e.g. 'indexes:22,23,27')");
     or.AppendFormat("     [~custom-template~] is of the form:");
     or.AppendFormat("          template:<name> - specifies a custom template <name> defined in the \"music.template\" file");
     or.AppendFormat("     [size-x:~width~] - Resizes the served image, where ~width~ is the max width of the served image");
     or.AppendFormat("     [size-y:~height~] - Resizes the served image, where ~height~ is the max height of the served image");
     or.AppendFormat(" ");
     or.AppendFormat("Parameter Notes:");
     or.AppendFormat("     - Filter names containing two or more words must be enclosed in quotes.");
     or.AppendFormat("     - [~playlist-name~] must be combined with another filter and can be an existing playlist to update.");
     or.AppendFormat("     - [~song-filter~] can only be used with play and queue commands.");
     or.AppendFormat("     - Index numbers are just an index into the returned results and may change - they are not static!");
     or.AppendFormat("     - Both size-x and size-y must be > 0 or the original image will be returned without resizing.");
     or.AppendFormat(" ");
     or.AppendFormat(" ");
     or.AppendFormat("Examples:");
     or.AppendFormat("     music-list-artists - would return all artists in the music collection");
     or.AppendFormat("     music-list-album-artists - would return all album artists in the music collection");
     or.AppendFormat("          - WARNING: artists are filtered on the track level so this may be inconsistent");
     or.AppendFormat("     music-list-genres - would return all the genres in the music collection");
     or.AppendFormat("     music-list-artists artist:b - would return all artists in the music collection whose name starts with \"B\"");
     or.AppendFormat("     music-list-artists album:b - would return all artists in the music collection who have an album with a title that starts with \"B\"");
     or.AppendFormat("     music-list-albums artist:b - would return all albums by an artist whose name starts with \"B\"");
     or.AppendFormat("     music-list-albums artist:b album:*b - would return all albums that have a word starting with \"B\" by an artist whose name starts with \"B\"");
     or.AppendFormat("     music-list-albums genre:jazz - would return all the jazz albums");
     or.AppendFormat("     music-list-songs exact-artist:\"tom petty\" - would return all songs by \"Tom Petty\", but not songs by \"Tom Petty and the Heart Breakers \"");
     or.AppendFormat("     music-play exact-album:\"abbey road\" indexes:1,3 - would play the second and third songs (indexes are zero based) returned by the search for an album named \"Abbey Road\"");
     or.AppendFormat("     music-queue exact-artist:\"the who\" - would add all songs by \"The Who\" to the now playing list");
     return or;
 }
예제 #35
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();

            //try
            //{
            Match match = m_regex.Match(param);

            if (match.Success)
            {
                //try
                //{
                //msgResult = msg.Execute(msgboxcmd);
                //}
                //catch (Exception ex)
                //{
                //EventLog.WriteEntry("VmcController Client AddIn", "Error in Announce: " + ex.ToString());
                //}

                //EventLog.WriteEntry("VmcController Client AddIn", "Past msgboxrich");
                //AddInHost.Current.MediaCenterEnvironment.Dialog("Doing the playback", "", DialogButtons.Ok, 5, true);


                //first show the message box
                //MsgBoxRichCmd msg = new MsgBoxRichCmd();
                //string msgboxcmd = "\"" + match.Groups["caption"].Value + "\" \"" + match.Groups["message"].Value + "\" " + match.Groups["timeout"].Value + " \"" + match.Groups["buttoncodes"].Value + "\" \"" + match.Groups["modal"].Value + "\" \"" + match.Groups["imagepath"].Value + "\"";

                Messenger msg = new Messenger("\"" + match.Groups["caption"].Value + "\" \"" + match.Groups["message"].Value + "\" " + match.Groups["timeout"].Value + " \"" + match.Groups["buttoncodes"].Value + "\" \"" + match.Groups["modal"].Value + "\" \"" + match.Groups["imagepath"].Value + "\"");
                //EventLog.WriteEntry("VmcController Client AddIn", "Executing msgboxrich: " + msgboxcmd);

                //OpResult msgResult;

                //AddInHost.Current.MediaCenterEnvironment.Dialog("Playback state: " + isPlaying.ToString(), "", DialogButtons.Ok, 5, true);
                //then if not playing, speak the message

                Thread t = new Thread(new ThreadStart(msg.ShowMessage));
                if (isPlaying() == true)
                {
                    t.Start();
                }
                else
                {
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Not playing. Proceeding", "", DialogButtons.Ok, 5, true);

                    FileInfo fi;
                    if (match.Groups["ssmltospeak"].Value.Length > 1)
                    {
                        fi = MakeAudioFile(match.Groups["ssmltospeak"].Value);
                    }
                    else
                    {
                        //AddInHost.Current.MediaCenterEnvironment.Dialog("Making the audio file from the message", "", DialogButtons.Ok, 5, true);
                        fi = MakeAudioFile(match.Groups["message"].Value);
                    }


                    //long fileDurationInMS = (fi.Length / 352000) * 1000;  //much older code


                    //long fileDurationInMS = ((fi.Length / 44100) * 1000)-3000;  //current code
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Duration: " + fileDurationInMS.ToString(), "", DialogButtons.Ok, 3, true);

                    /*
                     * WMPLib.WindowsMediaPlayer Player = new WMPLib.WindowsMediaPlayer();
                     * Player.settings.autoStart = true;
                     * Player.URL = fi.FullName;
                     *
                     *
                     */



                    //show the message box
                    //msgResult = msg.Execute(msgboxcmd);

                    t.Start();
                    //ThreadPriority PreviousPriority = Thread.CurrentThread.Priority;
                    //Thread.CurrentThread.Priority = ThreadPriority.Highest;
                    WMPLib.WindowsMediaPlayer Player = new WMPLib.WindowsMediaPlayer();
                    Player.settings.playCount = 1;
                    Player.settings.setMode("loop", false);
                    Player.URL = fi.FullName;

                    //AddInHost.Current.MediaCenterEnvironment.PlayMedia(MediaType.Audio, fi.FullName, false);

                    //DateTime ExpectedEndTime = DateTime.Now.AddMilliseconds(fileDurationInMS);
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Now we're playing", "", DialogButtons.Ok, 5, true);
                    //AddInHost.Current.MediaCenterEnvironment.Dialog("Playstate: " + (AddInHost.Current.MediaCenterEnvironment.MediaExperience == null).ToString(), "", DialogButtons.Ok, 5, true);
                    //SendKeyCmd StopCmd = new SendKeyCmd('S', true, true, false);
                    //OpResult StopResult = null;

                    //while (AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Playing)

                    //wait for the required duration to elapse


                    //while (isPlaying() == true)
                    //{
                    //  if (DateTime.Compare(DateTime.Now,ExpectedEndTime) >= 0)
                    //{

                    //ensure it only plays once, regardless of shuffle/repeat state. Don't know why we have to keep sending the stop command
                    //probably something to do with timing
                    //while (AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.PlayState == PlayState.Playing)
                    //{
                    //StopResult = StopCmd.Execute("");

                    //System.Windows.Forms.Application.DoEvents(); //ensures that the stop command is responded to
                    //System.Threading.Thread.Sleep(100);
                    //}
                    //break;
                    // }

                    // System.Threading.Thread.Sleep(100);
                    //}
                    //Thread.CurrentThread.Priority = PreviousPriority;
                    fi.Delete();
                }

                //opResult.AppendFormat(msgResult.StatusText);
                opResult.AppendFormat("Ok");
                opResult.StatusCode = OpStatusCode.Ok;
            }

            //}
            //catch (Exception ex)
            //{
            //    EventLog.WriteEntry("VmcController Client AddIn", ex.ToString());
            //    opResult.StatusCode = OpStatusCode.Exception;
            //    opResult.StatusText = ex.Message;
            //}
            return(opResult);
        }
예제 #36
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            bool bTemplate = true;
            OpResult opResult = new OpResult();
            string page_file = "";
            string page = "";

            opResult.StatusCode = OpStatusCode.Ok;
            try
            {
                if (param.IndexOf("-help") >= 0)
                {
                    opResult = showHelp(opResult);
                    return opResult;
                }

                // Use custom format?
                if (!m_templates.ContainsKey(param))
                {
                    bTemplate = false;
                    page = "Error: Template '" + param + "' not found!\r\n All available templates:\r\n";
                    page += listTemplates();
                }
                else page_file = m_templates[param];
                if (page_file.Length > 0) page = loadTemplateFile(page_file);

                // Convert tags:
                if (bTemplate)
                {
                    Regex rTags = new Regex("%%(?<rex>.+?)%%");
                    Match match = rTags.Match(page);
                    while (match.Success)
                    {
                        string value = getRex(match.Groups["rex"].Value);
                        page = page.Replace("%%" + match.Groups["rex"].Value + "%%", value);
                        match = match.NextMatch();
                    }
                }

                opResult.AppendFormat("{0}", page);
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }
예제 #37
0
        public OpResult showHelp(OpResult or)
        {
            or.AppendFormat("Currently defined templates:\r\n" + listTemplates());
            or.AppendFormat("Custom Formatting Notes:");
            or.AppendFormat("     All custom formats must be defined in the \"custom.template\" file");
            or.AppendFormat("     The \"custom.template\" file must be manually coppied to the ehome directory (usually C:\\Windows\\ehome)");
            or.AppendFormat("     The \"custom.template\" file contains notes / examples on formatting");

            return or;
        }
예제 #38
0
        private OpResult list_recent(OpResult or, string template, int count)
        {
            ArrayList mrp_content = get_mrp(true);
            int result_count = mrp_content.Count;
            if (count > 0) result_count = (count < result_count) ? count : result_count;
            or.AppendFormat("{0}", basic_replacer(getTemplate(template + ".H", ""), "", "", result_count, -1)); // Header
            for (int j = 0; j < result_count; j++)
            {
                string list_item = (string)mrp_content[j];
                if (list_item.Length > 0)
                {
                    string s_out = "";
                    string[] values = list_item.Split('\t');
                    s_out = getTemplate(template + ".Entry", "%index%. %type%: %description% (%param%)");
                    s_out = basic_replacer(s_out, "full_type", values[0], result_count, j);
                    s_out = basic_replacer(s_out, "description", values[1], result_count, j);
                    s_out = basic_replacer(s_out, "param", values[2], result_count, j);
                    s_out = basic_replacer(s_out, "trackCount", values[3], result_count, j);
                    if (s_out.IndexOf("%title%") > 0)
                    {
                        string title = values[1];
                        if (title.IndexOf(":") > 0) title = title.Substring(title.LastIndexOf(":") + 1);
                        s_out = basic_replacer(s_out, "title", title, result_count, j);
                    }
                    if (s_out.IndexOf("%type%") > 0)
                    {
                        string type = values[0];
                        if (type.IndexOf("/") > 0) type = type.Substring(type.LastIndexOf("/") + 1);
                        s_out = basic_replacer(s_out, "type", type, result_count, j);
                    }

                    if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Entry
                }
            }
            or.AppendFormat("{0}", basic_replacer(getTemplate(template + ".F", "result_count=%resultCount%"), "", "", result_count, -1));

            return or;
        }
예제 #39
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            debug_last_action = "Execute: Start";

            DateTime startTime = DateTime.Now;

            OpResult opResult = new OpResult();
            opResult.StatusCode = OpStatusCode.Ok;

            bool bFirst = false;
            int size_x = 0;
            int size_y = 0;

            string template = "";
            string cache_fn = make_cache_fn(String.Format("{0}-{1}.txt", which_command, param));
            string cache_body = "";
            bool is_cached = false;

            try
            {
                if (param.IndexOf("-help") >= 0)
                {
                    opResult = showHelp(opResult);
                    return opResult;
                }
                //if (Player == null) Player = new WMPLib.WindowsMediaPlayer();

                WMPLib.IWMPMediaCollection2 collection = (WMPLib.IWMPMediaCollection2)Player.mediaCollection;
                int ver = Player.mediaCollection.getByAttribute("MediaType", "Audio").count;//.GetHashCode();
                string cache_ver = String.Format("{0}", ver);
                WMPLib.IWMPQuery query = collection.createQuery();
                WMPLib.IWMPPlaylist mediaPlaylist = null;
                WMPLib.IWMPMedia media_item;

                ArrayList a_idx = new ArrayList();

                bool b_query = false;

                string recent_text = "";
                string recent_text_type = "";

                debug_last_action = "Execution: Parsing params";

                request_params = HttpUtility.UrlEncode(param);

                if (param.Contains("exact-genre:"))
                {
                    string genre = param.Substring(param.IndexOf("exact-genre:") + "exact-genre:".Length);
                    genre = trim_parameter(genre);
                    query.addCondition("Genre", "Equals", genre);
                    genre_filter = genre;
                    recent_text = genre;
                    recent_text_type = "Genre";
                    b_query = true;
                }
                else if (param.Contains("genre:*"))
                {
                    string genre = param.Substring(param.IndexOf("genre:*") + "genre:*".Length);
                    genre = trim_parameter(genre);
                    query.addCondition("Genre", "BeginsWith", genre);
                    query.beginNextGroup();
                    query.addCondition("Genre", "Contains", " " + genre);
                    genre_filter = genre;
                    recent_text = genre;
                    recent_text_type = "Genre";
                    b_query = true;
                }
                else if (param.Contains("genre:"))
                {
                    string genre = param.Substring(param.IndexOf("genre:") + "genre:".Length);
                    genre = trim_parameter(genre);
                    query.addCondition("Genre", "BeginsWith", genre);
                    genre_filter = genre;
                    recent_text = genre;
                    recent_text_type = "Genre";
                    b_query = true;
                }

                if (param.Contains("exact-artist:"))
                {
                    string artist = param.Substring(param.IndexOf("exact-artist:") + "exact-artist:".Length);
                    artist = trim_parameter(artist);
                    query.addCondition("Artist", "Equals", artist);
                    artist_filter = artist;
                    if (recent_text.Length > 0)
                    {
                        recent_text += ": ";
                        recent_text_type += "/";
                    }
                    recent_text += artist;
                    recent_text_type += "Artist";
                    b_query = true;
                }
                else if (param.Contains("artist:*"))
                {
                    string artist = param.Substring(param.IndexOf("artist:*") + "artist:*".Length);
                    artist = trim_parameter(artist);
                    query.addCondition("Artist", "BeginsWith", artist);
                    query.beginNextGroup();
                    query.addCondition("Artist", "Contains", " " + artist);
                    artist_filter = artist;
                    if (recent_text.Length > 0)
                    {
                        recent_text += ": ";
                        recent_text_type += "/";
                    }
                    recent_text += artist;
                    recent_text_type += "Artist";
                    b_query = true;
                }
                else if (param.Contains("artist:"))
                {
                    string artist = param.Substring(param.IndexOf("artist:") + "artist:".Length);
                    artist = trim_parameter(artist);
                    query.addCondition("Artist", "BeginsWith", artist);
                    artist_filter = artist;
                    if (recent_text.Length > 0)
                    {
                        recent_text += ": ";
                        recent_text_type += "/";
                    }
                    recent_text += artist;
                    recent_text_type += "Artist";
                    b_query = true;
                }

                if (param.Contains("exact-album:"))
                {
                    string album = param.Substring(param.IndexOf("exact-album:") + "exact-album:".Length);
                    album = trim_parameter(album);
                    query.addCondition("WM/AlbumTitle", "Equals", album);
                    album_filter = album;
                    if (recent_text.Length > 0)
                    {
                        recent_text += ": ";
                        recent_text_type += "/";
                    }
                    recent_text += album;
                    recent_text_type += "Album";
                    b_query = true;
                }
                //else if (param.Contains("album:*"))
                //{
                //    string artist = param.Substring(param.IndexOf("album:*") + "album:*".Length);
                //    if (album.IndexOf(" ") >= 0) album = album.Substring(0, album.IndexOf(" "));
                //    query.addCondition("WM/AlbumTitle", "BeginsWith", album);
                //    query.beginNextGroup();
                //    query.addCondition("WM/AlbumTitle", "Contains", " " + album);
                //}
                else if (param.Contains("album:"))
                {
                    string album = param.Substring(param.IndexOf("album:") + "album:".Length);
                    album = trim_parameter(album);
                    query.addCondition("WM/AlbumTitle", "BeginsWith", album);
                    album_filter = album;
                    if (recent_text.Length > 0)
                    {
                        recent_text += ": ";
                        recent_text_type += "/";
                    }
                    recent_text += album;
                    recent_text_type += "Album";
                    b_query = true;
                }

                // Indexes specified?
                if (param.Contains("indexes:"))
                {
                    string indexes = param.Substring(param.IndexOf("indexes:") + "indexes:".Length);
                    if (indexes.IndexOf(" ") >= 0) indexes = indexes.Substring(0, indexes.IndexOf(" "));
                    string[] s_idx = indexes.Split(',');
                    foreach (string s in s_idx)
                    {
                        if (s.Length > 0) a_idx.Add(Int16.Parse(s));
                    }
                    if (recent_text.Length > 0)
                    {
                        recent_text += ": ";
                        recent_text_type += "/";
                    }
                    recent_text_type += "Tracks";
                    b_query = true;
                }
                if (!b_query) recent_text_type = recent_text = "All";

                // Cover size specified?
                if (param.Contains("size-x:"))
                {
                    string tmp_size = param.Substring(param.IndexOf("size-x:") + "size-x:".Length);
                    if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                    size_x = Convert.ToInt32(tmp_size);
                }
                if (param.Contains("size-y:"))
                {
                    string tmp_size = param.Substring(param.IndexOf("size-y:") + "size-y:".Length);
                    if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                    size_y = Convert.ToInt32(tmp_size);
                }
                // Use Custom Template?
                if (param.Contains("template:"))
                {
                    template = param.Substring(param.IndexOf("template:") + "template:".Length);
                    if (template.IndexOf(" ") >= 0) template = template.Substring(0, template.IndexOf(" "));
                }

                if (which_command == PLAY) bFirst = true;

                switch (which_command)
                {
                    case CLEAR_CACHE:
                        clear_cache();
                        return opResult;
                        break;
                    case LIST_GENRES:
                        cache_body = get_cached(cache_fn, cache_ver);
                        if (cache_body.Length == 0)
                        {
                            WMPLib.IWMPStringCollection genres = collection.getStringCollectionByQuery("Genre", query, "Audio", "Genre", true);
                            do_basic_list(opResult, genres, "genre", template, "genre=%genre%");
                            result_count = genres.count;
                        }
                        else
                        {
                            is_cached = true;
                            opResult.ContentText = cache_body;
                        }
                        break;
                    case LIST_ARTISTS:
                        cache_body = get_cached(cache_fn, cache_ver);
                        if (cache_body.Length == 0)
                        {
                            WMPLib.IWMPStringCollection artists = collection.getStringCollectionByQuery("Artist", query, "Audio", "Artist", true);
                            do_basic_list(opResult, artists, "artist", template, "artist=%artist%");
                            result_count = artists.count;
                        }
                        else
                        {
                            is_cached = true;
                            opResult.ContentText = cache_body;
                        }
                        break;
                    case LIST_ALBUM_ARTISTS:
                        cache_body = get_cached(cache_fn, cache_ver);
                        if (cache_body.Length == 0)
                        {
                            WMPLib.IWMPStringCollection artists = collection.getStringCollectionByQuery("WM/AlbumArtist", query, "Audio", "WM/AlbumArtist", true);
                            do_basic_list(opResult, artists, "artist", template, "album_artist=%artist%");
                            result_count = artists.count;
                        }
                        else
                        {
                            is_cached = true;
                            opResult.ContentText = cache_body;
                        }
                        break;
                    case LIST_ALBUMS:
                        cache_body = get_cached(cache_fn, cache_ver);
                        if (cache_body.Length == 0)
                        {
                            WMPLib.IWMPStringCollection albums = collection.getStringCollectionByQuery("WM/AlbumTitle", query, "Audio", "WM/AlbumTitle", true);
                            do_basic_list(opResult, albums, "album", template, "album=%album%");
                            result_count = albums.count;
                        }
                        else
                        {
                            is_cached = true;
                            opResult.ContentText = cache_body;
                        }
                        break;
                    case LIST_SONGS:
                        cache_body = get_cached(cache_fn, cache_ver);
                        if (cache_body.Length == 0)
                        {
                            WMPLib.IWMPStringCollection songs = collection.getStringCollectionByQuery("Title", query, "Audio", "Title", true);
                            do_basic_list(opResult, songs, "song", template, "index=%index%, song=%song%");
                            result_count = songs.count;
                        }
                        else
                        {
                            is_cached = true;
                            opResult.ContentText = cache_body;
                        }
                        break;
                    case LIST_RECENT:
                        if (param.Contains("count:"))
                        {
                            string scount = param.Substring(param.IndexOf("count:") + "count:".Length);
                            if (scount.IndexOf(" ") >= 0) scount = scount.Substring(0, scount.IndexOf(" "));
                            int count = Convert.ToInt32(scount);
                            list_recent(opResult, template, count);
                        }
                        else list_recent(opResult, template);
                        return opResult;
                        break;
                    case LIST_STATS:
                        cache_body = get_cached(cache_fn, cache_ver);
                        if (cache_body.Length == 0)
                        {
                            list_stats(opResult, template);
                        }
                        else
                        {
                            is_cached = true;
                            opResult.ContentText = cache_body;
                        }
                        break;
                    case LIST_DETAILS:
                    case PLAY:
                    case QUEUE:
                    case SERV_COVER:
                        if (which_command == LIST_DETAILS)
                        {
                            cache_body = get_cached(cache_fn, cache_ver);
                            if (cache_body.Length > 0)
                            {
                                is_cached = true;
                                opResult.ContentText = cache_body;
                                break;
                            }
                        }
                        if (which_command == SERV_COVER || which_command == LIST_DETAILS) the_state.init();

                        if (b_query) mediaPlaylist = collection.getPlaylistByQuery(query, "Audio", "Artist", true);
                        else mediaPlaylist = Player.mediaCollection.getByAttribute("MediaType", "Audio");

                        if (a_idx.Count > 0) result_count = a_idx.Count;
                        else result_count = mediaPlaylist.count;

                        // Header
                        opResult.AppendFormat("{0}", basic_replacer(getTemplate(template + ".H", ""), "", "", result_count, -1));

                        if (a_idx.Count > 0)
                        {
                            result_count = 0;
                            for (int j = 0; j < a_idx.Count; j++)
                            {
                                try { media_item = mediaPlaylist.get_Item((Int16)a_idx[j]); }
                                catch (Exception) { media_item = null; }
                                if (media_item != null)
                                {
                                    result_count++;
                                    if (which_command == LIST_DETAILS || which_command == SERV_COVER) // Display it
                                    {
                                        do_detailed_list(opResult, media_item, (Int16)a_idx[j], template);
                                        if (which_command == SERV_COVER)
                                        {
                                            photoCmd pc;
                                            pc = new photoCmd(photoCmd.SERV_PHOTO);
                                            if (the_state.albumImage.Length == 0)
                                                return pc.getPhoto(DEFAULT_IMAGE, "jpeg", size_x, size_y);
                                            else return pc.getPhoto(the_state.albumImage, "jpeg", size_x, size_y);
                                        }
                                    }
                                    else // Play / Queue it
                                    {
                                        recent_text += ((j == 0) ? "" : ", ") + (Int16)a_idx[j] + ". " + media_item.getItemInfo("Title");
                                        PlayMediaCmd pmc;
                                        pmc = new PlayMediaCmd(MediaType.Audio, !bFirst);
                                        bFirst = false;
                                        opResult = pmc.Execute(media_item.sourceURL);
                                    }
                                }
                            }
                        }
                        else
                        {
                            for (int j = 0; j < mediaPlaylist.count; j++)
                            {
                                media_item = mediaPlaylist.get_Item(j);
                                if (which_command == LIST_DETAILS || which_command == SERV_COVER) // Display it
                                {
                                    do_detailed_list(opResult, media_item, j, template);
                                    if (which_command == SERV_COVER)
                                    {
                                        photoCmd pc;
                                        pc = new photoCmd(photoCmd.SERV_PHOTO);
                                        if (the_state.albumImage.Length == 0)
                                            return pc.getPhoto(DEFAULT_IMAGE, "jpeg", size_x, size_y);
                                        else return pc.getPhoto(the_state.albumImage, "jpeg", size_x, size_y);
                                    }
                                }
                                else // Play / Queue it
                                {
                                    PlayMediaCmd pmc;
                                    pmc = new PlayMediaCmd(MediaType.Audio, !bFirst);
                                    bFirst = false;
                                    opResult = pmc.Execute(media_item.sourceURL);
                                }
                            }
                        }
                        if (which_command == LIST_DETAILS) do_detailed_list(opResult, null, -1, template);

                        if ((which_command == PLAY || which_command == QUEUE) && result_count > 0)
                        {
                            // Type, Artist, Album, Track, param, count
                            add_to_mrp(recent_text_type, recent_text, param, result_count); //Add to recent played list
                        }
                        break;
                }

                // Footer
                if (!is_cached)
                {
                    if (which_command != LIST_DETAILS) opResult.AppendFormat("{0}", basic_replacer(getTemplate(template + ".F", "result_count=%resultCount%"), "", "", result_count, -1));
                    else opResult.AppendFormat("{0}", replacer(getTemplate(template + ".F", "result_count=%index%"), result_count));
                    //opResult.AppendFormat("result_count={0}", result_count);
                    save_to_cache(cache_fn, opResult.ToString(), cache_ver);
                }
                string sub_footer = basic_replacer(getTemplate(template + ".C", "from_cache=%wasCached%\r\nellapsed_time=%ellapsedTime%"), "wasCached", is_cached.ToString(), -1, -1);
                TimeSpan duration = DateTime.Now - startTime;
                sub_footer = basic_replacer(sub_footer, "ellapsedTime", String.Format("{0}", duration.TotalSeconds), -1, -1);
                opResult.AppendFormat("{0}", sub_footer);
            }
            catch (Exception ex)
            {
                opResult = new OpResult();
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
                opResult.AppendFormat("{0}", debug_last_action);
                opResult.AppendFormat("{0}", ex.Message);
            }

            debug_last_action = "Execute: End";

            return opResult;
        }
예제 #40
0
        public OpResult clear_cache()
        {
            OpResult op_return = new OpResult(OpStatusCode.Ok);

            try { System.IO.Directory.Delete(CACHE_RESIZE_DIR, true); }
            catch (Exception ex)
            {
                op_return.StatusCode = OpStatusCode.Exception;
                op_return.StatusText = ex.Message;
                op_return.AppendFormat("Exception trying to delete cache directory: \"{0}\"", CACHE_RESIZE_DIR);
                op_return.AppendFormat("{0}", ex.Message);
            }
            try { System.IO.Directory.Delete(CACHE_QUERY_DIR, true); }
            catch (Exception ex)
            {
                op_return.StatusCode = OpStatusCode.Exception;
                op_return.StatusText = ex.Message;
                op_return.AppendFormat("Exception trying to delete cache directory: \"{0}\"", CACHE_QUERY_DIR);
                op_return.AppendFormat("{0}", ex.Message);
            }
            if (!in_generate_cache)
            {
                try { System.IO.Directory.Delete(CACHE_DIR, true); }
                catch (Exception ex)
                {
                    op_return.StatusCode = OpStatusCode.Exception;
                    op_return.StatusText = ex.Message;
                    op_return.AppendFormat("Exception trying to delete cache directory: \"{0}\"", CACHE_DIR);
                    op_return.AppendFormat("{0}", ex.Message);
                }
            }
            else
            {
                op_return.StatusCode = OpStatusCode.BadRequest;
                op_return.AppendFormat("ERROR: Cannot delete cache while generating cache!");
                if (keywords.ContainsKey(ELAPSED))
                    op_return.AppendFormat("Currently generating cache, last time this operation took {0} seconds.", keywords[ELAPSED][0]);
                else op_return.AppendFormat("Currently generating cache, First time generating - be patient.");
            }
            return op_return;
        }
예제 #41
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            OpResult opResult = new OpResult();
            bool     bFirst   = !queue;
            bool     bByIndex = false;
            int      idx      = 0;

            opResult.StatusCode = OpStatusCode.Ok;
            try
            {
                if (Player == null)
                {
                    Player = new WMPLib.WindowsMediaPlayer();
                }

                if (param.IndexOf("-help") >= 0)
                {
                    opResult = showHelp(opResult);
                    return(opResult);
                }

                DateTime startTime = DateTime.Now;

                // Use custom format?
                Match custom_match = custom_regex.Match(param);
                if (custom_match.Success)
                {
                    showWhat = System.Convert.ToInt32(custom_match.Groups["index"].Value, 10);
                    param    = custom_match.Groups["remainder"].Value;
                }

                Match match = index_regex.Match(param);
                if (match.Success)
                {
                    idx      = System.Convert.ToInt32(match.Groups["index"].Value, 10);
                    bByIndex = true;
                    param    = "";
                }
                else
                {
                    idx   = 0;
                    param = param.ToLower();
                }

                if (showWhat == 0)
                {
                    opResult = listArtistsOnly(opResult, param);
                    TimeSpan duration = DateTime.Now - startTime;
                    opResult.AppendFormat("elapsed_time={0}", duration.TotalSeconds);
                    return(opResult);
                }
                if (param.Length > 0)
                {
                    mediaPlaylist = byArtist(param);
                }
                else
                {
                    mediaPlaylist = Player.mediaCollection.getByAttribute("MediaType", "Audio");
                }

                bool bArtistMatch = false;
                the_state.init();

                int iCount = mediaPlaylist.count;

                string keyArtist = "";
                string keyAlbum  = "";

                // Header:
                templateOut(String.Format("{0}H", showWhat), opResult, 0, -1);

                for (int x = idx; x < iCount; x++)
                {
                    media = mediaPlaylist.get_Item(x);
                    the_state.nextArtist = media.getItemInfo("WM/AlbumArtist");
                    if (the_state.nextArtist == "")
                    {
                        the_state.nextArtist = media.getItemInfo("Author");
                    }
                    the_state.nextAlbum = media.getItemInfo("WM/AlbumTitle");
                    if (bByIndex && x == idx)
                    {
                        keyArtist = the_state.nextArtist;
                        keyAlbum  = the_state.nextAlbum;
                    }
                    else
                    {
                        if (showBy == by_track && keyArtist.Length > 0 && x != idx)
                        {
                            break;
                        }
                        if (showBy == by_artist && keyArtist.Length > 0 && the_state.nextArtist != keyArtist)
                        {
                            break;
                        }
                        if (showBy == by_album && keyArtist.Length > 0 && (the_state.nextAlbum != keyAlbum || the_state.nextArtist != keyArtist))
                        {
                            break;
                        }
                    }

                    if (the_state.nextArtist != the_state.artist) // New artist?
                    {
                        if (bArtistMatch)                         // Did last artist match?
                        {
                            // Close album:
                            if (the_state.album.Length > 0)
                            {
                                if (!templateOut(String.Format("{0}.{1}-", showWhat, show_albums), opResult, x, -1) && ((showWhat & show_albums) != 0) && the_state.albumTrackCount > 0)
                                {
                                    opResult.AppendFormat("    Album_song_count: {0}", the_state.albumTrackCount);
                                }
                            }
                            the_state.resetAlbum();
                            // Close artist"
                            if (!templateOut(String.Format("{0}.{1}-", showWhat, show_artists), opResult, x, -1))
                            {
                                if (the_state.artistAlbumCount > 0)
                                {
                                    opResult.AppendFormat("  Artist_album_count: {0}", the_state.artistAlbumCount);
                                }
                                if (the_state.artistTrackCount > 0)
                                {
                                    opResult.AppendFormat("  Artist_song_count: {0}", the_state.artistTrackCount);
                                }
                            }
                            the_state.resetArtist();
                        }
                        if (the_state.nextArtist.ToLower().StartsWith(param))
                        {
                            bArtistMatch           = true;
                            the_state.artistCount += 1;

                            the_state.artistIndex = x;

                            if (keyArtist.Length <= 0)
                            {
                                keyArtist = the_state.nextArtist;
                                keyAlbum  = the_state.nextAlbum;
                            }
                        }
                        else
                        {
                            bArtistMatch = false;
                        }
                        the_state.artist = the_state.nextArtist;
                        if (bArtistMatch)
                        {
                            // Open Artist
                            if (!templateOut(String.Format("{0}.{1}+", showWhat, show_artists), opResult, x, -1) && ((showWhat & show_artists) != 0))
                            {
                                opResult.AppendFormat("Artist:<{0}> \"{1}\"", x, the_state.artist);
                            }
                        }
                    }
                    if (bArtistMatch)
                    {
                        the_state.artistTrackCount += 1;
                        the_state.trackCount       += 1;
                        if (the_state.nextAlbum != the_state.album)
                        {
                            if (the_state.album.Length > 0)
                            {
                                // Close album
                                if (!templateOut(String.Format("{0}.{1}-", showWhat, show_albums), opResult, x, -1) && ((showWhat & show_albums) != 0) && the_state.albumTrackCount > 0)
                                {
                                    opResult.AppendFormat("    Album_song_count: {0}", the_state.albumTrackCount);
                                }
                            }
                            the_state.resetAlbum();
                            the_state.album = the_state.nextAlbum;
                            if (the_state.nextAlbum.Length > 0)
                            {
                                the_state.albumIndex        = x;
                                the_state.albumCount       += 1;
                                the_state.artistAlbumCount += 1;
                                the_state.albumList_add(the_state.nextAlbum);
                                the_state.albumYear  = media.getItemInfo("WM/Year");
                                the_state.albumGenre = media.getItemInfo("WM/Genre");
                                the_state.findAlbumCover(media.sourceURL);
                                // Open album
                                if (!templateOut(String.Format("{0}.{1}+", showWhat, show_albums), opResult, x, -1) && ((showWhat & show_albums) != 0))
                                {
                                    opResult.AppendFormat("  Album:<{0}> \"{1}\"", x, the_state.nextAlbum);
                                }
                            }
                        }
                        the_state.album            = the_state.nextAlbum;
                        the_state.albumTrackCount += 1;
                        the_state.song             = media.getItemInfo("Title");
                        the_state.songLocation     = media.sourceURL;
                        the_state.songTrackNumber  = media.getItemInfo("WM/TrackNumber");
                        the_state.songLength       = media.durationString;
                        if (the_state.albumYear == "" || the_state.albumYear.Length < 4)
                        {
                            the_state.albumYear = media.getItemInfo("WM/OriginalReleaseYear");
                        }
                        the_state.albumGenre_add(media.getItemInfo("WM/Genre"));
                        the_state.findAlbumCover(the_state.songLocation);

                        // Open / close song
                        if (!templateOut(String.Format("{0}.{1}-", showWhat, show_songs), opResult, x, -1) && ((showWhat & show_songs) != 0) && the_state.song.Length > 0)
                        {
                            opResult.AppendFormat("    Song:<{0}> \"{1}\" ({2})", x, the_state.song, the_state.songLength);
                        }
                        templateOut(String.Format("{0}.{1}+", showWhat, show_songs), opResult, x, -1);

                        // Play / queue song?
                        if (play)
                        {
                            PlayMediaCmd pmc;
                            pmc      = new PlayMediaCmd(MediaType.Audio, !bFirst);
                            bFirst   = false;
                            opResult = pmc.Execute(media.sourceURL);
                        }
                    }
                }
                if (play)
                {
                    opResult.AppendFormat("Queued {0} songs to play", the_state.trackCount);
                }
                else
                {
                    // Close album:
                    if (the_state.album.Length > 0)
                    {
                        if (!templateOut(String.Format("{0}.{1}-", showWhat, show_albums), opResult, the_state.trackCount, -1) && ((showWhat & show_albums) != 0) && the_state.albumTrackCount > 0)
                        {
                            opResult.AppendFormat("    Album_song_count: {0}", the_state.albumTrackCount);
                        }
                    }
                    the_state.resetAlbum();
                    // Close artist:
                    if (!templateOut(String.Format("{0}.{1}-", showWhat, show_artists), opResult, the_state.trackCount, -1))
                    {
                        if (the_state.artistAlbumCount > 0)
                        {
                            opResult.AppendFormat("  Artist_album_count: {0}", the_state.artistAlbumCount);
                        }
                        if (the_state.artistTrackCount > 0)
                        {
                            opResult.AppendFormat("  Artist_song_count: {0}", the_state.artistTrackCount);
                        }
                    }
                    the_state.resetArtist();
                }
                // Footer:
                TimeSpan elapsed_duration = DateTime.Now - startTime;
                if (!templateOut(String.Format("{0}F", showWhat), opResult, the_state.trackCount, elapsed_duration.TotalSeconds))
                {
                    if (the_state.artistCount > 0)
                    {
                        opResult.AppendFormat("Artist_count: {0}", the_state.artistCount);
                    }
                    if (the_state.albumCount > 0)
                    {
                        opResult.AppendFormat("Album_count: {0}", the_state.albumCount);
                    }
                    if (the_state.trackCount > 0)
                    {
                        opResult.AppendFormat("Song_count: {0}", the_state.trackCount);
                    }
                    opResult.AppendFormat("elapsed_time={0}", elapsed_duration.TotalSeconds);
                }
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
예제 #42
0
        public OpResult clear_slide_show()
        {
            OpResult op_return = new OpResult(OpStatusCode.Ok);

            if (!in_generate_slideshow)
            {
                try { System.IO.Directory.Delete(SLIDE_SHOW_DIR, true); }
                catch (Exception ex)
                {
                    op_return.StatusCode = OpStatusCode.Exception;
                    op_return.StatusText = ex.Message;
                    op_return.AppendFormat("Exception trying to delete slide show directory: \"{0}\"", SLIDE_SHOW_DIR);
                    op_return.AppendFormat("{0}", ex.Message);
                }
            }
            else
            {
                op_return.StatusCode = OpStatusCode.BadRequest;
                op_return.AppendFormat("ERROR: Cannot delete slide shoe while generating slide show!");
            }
            return op_return;
        }
예제 #43
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            reset_globals();

            debug_last_action = "Execute: Start";

            HashSet<int> results = new HashSet<int>();

            DateTime startTime = DateTime.Now;

            OpResult opResult = new OpResult();
            opResult.StatusCode = OpStatusCode.Ok;

            string template = "";

            page_limit = 0xFFFF;
            page_start = 0;

            bool bFilter = false;
            string clean_filter_params = "";
            string clean_paging_params = "";

            try
            {
                if (param.IndexOf("-help") >= 0)
                {
                    opResult = showHelp(opResult);
                    return opResult;
                }
                if (action == CLEAR_CACHE)
                {
                    opResult = clear_cache();
                    launch_generate_tags_list();
                    return opResult;
                }
                if (Player == null) Player = new WMPLib.WindowsMediaPlayer();
                photo_media_play_list = Player.mediaCollection.getByAttribute("MediaType", "Photo");

                debug_last_action = "Execution: Parsing params";
                // "Paging"?
                if (param.Contains("page-limit:"))
                {
                    page_limit = parse_int(param.Substring(param.IndexOf("page-limit:") + "page-limit:".Length));
                    clean_paging_params += "page-limit:" + page_limit + " ";
                }
                if (param.Contains("page-start:"))
                {
                    page_start = parse_int(param.Substring(param.IndexOf("page-start:") + "page-start:".Length));
                    clean_paging_params += "page-start:" + page_start + " ";
                }

                // Use Custom Template?
                if (param.Contains("template:"))
                {
                    template = param.Substring(param.IndexOf("template:") + "template:".Length);
                    if (template.IndexOf(" ") >= 0) template = template.Substring(0, template.IndexOf(" "));
                    clean_paging_params += "template:" + template + " ";
                }

                // Check if any filters are used
                if (param.Contains("is-tagged:"))
                {
                    bFilter = true;
                    string tag_string = param.Substring(param.IndexOf("is-tagged:") + "is-tagged:".Length);
                    if (tag_string.IndexOf(" ") >= 0) tag_string = tag_string.Substring(0, tag_string.IndexOf(" "));
                    List<string> tag_list = new List<string>(tag_string.Split(';'));
                    tag_list.Sort();
                    clean_filter_params += "is-tagged:" + String.Join(";", tag_list.ToArray()) + " ";
                }
                if (param.Contains("not-tagged:"))
                {
                    bFilter = true;
                    string tag_string = param.Substring(param.IndexOf("not-tagged:") + "not-tagged:".Length);
                    if (tag_string.IndexOf(" ") >= 0) tag_string = tag_string.Substring(0, tag_string.IndexOf(" "));
                    List<string> tag_list = new List<string>(tag_string.Split(';'));
                    tag_list.Sort();
                    clean_filter_params += "not-tagged:" + String.Join(";", tag_list.ToArray()) + " ";
                }
                if (param.Contains("start-date:"))
                {
                    bFilter = true;
                    string date_string = param.Substring(param.IndexOf("start-date:") + "start-date:".Length);
                    DateTime date;
                    if (date_string.IndexOf(" ") >= 0) date_string = date_string.Substring(0, date_string.IndexOf(" "));
                    string[] date_elements = date_string.Split('-');
                    if (date_elements.Length >= 3)
                    {
                        date = new DateTime(Int32.Parse(date_elements[2]),
                            Int32.Parse(date_elements[0]), Int32.Parse(date_elements[1]));
                        date_string = date.ToShortDateString();
                        date_string = date_string.Replace("/", "-");
                        clean_filter_params += "start-date:" + date_string + " ";
                    }
                }
                if (param.Contains("end-date:"))
                {
                    bFilter = true;
                    string date_string = param.Substring(param.IndexOf("end-date:") + "end-date:".Length);
                    DateTime date;
                    if (date_string.IndexOf(" ") >= 0) date_string = date_string.Substring(0, date_string.IndexOf(" "));
                    string[] date_elements = date_string.Split('-');
                    if (date_elements.Length >= 3)
                    {
                        date = new DateTime(Int32.Parse(date_elements[2]),
                            Int32.Parse(date_elements[0]), Int32.Parse(date_elements[1]));
                        date_string = date.ToShortDateString();
                        date_string = date_string.Replace("/", "-");
                        clean_filter_params += "end-date:" + date_string + " ";
                    }
                }

                // Results specified? OVERRIDES OTHER FILTERS!
                if (param.Contains("ids:"))
                {
                    results = parse_ids(param.Substring(param.IndexOf("ids:") + "ids:".Length));
                    clean_filter_params = "ids:" + results.GetHashCode();
                }

                // Validate caches:
                validate_cache();
                // look for page cache - use filter + paging params, return if found
                if (action != PLAY_PHOTOS && action != QUEUE_PHOTOS && action != SERV_PHOTO && action != SHOW_STATS) //Check cache
                {
                    try
                    {
                        OpResult or = new OpResult();
                        or.StatusCode = OpStatusCode.Ok;
                        or = deserialize_rendered_page(or, action + "_" + clean_filter_params + clean_paging_params);
                        if (or != null) return or;
                    }
                    catch (Exception) { ; }
                }

                switch (action)
                {
                    case SHOW_STATS:
                    case LIST_TAGS:
                        //int pic_count = photo_media_play_list.count;
                        if (bFilter)    // Generate subset of tags based on images
                        {
                            if (results.Count == 0) results = get_list(results, clean_filter_params);
                            //pic_count = results.Count;
                            opResult = list_tags(opResult, template, generate_filtered_tags_list(results));
                        }
                        else            // Full set of tags
                            opResult = list_tags(opResult, template);
                        if (action == SHOW_STATS) opResult = show_stats(template, results);
                        break;
                    case LIST_PHOTOS:
                    case PLAY_PHOTOS:
                    case QUEUE_PHOTOS:
                    case SERV_PHOTO:
                        if (results.Count == 0)
                        {
                            results = get_list(results, clean_filter_params);
                        }

                        // Output results
                        if (action == SERV_PHOTO)
                        {
                            int size_x = 0;
                            int size_y = 0;
                            int size_short = 0;
                            int size_long = 0;

                            debug_last_action = "Execute: Serv Start";
                            if (param.Contains("size-x:"))
                            {
                                string tmp_size = param.Substring(param.IndexOf("size-x:") + "size-x:".Length);
                                if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                                size_x = Convert.ToInt32(tmp_size);
                            }
                            if (param.Contains("size-y:"))
                            {
                                string tmp_size = param.Substring(param.IndexOf("size-y:") + "size-y:".Length);
                                if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                                size_y = Convert.ToInt32(tmp_size);
                            }
                            if (param.Contains("size-short:"))
                            {
                                string tmp_size = param.Substring(param.IndexOf("size-short:") + "size-short:".Length);
                                if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                                size_short = Convert.ToInt32(tmp_size);
                            }
                            if (param.Contains("size-long:"))
                            {
                                string tmp_size = param.Substring(param.IndexOf("size-long:") + "size-long:".Length);
                                if (tmp_size.IndexOf(" ") >= 0) tmp_size = tmp_size.Substring(0, tmp_size.IndexOf(" "));
                                size_long = Convert.ToInt32(tmp_size);
                            }
                            // Return one photo (may be only one)
                            int random_index = -1;
                            int image_index = 0;
                            if (param.Contains("random")) random_index = new Random().Next(results.Count);
                            int result_count = 0;
                            foreach (int i in results)
                            {
                                if (random_index < 0 && result_count >= page_start && result_count < page_start + page_limit)
                                {
                                    image_index = i;
                                    break;
                                }
                                else if (random_index >= 0 && random_index <= result_count)
                                {
                                    image_index = i;
                                    break;
                                }
                                result_count++;
                            }
                            last_img_served = image_index;
                            opResult = getPhoto(photo_media_play_list.get_Item(image_index), size_x, size_y, size_short, size_long);
                            debug_last_action = "Execute: Serv End";
                        }
                        else
                        {
                            string template_result = (action == LIST_PHOTOS) ? getTemplate(template, DEFAULT_RESULT) : getTemplate(template, DEFAULT_PLAY_RESULT);
                            template_result = file_includer(template_result);

                            debug_last_action = "Execute: List: Header";
                            string s_head = (action == LIST_PHOTOS) ? getTemplate(template + "+", DEFAULT_HEAD):getTemplate(template + "+", DEFAULT_PLAY_HEAD);
                            s_head = file_includer(s_head);
                            s_head = do_conditional_replace(s_head, "results_count", String.Format("{0}", results.Count));
                            opResult.AppendFormat("{0}", s_head);

                            debug_last_action = "Execute: List: Items";

                            if (action == PLAY_PHOTOS)
                            {
                                clear_slide_show();
                            }

                            int result_count = 0;
                            string in_file = "";
                            string out_file = "";
                            foreach (int i in results)
                            {
                                if (action == PLAY_PHOTOS || action == QUEUE_PHOTOS)
                                {
                                    //Create dir if needed:
                                    if (!Directory.Exists(SLIDE_SHOW_DIR)) create_dirs();
                                    // Add photo to slideshow directory
                                    in_file = photo_media_play_list.get_Item(i).getItemInfo("SourceURL");
                                    out_file = SLIDE_SHOW_DIR + "\\" + make_cache_fn(in_file, 100);
                                    File.Copy(in_file, out_file, true);
                                }
                                else if (result_count >= page_start && result_count < page_start + page_limit)
                                {
                                    string s = "";
                                    s = replacer(template_result, photo_media_play_list.get_Item(i), i);
                                    opResult.AppendFormat("{0}", s);
                                }
                                result_count++;
                            }
                            if (action == PLAY_PHOTOS || action == QUEUE_PHOTOS)
                            {
                                // Start playing:
                                Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.NavigateToPage(Microsoft.MediaCenter.PageId.Slideshow, SLIDE_SHOW_DIR);
                                //Old: Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.NavigateToPage(Microsoft.MediaCenter.PageId.MyPictures, SLIDE_SHOW_DIR);
                            }
                            debug_last_action = "Execute: List: Footer";
                            TimeSpan duration = DateTime.Now - startTime;
                            string s_foot = (action == LIST_PHOTOS) ? getTemplate(template + "-", DEFAULT_FOOT):getTemplate(template + "-", DEFAULT_PLAY_FOOT);
                            s_foot = file_includer(s_foot);
                            s_foot = do_conditional_replace(s_foot, "elapsed_time", String.Format("{0}", duration.TotalSeconds));
                            s_foot = do_conditional_replace(s_foot, "results_count", String.Format("{0}", results.Count));
                            opResult.AppendFormat("{0}", s_foot);
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                opResult = new OpResult();
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
                opResult.AppendFormat("{0}", debug_last_action);
                opResult.AppendFormat("{0}", ex.Message);
            }

            if (action == LIST_TAGS)
            {
                debug_last_action = "Execute: List: Footer";
                TimeSpan duration = DateTime.Now - startTime;
                string s_foot = getTemplate(template + "-", DEFAULT_REPORT_FOOT);
                s_foot = file_includer(s_foot);
                s_foot = do_conditional_replace(s_foot, "elapsed_time", String.Format("{0}", duration.TotalSeconds));
                s_foot = do_conditional_replace(s_foot, "results_count", String.Format("{0}", kw_count));
                s_foot = do_conditional_replace(s_foot, "first_date", String.Format("{0}", first_date.ToShortDateString()));
                s_foot = do_conditional_replace(s_foot, "last_date", String.Format("{0}", last_date.ToShortDateString()));
                opResult.AppendFormat("{0}", s_foot);
            }

            // save page to cache - use filter + paging params
            // TODO: elapsed time is incorrectly cached! Add is_cached to custom templates
            if (opResult.StatusCode == OpStatusCode.Ok &&
                action != PLAY_PHOTOS && action != QUEUE_PHOTOS && action != SERV_PHOTO && action != SHOW_STATS) // Save cache
            {
                debug_last_action = "Execute: Saving page to cache";
                try { serialize_rendered_page(opResult, action + "_" + clean_filter_params + clean_paging_params); }
                catch (Exception e) { debug_last_action = "Execute: Save to Cache failed: " + e.Message; }
            }

            debug_last_action = "Execute: End";

            return opResult;
        }
예제 #44
0
        private OpResult list_stats(OpResult or, string template)
        {
            or.AppendFormat("{0}", basic_replacer(getTemplate(template + ".H", ""), "", "", 0, -1)); // Header

            string s_out = getTemplate(template + ".Entry", DEFAULT_STATS);
            s_out = basic_replacer(s_out, "track_count",
                    String.Format("{0}", Player.mediaCollection.getByAttribute("MediaType", "Audio").count), 0, -1);

            WMPLib.IWMPMediaCollection2 collection = (WMPLib.IWMPMediaCollection2)Player.mediaCollection;
            WMPLib.IWMPQuery stats_query = collection.createQuery();

            s_out = basic_replacer(s_out, "artist_count",
                    String.Format("{0}", collection.getStringCollectionByQuery("Artist", stats_query, "Audio", "Artist", true).count), 0, -1);
            s_out = basic_replacer(s_out, "album_count",
                    String.Format("{0}", collection.getStringCollectionByQuery("WM/AlbumTitle", stats_query, "Audio", "WM/AlbumTitle", true).count), 0, -1);
            s_out = basic_replacer(s_out, "genre_count",
                    String.Format("{0}", collection.getStringCollectionByQuery("Genre", stats_query, "Audio", "Genre", true).count), 0, -1);

            if (s_out.IndexOf("%cache_age%") >= 0)
            {
                string cache_age = "No cache";
                try
                {
                    cache_age = System.IO.File.GetCreationTime(CACHE_VER_FILE).ToString();
                }
                catch (Exception) { ; }
                s_out = basic_replacer(s_out, "cache_age", cache_age, 0, -1);
            }

            if (s_out.IndexOf("%available_templates%") >= 0)
            {
                string template_list = "";
                foreach (KeyValuePair<string, string> t in m_templates)
                {
                    if (t.Key.EndsWith(".Entry"))
                    {
                        if (template_list.Length > 0) template_list += ", ";
                        template_list += t.Key.Substring(0, t.Key.Length - ".Entry".Length);
                    }
                }
                s_out = basic_replacer(s_out, "available_templates", template_list, 0, -1);
            }
            if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Entry

            or.AppendFormat("{0}", basic_replacer(getTemplate(template + ".F", ""), "", "", 0, -1)); // Footer

            return or;
        }
예제 #45
0
        public OpResult launch_generate_tags_list()
        {
            OpResult op_return = new OpResult(OpStatusCode.Ok);

            if (in_generate_cache)
            {
                if (keywords.ContainsKey(ELAPSED))
                    op_return.AppendFormat("Already generating cache, last time this operation took {0} seconds.", keywords[ELAPSED][0]);
                else op_return.AppendFormat("Already generating cache, First time generating - be patient.");
                return op_return;
            }
            else
            {
                tag_thread = new Thread(new ThreadStart(generate_tags_list));
                if (keywords != null && keywords.ContainsKey(ELAPSED))
                    op_return.AppendFormat("Generating cache, last time this operation took {0} seconds.", keywords[ELAPSED][0]);
                else
                {
                    keywords = new Dictionary<string, List<int>>();
                    string tmp_keyword = KEYWORD + "--Please_be_patient_generating_tags_list--";
                        keywords.Add(tmp_keyword, new List<int>());
                    op_return.AppendFormat("Generating cache, First time generating - be patient.");
                }
                tag_thread.Start();
            }

            return op_return;
        }
예제 #46
0
        public OpResult showHelp(OpResult or)
        {
            or.AppendFormat("music-list-artists [~filters~] [~custom-template~] - lists all matching artists");
            or.AppendFormat("music-list-album-artists [~filters~] [~custom-template~] - lists all matching album artists - See WARNING");
            or.AppendFormat("music-list-songs [~filters~] [~custom-template~] - lists all matching songs");
            or.AppendFormat("music-list-albums [~filters~] [~custom-template~] - lists all matching albums");
            or.AppendFormat("music-list-genres [~filters~] [~custom-template~] - lists all matching genres");
            or.AppendFormat("music-play [~filters~] [~index-list~] - plays all matching songs");
            or.AppendFormat("music-queue [~filters~] [~index-list~] - queues all matching songs");
            or.AppendFormat("music-cover [~filters~] [~index-list~] [size-x:width] [size-y:height] - serves the cover image (first match)");
            or.AppendFormat(" ");
            or.AppendFormat("Where:");
            or.AppendFormat("     [~filters~] is one or more of: [~artist-filter~] [~album-filter~] [~genre-filter~] ");
            or.AppendFormat("     [~artist-filter~] is one of:");
            or.AppendFormat("          artist:<text> - matches track artists that start with <text> (\"artist:ab\" would match artists \"ABBA\" and \"ABC\")");
            or.AppendFormat("          artist:*<text> - matches track artists that have any words that start with <text> (\"artist:*ab\" would match \"ABBA\" and \"The Abstracts\")");
            or.AppendFormat("          exact-artist:<text> - matches the track artist that exactly matches <text> (\"exact-artist:ab\" would only match an artist names \"Ab\")");
            or.AppendFormat("     [~album-filter~] is one of:");
            or.AppendFormat("          album:<text> - matches albums that start with <text> (\"album:ab\" would match the album \"ABBA Gold\" and \"Abbey Road\")");
            or.AppendFormat("          exact_album:<text> - matches the album exactly named <text> (\"exact_album:ab\" would only match an album named \"Ab\")");
            or.AppendFormat("     [~genre-filter~] is one of:");
            or.AppendFormat("          genre:<text> - matches genre that start with <text> (\"genre:ja\" would match the genre \"Jazz\")");
            or.AppendFormat("          genre:*<text> - matches genres that contain <text> (\"genre:*rock\" would match \"Rock\" and \"Alternative Rock\")");
            or.AppendFormat("          exact_genre:<text> - matches the genere exactly named <text> (\"exact_genre:ja\" would only match an genre named \"Ja\")");
            or.AppendFormat("     [~index-list~] is of the form:");
            or.AppendFormat("          indexes:idx1,idx2... - specifies one or more specific songs returned by the filter");
            or.AppendFormat("               Where idx1,idx2... is a comma separated list with no spaces (e.g. 'indexes:22,23,27')");
            or.AppendFormat("     [~custom-template~] is of the form:");
            or.AppendFormat("          template:<name> - specifies a custom template <name> defined in the \"music.template\" file");
            or.AppendFormat("     [size-x:~width~] - Resizes the served image, where ~width~ is the max width of the served image");
            or.AppendFormat("     [size-y:~height~] - Resizes the served image, where ~height~ is the max height of the served image");
            or.AppendFormat(" ");
            or.AppendFormat("Parameter Notes:");
            or.AppendFormat("     - Index numbers are just an index into the returned results and may change - they are not static!");
            or.AppendFormat("     - Both size-x and size-y must be > 0 or the original image will be returned without resizing.");
            or.AppendFormat(" ");
            or.AppendFormat(" ");
            or.AppendFormat("Examples:");
            or.AppendFormat("     music-list-artists - would return all artists in the music collection");
            or.AppendFormat("     music-list-album-artists - would return all album artists in the music collection");
            or.AppendFormat("          - WARNING: artists are filtered on the track level so this may be inconsistent");
            or.AppendFormat("     music-list-genres - would return all the genres in the music collection");
            or.AppendFormat("     music-list-artists artist:b - would return all artists in the music collection whose name starts with \"B\"");
            or.AppendFormat("     music-list-artists album:b - would return all artists in the music collection who have an album with a title that starts with \"B\"");
            or.AppendFormat("     music-list-albums artist:b - would return all albums by an artist whose name starts with \"B\"");
            or.AppendFormat("     music-list-albums artist:b album:*b - would return all albums that have a word starting with \"B\" by an artist whose name starts with \"B\"");
            or.AppendFormat("     music-list-albums genre:jazz - would return all the jazz albums");
            or.AppendFormat("     music-list-songs exact-artist:\"tom petty\" - would return all songs by \"Tom Petty\", but not songs by \"Tom Petty and the Heart Breakers \"");
            or.AppendFormat("     music-play exact_album:\"abbey road\" indexes:1,3 - would play the second and third songs (indexes are zero based) returned by the search for an album named \"Abbey Road\"");
            or.AppendFormat("     music-queue exact-artist:\"the who\" - would add all songs by \"The Who\" to the now playing list");

            return or;
        }
예제 #47
0
        public OpResult list_tags(OpResult opResult, string template, Dictionary<string, List<int>> kw_dic)
        {
            debug_last_action = "List tags: Start";
            //Sort keywords:
            List<string> keyword_list = new List<string>(kw_dic.Keys);
            keyword_list.Sort();
            kw_count = 0;
            string output_template = getTemplate(template, DEFAULT_REPORT_RESULT);
            output_template = file_includer(output_template);

            DateTime tmp_date = new DateTime();

            // Header (note no substitutions)
            string s_head = getTemplate(template + "+", DEFAULT_REPORT_HEAD);
            s_head = file_includer(s_head);
            opResult.AppendFormat("{0}", s_head);

            foreach (string s in keyword_list)
            {
                if (s.StartsWith(KEYWORD))
                {
                    string kw = s.Substring(KEYWORD.Length);
                    string s_out = do_conditional_replace(output_template, "tag_count", String.Format("{0}", kw_dic[s].Count));
                    s_out = do_conditional_replace(s_out, "tag", kw);
                    opResult.AppendFormat("{0}", s_out);
                    kw_count++;
                }
                else if (s.StartsWith(DATE))
                {
                    string date = s.Substring(DATE.Length);
                    string[] date_elements = date.Split('-');
                    if (date_elements.Length >= 3) tmp_date = new DateTime(Int32.Parse(date_elements[2]),
                            Int32.Parse(date_elements[0]), Int32.Parse(date_elements[1]));
                    if (tmp_date < first_date) first_date = tmp_date;
                    if (tmp_date > last_date) last_date = tmp_date;
                }
            }
            debug_last_action = "List tags: Finished foreach loop";

            debug_last_action = "List tags: Done";

            return opResult;
        }
예제 #48
0
        private OpResult do_detailed_list(OpResult or, WMPLib.IWMPMedia media_item, int idx, string template)
        {
            string artist = "";
            string album = "";
            string letter = "";
            bool added = false;

            int index = idx;
            if (index < 0)
                index = the_state.trackCount;

            if (media_item != null)
            {
                artist = media_item.getItemInfo("WM/AlbumArtist");
                if (artist == "") artist = media_item.getItemInfo("Author");
                album = media_item.getItemInfo("WM/AlbumTitle");
                letter = first_letter(artist);
            }

            // End of artist?
            if (artist != the_state.artist)
            {
                if (the_state.album.Length > 0)
                {
                    var s_out = replacer(getTemplate(template + ".Album-", DEFAULT_DETAIL_ALBUM_END), index);
                    if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                }
                if (the_state.artist.Length > 0)
                {
                    var s_out = replacer(getTemplate(template + ".Artist-", DEFAULT_DETAIL_ARTIST_END), index);
                    if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                }
                // End of current aplha?
                if (letter != the_state.letter && the_state.letter.Length == 1)
                {
                    var s_out = replacer(getTemplate(template + ".Alpha-", ""), index);
                    if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                }

                if (index >= 0)
                {
                    the_state.resetArtist(artist);
                    the_state.resetAlbum(album);
                }

                if (media_item != null)
                {
                    the_state.add_song_to_album(media_item);
                    added = true;
                    // Start new aplha?
                    if (letter != the_state.letter)
                    {
                        the_state.letter = letter;
                        var s_out = replacer(getTemplate(template + ".Alpha+", ""), index);
                        if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                    }
                    // Start new artist
                    if (the_state.artist.Length > 0)
                    {
                        var s_out = replacer(getTemplate(template + ".Artist+", DEFAULT_DETAIL_ARTIST_START), index);
                        if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                    }
                    // Start new album
                    if (the_state.album.Length > 0)
                    {
                        var s_out = replacer(getTemplate(template + ".Album+", DEFAULT_DETAIL_ALBUM_START), index);
                        if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                    }
                }
            }
            // End of album?
            else if (album != the_state.album)
            {
                if (the_state.album.Length > 0)
                {
                    var s_out = replacer(getTemplate(template + ".Album-", DEFAULT_DETAIL_ALBUM_END), index);
                    if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                }
                if (index >= 0) the_state.resetAlbum(album);
                if (media_item != null)
                {
                    the_state.add_song_to_album(media_item);
                    added = true;
                    if (the_state.album.Length > 0)
                    {
                        var s_out = replacer(getTemplate(template + ".Album+", DEFAULT_DETAIL_ALBUM_START), index);
                        if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
                    }
                }
            }

            // Do track:
            if (media_item != null)
            {
                if (!added) the_state.add_song_to_album(media_item);
                var s_out = replacer(getTemplate(template + ".Entry", DEFAULT_DETAIL_SONG), index);
                if (s_out.Length > 0) or.AppendFormat("{0}", s_out);
            }

            return or;
        }
예제 #49
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult Execute(string param)
        {
            List<ScheduleEvent> events;
            StringBuilder sb = new StringBuilder();
            OpResult opResult = new OpResult();

            if (m_eventSchedule == null)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = m_exception;
                return opResult;
            }

            try
            {
                if (param.Equals("recorded", StringComparison.InvariantCultureIgnoreCase))
                    events = m_eventSchedule.GetScheduleEvents(DateTime.MinValue, DateTime.MaxValue, ScheduleEventStates.HasOccurred) as List<ScheduleEvent>;
                else if (param.Equals("recording", StringComparison.InvariantCultureIgnoreCase))
                    events = m_eventSchedule.GetScheduleEvents(DateTime.MinValue, DateTime.MaxValue, ScheduleEventStates.IsOccurring) as List<ScheduleEvent>;
                else if (param.Equals("scheduled", StringComparison.InvariantCultureIgnoreCase))
                    events = m_eventSchedule.GetScheduleEvents(DateTime.Now, DateTime.Now.AddDays(7), ScheduleEventStates.WillOccur) as List<ScheduleEvent>;
                else
                {
                    opResult.StatusCode = OpStatusCode.BadRequest;
                    return opResult;
                }

                events.Sort(CompareScheduleEvents);
                foreach (ScheduleEvent item in events)
                {
                    opResult.AppendFormat("{0}={1} ({2}-{3})",
                        item.Id, item.GetExtendedProperty("Title"),
                        item.StartTime.ToLocalTime().ToString("g"),
                        item.EndTime.ToLocalTime().ToShortTimeString()
                        );
                }
                opResult.StatusCode = OpStatusCode.Ok;
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return opResult;
        }