public void MediaUrlInitsWithNoArgs()
        {
            var mediaUrl = new MediaUrl();

            Assert.NotNull(mediaUrl);
            Assert.IsType <MediaUrl>(mediaUrl);
        }
Example #2
0
        /// <summary>
        /// Adds the trailer URL.
        /// </summary>
        public static void AddTrailerUrl(this BaseItem item, string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            var current = item.RemoteTrailers.FirstOrDefault(i => string.Equals(i.Url, url, StringComparison.OrdinalIgnoreCase));

            if (current == null)
            {
                var mediaUrl = new MediaUrl
                {
                    Url = url
                };

                if (item.RemoteTrailers.Length == 0)
                {
                    item.RemoteTrailers = new[] { mediaUrl };
                }
                else
                {
                    item.RemoteTrailers = item.RemoteTrailers.Concat(new [] { mediaUrl }).ToArray();
                }
            }
        }
Example #3
0
        /// <summary>
        /// Adds the trailer URL.
        /// </summary>
        public static void AddTrailerUrl(this IHasTrailers item, string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            var current = item.RemoteTrailers.FirstOrDefault(i => string.Equals(i.Url, url, StringComparison.OrdinalIgnoreCase));

            if (current == null)
            {
                var mediaUrl = new MediaUrl
                {
                    Url = url
                };

                if (item.RemoteTrailers.Length == 0)
                {
                    item.RemoteTrailers = new[] { mediaUrl };
                }
                else
                {
                    var list = item.RemoteTrailers.ToArray(item.RemoteTrailers.Length + 1);
                    list[list.Length - 1] = mediaUrl;

                    item.RemoteTrailers = list;
                }
            }
        }
Example #4
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Object Container: Use objectContainer.Get<T>() to retrieve objects from the scope
            var objectContainer = context.GetFromContext <IObjectContainer>(TwilioApiScope.ParentContainerPropertyTag);

            // Inputs
            var to              = To.Get(context);
            var mediaurl        = MediaUrl.Get(context);
            var from            = From.Get(context);
            var quality         = Quality.Get(context);
            var storemedia      = StoreMedia.Get(context);
            var minutestosend   = MinutesToSend.Get(context);
            var sipauthusername = SipAuthUsername.Get(context);
            var sipauthpassword = SipAuthPassword.Get(context);
            var statuscallback  = StatusCallback.Get(context);
            var twilioQuality   = quality == FaxQuality.Fine ? FaxResource.QualityEnum.Fine :
                                  quality == FaxQuality.SuperFine ? FaxResource.QualityEnum.Superfine :
                                  FaxResource.QualityEnum.Standard;
            var statusCallbackUri = statuscallback != null ? new Uri(statuscallback) : null;
            var sent = await FaxWrappers.SendFaxAsync(objectContainer.Get <ITwilioRestClient>(), from, to, new Uri(mediaurl),
                                                      twilioQuality, sipauthusername, sipauthpassword, statusCallbackUri, storemedia, minutestosend);

            // Outputs
            return((ctx) => {
                Fax.Set(ctx, sent);
            });
        }
Example #5
0
        public static void AddTrailerUrl(this BaseItem item, string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            var current = item.RemoteTrailers.FirstOrDefault(i => string.Equals(i.Url, url, StringComparison.OrdinalIgnoreCase));

            if (current == null)
            {
                var mediaUrl = new MediaUrl
                {
                    Url = url
                };

                if (item.RemoteTrailers.Count == 0)
                {
                    item.RemoteTrailers = new[] { mediaUrl };
                }
                else
                {
                    var oldIds = item.RemoteTrailers;
                    var newIds = new MediaUrl[oldIds.Count + 1];
                    oldIds.CopyTo(newIds);
                    newIds[oldIds.Count] = mediaUrl;
                    item.RemoteTrailers  = newIds;
                }
            }
        }
        private void ImageView_Click(object sender, EventArgs e)
        {
            ImageView view = sender as ImageView;
            MediaUrl  url  = view.DataContext as MediaUrl;

            medialist.setPosition(url.Index);
        }
        public void TestRemove()
        {
            MediaUrl url = new MediaUrl()
            {
                Id = 1, Tweet = new Tweet()
                {
                    Id = 0
                }
            };
            //Setup
            var urls = new List <MediaUrl>()
            {
                url
            };
            var data       = urls.AsQueryable();
            var urlMockSet = setUpAsQueriable(data);

            urlMockSet.Setup(d => d.Add(It.IsAny <MediaUrl>())).Callback <MediaUrl>((r) => urls.Add(r));
            urlMockSet.Setup(d => d.Remove(It.IsAny <MediaUrl>())).Callback <MediaUrl>((r) => urls.Remove(r));

            var mockContext = new Mock <TweetContext>();

            mockContext.Setup(c => c.MediaUrls).Returns(urlMockSet.Object);

            // Arrange
            MediaDBRepository repo = new MediaDBRepository(mockContext.Object);

            // Act
            repo.Remove(1);

            // Asert
            Assert.Null(repo.Get(1));
        }
Example #8
0
        public static async Task <bool> TryPostGifAsync(this IDialogContext context, string searchTerm, string title = null)
        {
            if (string.IsNullOrWhiteSpace(searchTerm))
            {
                return(false);
            }
            try
            {
                MediaUrl mediaUrl = await GifHelpers.GetGifMediaUrlAsync(searchTerm);

                if (mediaUrl != null)
                {
                    var message = context.MakeMessage();
                    message.AddAnimationCard(mediaUrl, title);
                    await context.PostAsync(message);

                    return(true);
                }

                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private async Task<List<MediaUrl>> GenerateLocalImages(List<string> urls, CancellationToken token)
        {
            // Regex for checking image items
            Regex image_expr = new Regex(@".(?:jpg|jpeg|png|bmp|gif|gifv)$");
            Regex gifv_expr = new Regex(@".(?:gifv)$");

            // Regex for identifying non-type-labelled imgur links
            Regex imgur_album = new Regex(@"(?:[a-zA-Z0-0]\.)?imgur.com\/(?:a|gallery|t\/[a-zA-Z0-9]*)\/([a-zA-Z0-9]*)");
            Regex imgur_unmarked = new Regex(@"(?:[a-zA-Z0-0]\.)?imgur.com\/([a-zA-Z0-9]{3,})");

            // Regex for identifying gfycat(beautifully simple) links
            Regex gfycat_links = new Regex(@"gfycat.com\/([a-zA-Z0-9]*)");
            int imgur_remaining = 0;
            int total_link_count = urls.Count;
            int current_link_count = 0;
            int current_image_count = 0;

            List<MediaUrl> list = new List<MediaUrl>();

            Stopwatch watch = new Stopwatch();
            watch.Start();

            foreach (string path in urls)
            {
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
                IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
                
                foreach (StorageFile file in files)
                {
                    if (file != null)
                    {
                        string title = file.Name;
                        string url = file.Path;
                        string thumb_url = url;
                        string self_url = url;

                        MediaUrl media_obj = new MediaUrl(title, url, thumb_url, self_url);
                        //await media_obj.RetrieveContent();
                        list.Add(media_obj);
                        current_image_count++;

                        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            ImagesCountText.Text = "Loaded " + current_image_count + " Images";
                        });
                    }
                }

                current_link_count++;
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    OverallProgressText.Text = "Processed " + current_link_count + " / " + total_link_count + " Links";
                    OverallProgressLoader.Value = (float)current_link_count / total_link_count * 100;
                });
            }

            return list;
        }
Example #10
0
        public async Task InitializeFord(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var response = await argument;
            var rk       = LuisFetcher.GetAnswers(response.Text.ToString()).Result;
            await context.SendTypingAcitivity();

            switch (rk.TopScoringIntent.IntentIntent)
            {
            case "FordSiteInfo":
                var answer = QnAMaker.QnAFetchter.GetAnswers("whats this site?").
                             Result.Answers[0].AnswerAnswer;
                MediaUrl mediaUrl = new MediaUrl("https://marczak.io/images/botseries-rich-cards/CreatingBot.mp4");
                await context.PostAsync(answer);

                //var k = ResultCard.GetVideoCard("Welcome to Leadership Learning Site", "", "Ford HR ", mediaUrl);
                //var reply = context.MakeMessage();
                //reply.Attachments = new List<Attachment>();
                //reply.Attachments.Add(k);
                //await context.PostAsync(reply);
                context.Done("competed");
                break;

            case "FordCurrentAffair":
                answer = QnAMaker.QnAFetchter.GetAnswers("Whats cooking?").
                         Result.Answers[0].AnswerAnswer;
                await context.PostAsync(answer);

                ResultCard result = new ResultCard();
                var        reply  = context.MakeMessage();
                reply.Text             = "Would you like to learn more?";
                reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "yes", "no" });
                await context.PostAsync(reply);

                context.Wait(handleSiteInfo);
                break;

            case "FordModels":
                ResultCard resultCard = new ResultCard();
                reply = context.MakeMessage();
                resultCard.ConvertToOptionsCard(reply, new[] { "Critical Thinking", "Design Thinking", "System Thinking" }, new[] { "http://syedamrullahravepoc.azurewebsites.net/content/criticalthinking.png", "http://syedamrullahravepoc.azurewebsites.net/content/designthinking.png", "http://syedamrullahravepoc.azurewebsites.net/content/systemthinking.png" });
                await context.PostAsync(reply);

                context.Wait(FordModelSelection);
                break;

            case "FordTraining":
                result                 = new ResultCard();
                reply                  = context.MakeMessage();
                reply.Text             = "If training was to be made available what would be your preference be:";
                reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "Webex Training", "Class Room" });
                await context.PostAsync(reply);

                context.Wait(handleLocationTraining);
                break;

            default: break;
            }
        }
Example #11
0
        /// <summary>
        /// Generate the necessary parameters
        /// </summary>
        public List <KeyValuePair <string, string> > GetParams()
        {
            var p = new List <KeyValuePair <string, string> >();

            if (To != null)
            {
                p.Add(new KeyValuePair <string, string>("To", To.ToString()));
            }

            if (From != null)
            {
                p.Add(new KeyValuePair <string, string>("From", From.ToString()));
            }

            if (MessagingServiceSid != null)
            {
                p.Add(new KeyValuePair <string, string>("MessagingServiceSid", MessagingServiceSid.ToString()));
            }

            if (Body != null)
            {
                p.Add(new KeyValuePair <string, string>("Body", Body));
            }

            if (MediaUrl != null)
            {
                p.AddRange(MediaUrl.Select(prop => new KeyValuePair <string, string>("MediaUrl", prop.AbsoluteUri)));
            }

            if (StatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("StatusCallback", StatusCallback.AbsoluteUri));
            }

            if (ApplicationSid != null)
            {
                p.Add(new KeyValuePair <string, string>("ApplicationSid", ApplicationSid.ToString()));
            }

            if (MaxPrice != null)
            {
                p.Add(new KeyValuePair <string, string>("MaxPrice", MaxPrice.Value.ToString()));
            }

            if (ProvideFeedback != null)
            {
                p.Add(new KeyValuePair <string, string>("ProvideFeedback", ProvideFeedback.Value.ToString()));
            }

            if (ValidityPeriod != null)
            {
                p.Add(new KeyValuePair <string, string>("ValidityPeriod", ValidityPeriod.Value.ToString()));
            }

            return(p);
        }
        public void MediaUrlInits()
        {
            var url     = "http://example.com";
            var profile = "myProfile";

            var mediaUrl = new MediaUrl(url, profile);

            Assert.NotNull(mediaUrl);
            Assert.IsType <MediaUrl>(mediaUrl);
            Assert.Equal(url, mediaUrl.Url);
            Assert.Equal(profile, mediaUrl.Profile);
        }
Example #13
0
 // Create Image
 public static AdaptiveImage CreateImage(MediaUrl image, AdaptiveImageSize size = AdaptiveImageSize.Medium, string id = "Image")
 {
     if (image != null)
     {
         return(new AdaptiveImage()
         {
             Id = id ?? string.Empty,
             Url = new Uri(image.Url),
             Size = size
         });
     }
     return(null);
 }
Example #14
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = MediaUrl?.GetHashCode() ?? 0;
         hashCode = (hashCode * 397) ^ (MimeType?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Caption?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (AlternateText?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (FolderPath?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (FileName?.GetHashCode() ?? 0);
         return(hashCode);
     }
 }
Example #15
0
        public static void AddAnimationCard(this IMessageActivity messageActivity, MediaUrl mediaUrl, string title = null)
        {
            var animationCard = new AnimationCard {
                Media = new List <MediaUrl> {
                    mediaUrl
                }
            };

            if (!string.IsNullOrWhiteSpace(title))
            {
                animationCard.Title = title;
            }
            messageActivity.Attachments.Add(animationCard.ToAttachment());
        }
        private async void downloadImageAsync(object sender, RoutedEventArgs e)
        {
            if (medialist.Count != 0)
            {
                MediaUrl current_image = await medialist.GetUrl();

                if (current_image.Image_retrieved && !current_image.Failed)
                {
                    try
                    {
                        await totalRequestSemaphore.WaitAsync();


                        HttpClientHandler handler = new HttpClientHandler();
                        handler.AllowAutoRedirect = false;
                        HttpClient client = new HttpClient(handler);

                        HttpResponseMessage response = await client.GetAsync(current_image.Image_Uri);

                        while (response.StatusCode == System.Net.HttpStatusCode.Redirect || response.StatusCode == System.Net.HttpStatusCode.MovedPermanently)
                        {
                            // Redirect required.
                            Uri redirect_uri = response.Headers.Location;
                            response = await client.GetAsync(redirect_uri);
                        }

                        byte[] img = await response.Content.ReadAsByteArrayAsync();

                        String      filename = current_image.Image_Uri.Segments.Last();
                        StorageFile x        = await KnownFolders.SavedPictures.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

                        using (IRandomAccessStream stream = await x.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            using (var output = stream.GetOutputStreamAt(0))
                            {
                                using (DataWriter writer = new DataWriter(output))
                                {
                                    writer.WriteBytes(img);
                                    await writer.StoreAsync();
                                }
                            }
                        }
                    }
                    catch (System.Threading.Tasks.TaskCanceledException except2)
                    {
                        Debug.WriteLine(except2);
                    }
                }
Example #17
0
        public void MediaUrl()
        {
            var m = new MediaUrl();
            var e = new[] { "albinutte", "gallery", "*" };
            var a = m.mediaUrl("https://media.codefights.com/Albinutte");

            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "gallery", "video" };
            a = m.mediaUrl("http://media.codefights.com/Albinutte/date/video");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "details", "2016-10-11/15:14:39" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/date/2016-10-11/15:14:39");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new string[] { };
            a = m.mediaUrl("https://media.codefights.com/date/2016-10-11/15:14:39");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "gallery", "2016" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/date/2016");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "gallery", "photo" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/date/photo");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "album", "366934" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/albums/366934");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "gallery", "*" };
            a = m.mediaUrl("http://media.codefights.com/Albinutte/date/15:15:05/2016-10-11");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "gallery", "*" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/date/2016-10-11/24:14:39");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "details", "2016-11-05/12:14:39" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/date/2016-11-05/12:14:39");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));

            e = new[] { "albinutte", "gallery", "*" };
            a = m.mediaUrl("https://media.codefights.com/Albinutte/2016-10-11/15:15:12");
            Assert.AreEqual(String.Join(",", e), String.Join(",", a));
        }
        public void RemoveTweetImage(long imageId, string streamName)
        {
            TwitterStream ts = streamManager.GetStream(streamName);

            if (ts != null)
            {
                MediaUrl media = ts._mediaRepo.Find(m => m.Id == imageId).SingleOrDefault();
                if (media != null)
                {
                    ts._mediaRepo.Remove(imageId);
                    Tweet tweet = ts._tweetRepo.Find(t => t.Id == media.Tweet.Id).SingleOrDefault();
                    if (tweet != null)
                    {
                        ts.UpdateTweet(media.Tweet.Id);
                        TweetUpdate(tweet, streamName);
                    }
                }
            }
        }
        public void SetTweetImageVisibility(long imageId, string streamName, bool visible)
        {
            TwitterStream ts = streamManager.GetStream(streamName);

            if (ts != null)
            {
                MediaUrl media = ts._mediaRepo.Find(m => m.Id == imageId).SingleOrDefault();
                if (media != null && media.Visible != visible)
                {
                    ts._mediaRepo.SetVisibility(imageId, visible);
                    Tweet tweet = ts._tweetRepo.Find(t => t.Id == media.Tweet.Id).SingleOrDefault();
                    if (tweet != null)
                    {
                        ts.UpdateTweet(media.Tweet.Id);
                        TweetUpdate(tweet, streamName);
                    }
                }
            }
        }
        private async Task AddMediaAsync(ObjectId residentId, MediaUrl mediaUrl, EMediaType mediaType)
        {
            switch (mediaType)
            {
            case EMediaType.Audio:
                await AddMediaAsync(residentId, x => x.Music, mediaUrl);

                break;

            case EMediaType.Video:
                await AddMediaAsync(residentId, x => x.Videos, mediaUrl);

                break;

            case EMediaType.Image:
                await AddMediaAsync(residentId, x => x.Images, mediaUrl);

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(mediaType), mediaType, null);
            }
        }
        private async Task <List <MediaUrl> > GenerateRedditImages(List <string> urls, CancellationToken token)
        {
            // Regex for checking image items
            Regex image_expr = new Regex(@".(?:jpg|jpeg|png|bmp|gif|gifv)$");
            Regex gifv_expr  = new Regex(@".(?:gifv)$");

            // Regex for identifying non-type-labelled imgur links
            Regex imgur_album    = new Regex(@"(?:[a-zA-Z0-0]\.)?imgur.com\/(?:a|gallery|t\/[a-zA-Z0-9]*)\/([a-zA-Z0-9]*)");
            Regex imgur_unmarked = new Regex(@"(?:[a-zA-Z0-0]\.)?imgur.com\/([a-zA-Z0-9]{3,})");

            // Regex for identifying gfycat(beautifully simple) links
            Regex gfycat_links    = new Regex(@"gfycat.com\/([a-zA-Z0-9]*)");
            int   imgur_remaining = 0;

            List <MediaUrl> list = new List <MediaUrl>();

            using (HttpClient client = new HttpClient())
            {
                string imgur_available_url = "https://api.imgur.com/3/credits";
                if (token.IsCancellationRequested)
                {
                    return(new List <MediaUrl>());
                }
                try
                {
                    var reqMsg = new HttpRequestMessage(HttpMethod.Get, imgur_available_url);
                    reqMsg.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", ImgurAuth.client_id);
                    HttpResponseMessage imgurresponse = await client.SendAsync(reqMsg);

                    if (imgurresponse.IsSuccessStatusCode)
                    {
                        string imgurcontent = await imgurresponse.Content.ReadAsStringAsync();

                        var creditsdata = JsonConvert.DeserializeObject <Creditsobject>(imgurcontent);
                        imgur_remaining = creditsdata.data.ClientRemaining;
                    }
                    else
                    {
                        imgur_remaining = 0;
                    }
                }
                catch (HttpRequestException e)
                {
                    imgur_remaining = 0;
                    Debug.WriteLine(e);
                }
                catch (JsonReaderException e)
                {
                    imgur_remaining = 0;
                    Debug.WriteLine(e);
                }
                catch (NullReferenceException e)
                {
                }
                catch (JsonSerializationException e)
                {
                    Debug.WriteLine(e);
                }

                int total_link_count    = urls.Count;
                int current_link_count  = 0;
                int current_image_count = 0;

                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    OverallProgressText.Text = "Processed " + current_link_count + " / " + total_link_count + " Links";
                });

                IEnumerable <string> full_uris = urls.Select(str => "https://www.reddit.com/" + str + ".json?limit=100");
                int       downloaded           = 0;
                Stopwatch watch = new Stopwatch();
                watch.Start();

                foreach (string link in full_uris)
                {
                    if (token.IsCancellationRequested)
                    {
                        return(new List <MediaUrl>());
                    }
                    HttpResponseMessage response = await client.GetAsync(link);

                    if (response.IsSuccessStatusCode)
                    {
                        try
                        {
                            string result = await response.Content.ReadAsStringAsync();

                            var rootResult = JsonConvert.DeserializeObject <Rootobject>(result);
                            foreach (var child in rootResult.data.children)
                            {
                                if (token.IsCancellationRequested)
                                {
                                    return(new List <MediaUrl>());
                                }
                                if (image_expr.IsMatch(child.data.url))
                                {
                                    string url;
                                    if (gifv_expr.IsMatch(child.data.url))
                                    {
                                        url = child.data.url.Substring(0, child.data.url.LastIndexOf('v'));
                                        Debug.WriteLine("Changing " + child.data.url + " -> " + url);
                                    }
                                    else
                                    {
                                        url = child.data.url;
                                    }
                                    string thumb_url = url;
                                    string self_url  = "www.reddit.com" + child.data.permalink;
                                    if (!String.IsNullOrEmpty(child.data.thumbnail))
                                    {
                                        thumb_url = child.data.thumbnail;
                                    }

                                    if (!String.IsNullOrEmpty(thumb_url) && !String.IsNullOrEmpty(url) && !String.IsNullOrEmpty(self_url))
                                    {
                                        MediaUrl media_obj = new MediaUrl(child.data.title, url, thumb_url, self_url);
                                        list.Add(media_obj);
                                        current_image_count++;
                                        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                        {
                                            ImagesCountText.Text = "Loaded " + current_image_count + " Images";
                                        });
                                    }
                                }
                                else if (imgur_album.IsMatch(child.data.url) && imgur_remaining > 500)
                                {
                                    imgur_remaining--;
                                    Match  match           = imgur_album.Match(child.data.url);
                                    string imgur_album_url = "https://api.imgur.com/3/album/" + match.Groups[1].Value;
                                    Debug.WriteLine(imgur_album_url);
                                    try
                                    {
                                        var requestMessage = new HttpRequestMessage(HttpMethod.Get, imgur_album_url);
                                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", ImgurAuth.client_id);
                                        HttpResponseMessage imgurresponse = await client.SendAsync(requestMessage);

                                        if (imgurresponse.IsSuccessStatusCode)
                                        {
                                            string imgurcontent = await imgurresponse.Content.ReadAsStringAsync();

                                            var imgurdata = JsonConvert.DeserializeObject <Albumobject>(imgurcontent);


                                            if (imgurdata.success)
                                            {
                                                foreach (Models.Imgur.Image img in imgurdata.data.images)
                                                {
                                                    string url = img.link;

                                                    string thumb_url = url;
                                                    string self_url  = "www.reddit.com" + child.data.permalink;
                                                    if (!String.IsNullOrEmpty(child.data.thumbnail))
                                                    {
                                                        thumb_url = child.data.thumbnail;
                                                    }
                                                    string title = child.data.title;


                                                    if (!String.IsNullOrEmpty(thumb_url) && !String.IsNullOrEmpty(url) && !String.IsNullOrEmpty(self_url))
                                                    {
                                                        MediaUrl media_obj = new MediaUrl(title, url, thumb_url, self_url);
                                                        list.Add(media_obj);
                                                        current_image_count++;
                                                        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                                        {
                                                            ImagesCountText.Text = "Loaded " + current_image_count + " Images";
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (HttpRequestException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (JsonReaderException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (NullReferenceException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (JsonSerializationException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                }
                                else if (imgur_unmarked.IsMatch(child.data.url) && imgur_remaining > 500)
                                {
                                    imgur_remaining--;
                                    Match  match           = imgur_unmarked.Match(child.data.url);
                                    string imgur_album_url = "https://api.imgur.com/3/album/" + match.Groups[1].Value;
                                    Debug.WriteLine(imgur_album_url);
                                    try
                                    {
                                        var requestMessage = new HttpRequestMessage(HttpMethod.Get, imgur_album_url);
                                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", ImgurAuth.client_id);
                                        HttpResponseMessage imgurresponse = await client.SendAsync(requestMessage);

                                        if (imgurresponse.IsSuccessStatusCode)
                                        {
                                            string imgurcontent = await imgurresponse.Content.ReadAsStringAsync();

                                            var imgurdata = JsonConvert.DeserializeObject <Albumobject>(imgurcontent);


                                            if (imgurdata.success)
                                            {
                                                foreach (Models.Imgur.Image img in imgurdata.data.images)
                                                {
                                                    string url = img.link;

                                                    string thumb_url = url;
                                                    string self_url  = "www.reddit.com" + child.data.permalink;
                                                    if (!String.IsNullOrEmpty(child.data.thumbnail))
                                                    {
                                                        thumb_url = child.data.thumbnail;
                                                    }
                                                    string title = child.data.title;

                                                    if (!String.IsNullOrEmpty(thumb_url) && !String.IsNullOrEmpty(url) && !String.IsNullOrEmpty(self_url))
                                                    {
                                                        MediaUrl media_obj = new MediaUrl(title, url, thumb_url, self_url);
                                                        list.Add(media_obj);
                                                        current_image_count++;
                                                        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                                        {
                                                            ImagesCountText.Text = "Loaded " + current_image_count + " Images";
                                                        });
                                                    }
                                                }
                                            }
                                            else if (imgur_remaining > 500)
                                            {
                                                imgur_remaining--;
                                                imgur_album_url = "https://api.imgur.com/3/image/" + match.Groups[1].Value;
                                                try
                                                {
                                                    requestMessage = new HttpRequestMessage(HttpMethod.Get, imgur_album_url);
                                                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", ImgurAuth.client_id);
                                                    imgurresponse = await client.SendAsync(requestMessage);

                                                    if (imgurresponse.IsSuccessStatusCode)
                                                    {
                                                        imgurcontent = await imgurresponse.Content.ReadAsStringAsync();

                                                        var imgur_img = JsonConvert.DeserializeObject <Imageobject>(imgurcontent);
                                                        if (imgur_img.success)
                                                        {
                                                            string url = imgur_img.data.link;

                                                            string thumb_url = url;
                                                            string self_url  = "www.reddit.com" + child.data.permalink;
                                                            if (!String.IsNullOrEmpty(child.data.thumbnail))
                                                            {
                                                                thumb_url = child.data.thumbnail;
                                                            }
                                                            string title = child.data.title;

                                                            if (!String.IsNullOrEmpty(thumb_url) && !String.IsNullOrEmpty(url) && !String.IsNullOrEmpty(self_url))
                                                            {
                                                                MediaUrl media_obj = new MediaUrl(title, url, thumb_url, self_url);
                                                                list.Add(media_obj);
                                                                current_image_count++;
                                                                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                                                {
                                                                    ImagesCountText.Text = "Loaded " + current_image_count + " Images";
                                                                });
                                                            }
                                                        }
                                                    }
                                                }
                                                catch (HttpRequestException e)
                                                {
                                                    Debug.WriteLine(e);
                                                }
                                                catch (JsonReaderException e)
                                                {
                                                    Debug.WriteLine(e);
                                                }
                                                catch (NullReferenceException e)
                                                {
                                                    Debug.WriteLine(e);
                                                }
                                                catch (JsonSerializationException e)
                                                {
                                                    Debug.WriteLine(e);
                                                }
                                            }
                                        }
                                    }
                                    catch (HttpRequestException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (JsonReaderException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (NullReferenceException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (JsonSerializationException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                }
                                else if (gfycat_links.IsMatch(child.data.url))
                                {
                                    Match match = gfycat_links.Match(child.data.url);
                                    Debug.WriteLine(match.Groups[1] + " <- " + child.data.url);
                                    string gfy_url = "https://gfycat.com/cajax/get/" + match.Groups[1].Value;
                                    Debug.WriteLine(gfy_url);

                                    try
                                    {
                                        HttpResponseMessage gfyresponse = await client.GetAsync(gfy_url);

                                        if (gfyresponse.IsSuccessStatusCode)
                                        {
                                            string gfycontent = await gfyresponse.Content.ReadAsStringAsync();

                                            var gfydata = JsonConvert.DeserializeObject <Gfyobject>(gfycontent);
                                            var gfyurl  = gfydata.gfyItem.gifUrl;

                                            string thumb_url = gfydata.gfyItem.max2mbGif;
                                            string self_url  = "www.reddit.com" + child.data.permalink;
                                            if (!String.IsNullOrEmpty(child.data.thumbnail))
                                            {
                                                thumb_url = child.data.thumbnail;
                                            }

                                            if (!String.IsNullOrEmpty(thumb_url) && !String.IsNullOrEmpty(gfyurl) && !String.IsNullOrEmpty(self_url))
                                            {
                                                MediaUrl media_obj = new MediaUrl(child.data.title, gfyurl, thumb_url, self_url);
                                                list.Add(media_obj);
                                                current_image_count++;
                                                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                                {
                                                    ImagesCountText.Text = "Loaded " + current_image_count + " Images";
                                                });
                                            }
                                        }
                                    }
                                    catch (HttpRequestException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (NullReferenceException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (JsonReaderException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                    catch (JsonSerializationException e)
                                    {
                                        Debug.WriteLine(e);
                                    }
                                }
                            }
                        }
                        catch (UriFormatException e)
                        {
                            Debug.WriteLine(e);
                        }
                        catch (JsonReaderException e)
                        {
                            Debug.WriteLine(e);
                        }
                        catch (NullReferenceException e)
                        {
                            Debug.WriteLine(e);
                        }
                        catch (JsonSerializationException e)
                        {
                            Debug.WriteLine(e);
                        }
                    }
                    downloaded++;

                    if (downloaded >= 50)
                    {
                        int seconds_since = watch.Elapsed.Seconds;
                        watch.Reset();
                        if (seconds_since < 60)
                        {
                            await Task.Delay((60 - seconds_since) * 1000);
                        }

                        downloaded = downloaded < 60 ? 0 : downloaded - 60;
                    }
                    current_link_count++;
                    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        OverallProgressText.Text    = "Processed " + current_link_count + " / " + total_link_count + " Links";
                        OverallProgressLoader.Value = (float)current_link_count / total_link_count * 100;
                    });
                }
            }
            return(list);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Debug.WriteLine("OnNavigatedTo!");
            base.OnNavigatedTo(e);


            object[] param = e.Parameter as object[];
            GenerateImages(param, downloadTaskCancelToken.Token).ContinueWith((result) =>
            {
                Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    ContentLoadingPanel.Visibility = Visibility.Collapsed;
                });

                for (int i = 0; i < result.Result.Count - 1; i++)
                {
                    MediaUrl obj = result.Result[i];
                    medialist.Add(obj);
                }
                ;


                medialist.addListener(async(a, f) =>
                {
                    Debug.WriteLine("MediaLIst Property changed!");
                    MediaUrl url = await medialist.GetUrl();
                    MainSlideshowImage.Source = url.Image;
                    SlideshowImageTitle.Text  = url.Title;
                    CurrentImageUrl.Text      = url.Self;
                    if (url.Failed)
                    {
                        Debug.WriteLine("MediaLIst Url Failed!");
                        LoadingRing.Visibility        = Visibility.Collapsed;
                        FailedNotification.Visibility = Visibility.Visible;
                    }
                    else if (!url.Image_retrieved)
                    {
                        Debug.WriteLine("MediaLIst Url not retrieved!");
                        FailedNotification.Visibility = Visibility.Collapsed;
                        LoadingRing.Visibility        = Visibility.Visible;
                    }
                    else
                    {
                        Debug.WriteLine("MediaLIst Url retrieved!");
                        FailedNotification.Visibility = Visibility.Collapsed;
                        LoadingRing.Visibility        = Visibility.Collapsed;
                    }
                });

                if (result.Result.Count != 0)
                {
                    medialist.Add(result.Result.Last());
                }



                if (result.Result.Count == 0 && !downloadTaskCancelToken.Token.IsCancellationRequested)
                {
                    // No Urls retrieved, show error, return to sender.

                    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Debug.WriteLine("No Urls Retrieved");
                        var dialog = new ContentDialog()
                        {
                            Title      = "Error - 404 Not Found",
                            Background = Application.Current.Resources["MainTheme_color_highlight"] as SolidColorBrush,
                        };
                        var panel = new StackPanel()
                        {
                        };
                        panel.Children.Add(new TextBlock
                        {
                            Text         = "Unfortunately we couldn't find any image urls (ending in .png, .jpg, etc...) at the specified subreddit.",
                            TextWrapping = TextWrapping.Wrap,
                        });

                        dialog.Content = panel;

                        dialog.PrimaryButtonText   = "Ok";
                        dialog.PrimaryButtonClick += (sender, args) =>
                        {
                            GoBackButtonClick(sender, new RoutedEventArgs());
                        };


                        dialog.ShowAsync();
                    });
                }
            });
        }
Example #23
0
        public static Attachment GetVideoCard(string title, string subtitle, string text, MediaUrl cardImage)
        {
            var heroCard = new VideoCard
            {
                Title    = title,
                Subtitle = subtitle,
                Text     = text,
                Media    = new List <MediaUrl>()
            };

            return(heroCard.ToAttachment());
        }
Example #24
0
        private VideoCard MakeVideoCard()
        {
            var url = new MediaUrl(url: CorgiOnCarouselVideo);

            return(new VideoCard(title: "Video Card", media: new[] { url }));
        }
Example #25
0
        public ActionResult UploadMedia()
        {
            List <WechatMedia> mList = new List <WechatMedia>();
            var mdb       = Sitecore.Configuration.Factory.GetDatabase("master");
            var mItem     = mdb.GetItem(Request.Params["myItem"]);
            var localItem = mdb.GetItem(Request.Params["localItem"]);

            if ((mItem == null) || (localItem == null))
            {
                return(Content("Item is not existing!"));
            }


            if (!UploadThumbnail(mItem))
            {
                //return UploadThumbnail(mItem);
                return(Content("Upload News Thumbnail failed!"));
            }
            //ChildList mChldren =(ChildList)mItem.GetChildren().Where(i => i.TemplateName == "Msg Paragraph");
            ChildList mChildren = localItem.GetChildren();

            if (mChildren == null)
            {
                return(Content("Children are empty!"));
            }

            MediaParams mediaParams = new MediaParams();



            foreach (Item i in mChildren)
            {
                var       mField    = (ImageField)i.Fields["PImage"];
                MediaItem mediaItem = mField.MediaItem;

                mediaParams.filename    = mediaItem.Name + "." + mediaItem.Extension;
                mediaParams.filelength  = (int)mediaItem.GetMediaStream().Length;
                mediaParams.contenttype = mediaItem.MimeType;
                mediaParams.media       = new byte[(int)mediaItem.GetMediaStream().Length];

                using (Stream stream = mediaItem.GetMediaStream())
                {
                    stream.Read(mediaParams.media, 0, (int)mediaItem.GetMediaStream().Length);
                }

                MediaUrl mediaUrl = (MediaUrl)JsonConvert.DeserializeObject(MsgService.UploadImg(mediaParams), typeof(MediaUrl));

                mList.Add(new WechatMedia
                {
                    itemId   = i.ID.ToString(),
                    mediaId  = null,
                    mediaUrl = HttpUtility.UrlDecode(mediaUrl.Url)
                });
            }

            if (UpdateUrl(mList))
            {
                return(Content("Update Media Urls Successfully"));
            }
            else
            {
                return(Content("Update Media Urls failed"));
            }
        }
Example #26
0
        /// <summary>
        /// Generate the necessary parameters
        /// </summary>
        public List <KeyValuePair <string, string> > GetParams()
        {
            var p = new List <KeyValuePair <string, string> >();

            if (To != null)
            {
                p.Add(new KeyValuePair <string, string>("To", To.ToString()));
            }

            if (From != null)
            {
                p.Add(new KeyValuePair <string, string>("From", From.ToString()));
            }

            if (MessagingServiceSid != null)
            {
                p.Add(new KeyValuePair <string, string>("MessagingServiceSid", MessagingServiceSid.ToString()));
            }

            if (Body != null)
            {
                p.Add(new KeyValuePair <string, string>("Body", Body));
            }

            if (MediaUrl != null)
            {
                p.AddRange(MediaUrl.Select(prop => new KeyValuePair <string, string>("MediaUrl", prop.AbsoluteUri.TrimEnd('/'))));
            }

            if (StatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("StatusCallback", StatusCallback.AbsoluteUri.TrimEnd('/')));
            }

            if (ApplicationSid != null)
            {
                p.Add(new KeyValuePair <string, string>("ApplicationSid", ApplicationSid.ToString()));
            }

            if (MaxPrice != null)
            {
                p.Add(new KeyValuePair <string, string>("MaxPrice", MaxPrice.Value.ToString()));
            }

            if (ProvideFeedback != null)
            {
                p.Add(new KeyValuePair <string, string>("ProvideFeedback", ProvideFeedback.Value.ToString().ToLower()));
            }

            if (ValidityPeriod != null)
            {
                p.Add(new KeyValuePair <string, string>("ValidityPeriod", ValidityPeriod.Value.ToString()));
            }

            if (MaxRate != null)
            {
                p.Add(new KeyValuePair <string, string>("MaxRate", MaxRate));
            }

            if (ForceDelivery != null)
            {
                p.Add(new KeyValuePair <string, string>("ForceDelivery", ForceDelivery.Value.ToString().ToLower()));
            }

            if (ProviderSid != null)
            {
                p.Add(new KeyValuePair <string, string>("ProviderSid", ProviderSid.ToString()));
            }

            if (ContentRetention != null)
            {
                p.Add(new KeyValuePair <string, string>("ContentRetention", ContentRetention.ToString()));
            }

            if (AddressRetention != null)
            {
                p.Add(new KeyValuePair <string, string>("AddressRetention", AddressRetention.ToString()));
            }

            if (SmartEncoded != null)
            {
                p.Add(new KeyValuePair <string, string>("SmartEncoded", SmartEncoded.Value.ToString().ToLower()));
            }

            return(p);
        }
Example #27
0
        private AnimationCard MakeAnimationCard()
        {
            var url = new MediaUrl(url: MindBlownGif);

            return(new AnimationCard(title: "Animation Card", media: new[] { url }, autostart: true));
        }
Example #28
0
        /// <summary>
        /// Generate the necessary parameters
        /// </summary>
        public List <KeyValuePair <string, string> > GetParams()
        {
            var p = new List <KeyValuePair <string, string> >();

            if (To != null)
            {
                p.Add(new KeyValuePair <string, string>("To", To.ToString()));
            }

            if (From != null)
            {
                p.Add(new KeyValuePair <string, string>("From", From.ToString()));
            }

            if (MessagingServiceSid != null)
            {
                p.Add(new KeyValuePair <string, string>("MessagingServiceSid", MessagingServiceSid.ToString()));
            }

            if (Body != null)
            {
                p.Add(new KeyValuePair <string, string>("Body", Body));
            }

            if (MediaUrl != null)
            {
                p.AddRange(MediaUrl.Select(prop => new KeyValuePair <string, string>("MediaUrl", Serializers.Url(prop))));
            }

            if (StatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("StatusCallback", Serializers.Url(StatusCallback)));
            }

            if (ApplicationSid != null)
            {
                p.Add(new KeyValuePair <string, string>("ApplicationSid", ApplicationSid.ToString()));
            }

            if (MaxPrice != null)
            {
                p.Add(new KeyValuePair <string, string>("MaxPrice", MaxPrice.Value.ToString()));
            }

            if (ProvideFeedback != null)
            {
                p.Add(new KeyValuePair <string, string>("ProvideFeedback", ProvideFeedback.Value.ToString().ToLower()));
            }

            if (ValidityPeriod != null)
            {
                p.Add(new KeyValuePair <string, string>("ValidityPeriod", ValidityPeriod.ToString()));
            }

            if (ForceDelivery != null)
            {
                p.Add(new KeyValuePair <string, string>("ForceDelivery", ForceDelivery.Value.ToString().ToLower()));
            }

            if (SmartEncoded != null)
            {
                p.Add(new KeyValuePair <string, string>("SmartEncoded", SmartEncoded.Value.ToString().ToLower()));
            }

            if (InteractiveData != null)
            {
                p.Add(new KeyValuePair <string, string>("InteractiveData", InteractiveData));
            }

            if (ForceOptIn != null)
            {
                p.Add(new KeyValuePair <string, string>("ForceOptIn", ForceOptIn.Value.ToString().ToLower()));
            }

            return(p);
        }
Example #29
0
        private AudioCard MakeAudioCard()
        {
            var url = new MediaUrl(url: $"{_serverUrl}api/music");

            return(new AudioCard(title: "Audio Card", media: new[] { url }, autoloop: true));
        }
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            podcast pod = new podcast();

            var activity = await result as Activity;
            var message  = context.MakeMessage();

            // This handles cortana invokation it is usually good to do a very short invokation reply.
            var isCortanalaunch = activity.Entities.Where(e => e.Type == "Intent" && e.Properties["name"].ToString() == "Microsoft.Launch").Any();

            if (isCortanalaunch)
            {
                message.Text = "What do you want me to play?";
                //message.Speak = @"<voice name=""Microsoft Server Speech Text to Speech Voice (da-DK, HelleRUS)"">Hvad skal jeg spille?</voice>";
                //message.Speak = SSMLHelper.Speak("What to play?"); //<voice name=""Microsoft Server Speech Text to Speech Voice (da-DK, HelleRUS)"">Hvad skal jeg spille?</voice>";
                message.InputHint = InputHints.ExpectingInput;
            }
            else
            {
                message.Attachments = new List <Attachment>();


                if (activity.Text.Contains("24") || activity.Text.ToLower().Contains("twenty four"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live.taleradio.dk/Web") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to Radio twentyfour seven";
                }
                else if (matchRegex(activity.Text.ToLower(), @"(B|D|E|G|P|the|tea|tee|T)\s?(1|one)"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live-icy.gslb01.dr.dk:80/A/A03H.mp3") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to P1.";
                }
                else if (matchRegex(activity.Text.ToLower(), @"(B|D|E|G|P|the|tea|tee|T)\s?(2|two|too)"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live-icy.gslb01.dr.dk:80/A/A04H.mp3") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to P2.";
                }
                else if (matchRegex(activity.Text.ToLower(), @"(B|D|E|G|P|the|tea|tee|T)\s?(5|five)"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live-icy.gslb01.dr.dk:80/A/A25H.mp3") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to P5.";
                }
                else if (matchRegex(activity.Text.ToLower(), @"(B|D|E|G|P|the|tea|tee|T)\s?(3|tree|three)"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live-icy.gslb01.dr.dk:80/A/A05H.mp3") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to P3.";
                }
                else if (activity.Text.ToLower().Contains("jazz"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live-icy.gslb01.dr.dk:80/A/A22H.mp3") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to P8 Jazz.";
                }
                else if (activity.Text.ToLower().Contains("mix") || activity.Text.ToLower().Contains("mechs"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://live-icy.gslb01.dr.dk:80/A/A21H.mp3") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to P7 Mix.";
                }
                else if (activity.Text.ToLower().Contains("nova"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://195.184.101.204/nova128") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to Nova FM";
                }
                else if (activity.Text.ToLower().Contains("rock"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://stream.myrock.fm/myrock128") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to My Rock";
                }
                else if (activity.Text.ToLower().Contains("pop"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://195.184.101.202/pop128") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to POP FM";
                }
                else if (activity.Text.ToLower().Contains("voice"))
                {
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl("http://195.184.101.203/voice128") };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Tuning in to : THE VOICE";
                }
                else if (activity.Text.ToLower().Contains("news"))
                {
                    // var murl = pod.getmediaURL("https://www.dr.dk/mu/feed/p1-radioavisen.xml?format=podcast&limit=10");

                    var item = await pod.getmediaURL("https://arkiv.radio24syv.dk/audiopodcast/channel/3561248");

                    var diffString = "";

                    if (DateTime.Now.AddHours(1).Subtract(item.pubDate).Hours < 1)
                    {
                        diffString = DateTime.Now.AddHours(1).Subtract(item.pubDate).Minutes.ToString() + " minutes";
                    }
                    else
                    {
                        diffString = DateTime.Now.AddHours(1).Subtract(item.pubDate).Hours.ToString() + " hours";
                    }
                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl(item.url) };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Playing the news from " + diffString + " ago";
                }
                else if (activity.Text.ToLower().Contains("campaign") || activity.Text.ToLower().Contains("trail"))
                {
                    // var murl = pod.getmediaURL("https://www.dr.dk/mu/feed/p1-radioavisen.xml?format=podcast&limit=10");

                    var item = await pod.getmediaURL("https://arkiv.radio24syv.dk/audiopodcast/channel/13965705");

                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl(item.url) };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;

                    message.Text = "Playing Campaign Trail";
                }
                else if (activity.Text.ToLower().Contains("azure") || activity.Text.ToLower().Contains("azure podcast") || activity.Text.ToLower().Contains("assure podcast") || activity.Text.ToLower().Contains("assure "))
                {
                    // var murl = pod.getmediaURL("https://www.dr.dk/mu/feed/p1-radioavisen.xml?format=podcast&limit=10");

                    var item = await pod.getmediaURL("http://feeds.feedburner.com/TheAzurePodcast?format=xml");

                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl(item.url) };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Playing The Azure Podcast";
                }
                else if (activity.Text.ToLower().Contains("sunshine"))
                {
                    var item = await pod.getmediaURL("https://arkiv.radio24syv.dk/audiopodcast/channel/13967997");

                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl(item.url) };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Playing : Are you Sunshine?";
                }
                else if (activity.Text.ToLower().Contains("short"))
                {
                    var item = await pod.getmediaURLs("https://arkiv.radio24syv.dk/audiopodcast/channel/10839671");

                    MediaUrl[] medias    = new MediaUrl[] { new MediaUrl(item[item.Count - 2].url), new MediaUrl(item[item.Count - 1].url) };
                    AudioCard  audioCard = new AudioCard()
                    {
                        Media = medias,
                    };
                    Attachment audioCardAttach = audioCard.ToAttachment();
                    message.Attachments.Add(audioCardAttach);
                    message.InputHint = InputHints.AcceptingInput;
                    message.Text      = "Playing : Kirsten Birgit";
                }

                else if (activity.Text.Contains("help"))
                {
                    message.Text      = $"Say 24 for radio twentyfour seven. Say P1, P2 or P3 for DR Programs";
                    message.InputHint = InputHints.ExpectingInput;
                }
                else
                {
                    message.Text      = $"I heard {activity.Text}. I don't get that. Try again, or say help to get availible stations.";
                    message.InputHint = InputHints.ExpectingInput;
                }
            }
            message.Speak = message.Text;


            await context.PostAsync(message);

            context.Wait(MessageReceivedAsync);
        }