Exemplo n.º 1
0
 public ThumbnailViewModel(YoutubeModel youtubeModel)
 {
     this.Id          = youtubeModel.Id;
     this.Title       = youtubeModel.Title;
     this.ImageUrl    = youtubeModel.ImageUrl;
     this.Description = youtubeModel.Description;
     this.Type        = ThumbnailType.Youtube;
 }
Exemplo n.º 2
0
        public async Task TestDownload()
        {
            _ytModel = await _ytHandler.DownloadVideoAsync(_ytAddress);

            Assert.NotNull(_ytModel);

            var fileExists = File.Exists(_ytModel.Path);

            Assert.True(fileExists);
        }
Exemplo n.º 3
0
        public YoutubeViewModel(YoutubeModel model)
        {
            this.model = model;

            //dinamically link the properties of the model through the viewmodel
            //only works if the property names are the same.
            model.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
            {
                this.GetType()
                .GetProperties()
                .FirstOrDefault((pi) => pi.Name == e.PropertyName)
                .SetValue(this, sender.GetType()
                          .GetProperties()
                          .FirstOrDefault((pi) => pi.Name == e.PropertyName)
                          .GetValue(sender));
            };

            model.DownloadFinished += delegate(object sender, EventArgs e)
            {
                if (this.Model_DownloadFinished != null)
                {
                    Model_DownloadFinished(this, EventArgs.Empty);
                }
            };

            YoutubeDownloadVideoCommand = new DelegateCommand(param =>
            {
                try
                {
                    model.DownloadVideo();
                }
                catch { }
            });
            YoutubeUrlTextChangedCommand = new DelegateCommand(param =>
            {
                try
                {
                    model.GetVideoQualityOptions();
                }
                catch { }
            });

            TwitcherWindowCommand = new DelegateCommand(param =>
            {
                OnTwitcherWindowCommandInvoked();
            });
        }
Exemplo n.º 4
0
        public async void GetYoutubeVideos(Action <List <YoutubeModel> > callback)
        {
            string[] keyword = new string[5] {
                "easyrecipes", "indian simple recipes", "best snacks recipes", "best desserts recipes", "best non-vegetarian recipes"
            };

            int    d      = rnd.Next(0, 4);
            string keywrd = keyword[d];

            Task.Run(async() =>
            {
                try
                {
                    List <YoutubeModel> vds = new List <YoutubeModel>();
                    string url   = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + keywrd + "&key=AIzaSyAkgdpxDgH9PtvbiLxhT2i5TA71n-eAUrc&maxResults=50";
                    var response = await GetResponse(url);
                    if (response != null && response.IsSuccess)
                    {
                        var dat = Newtonsoft.Json.JsonConvert.DeserializeObject <YoutubeSearchRoot>(response.Content);
                        if (dat != null && dat.items != null)
                        {
                            foreach (var item in dat.items)
                            {
                                YoutubeModel dt = new YoutubeModel();
                                dt.Title        = item.snippet.title;
                                dt.VideoId      = item.id.videoId;
                                dt.Summary      = item.snippet.description;
                                dt.ImageUrl     = item.snippet.thumbnails.high.url;
                                vds.Add(dt);       //dt.EmbedHtmlFragment=
                            }
                        }
                        callback(vds);
                    }
                    else
                    {
                        if (callback != null)
                        {
                            callback(null);
                        }
                    }
                }
                catch (Exception)
                {
                    callback(null);
                }
            });
        }
Exemplo n.º 5
0
        private void App_Startup(object sender, EventArgs e)
        {
            _model     = new TwitcherModel();
            _viewModel = new TwitcherViewModel(_model);

            _viewModel.ExitApplication += delegate(object twitcherViewModelSender, EventArgs twitcherViewModelEventArgs)
            {
                Shutdown();
            };
            _viewModel.YoutubeWindowCommandInvoked += delegate(object twitcherViewModelSender, EventArgs twitcherViewModelEventArgs)
            {
                _view.Hide();

                youtubeModel     = new YoutubeModel();
                youtubeViewModel = new YoutubeViewModel(youtubeModel);

                youtubeWindow             = new YoutubeWindow();
                youtubeWindow.DataContext = youtubeViewModel;

                youtubeViewModel.TwitcherCommandInvoked += delegate(object youtubeViewModelSender, EventArgs youtubeViewModelEventArgs)
                {
                    youtubeWindow.Close();

                    _view.Show();
                };

                youtubeViewModel.Model_DownloadFinished += delegate(object youtubeViewModelSender, EventArgs youtubeViewModelEventArgs)
                {
                    MessageBox.Show("Download finished!", "Youtube video download", MessageBoxButton.OK);
                };

                youtubeWindow.Show();
            };


            _view             = new MainWindow();
            _view.DataContext = _viewModel;

            _view.Show();
        }
Exemplo n.º 6
0
        public async Task <YoutubeResultModel> Link(string token, [FromBody] YoutubeModel data)
        {
            int lang = data.Lang;

            if (lang < 3 || lang > 4)
            {
                lang = 2;
            }

            RacLib.RacMsg msgs = RacLib.RacMsg.cache.GetMessage((RacLib.RacMsg.Language)lang);

            YoutubeResultModel yrm = new YoutubeResultModel();

            try
            {
                string machine = HttpContext.Features.Get <IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
                string userId  = SessionCode.ValidateSessionCode(token, machine);
                if (userId != null)
                {
                    Profile prf = Profile.LoadProfile(userId);
                    if (prf != null)
                    {
                        string videoCode = "";

                        if (data.Link.Contains("youtu.be/"))
                        {
                            int idx = data.Link.IndexOf("youtu.be/");

                            int s = idx + 9;

                            for (int i = s; i < data.Link.Length; i++)
                            {
                                if (data.Link[i] == '/' || data.Link[i] == '&' || data.Link[i] == '?')
                                {
                                    break;
                                }

                                videoCode += data.Link[i];
                            }
                        }
                        else
                        {
                            int idx = data.Link.IndexOf("?");

                            string   pars = data.Link.Substring(idx + 1);
                            string[] p    = pars.Split('&');

                            for (int i = 0; i < p.Length; i++)
                            {
                                if (p[i].StartsWith("v="))
                                {
                                    videoCode = p[i].Substring(2);
                                    break;
                                }
                            }
                        }

                        RacLib.BaseLog.log.Log(RacLib.BaseLog.LogType.Informative, "videoCode = '" + videoCode + "'");

                        // Links do youtube e do bitchute

                        yrm.YoutubeLink  = data.Link;
                        yrm.BitchuteLink = "";

                        // Pega a figura

                        string figlink = "https://i.ytimg.com/vi/" + videoCode + "/maxresdefault.jpg";

                        HttpClient          client_fig   = new HttpClient();
                        HttpResponseMessage response_fig = await client_fig.GetAsync(figlink);

                        byte[] imageBytes = await response_fig.Content.ReadAsByteArrayAsync();

                        RacLib.BaseLog.log.Log(RacLib.BaseLog.LogType.Informative, "Got bits");

                        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
                        ms.Write(imageBytes, 0, imageBytes.Length);
                        System.Drawing.Image img = System.Drawing.Image.FromStream(ms, true);

                        int cw = img.Width;
                        int ch = img.Height;

                        int dw = 1280;
                        int dh = 720;

                        float ew = (float)cw / (float)dw;
                        float eh = (float)ch / (float)dh;

                        int px = 0, py = 0;
                        int lw = 0, lh = 0;

                        if (ew == eh) // Nenhum crop necessário, só resize
                        {
                            px = 0;
                            py = 0;
                            lw = cw;
                            lh = ch;
                        }
                        else if (ew > eh) // Tem que cropar na largura
                        {
                            int totw = (int)(cw / eh);
                            px = (totw - dw) / 2;
                            py = 0;

                            lw = (int)(dw * eh);
                            lh = ch;
                        }
                        else if (ew < eh)// Tem que cropar na altura
                        {
                            int toth = (int)(ch / ew);
                            px = 0;
                            py = (toth - dh) / 2;

                            lw = cw;
                            lh = (int)(dh * ew);
                        }

                        ImageAttributes ia = new ImageAttributes();
                        ia.SetWrapMode(WrapMode.TileFlipXY);

                        using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(dw, dh, PixelFormat.Format32bppPArgb))
                        {
                            _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                            using (Graphics _graphic = Graphics.FromImage(_bitmap))
                            {
                                _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                                _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                                _graphic.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceOver;

                                _graphic.Clear(Color.White);

                                _graphic.DrawImage(img, new Rectangle(0, 0, dw, dh), new Rectangle(px, py, lw, lh), GraphicsUnit.Pixel);

                                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                                _bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                yrm.Image = Convert.ToBase64String(stream.ToArray());
                            }
                        }

                        RacLib.BaseLog.log.Log(RacLib.BaseLog.LogType.Informative, "Got image");

                        string apiCall = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + videoCode + "&key=AIzaSyDZyxrWNvN0MLWexTptTPDHzhnXHwebnCU";

                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
                        HttpResponseMessage response = await client.GetAsync(apiCall);

                        string pageContents = await response.Content.ReadAsStringAsync();

                        RacLib.BaseLog.log.Log(RacLib.BaseLog.LogType.Informative, "Got stuff");

                        dynamic stuff = JsonConvert.DeserializeObject(pageContents);

                        if (stuff.items.Count > 0)
                        {
                            yrm.Title       = stuff.items[0].snippet.title;
                            yrm.Description = stuff.items[0].snippet.description;
                            yrm.Tags        = "";

                            try
                            {
                                for (int i = 0; i < stuff.items[0].snippet.tags.Count; i++)
                                {
                                    if (yrm.Tags != "")
                                    {
                                        yrm.Tags += ", ";
                                    }

                                    yrm.Tags += stuff.items[0].snippet.tags[i];
                                }
                            }
                            catch { }

                            RacLib.BaseLog.log.Log(RacLib.BaseLog.LogType.Informative, "Got all");
                        }
                        else
                        {
                            yrm.Result           = (int)RacMsg.Id.InternalError;
                            yrm.ResultComplement = "Não encontrei o vídeo no youtube";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                RacLib.BaseLog.log.Log(RacLib.BaseLog.LogType.Informative, "Exception");
                RacLib.BaseLog.log.Log(ex);

                yrm.Result           = (int)RacMsg.Id.InternalError;
                yrm.ResultComplement = ex.Message;
            }

            return(yrm);
        }
Exemplo n.º 7
0
        //show videos by region code.
        public async Task <ResponseModel> GetVideoList(string regionCode)
        {
            try
            {
                var ApiKey         = "AIzaSyA8hPK8F-8BbO-8H6tQZuiopY5nYES1UR0";
                var model          = new EditVideoPageModel();
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey          = ApiKey,
                    ApplicationName = this.GetType().ToString()
                });

                // get category of US region
                //var categories = youtubeService.VideoCategories.List("snippet");
                //var languages = youtubeService.I18nLanguages.List("snippet");
                //var playList = youtubeService.Playlists.List("snippet");
                //var contents = youtubeService..List("snippet");
                //gapi.client.youtube.videos.list({ part: 'snippet,id', chart: 'mostPopular', regionCode: 'RU', maxResults: 8 })
                //playList.Callbac = true;


                VideosResource.ListRequest search_response = youtubeService.Videos.List("snippet,contentDetails,statistics");
                //search_response.Type = "video";
                search_response.RegionCode = regionCode;
                search_response.Chart      = VideosResource.ListRequest.ChartEnum.MostPopular;
                search_response.MaxResults = 50;
                //search_response.ChannelId = channelId;
                VideoListResponse searchresponse = search_response.Execute();

                List <string> videos    = new List <string>();
                List <string> channels  = new List <string>();
                List <string> playlists = new List <string>();

                // Add each result to the appropriate list, and then display the lists of
                // matching videos, channels, and playlists.
                List <YoutubeModel> searchmodel = new List <YoutubeModel>();
                YoutubeModel        obj         = null;
                foreach (var searchResult in searchresponse.Items)
                {
                    obj               = new YoutubeModel();
                    obj.title         = searchResult.Snippet.Title;
                    obj.regionCode    = regionCode;
                    obj.url           = "https://youtu.be/" + searchResult.Id;
                    obj.description   = searchResult.Snippet.Description;
                    obj.picture       = GetMainImg(searchResult.Snippet.Thumbnails);
                    obj.thumbnail     = GetThumbnailImg(searchResult.Snippet.Thumbnails);
                    obj.publishedAt   = searchResult.Snippet.PublishedAt;
                    obj.channelId     = searchResult.Snippet.ChannelId;
                    obj.channelTitle  = searchResult.Snippet.ChannelTitle;
                    obj.duration      = GetDuration(searchResult.ContentDetails.Duration);
                    obj.viewCount     = searchResult.Statistics.ViewCount.ToString();
                    obj.likeCount     = searchResult.Statistics.LikeCount.ToString();
                    obj.dislikeCount  = searchResult.Statistics.DislikeCount.ToString();
                    obj.favoriteCount = searchResult.Statistics.FavoriteCount.ToString();
                    obj.commentCount  = searchResult.Statistics.CommentCount.ToString();

                    searchmodel.Add(obj);
                    videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, "https://youtu.be/" + searchResult.Id));
                }
                response.Data = searchmodel;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            response.Status_Code = 200;
            response.Success     = true;
            return(response);
        }
        public async Task <IActionResult> Index(YoutubeModel model)
        {
            if (model == null)
            {
                model = new YoutubeModel();
            }

            var api = _dbRepository.GetGoogleApiToUse();

            if (api != null)
            {
                if (string.IsNullOrWhiteSpace(model.CommentText))
                {
                    model.CommentText = _youtubeSettings.CommentDefault;
                }
                if (model.Max == null)
                {
                    model.Max = _youtubeSettings.MaxResultDefault;
                }

                //Stars star = new Stars();

                if (model.SelectedVideo != null && model.SelectedVideo.Count > 0)
                {
                    await _youtubeHelper.Comment(model.SelectedVideo, model.CommentText);
                }

                if (string.IsNullOrWhiteSpace(model.Search))
                {
                    //                    star = await _dbRepository.GetStar();

                    //                    if (star != null)
                    //                    {
                    //                        model.Search = star.Title.Length > 10 ? star.Title : (star.Title + " jav star");
                    //                        model.CommentText = string.Format(@"http://javmile.com/pornstar/{0}
                    //{1} Video Sex, {1} JAV HD, Videos {1}, {1} sex

                    //#{0} #javhd #jav #xxx #asianvideo #p**n #asiansex #sex #18+", star.Slug, star.Title);
                    //                    }

                    model.Search = "football 2019";
                }

                if (!string.IsNullOrWhiteSpace(model.Search) && model.Max != null && model.Max > 0)
                {
                    model.Videos = await _youtubeHelper.Search(model.Search, model.Max.Value, model.Lat, model.Lon, model.Radius, model.PublishedAfter, model.PageToken);

                    if (model.Videos != null && model.Videos.Count > 0)
                    {
                        var videoid = model.Videos.Select(x => x.VideoId).ToList();

                        var commented = _dbRepository.GetYoutubeComment(videoid);

                        foreach (var video in model.Videos)
                        {
                            var c = commented.FirstOrDefault(x => x.VideoId == video.VideoId);
                            if (c != null)
                            {
                                video.CommentedAt = c.CreatedAt;
                            }
                        }
                    }
                }
            }
            return(View(model));
        }
Exemplo n.º 9
0
        public async Task <YoutubeDto> Search(string query)
        {
            var youtubeConfigs = _config.GetSection("YoutubeConfigs");
            var baseUrl        = youtubeConfigs["baseUrl"].ToString();
            var key            = youtubeConfigs["key"].ToString();

            var readerParams = new ReaderParams
            {
                urlParams = new Dictionary <string, string>
                {
                    { "part", "snippet" },
                    { "q", query },
                    { "key", key }
                }
            };

            var youtubeResponse = await _reader.Get <YoutubeResponse>(baseUrl + "search?", readerParams);

            var youtubeDto = new YoutubeDto
            {
                NextPageToken = youtubeResponse.nextPageToken,
            };

            foreach (var item in youtubeResponse.items)
            {
                var ytModel = new YoutubeModel();

                ytModel.Title        = item.snippet.title;
                ytModel.Description  = item.snippet.description;
                ytModel.PublishedAt  = item.snippet.publishedAt;
                ytModel.IsChannel    = false;
                ytModel.ChannelName  = item.snippet.channelTitle;
                ytModel.ThumbnailUrl = item.snippet.thumbnails.medium.url;

                if (item.id.kind == "youtube#channel")
                {
                    ytModel.IsChannel = true;
                    ytModel.youtubeId = item.id.channelId;
                }
                else if (item.id.kind == "youtube#video")
                {
                    ytModel.youtubeId = item.id.videoId;
                }
                else
                {
                    ytModel.youtubeId = item.id.playlistId;
                }

                if (_youtubeRepository.Exists(x => x.youtubeId == ytModel.youtubeId))
                {
                    var res = _youtubeRepository.ListBy(x => x.youtubeId == ytModel.youtubeId).Result.FirstOrDefault();
                    ytModel.Id = res.Id;
                    await _youtubeRepository.Update(ytModel);
                }
                else
                {
                    await _youtubeRepository.Create(ytModel);
                }

                youtubeDto.Items.Add(ytModel);
            }

            return(youtubeDto);
        }
Exemplo n.º 10
0
 public async Task Download(string input)
 {
     _lastDownload = await Youtube.DownloadVideoAsync(input);
 }