private void UpdateFile(object target, File file)
 {
     if (target is LottieView player && player.IsLoaded)
     {
         player.Source = UriEx.ToLocal(file.Local.Path);
     }
 }
        private async void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            if (args.InRecycleQueue)
            {
                return;
            }

            var content = args.ItemContainer.ContentTemplateRoot as Grid;
            var sticker = args.Item as Sticker;

            var file = sticker.StickerValue;

            if (file.Local.IsDownloadingCompleted)
            {
                if (content.Children[0] is Border border && border.Child is Image photo)
                {
                    photo.Source = await PlaceholderHelper.GetWebPFrameAsync(file.Local.Path, 60);

                    ElementCompositionPreview.SetElementChildVisual(content.Children[0], null);
                }
                else if (args.Phase == 0 && content.Children[0] is LottieView lottie)
                {
                    lottie.Source = UriEx.ToLocal(file.Local.Path);
                }
            }
Example #3
0
 private void UpdateThumbnail(object target, File file)
 {
     if (target is AnimationView view)
     {
         view.Thumbnail = new BitmapImage(UriEx.ToLocal(file.Local.Path));
     }
 }
Example #4
0
        private void UpdateThumbnail(MessageViewModel message, Video video, File file, bool download)
        {
            var thumbnail     = video.Thumbnail;
            var minithumbnail = video.Minithumbnail;

            if (thumbnail != null && thumbnail.Format is ThumbnailFormatJpeg)
            {
                if (file.Local.IsFileExisting())
                {
                    Texture.Source = new BitmapImage(UriEx.ToLocal(file.Local.Path));
                }
                else if (download)
                {
                    if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
                    {
                        if (minithumbnail != null)
                        {
                            Texture.Source = PlaceholderHelper.GetBlurred(minithumbnail.Data);
                        }

                        message.ProtoService.DownloadFile(file.Id, 1);
                    }

                    UpdateManager.Subscribe(this, message, file, ref _thumbnailToken, UpdateThumbnail, true);
                }
            }
            else if (minithumbnail != null)
            {
                Texture.Source = PlaceholderHelper.GetBlurred(minithumbnail.Data);
            }
            else
            {
                Texture.Source = null;
            }
        }
Example #5
0
        private void ProcessingComplete(Tweet tweet, UriEx l, object m)
        {
            if (m is UrlEntity || m is MediaEntity)
            {
                tweet.TweetText = tweet.Status.Text.Replace(((dynamic)m).Url, "<a target=\"_blank\" href=\"" + l.Uri + "\">[" + l.Title + "]</a>");
            }

            if (l.Image != null && tweet.Image == null)
            {
                try
                {
                    using (var response = l.Image.GetWebRequest().GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null && responseStream.CanRead)
                            {
                                var imgData = new byte[responseStream.Length];
                                responseStream.Read(imgData, 0, imgData.Length);
                                using (var memstrm = new MemoryStream(imgData))
                                {
                                    tweet.Image = (Bitmap)Bitmap.FromStream(memstrm);
                                }
                            }
                        }
                    }
                }
                catch { }
            }
        }
        private void OnContainerContentChanged(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            if (args.InRecycleQueue)
            {
                return;
            }

            var element  = args.ItemContainer.ContentTemplateRoot as FrameworkElement;
            var reaction = args.Item as SupergroupReactionOption;

            var player = element.FindName("Player") as LottieView;

            if (player != null)
            {
                player.FrameSize = new Size(48, 48);

                var file = reaction.Reaction.CenterAnimation.StickerValue;
                if (file.Local.IsFileExisting())
                {
                    player.Source = UriEx.ToLocal(file.Local.Path);
                }
                else
                {
                    player.Source = null;

                    UpdateManager.Subscribe(player, ViewModel.ProtoService, file, UpdateFile, true);

                    if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
                    {
                        ViewModel.ProtoService.DownloadFile(file.Id, 16);
                    }
                }
            }
        }
Example #7
0
        public void UpdateFile(MessageViewModel message, File file)
        {
            var sticker = GetContent(message);

            if (sticker == null || !_templateApplied)
            {
                return;
            }

            if (sticker.StickerValue.Id != file.Id)
            {
                return;
            }

            if (file.Local.IsDownloadingCompleted)
            {
                Player.IsLoopingEnabled = message.Content is MessageSticker && SettingsService.Current.Stickers.IsLoopingEnabled;
                Player.Source           = UriEx.ToLocal(file.Local.Path);
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
            {
                Player.Source = null;
                message.ProtoService.DownloadFile(file.Id, 1);
            }
        }
 private void UpdateFile(object target, File file)
 {
     if (target is LottieView lottie)
     {
         lottie.Source = UriEx.ToLocal(file.Local.Path);
     }
 }
Example #9
0
        private void UpdateThumbnail(MessageWithOwner message, Thumbnail thumbnail, File file)
        {
            if (file.Local.IsFileExisting())
            {
                double ratioX = (double)48 / thumbnail.Width;
                double ratioY = (double)48 / thumbnail.Height;
                double ratio  = Math.Max(ratioX, ratioY);

                var width  = (int)(thumbnail.Width * ratio);
                var height = (int)(thumbnail.Height * ratio);

                Texture.Background = new ImageBrush {
                    ImageSource = new BitmapImage(UriEx.ToLocal(file.Local.Path))
                    {
                        DecodePixelWidth = width, DecodePixelHeight = height
                    }, Stretch = Stretch.UniformToFill, AlignmentX = AlignmentX.Center, AlignmentY = AlignmentY.Center
                };
                Button.Style = BootStrapper.Current.Resources["ImmersiveFileButtonStyle"] as Style;
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
            {
                message.ProtoService.DownloadFile(file.Id, 1);

                Texture.Background = null;
                Button.Style       = BootStrapper.Current.Resources["InlineFileButtonStyle"] as Style;
            }
        }
Example #10
0
        private List <Uri> ExtractImageUris(UriEx uriex, HtmlAgilityPack.HtmlDocument doc)
        {
            var images       = new List <Uri>();
            var strongFilter = false;
            var imageNodes   = doc.DocumentNode.SelectNodes("//article/descendant-or-self::img");

            if (imageNodes == null && !string.IsNullOrEmpty(uriex.Title))
            {
                var titleNode = doc.DocumentNode.SelectNodes("//body/descendant-or-self::*[starts-with(., '" + uriex.Title.Split('\'')[0] + "')]");
                if (titleNode != null)
                {
                    imageNodes   = titleNode.FirstOrDefault().ParentNode.SelectNodes("/descendant-or-self::img");
                    strongFilter = true;
                }
            }

            if (imageNodes != null)
            {
                var imageUrls = imageNodes
                                .Where(i => i.Attributes["src"] != null &&
                                       i.Attributes["src"].Value != null)
                                .Select(i => { try { return(new Uri(i.Attributes["src"].Value)); } catch { return(null); } })
                                .Where(x => x != null && (!strongFilter || x.Host == uriex.Uri.Host))
                                .ToList();
                return(imageUrls);
            }
            else
            {
                return(new List <Uri>());
            }
        }
Example #11
0
        private static async Task <ImageSource> GetLottieFrame(string path, int frame, int width, int height)
        {
            var dpi = WindowContext.Current.RasterizationScale;

            width  = (int)(width * dpi);
            height = (int)(height * dpi);

            var cache = $"{path}.{width}x{height}.png";

            if (System.IO.File.Exists(cache))
            {
                return(new BitmapImage(UriEx.ToLocal(cache)));
            }

            await Task.Run(() =>
            {
                var frameSize = new Windows.Graphics.SizeInt32 {
                    Width = width, Height = height
                };

                var animation = LottieAnimation.LoadFromFile(path, frameSize, false, null);
                if (animation != null)
                {
                    animation.RenderSync(cache, frame);
                    animation.Dispose();
                }
            });

            return(new BitmapImage(UriEx.ToLocal(cache)));
        }
Example #12
0
        public async void UpdateFile(File file)
        {
            if (_stickers.TryGetValue(file.Id, out List <StickerViewModel> items) && items.Count > 0)
            {
                foreach (var sticker in items.ToImmutableHashSet())
                {
                    sticker.UpdateFile(file);

                    var container = List.ContainerFromItem(sticker) as SelectorItem;
                    if (container == null)
                    {
                        continue;
                    }

                    var content = container.ContentTemplateRoot as Border;
                    if (content == null)
                    {
                        continue;
                    }

                    if (content.Child is Border border && border.Child is Image photo)
                    {
                        photo.Source = await PlaceholderHelper.GetWebPFrameAsync(file.Local.Path, 68);

                        ElementCompositionPreview.SetElementChildVisual(content.Child, null);
                    }
                    else if (content.Child is LottieView lottie)
                    {
                        lottie.Source = UriEx.ToLocal(file.Local.Path);
                        _handler.ThrottleVisibleItems();
                    }
                }
        private void ProcessMaps()
        {
            countryMaps = new Dictionary <string, List <Tuple <string, string, string, string> > >();
            foreach (var item in countryMapsUrlHash)
            {
                service.Navigate(item.Item2);
                var elements = service.GetElementsXPath(@"//*[@id='content-core']/div[2]/table/tbody/tr[position() > 1]");
                var listMaps = new List <Tuple <string, string, string, string> >();

                foreach (var trow in elements)
                {
                    var tdataList   = trow.FindElements(By.XPath(@"td"));
                    var jpegHref    = tdataList[4].FindElement(By.XPath(@".//a")).GetAttribute("href");
                    var fullJpegUrl = UriEx.Full(item.Item2, jpegHref);

                    var download = new HttpDownloadFile(fullRootWfDirectory);
                    download.Download(fullJpegUrl, true, ImageFormat.Jpeg);

                    var maps = new Tuple <string, string, string, string>(
                        tdataList[0].Text,
                        tdataList[1].Text, fullJpegUrl, download.LocalFile
                        );

                    listMaps.Add(maps);
                }

                countryMaps.Add(item.Item1, listMaps);
            }
        }
        private async void UpdateFile(object target, File file)
        {
            var content = target as Grid;

            if (content == null)
            {
                return;
            }

            if (content.Children[0] is Image photo)
            {
                photo.Source = await PlaceholderHelper.GetWebPFrameAsync(file.Local.Path, 48);

                ElementCompositionPreview.SetElementChildVisual(content.Children[0], null);
            }
            else if (content.Children[0] is LottieView lottie)
            {
                lottie.Source = UriEx.ToLocal(file.Local.Path);
                _handler.ThrottleVisibleItems();
            }
            else if (content.Children[0] is AnimationView animation)
            {
                animation.Source = new LocalVideoSource(file);
                _handler.ThrottleVisibleItems();
            }
        }
Example #15
0
        private void Play(Grid parent, GalleryContent item, File file)
        {
            try
            {
                if (!file.Local.IsDownloadingCompleted && !SettingsService.Current.IsStreamingEnabled)
                {
                    return;
                }

                if (_surface != null && _mediaPlayerElement != null)
                {
                    _surface.Children.Remove(_mediaPlayerElement);
                    _surface = null;
                }

                if (_mediaPlayer == null)
                {
                    _mediaPlayer = Task.Run(() => new MediaPlayer()).Result;
                    _mediaPlayer.VolumeChanged += OnVolumeChanged;
                    _mediaPlayer.SourceChanged += OnSourceChanged;
                    _mediaPlayer.MediaOpened   += OnMediaOpened;
                    _mediaPlayer.PlaybackSession.PlaybackStateChanged += OnPlaybackStateChanged;
                    _mediaPlayerElement.SetMediaPlayer(_mediaPlayer);
                }

                var dpi = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f;
                _mediaPlayer.SetSurfaceSize(new Size(parent.ActualWidth * dpi, parent.ActualHeight * dpi));

                _surface = parent;
                _surface.Children.Add(_mediaPlayerElement);

                if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.MediaTransportControls", "ShowAndHideAutomatically"))
                {
                    Transport.ShowAndHideAutomatically = true;
                }

                Transport.DownloadMaximum = file.Size;
                Transport.DownloadValue   = file.Local.DownloadOffset + file.Local.DownloadedPrefixSize;

                var streamable = SettingsService.Current.IsStreamingEnabled && item.IsStreamable /*&& !file.Local.IsDownloadingCompleted*/;
                if (streamable)
                {
                    _streamingInterop   = new RemoteFileStream(item.ProtoService, file, TimeSpan.FromSeconds(item.Duration));
                    _mediaPlayer.Source = MediaSource.CreateFromStream(_streamingInterop, item.MimeType);

                    Transport.DownloadMaximum = file.Size;
                    Transport.DownloadValue   = file.Local.DownloadOffset + file.Local.DownloadedPrefixSize;
                }
                else
                {
                    _mediaPlayer.Source = MediaSource.CreateFromUri(UriEx.GetLocal(file.Local.Path));
                }

                _mediaPlayer.IsLoopingEnabled = item.IsLoop;
                _mediaPlayer.Play();
            }
            catch { }
        }
        private async void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            if (args.InRecycleQueue)
            {
                return;
            }

            var content    = args.ItemContainer.ContentTemplateRoot as Grid;
            var stickerSet = args.Item as StickerSetInfo;

            var title = content.Children[1] as TextBlock;

            title.Text = stickerSet.Title;

            var subtitle = content.Children[2] as TextBlock;

            subtitle.Text = Locale.Declension("Stickers", stickerSet.Size);

            var file = stickerSet.GetThumbnail(out var outline, out _);

            if (file == null)
            {
                return;
            }

            if (file.Local.IsDownloadingCompleted)
            {
                if (content.Children[0] is Image photo)
                {
                    photo.Source = await PlaceholderHelper.GetWebPFrameAsync(file.Local.Path, 48);

                    ElementCompositionPreview.SetElementChildVisual(content.Children[0], null);
                }
                else if (args.Phase == 0 && content.Children[0] is LottieView lottie)
                {
                    lottie.Source = UriEx.ToLocal(file.Local.Path);
                }
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
            {
                if (content.Children[0] is Image photo)
                {
                    photo.Source = null;
                }
                else if (args.Phase == 0 && content.Children[0] is LottieView lottie)
                {
                    lottie.Source = null;
                }

                CompositionPathParser.ParseThumbnail(outline, out ShapeVisual visual, false);
                ElementCompositionPreview.SetElementChildVisual(content.Children[0], visual);

                _filesMap[file.Id].Add(stickerSet);
                ViewModel.ProtoService.DownloadFile(file.Id, 1);
            }

            args.Handled = true;
        }
 private void UpdateThumbnail(object target, File file)
 {
     if (target is Image photo)
     {
         photo.Source = new BitmapImage {
             UriSource = UriEx.ToLocal(file.Local.Path), DecodePixelWidth = 40, DecodePixelHeight = 40
         };
     }
 }
Example #18
0
        public void PlayPremium(MessageViewModel message, Sticker sticker)
        {
            if (Interactions == null)
            {
                InteractionsPopup = GetTemplateChild(nameof(InteractionsPopup)) as Popup;
                Interactions      = GetTemplateChild(nameof(Interactions)) as Grid;
            }

            var file = sticker.PremiumAnimation;

            if (file.Local.IsFileExisting() && Interactions.Children.Count < 1)
            {
                var dispatcher = DispatcherQueue.GetForCurrentThread();

                var player = new LottieView();
                player.Width            = 270;
                player.Height           = 270;
                player.IsFlipped        = !message.IsOutgoing;
                player.IsLoopingEnabled = false;
                player.IsHitTestVisible = false;
                player.FrameSize        = new Size(270 * 2, 270 * 2);
                player.Source           = UriEx.ToLocal(file.Local.Path);
                player.PositionChanged += (s, args) =>
                {
                    if (args == 1)
                    {
                        dispatcher.TryEnqueue(() =>
                        {
                            Interactions.Children.Remove(player);
                            InteractionsPopup.IsOpen = false;
                        });
                    }
                };

                var left   = 75;
                var right  = 15;
                var top    = 45;
                var bottom = 45;

                if (message.IsOutgoing)
                {
                    player.Margin = new Thickness(-left, -top, -right, -bottom);
                }
                else
                {
                    player.Margin = new Thickness(-right, -top, -left, -bottom);
                }

                Interactions.Children.Add(player);
                InteractionsPopup.IsOpen = true;
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
            {
                message.Delegate.DownloadFile(message, file);
                UpdateManager.Subscribe(this, message, file, ref _interactionToken, UpdateFile, true);
            }
        }
Example #19
0
        private void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            if (args.InRecycleQueue)
            {
                return;
            }

            var wallpaper = args.Item as Background;
            var root      = args.ItemContainer.ContentTemplateRoot as Grid;

            var preview = root.Children[0] as ChatBackgroundPreview;
            var content = root.Children[1] as Image;
            var check   = root.Children[2];

            check.Visibility = wallpaper == ViewModel.SelectedItem ? Visibility.Visible : Visibility.Collapsed;

            if (wallpaper.Document != null)
            {
                if (wallpaper.Type is BackgroundTypePattern pattern)
                {
                    content.Opacity = pattern.Intensity / 100d;
                    preview.Fill    = pattern.Fill;
                }
                else
                {
                    content.Opacity = 1;
                    preview.Fill    = null;
                }

                var small = wallpaper.Document.Thumbnail;
                if (small == null)
                {
                    return;
                }

                var file = small.File;
                if (file.Local.IsDownloadingCompleted)
                {
                    content.Source = UriEx.ToBitmap(file.Local.Path, wallpaper.Document.Thumbnail.Width, wallpaper.Document.Thumbnail.Height);
                }
                else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
                {
                    content.Source = null;

                    _backgrounds[file.Id].Add(wallpaper);
                    ViewModel.ProtoService.DownloadFile(file.Id, 1);
                }
            }
            else if (wallpaper.Type is BackgroundTypeFill fill)
            {
                content.Opacity = 1;
                preview.Fill    = fill.Fill;
                content.Source  = null;
            }
        }
        private void GetListofCountryAndMapsLinks()
        {
            countryMapsUrlHash = new List <Tuple <string, string> >();
            var optionsCountryMapsLinks = service.GetElementsXPath(@"//*[@id='ciaSelectPublication']/fieldset/select/option[position() > 1]");

            foreach (var element in optionsCountryMapsLinks)
            {
                countryMapsUrlHash.Add(new Tuple <string, string>(
                                           element.Text, UriEx.Full(wfUrl, element.GetAttribute("value"))));
            }
        }
Example #21
0
 private void UpdateThumbnail(MessageViewModel message, File file)
 {
     if (file.Local.IsFileExisting())
     {
         Texture.Source = new BitmapImage(UriEx.ToLocal(file.Local.Path));
     }
     else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
     {
         message.ProtoService.DownloadFile(file.Id, 1);
     }
 }
Example #22
0
        private void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            var content   = args.ItemContainer.ContentTemplateRoot as Border;
            var animation = args.Item as Animation;

            if (args.InRecycleQueue)
            {
                if (content.Child is AnimationView recycle)
                {
                    recycle.Source = null;
                }

                return;
            }

            var view = content.Child as AnimationView;

            var file = animation.AnimationValue;

            if (file == null)
            {
                return;
            }

            if (file.Local.IsDownloadingCompleted)
            {
                view.Source    = new LocalVideoSource(file);
                view.Thumbnail = null;
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
            {
                view.Source = null;
                DownloadFile(file.Id, animation);

                var thumbnail = animation.Thumbnail?.File;
                if (thumbnail != null)
                {
                    if (thumbnail.Local.IsDownloadingCompleted)
                    {
                        view.Thumbnail = new BitmapImage(UriEx.ToLocal(thumbnail.Local.Path));
                    }
                    else if (thumbnail.Local.CanBeDownloaded && !thumbnail.Local.IsDownloadingActive)
                    {
                        view.Thumbnail = null;
                        DownloadFile(thumbnail.Id, animation);
                    }
                }
            }
        }
Example #23
0
        public void UpdateFile(File file)
        {
            if (!file.Local.IsDownloadingCompleted)
            {
                return;
            }

            if (_thumbnails.TryGetValue(file.Id, out List <InlineQueryResult> items) && items.Count > 0)
            {
                foreach (var result in items)
                {
                    result.UpdateFile(file);

                    var index = ViewModel.InlineBotResults?.IndexOf(result) ?? -1;
                    if (index < 0)
                    {
                        continue;
                    }

                    var button = Repeater.TryGetElement(index) as Button;
                    if (button == null)
                    {
                        continue;
                    }

                    var content = button.Content as Grid;
                    if (content.Children[0] is Image image)
                    {
                        if (result is InlineQueryResultPhoto or InlineQueryResultVideo)
                        {
                            image.Source = new BitmapImage(UriEx.ToLocal(file.Local.Path));
                        }
                        else if (result is InlineQueryResultSticker)
                        {
                            image.Source = PlaceholderHelper.GetWebPFrame(file.Local.Path);
                        }
                    }
                    else if (content.Children[0] is AnimationView animationView)
                    {
                        animationView.Thumbnail = new BitmapImage(UriEx.ToLocal(file.Local.Path));
                    }
                    else if (content.Children[0] is Grid presenter)
                    {
                        //var presenter = content.Children[0] as Grid;
                        var thumb = presenter.Children[0] as Image;
                        thumb.Source = new BitmapImage(UriEx.ToLocal(file.Local.Path));
                    }
                }
Example #24
0
        private void UpdateFile(object target, File file)
        {
            if (target is Grid content)
            {
                if (content.Children[0] is LottieView stickerView)
                {
                    stickerView.Source = UriEx.ToLocal(file.Local.Path);
                }
                else if (content.Children[0] is AnimationView animationView)
                {
                    animationView.Source = new LocalVideoSource(file);
                }
            }

            _handler.ThrottleVisibleItems();
        }
        public void UpdateSticker()
        {
            var index = _index + 1;

            if (index >= _stickers.Count)
            {
                index = 0;
            }

            var sticker = _stickers[index];

            Animation1.Source        = UriEx.ToLocal(sticker.StickerValue.Local.Path);
            PremiumAnimation1.Source = UriEx.ToLocal(sticker.PremiumAnimation.Local.Path);

            _index = index;
            PreloadSticker();
        }
Example #26
0
 private void UpdateThumbnail(object target, File file)
 {
     if (target is Image image)
     {
         if (image.Tag is InlineQueryResultSticker)
         {
             image.Source = PlaceholderHelper.GetWebPFrame(file.Local.Path);
         }
         else
         {
             image.Source = new BitmapImage(UriEx.ToLocal(file.Local.Path));
         }
     }
     else if (target is AnimationView animationView)
     {
         animationView.Thumbnail = new BitmapImage(UriEx.ToLocal(file.Local.Path));
     }
 }
        public void UpdateFile(MessageViewModel message, File file)
        {
            var text = message.Content as MessageText;

            if (text == null || !_templateApplied)
            {
                return;
            }

            var webPage = text.WebPage;

            if (webPage == null)
            {
                return;
            }

            var small = webPage.Photo?.GetSmall();

            if (small == null)
            {
                return;
            }

            if (small.Photo.Id != file.Id)
            {
                return;
            }

            if (file.Local.IsDownloadingCompleted)
            {
                double ratioX = (double)48 / small.Width;
                double ratioY = (double)48 / small.Height;
                double ratio  = Math.Max(ratioX, ratioY);

                var width  = (int)(small.Width * ratio);
                var height = (int)(small.Height * ratio);

                Texture.Source = UriEx.ToBitmap(file.Local.Path, width, height);
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive)
            {
                message.ProtoService.DownloadFile(file.Id, 1);
            }
        }
Example #28
0
        private void ExtractUriTasks(Tweet tweet)
        {
            if (tweet.Status.Entities != null && tweet.Status.Entities.UrlEntities != null)
            {
                foreach (var urlmentions in tweet.Status.Entities.UrlEntities)
                {
                    var link = new UriEx(urlmentions.ExpandedUrl);
                    UriActions.Add(new KeyValuePair <string, Action>(link.Uri.Authority, () => CreateUriAction(link, () => ProcessingComplete(tweet, link, urlmentions))));
                    tweet.Links.Add(link);
                    tweet.TweetText = tweet.Status.Text.Replace(urlmentions.Url, "<a target=\"_blank\" href=\"" + urlmentions.ExpandedUrl + "\">[" + link.Title + "]</a>");
                }
            }
            if (tweet.Status.Entities != null && tweet.Status.Entities.MediaEntities != null)
            {
                foreach (var media in tweet.Status.Entities.MediaEntities)
                {
                    var link = new UriEx(media.ExpandedUrl);
                    UriActions.Add(new KeyValuePair <string, Action>(link.Uri.Authority, () => CreateUriAction(link, () => ProcessingComplete(tweet, link, media))));
                    tweet.Links.Add(link);
                    tweet.TweetText = tweet.Status.Text.Replace(media.Url, "<a target=\"_blank\" href=\"" + media.ExpandedUrl + "\">[" + link.Title + "]</a>");
                }
            }

            /*
             * if (Links.Count == 0 && !string.IsNullOrEmpty(Status.Text))
             * {
             *  var regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
             *  var matches = regx.Matches(Status.Text);
             *  for (int i = 0; i < matches.Count; i++ )
             *  {
             *      var m = matches[i];
             *      var link = new UriEx(m.Value);
             *      CompletionTasks.Add(link.CreateProcessUriTask(l =>
             *          {
             *              TweetText = Status.Text.Replace(m.Value, "<a target=\"_blank\" href=\"" + m.Value + "\">[" + l.Title + "]</a>");
             *          }));
             *      link.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler((x, y) => { base.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Links")); });
             *      Links.Add(link);
             *      TweetText = Status.Text.Replace(m.Value, "<a target=\"_blank\" href=\"" + m.Value + "\">[" + link.Title + "]</a>");
             *  }
             * }
             */
        }
Example #29
0
        private static async Task <List <Bitmap> > ExtractImageContent(UriEx uriex, HtmlAgilityPack.HtmlDocument doc)
        {
            var images       = new List <Bitmap>();
            var strongFilter = false;
            var imageNodes   = doc.DocumentNode.SelectNodes("//article/descendant-or-self::img");

            if (imageNodes == null && !string.IsNullOrEmpty(uriex.Title))
            {
                var titleNode = doc.DocumentNode.SelectNodes("//body/descendant-or-self::*[starts-with(., '" + uriex.Title.Split('\'')[0] + "')]");
                if (titleNode != null)
                {
                    imageNodes   = titleNode.FirstOrDefault().ParentNode.SelectNodes("/descendant-or-self::img");
                    strongFilter = true;
                }
            }

            if (imageNodes != null)
            {
                var imageUrls = imageNodes
                                .Where(i => i.Attributes["src"] != null &&
                                       i.Attributes["src"].Value != null)
                                .Select(i => { try { return(new Uri(i.Attributes["src"].Value)); } catch { return(null); } })
                                .Where(x => x != null && (!strongFilter || x.Host == uriex.Uri.Host));
                foreach (var imageUrl in imageUrls)
                {
                    try
                    {
                        using (var resp = await imageUrl.GetWebRequest(15000, 15000).GetResponseAsync())
                        {
                            var img = new Bitmap(resp.GetResponseStream());
                            images.Add(img);
                        }
                    }
                    catch (Exception ex) { }
                }
                return(images);
            }
            else
            {
                return(new List <Bitmap>());
            }
        }
        public void Handle(UpdateFile update)
        {
            if (!update.File.Local.IsDownloadingCompleted)
            {
                return;
            }

            if (_filesMap.TryGetValue(update.File.Id, out List <StickerSetInfo> stickers))
            {
                this.BeginOnUIThread(async() =>
                {
                    foreach (var stickerSet in stickers.ToImmutableHashSet())
                    {
                        stickerSet.UpdateFile(update.File);

                        var container = List.ContainerFromItem(stickerSet) as SelectorItem;
                        if (container == null)
                        {
                            continue;
                        }

                        var content = container.ContentTemplateRoot as Grid;
                        if (content == null)
                        {
                            continue;
                        }

                        if (content.Children[0] is Image photo)
                        {
                            photo.Source = await PlaceholderHelper.GetWebPFrameAsync(update.File.Local.Path, 48);
                            ElementCompositionPreview.SetElementChildVisual(content.Children[0], null);
                        }
                        else if (content.Children[0] is LottieView lottie)
                        {
                            lottie.Source = UriEx.ToLocal(update.File.Local.Path);
                            _handler.ThrottleVisibleItems();
                        }
                    }
                });
            }
        }
Example #31
0
        private void ProcessingComplete(Tweet tweet, UriEx l, object m)
        {
            if (m is UrlEntity || m is MediaEntity)
            {
                tweet.TweetText = tweet.Status.Text.Replace(((dynamic)m).Url, "<a target=\"_blank\" href=\"" + l.Uri + "\">[" + l.Title + "]</a>");
            }

            if (l.Image != null && tweet.Image == null)
            {
                try
                {
                    using (var response = l.Image.GetWebRequest().GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null && responseStream.CanRead)
                            {
                                var imgData = new byte[responseStream.Length];
                                responseStream.Read(imgData, 0, imgData.Length);
                                using (var memstrm = new MemoryStream(imgData))
                                {
                                    tweet.Image = (Bitmap)Bitmap.FromStream(memstrm);
                                }
                            }
                        }
                    }
                }
                catch { }
            }
        }
        private List<Uri> ExtractImageUris(UriEx uriex, HtmlAgilityPack.HtmlDocument doc)
        {
            var images = new List<Uri>();
            var strongFilter = false;
            var imageNodes = doc.DocumentNode.SelectNodes("//article/descendant-or-self::img");
            if (imageNodes == null && !string.IsNullOrEmpty(uriex.Title))
            {
                var titleNode = doc.DocumentNode.SelectNodes("//body/descendant-or-self::*[starts-with(., '" + uriex.Title.Split('\'')[0] + "')]");
                if (titleNode != null)
                {
                    imageNodes = titleNode.FirstOrDefault().ParentNode.SelectNodes("/descendant-or-self::img");
                    strongFilter = true;
                }
            }

            if (imageNodes != null)
            {
                var imageUrls = imageNodes
                    .Where(i => i.Attributes["src"] != null &&
                        i.Attributes["src"].Value != null)
                    .Select(i => { try { return new Uri(i.Attributes["src"].Value); } catch { return null; } })
                    .Where(x => x != null && (!strongFilter || x.Host == uriex.Uri.Host))
                    .ToList();
                return imageUrls;
            }
            else
                return new List<Uri>();
        }
Example #33
0
        public void CreateUriAction(UriEx uriex, Action Finished)
        {
            uriex.Init();

            uriex.UrlTweetCount = uriex.Uri.GetTweetCount();
            uriex.UrlFacebookShareCount = uriex.Uri.GetFacebookShareCount();

            if (uriex.IsHtmlContentUrl)
            {
                var doc = new HtmlAgilityPack.HtmlDocument();
                try
                {
                    var req = uriex.Uri.GetWebRequest();
                    using (var resp = req.GetResponse())
                    {
                        using (var reader = new StreamReader(resp.GetResponseStream(), true))
                        {
                            doc.Load(reader);
                        }
                    }
                }
                catch(Exception ex)
                {
                    ex = ex;
                }
                if (doc.DocumentNode != null)
                {
                    var nodes = doc.DocumentNode.SelectNodes("//title");
                    if (nodes != null && nodes.Count > 0)
                    {
                        uriex.Title = nodes.First().InnerText.Trim();
                    }

                    nodes = doc.DocumentNode.SelectNodes("//link");
                    if (nodes != null && nodes.Count > 0)
                    {
                        var ogMeta = nodes
                            .Where(m => m.Attributes.SingleOrDefault(a => a.Name.ToLower() == "rel" && a.Value.ToLower().StartsWith("image_src")) != null)
                            .Select(m =>
                            new
                            {
                                Property = m.Attributes["rel"].Value.ToLower(),
                                Content = m.Attributes["href"].Value
                            });
                        if (ogMeta != null && ogMeta.Count() > 0)
                        {
                            uriex.Image = ogMeta.Where(x => x.Property == "image_src").Select(x => CreateUriSafely(uriex.Uri, x.Content)).FirstOrDefault();
                        }
                    }

                    nodes = doc.DocumentNode.SelectNodes("//meta");
                    if (nodes != null && nodes.Count > 0)
                    {
                        var ogMeta = nodes
                            .Where(m => m.Attributes.SingleOrDefault(a => a.Name.ToLower() == "property" && a.Value.ToLower().StartsWith("og:")) != null)
                            .Select(m =>
                            new
                            {
                                Property = m.Attributes["property"].Value.ToLower(),
                                Content = m.Attributes["content"] != null ? m.Attributes["content"].Value : (m.Attributes["value"] != null ? m.Attributes["value"].Value : "")
                            });
                        if (ogMeta != null && ogMeta.Count() > 0)
                        {
                            uriex.Title = (ogMeta.Where(x => x.Property == "og:title" && !string.IsNullOrEmpty(x.Content)).Select(x => x.Content).FirstOrDefault() ?? "").Trim();
                            uriex.Description = ogMeta.Where(x => x.Property == "og:description" && !string.IsNullOrEmpty(x.Content)).Select(x => x.Content).FirstOrDefault() ?? "";
                            uriex.Image = ogMeta.Where(x => x.Property == "og:image" && !string.IsNullOrEmpty(x.Content)).Select(x => CreateUriSafely(uriex.Uri, x.Content)).FirstOrDefault();
                            uriex.Video = ogMeta.Where(x => x.Property == "og:video" && !string.IsNullOrEmpty(x.Content)).Select(x => CreateUriSafely(uriex.Uri, x.Content)).FirstOrDefault();
                            uriex.Video = CleanYouTube(uriex.Video);
                        }

                        var twitterMeta = nodes
                            .Where(m => m.Attributes.SingleOrDefault(a => a.Name.ToLower() == "property" && a.Value.ToLower().StartsWith("twitter:")) != null)
                            .Select(m =>
                            new
                            {
                                Property = m.Attributes["property"].Value.ToLower(),
                                Content = m.Attributes["content"] != null ? m.Attributes["content"].Value : (m.Attributes["value"] != null ? m.Attributes["value"].Value : "")
                            });
                        if (twitterMeta != null && twitterMeta.Count() > 0)
                        {
                            if(string.IsNullOrEmpty(uriex.Title))
                                uriex.Title = (twitterMeta.Where(x => x.Property == "twitter:title" && !string.IsNullOrEmpty(x.Content)).Select(x => x.Content).FirstOrDefault() ?? "").Trim();
                            if (string.IsNullOrEmpty(uriex.Description))
                                uriex.Description = twitterMeta.Where(x => x.Property == "twitter:description" && !string.IsNullOrEmpty(x.Content)).Select(x => x.Content).FirstOrDefault() ?? "";
                            if (uriex.Image == null)
                                uriex.Image = twitterMeta.Where(x => x.Property == "twitter:image" && !string.IsNullOrEmpty(x.Content)).Select(x => CreateUriSafely(uriex.Uri, x.Content)).FirstOrDefault();
                            if (uriex.Video == null)
                            {
                                uriex.Video = twitterMeta.Where(x => x.Property == "twitter:player" && !string.IsNullOrEmpty(x.Content)).Select(x => CreateUriSafely(uriex.Uri, x.Content)).FirstOrDefault();
                                uriex.Video = CleanYouTube(uriex.Video);
                            }
                        }
                    }

                    if(uriex.Video == null)
                    {
                        nodes = doc.DocumentNode.SelectNodes("//iframe");
                        if (nodes != null && nodes.Count > 0)
                        {
                            var iframes = nodes
                            .Where(i => i.Attributes["src"] != null && i.Attributes["src"].Value.ToLower().StartsWith(YOUTUBE_EMBED))
                            .Select(i => i.Attributes["src"].Value);

                            if (iframes.Count() > 0)
                                uriex.Video = new Uri(iframes.FirstOrDefault());
                        }
                    }
                }
            }
            else if(uriex.IsImageContentUrl)
            {
                    uriex.Image = uriex.Uri;
                    uriex.Title = uriex.Uri.ToString();
            }

            Finished();
        }
Example #34
0
 private void ExtractUriTasks(Tweet tweet)
 {
     if (tweet.Status.Entities != null && tweet.Status.Entities.UrlEntities != null)
     {
         foreach (var urlmentions in tweet.Status.Entities.UrlEntities)
         {
             var link = new UriEx(urlmentions.ExpandedUrl);
             UriActions.Add(new KeyValuePair<string, Action>(link.Uri.Authority, () => CreateUriAction(link, () => ProcessingComplete(tweet, link, urlmentions))));
             tweet.Links.Add(link);
             tweet.TweetText = tweet.Status.Text.Replace(urlmentions.Url, "<a target=\"_blank\" href=\"" + urlmentions.ExpandedUrl + "\">[" + link.Title + "]</a>");
         }
     }
     if (tweet.Status.Entities != null && tweet.Status.Entities.MediaEntities != null)
     {
         foreach (var media in tweet.Status.Entities.MediaEntities)
         {
             var link = new UriEx(media.ExpandedUrl);
             UriActions.Add(new KeyValuePair<string, Action>(link.Uri.Authority, () => CreateUriAction(link, () => ProcessingComplete(tweet, link, media))));
             tweet.Links.Add(link);
             tweet.TweetText = tweet.Status.Text.Replace(media.Url, "<a target=\"_blank\" href=\"" + media.ExpandedUrl + "\">[" + link.Title + "]</a>");
         }
     }
     /*
     if (Links.Count == 0 && !string.IsNullOrEmpty(Status.Text))
     {
         var regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
         var matches = regx.Matches(Status.Text);
         for (int i = 0; i < matches.Count; i++ )
         {
             var m = matches[i];
             var link = new UriEx(m.Value);
             CompletionTasks.Add(link.CreateProcessUriTask(l =>
                 {
                     TweetText = Status.Text.Replace(m.Value, "<a target=\"_blank\" href=\"" + m.Value + "\">[" + l.Title + "]</a>");
                 }));
             link.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler((x, y) => { base.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Links")); });
             Links.Add(link);
             TweetText = Status.Text.Replace(m.Value, "<a target=\"_blank\" href=\"" + m.Value + "\">[" + link.Title + "]</a>");
         }
     }
      */
 }
Example #35
0
        private static async Task<List<Bitmap>> ExtractImageContent(UriEx uriex, HtmlAgilityPack.HtmlDocument doc)
        {
            var images = new List<Bitmap>();
            var strongFilter = false;
            var imageNodes = doc.DocumentNode.SelectNodes("//article/descendant-or-self::img");
            if (imageNodes == null && !string.IsNullOrEmpty(uriex.Title))
            {
                var titleNode = doc.DocumentNode.SelectNodes("//body/descendant-or-self::*[starts-with(., '" + uriex.Title.Split('\'')[0] + "')]");
                if (titleNode != null)
                {
                    imageNodes = titleNode.FirstOrDefault().ParentNode.SelectNodes("/descendant-or-self::img");
                    strongFilter = true;
                }
            }

            if (imageNodes != null)
            {
                var imageUrls = imageNodes
                    .Where(i => i.Attributes["src"] != null &&
                        i.Attributes["src"].Value != null)
                    .Select(i => { try { return new Uri(i.Attributes["src"].Value); } catch { return null; } })
                    .Where(x => x != null && (!strongFilter || x.Host == uriex.Uri.Host));
                foreach (var imageUrl in imageUrls)
                {
                    try
                    {
                        using (var resp = await imageUrl.GetWebRequest(15000, 15000).GetResponseAsync())
                        {
                            var img = new Bitmap(resp.GetResponseStream());
                            images.Add(img);
                        }
                    }
                    catch (Exception ex) { }
                }
                return images;
            }
            else
                return new List<Bitmap>();
        }