コード例 #1
0
 public IActionResult YoutubeStopLiveCallback([FromBody] YoutubeLiveCallbackBody body)
 {
     new Thread(() =>
     {
         var videoId = body.LiveLink.Split('=').Last();
         LogHelper.Info($"将在两个小时后开始爬取 {body.LiveTitle} ({videoId}) 的Live chat replay.");
         Thread.Sleep(1000 * 60 * 60 * 2);
         LogHelper.Info($"开始爬取 {body.LiveTitle} ({videoId}) 的Live chat replay.");
         try
         {
             var replay = YoutubeApi.GetWebLiveChatReplayAsync(videoId).GetAwaiter().GetResult();
             if (replay == null)
             {
                 LogHelper.Info("获取失败.");
                 return;
             }
             Program.Database.GetCollection <YoutubeWebLiveChat>("youtube-web-live-chats").InsertMany(replay);
             LogHelper.Info($"爬取完成,已保存 {replay.Count()} 条live chat.");
         }
         catch (Exception ex)
         {
             LogHelper.Error("出现异常", ex: ex);
         }
     })
     {
         IsBackground = true
     }.Start();
     return(Ok());
 }
コード例 #2
0
        public async Task <IActionResult> GetVideoDetails([Required] string videoIdOrUrl, CancellationToken ct = default(CancellationToken))
        {
            try {
                using (var api = new YoutubeApi(_settingsProvider.ApiKeys.Next())) {
                    var vidId = new VideoUrlParser().GetVideoId(videoIdOrUrl);
                    var vid   = await api.GetVideoDetails(vidId, ct);

                    var vids = vid.Items.Select(v => v.MapToDbEntity()).ToList();
                    if (!vids.Any())
                    {
                        return(NotFound(new ProblemDetails {
                            Status = StatusCodes.Status404NotFound,
                            Title = "Not Found",
                        }));
                    }
                    await _repository.SaveOrUpdate(vids);

                    return(Ok(vids));
                }
            }
            catch (Exception e) {
                return(BadRequest(new ProblemDetails {
                    Status = StatusCodes.Status400BadRequest,
                    Title = e.Message,
                    Type = e.GetType().FullName,
                }));
            }
        }
コード例 #3
0
 public void Search(string search)
 {
     if (search.Any())
     {
         Toggle(true);
         if (SearchList.Count > 0)
         {
             SearchList.Clear();
         }
         Task.Run(async() =>
         {
             // call api to get channels with a text.
             IYoutube api = new YoutubeApi();
             var call     = await api.GetChannels(search);
             Device.BeginInvokeOnMainThread(() =>
             {
                 foreach (var item in call.items)
                 {
                     item.IsActive = App.ChannelsDatastore.Exists(item.ChannelId);
                     SearchList.Add(item);
                 }
                 Console.Out.WriteLine("SearchList " + SearchList.Count);
                 Toggle(false);
             });
         });
     }
 }
コード例 #4
0
        public void Process(ISendMessageService service, MessageInfo message)
        {
            if (!message.IsGroupMessage)
            {
                service.SendToFriend(message.UserMember, "暂不支持好友互动!");
                return;
            }
            var args = message.Content.ToString().Split(' ');

            if (args.Length == 1)
            {
                service.SendToGroup(message.GroupNumber, "使用方法: 查询 <Youtube Id>");
                return;
            }

            var videos = YoutubeApi.GetVideosByChannelId(args[1]);

            if (videos.All(v => !v.IsLive))
            {
                service.SendToGroup(message.GroupNumber, "该频道目前没有直播");
                return;
            }

            var live = videos.First(v => v.IsLive);

            service.SendToGroup(message.GroupNumber, $"频道 {live.ChannelTitle} 当前正在直播中\r\n" +
                                $"Title: {live.Title}\r\n" +
                                $"Description: {live.Description}\r\n" +
                                $"Link: {live.VideoLink}");
        }
コード例 #5
0
 public YoutubeVideosController(DatabaseContext context)
 {
     _context   = context;
     rnd        = new Random();
     parser     = new Parser();
     youtubeApi = new YoutubeApi();
 }
コード例 #6
0
        public async Task <List <SearchResult> > GetVideos([FromBody] SearchHistory searchHistory)
        {
            var ya = new YoutubeApi();
            await ya.Run(searchHistory.SearchTerm);

            _service.InsertHistory(searchHistory);
            return(ya.Videos);
        }
コード例 #7
0
 public YoutubeModule(ChannelServices channelServices, YoutubeApi youtubeApi)
 {
     if (_channelServices == null)
     {
         _channelServices = channelServices;
     }
     if (_youtubeApi == null)
     {
         _youtubeApi = youtubeApi;
     }
 }
コード例 #8
0
 //LD custom exception
 private static void Test005()
 {
     //LD "YoutubeException.cs" and "YoutubeApi.cs"
     try
     {
         YoutubeApi aClassInstance = new YoutubeApi();
         aClassInstance.GetVideos();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
コード例 #9
0
        private void GetChannelActivity(StoredChannel channel, bool force)
        {
            IYoutube api = new YoutubeApi();

            channel.Searching = true;
            if (channel.Activity == null || force)
            {
                Task.Run(() => {
                    Task <YoutubeCall <YoutubeActivity> > result = Task.Run(() => api.GetChannelActivity(channel.ChannelId));
                    var webResult = result.Result;
                    OnActivityReceive(new ChannelActivityEvent(channel.ChannelId, webResult));
                });
            }
        }
コード例 #10
0
        private async Task <List <string> > GetVideoIdsFromList(IEnumerable <string> listIds, string apiKey)
        {
            var videoIds = new List <string>();

            using (var api = new YoutubeApi(apiKey)) {
                foreach (var listId in listIds)
                {
                    var ytVids = await api.GetAllVideosFromPlaylist(listId, _ct);

                    _logger.LogDebug($"found {ytVids.PageInfo.TotalResults} videos for list {listId}");
                    videoIds.AddRange(ytVids.Items.Select(v => v.ContentDetails.VideoId).Where(i => !string.IsNullOrWhiteSpace(i)));
                }
            }
            return(videoIds);
        }
コード例 #11
0
        private async Task <List <string> > GetVideoIdsFromChannels(IEnumerable <string> channelIds, string apiKey)
        {
            var videoIds = new List <string>();

            using (var api = new YoutubeApi(apiKey)) {
                foreach (var channelId in channelIds)
                {
                    var ytVids = await api.GetAllVideosFromChannel(channelId, _ct);

                    _logger.LogDebug($"found {ytVids.PageInfo.TotalResults} Videos for channel {channelId}");
                    videoIds.AddRange(ytVids.Items.Select(v => v.Id.VideoId).Where(i => !string.IsNullOrWhiteSpace(i)));
                }
                return(videoIds);
            }
        }
コード例 #12
0
        private async Task GetCommentsFromVideoIds(IEnumerable <string> videoIds, string apiKey, SyncCounter commentsCnt, SyncCounter updatesCnt, SyncCounter vidCntDown)
        {
            using (var api = new YoutubeApi(apiKey)) {
                foreach (var videoId in videoIds)
                {
                    CommentThreadListResponse ytComments = null;
                    try {
                        ytComments = await api.GetAllCommentsAndAnswersFromVideo(videoId, _ct);
                    }
                    catch (Google.GoogleApiException e) {
                        _logger.LogError($"error getting comments and answers for videoId={videoId} ({e.Message})");
                    }

                    if (ytComments == null)
                    {
                        try {
                            ytComments = await api.GetAllCommentsFromVideo(videoId, _ct);
                        }
                        catch (Google.GoogleApiException e) {
                            _logger.LogError($"error getting comments for videoId={videoId} ({e.Message})");
                        }
                    }


                    vidCntDown.Decrement();
                    if (ytComments == null)
                    {
                        continue;
                    }
                    var dbComments = new List <Comment>();

                    foreach (var thread in ytComments.Items)
                    {
                        var hasAnswers = (thread.Snippet.TotalReplyCount ?? 0) > 0;
                        dbComments.Add(thread.Snippet.TopLevelComment.MapToDbEntity(CommentType.Comment, videoId, hasAnswers));

                        if (hasAnswers && thread.Replies?.Comments != null)
                        {
                            dbComments.AddRange(thread.Replies.Comments.Select(a => a.MapToDbEntity(CommentType.Answer, videoId)));
                        }
                    }
                    commentsCnt.Add(dbComments.Count);
                    var updates = await _repository.SaveOrUpdate(dbComments);

                    updatesCnt.Add(updates);
                }
            }
        }
コード例 #13
0
        private async Task GetAnswersFromComments(IEnumerable <CommentBase> parents, string apiKey, SyncCounter answersCounter, SyncCounter updatesCounter, SyncCounter parentsCountDown)
        {
            using (var api = new YoutubeApi(apiKey)) {
                foreach (var parent in parents)
                {
                    var ytComments = await api.GetAllAnswersFromComment(parent.Id, _ct).TryHarder(_logger, ct: _ct);

                    parentsCountDown.Decrement();
                    var dbAnswers = ytComments.Items.Select(i => i.MapToDbEntity(CommentType.Answer, parent.VideoId)).ToList();
                    answersCounter.Add(dbAnswers.Count);
                    var updates = await _repository.SaveOrUpdate(dbAnswers);

                    updatesCounter.Add(updates);
                }
            }
        }
コード例 #14
0
        private async Task <List <Video> > GetVideoFromId(IEnumerable <string> videoIds, string apiKey, SyncCounter videoCountDown, CancellationToken ct)
        {
            var videos = new List <Video>();

            using (var api = new YoutubeApi(apiKey)) {
                foreach (var videoId in videoIds)
                {
                    var ytVid = await api.GetVideoDetails(videoId, ct);

                    var dbVid = ytVid.Items.Select(v => v.MapToDbEntity());
                    videoCountDown.Decrement();
                    videos.AddRange(dbVid);
                }
            }
            return(videos);
        }
コード例 #15
0
        public void StartRecord()
        {
            var num = 0;

            new Thread(() =>
            {
                while (true)
                {
                    var info = YoutubeApi.GetLiveChatInfo(LiveChatId);
                    if (info.PollingInterval == 0 && info.CommentsToken == null)
                    {
                        LiveStoppedEvent?.Invoke(LiveChatId, this);
                        break;
                    }
                    var comments = info.GetComments().Where(comment => RecordedComments.All(v => v.CommentId != comment.CommentId)).ToList();
                    if (comments.Any())
                    {
                        comments.ForEach(v => v.VideoId = VideoId);
                        try
                        {
                            _chatCollection.InsertMany(comments, new InsertManyOptions()
                            {
                                IsOrdered = false
                            });
                            RecordedComments.AddRange(comments);
                        }
                        catch (MongoBulkWriteException)
                        {
                            Thread.Sleep(10000);
                        }
                    }
                    if (++num % 20 == 0)
                    {
                        if (!CacheManager.Manager.LastCheckLiveStatus[Vtuber].IsLive)
                        {
                            LiveStoppedEvent?.Invoke(LiveChatId, this);
                            break;
                        }
                    }
                    Thread.Sleep(info.PollingInterval);
                }
            }).Start();
        }
コード例 #16
0
        private static void ExceptionHandling()
        {
            //using includes a built in finally block that releases the resource when scope is released
            //using (var streamReader = new StreamReader(@"c:\file.zip"))
            //{
            //    var content = streamReader.ReadToEnd();
            //}

            //using a custom exception
            try
            {
                var api    = new YoutubeApi();
                var videos = api.GetVideos("mosh");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                //Channels = Mockup.GetDummyChannels();
            }
            else
            {
                NavListBoxSelectionChangedCommand = new RelayCommand(NavListBoxSelectionChanged);
                MenuItemSettingsCommand           = new RelayCommand(OpenSettings);
                MenuItemExitCommand      = new RelayCommand(ShutdownService.RequestShutdown);
                KeyDownCommand           = new RelayCommand <KeyEventArgs>(KeyDown);
                AddChannelKeyDownCommand = new RelayCommand <KeyEventArgs>(AddChannelKeyDown);
                this.PropertyChanged    += this.MainViewModel_PropertyChanged;

                Channels   = new ObservableCollection <Channel>();
                Videos     = new ObservableCollection <Video>();
                YoutubeApi = new YoutubeApi(Settings.Instance.YoutubeApiKey);
                LoadChannels();
            }
        }
コード例 #18
0
 private void YoutubeLiveCheckTimer(List <VtuberInfo> vtubers)
 {
     foreach (var vtuber in vtubers)
     {
         if (!LastCheckLiveStatus.ContainsKey(vtuber))
         {
             LastCheckLiveStatus.Add(vtuber, new YoutubeVideo());
         }
         var nowLive = YoutubeApi.NowLive(vtuber.YoutubeChannelId);;
         if (nowLive && !LastCheckLiveStatus[vtuber].IsLive)
         {
             var live = YoutubeApi.GetVideosByChannelId(vtuber.YoutubeChannelId).FirstOrDefault(v => v.IsLive);
             if (live == null)
             {
                 var liveId = YoutubeApi.GetLiveVideoId(vtuber.YoutubeChannelId);
                 if (liveId == null)
                 {
                     LogHelper.Error("Error: liveId is null", false);
                     continue;
                 }
                 live = YoutubeApi.GetYoutubeVideo(liveId);
                 if (!live.IsLive)
                 {
                     continue;
                 }
             }
             if (!LastCheckLiveStatus[vtuber].IsLive)
             {
                 VtuberBeginLiveEvent?.Invoke(vtuber, live);
             }
             LastCheckLiveStatus[vtuber] = live;
         }
         if (!nowLive)
         {
             LastCheckLiveStatus[vtuber] = new YoutubeVideo();
         }
     }
 }
コード例 #19
0
 private void YoutubeVideoCheckTimer()
 {
     foreach (var vtuber in Config.DefaultConfig.Vtubers.ToArray().Where(v =>
                                                                         !string.IsNullOrEmpty(v.YoutubeChannelId) && string.IsNullOrEmpty(v.YoutubeUploadsPlaylistId)))
     {
         vtuber.YoutubeUploadsPlaylistId = YoutubeApi.GetUploadsPlaylistId(vtuber.YoutubeChannelId);
         Config.SaveToDefaultFile(Config.DefaultConfig);
         LogHelper.Info($"更新Vtuber {vtuber.OriginalName} Upload playlist id.");
     }
     foreach (var vtuber in Config.DefaultConfig.Vtubers.Where(v => !string.IsNullOrEmpty(v.YoutubeUploadsPlaylistId)))
     {
         var videos = YoutubeApi.GetPlaylistItems(vtuber.YoutubeUploadsPlaylistId, 10);
         if (!LastCheckVideos.ContainsKey(vtuber))
         {
             LastCheckVideos.Add(vtuber, videos);
         }
         if (LastCheckVideos[vtuber].FirstOrDefault()?.VideoId != videos.FirstOrDefault()?.VideoId)
         {
             VtuberUploadVideoEvent?.Invoke(vtuber, videos.First());
         }
         LastCheckVideos[vtuber] = videos;
     }
 }
コード例 #20
0
        public string GetAllMetrics(string youtubeChannelId = "", string twitterUser = "", string twitchUser = "")
        {
            Dictionary <string, dynamic> result = new Dictionary <string, dynamic>();

            if (youtubeChannelId.Length > 0)
            {
                YoutubeApi youtubeApi = new YoutubeApi();
                result.Add("Youtube", youtubeApi.getMetrics(youtubeChannelId));
            }

            if (twitterUser.Length > 0)
            {
                TwitterApi twitterApi = new TwitterApi();
                result.Add("Twitter", twitterApi.getMetrics(twitterUser));
            }

            if (twitchUser.Length > 0)
            {
                TwitchApi twitchApi = new TwitchApi();
                result.Add("Twitch", twitchApi.getMetrics(twitchUser));
            }

            return(JsonConvert.SerializeObject(result));
        }
コード例 #21
0
 public static void TestInitialize(TestContext context)
 {
     youtubeApi = new YoutubeApi();
 }
コード例 #22
0
        public LocalVtuberBot(ISendMessageService service, IServerMessageSubject transponder, QQUser user) : base(service, transponder, user)
        {
            _youtubeLiveCollection = Program.Database.GetCollection <YoutubeLiveInfo>("youtube-live-details");
            _biliLiveCollection    = Program.Database.GetCollection <BiliBiliLiveInfo>("bili-live-details");
            _tweetCollection       = Program.Database.GetCollection <TweetInfo>("tweet-details");
            CacheManager.Manager.VtuberBeginLiveEvent += (vtuber, video) =>
            {
                var info = YoutubeApi.GetYoutubeVideo(video.VideoId);
                LogHelper.Info($"Vtuber {vtuber.OriginalName} 开始了直播 {video.VideoLink}");
                foreach (var(key, value) in Config.DefaultConfig.Subscribes)
                {
                    var config = value.FirstOrDefault(v =>
                                                      string.Equals(v.VtuberName, vtuber.OriginalName, StringComparison.CurrentCultureIgnoreCase));
                    if (config?.BeginLive ?? false)
                    {
                        _service.SendToGroup(key, $"{vtuber.OriginalName} 在 {info.LiveDetails.ActualStartTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss} 开始直播 {video.Title}\r\n" +
                                             $"链接: {video.VideoLink}\r\n当前观众数量: {info.LiveDetails.ViewersCount}\r\n" +
                                             $"原定直播时间: {info.LiveDetails.ScheduledStartTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss}\r\n" +
                                             $"实际开播时间:  {info.LiveDetails.ActualStartTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss}");
                    }
                }

                var recorder = new LiveChatRecorder(info.LiveDetails.LiveChatId, vtuber, video.VideoId);
                recorder.StartRecord();
                recorder.LiveStoppedEvent += (id, recder) =>
                {
                    LogHelper.Info($"{vtuber.OriginalName} 已停止直播, 正在保存评论数据...");
                    info = YoutubeApi.GetYoutubeVideo(video.VideoId) ?? info;
                    var live = new YoutubeLiveInfo()
                    {
                        Title     = info.Title,
                        Channel   = info.ChannelId,
                        BeginTime = info.LiveDetails?.ActualStartTime ?? default(DateTime),
                        EndTime   = info.LiveDetails?.ActualEndTime ?? DateTime.Now,
                        VideoId   = video.VideoId
                    };
                    _youtubeLiveCollection.ReplaceOne(v => v.VideoId == live.VideoId, live,
                                                      new UpdateOptions()
                    {
                        IsUpsert = true
                    });
                    LogHelper.Info("保存完毕");
                };
            };

            CacheManager.Manager.VtuberUploadVideoEvent += (vtuber, video) =>
            {
                LogHelper.Info($"Vtuber {vtuber.OriginalName} 上传了视频 {video.Title}");
                foreach (var(key, value) in Config.DefaultConfig.Subscribes)
                {
                    var config = value.FirstOrDefault(v =>
                                                      string.Equals(v.VtuberName, vtuber.OriginalName, StringComparison.CurrentCultureIgnoreCase));
                    if (config?.UploadVideo ?? false)
                    {
                        _service.SendToGroup(key, $"{vtuber.OriginalName} 在 {video.PublishTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss} 上传了视频 {video.Title}\r\n" +
                                             $"链接: {video.VideoLink}");
                    }
                }
            };

            CacheManager.Manager.VtuberPublishTweetEvent += (vtuber, tweet) =>
            {
                LogHelper.Info($"Vtuber {vtuber.OriginalName} 发布了新的推特 {tweet.Content.Substring(0, 5)}....");
                foreach (var(key, value) in Config.DefaultConfig.Subscribes)
                {
                    var config = value.FirstOrDefault(v =>
                                                      string.Equals(v.VtuberName, vtuber.OriginalName, StringComparison.CurrentCultureIgnoreCase));
                    if (config?.PublishTweet ?? false)
                    {
                        _service.SendToGroup(key, $"{vtuber.OriginalName} 在 {tweet.CreateTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss} 发布了:\r\n" +
                                             $"{(tweet.Content.Length > 255 ? tweet.Content.Substring(0, 255) : tweet.Content)}");
                    }
                }

                try
                {
                    _tweetCollection.InsertOne(tweet);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("Insert object error", true, ex);
                }
            };

            CacheManager.Manager.VtuberReplyTweetEvent += (vtuber, tweet) =>
            {
                LogHelper.Info($"Vtuber {vtuber.OriginalName} 回复了 {tweet.ReplyScreenname} 的推特 {tweet.Content.Substring(0, 5)}....");
                foreach (var(key, value) in Config.DefaultConfig.Subscribes)
                {
                    var config = value.FirstOrDefault(v =>
                                                      string.Equals(v.VtuberName, vtuber.OriginalName, StringComparison.CurrentCultureIgnoreCase));
                    if (config?.ReplyTweet ?? false)
                    {
                        _service.SendToGroup(key, $"{vtuber.OriginalName} 在 {tweet.CreateTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss} 回复了 {tweet.RetweetedTweet}:\r\n" +
                                             $"{(tweet.Content.Length > 255 ? tweet.Content.Substring(0, 255) : tweet.Content)}");
                    }
                }
                try
                {
                    _tweetCollection.InsertOne(tweet);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("Insert object error", true, ex);
                }
            };

            CacheManager.Manager.VtuberRetweetedEvent += (vtuber, tweet) =>
            {
                LogHelper.Info($"Vtuber {vtuber.OriginalName} 转发了 {tweet.RetweetedTweet.User.Name} 的推特: {tweet.Content.Substring(0, 5)}....");
                foreach (var(key, value) in Config.DefaultConfig.Subscribes)
                {
                    var config = value.FirstOrDefault(v =>
                                                      string.Equals(v.VtuberName, vtuber.OriginalName, StringComparison.CurrentCultureIgnoreCase));
                    if (config?.Retweeted ?? false)
                    {
                        _service.SendToGroup(key, $"{vtuber.OriginalName} 在 {tweet.CreateTime.ToUniversalTime().AddHours(8):yyyy-MM-dd HH:mm:ss} 转发了 {tweet.RetweetedTweet.User.Name} 的推:\r\n" +
                                             $"{(tweet.Content.Length > 255 ? tweet.Content.Substring(0, 255) : tweet.Content)}");
                    }
                }
                try
                {
                    _tweetCollection.InsertOne(tweet);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("Insert object error", true, ex);
                }
            };

            CacheManager.Manager.VtuberBeginLiveBilibiliEvent += (vtuber, bUser) =>
            {
                var beginTime = DateTime.Now;
                LogHelper.Info($"Vtuber {vtuber.OriginalName} 在B站开始了直播 {bUser.LiveUrl}");
                foreach (var(key, value) in Config.DefaultConfig.Subscribes)
                {
                    var config = value.FirstOrDefault(v =>
                                                      string.Equals(v.VtuberName, vtuber.OriginalName, StringComparison.CurrentCultureIgnoreCase));
                    if (config?.BilibiliBeginLive ?? false)
                    {
                        _service.SendToGroup(key, $"{vtuber.OriginalName} 在B站开始了直播 {bUser.LiveTitle}\r\n" +
                                             $"链接: {bUser.LiveUrl}");
                    }
                }

                var liveId   = StringTools.RandomString;
                var liveInfo = new BiliBiliLiveInfo()
                {
                    LiveId        = liveId,
                    Title         = bUser.LiveTitle,
                    BeginTime     = beginTime,
                    EndTime       = beginTime,
                    MaxPopularity = 0
                };
                var live = _biliLiveCollection.FindAsync(v => v.MaxPopularity == 0 && v.Title == bUser.LiveTitle)
                           .GetAwaiter().GetResult().FirstOrDefault();
                if (live != null)
                {
                    liveId = live.LiveId;
                }
                else
                {
                    _biliLiveCollection.InsertOne(liveInfo);
                }
                var recorder = new DanmakuRecorder(bUser.LiveRoomId, liveId, vtuber);
                recorder.StartRecord();
                recorder.LiveStoppedEvent += info =>
                {
                    LogHelper.Info($"{vtuber.OriginalName} 已停止在B站的直播.");
                    liveInfo = new BiliBiliLiveInfo()
                    {
                        LiveId        = liveId,
                        Title         = bUser.LiveTitle,
                        BeginTime     = beginTime,
                        EndTime       = DateTime.Now,
                        MaxPopularity = recorder.Client.MaxPopularity
                    };
                    _biliLiveCollection.ReplaceOne(v => v.LiveId == liveInfo.LiveId, liveInfo,
                                                   new UpdateOptions()
                    {
                        IsUpsert = true
                    });
                };
            };
        }
コード例 #23
0
        private void YoutubeLiveCheckTimer(IEnumerable <VtuberEntity> vtubers)
        {
            var threadPool = new SimpleThreadPool()
            {
                MaxThread = 20
            };

            foreach (var vtuber in vtubers.Where(v => !string.IsNullOrEmpty(v.YoutubeChannelId)))
            {
                threadPool.Actions.Enqueue(() =>
                {
                    if (!LastCheckYoutubeLiveStatus.ContainsKey(vtuber))
                    {
                        LastCheckYoutubeLiveStatus.Add(vtuber, new YoutubeVideo());
                    }
                    var onLive = YoutubeApi.NowLive(vtuber.YoutubeChannelId).GetAwaiter().GetResult();
                    if (onLive)
                    {
                        var channelInfo = YoutubeApi.GetYoutubeChannelAsync(vtuber.YoutubeChannelId).GetAwaiter().GetResult();
                        if (!LastCheckYoutubeLiveStatus[vtuber].IsLive || channelInfo.LiveVideoId != LastCheckYoutubeLiveStatus[vtuber].VideoId)
                        {
                            var live = YoutubeApi.GetYoutubeVideoAsync(channelInfo.LiveVideoId).GetAwaiter().GetResult();
                            if (!live.IsLive)
                            {
                                return;
                            }
                            if (!LastCheckYoutubeLiveStatus[vtuber].IsLive)
                            {
                                LastCheckYoutubeLiveStatus[vtuber] = live;
                                var recorder = new YoutubeLiveChatRecorder(live.LiveDetails.LiveChatId, vtuber, live.VideoId)
                                {
                                    VtuberList = vtubers.ToList()
                                };
                                recorder.StartRecord();
                                recorder.LiveStoppedEvent += (id, sender) =>
                                {
                                    LogHelper.Info($"{vtuber.OriginalName} 已停止直播,正在保存评论数据");
                                    live     = YoutubeApi.GetYoutubeVideoAsync(channelInfo.LiveVideoId).Retry(5).GetAwaiter().GetResult() ?? live;
                                    var info = new YoutubeLiveInfo()
                                    {
                                        Title     = live.Title,
                                        Channel   = live.ChannelId,
                                        BeginTime = live.LiveDetails?.ActualStartTime ?? default(DateTime),
                                        EndTime   = live.LiveDetails?.ActualEndTime ?? DateTime.Now,
                                        VideoId   = live.VideoId
                                    };
                                    _youtubeLiveCollection.ReplaceOne(v => v.VideoId == live.VideoId, info,
                                                                      new UpdateOptions()
                                    {
                                        IsUpsert = true
                                    });
                                    LogHelper.Info("保存完毕");
                                    VtuberStoppedYoutubeLiveEvent?.Invoke(vtuber, live);
                                };
                                recorder.VtuberCommentedEvent += (author, message, sender) => VtuberCommentedYoutubeLiveEvent?.Invoke(author, sender.Vtuber, message, live);
                                VtuberBeginYoutubeLiveEvent?.Invoke(vtuber, live);
                            }
                        }
                    }
                    if (!onLive)
                    {
                        LastCheckYoutubeLiveStatus[vtuber] = new YoutubeVideo();
                    }
                });
            }
            threadPool.Run();
        }
コード例 #24
0
        public void StartRecord()
        {
            var num = 0;

            new Thread(() =>
            {
                while (true)
                {
                    var info = YoutubeApi.GetLiveChatInfoAsync(LiveChatId).GetAwaiter().GetResult();
                    if (info == null || (info.PollingInterval == 0 && info.CommentsToken == null))
                    {
                        LiveStoppedEvent?.Invoke(LiveChatId, this);
                        break;
                    }
                    var channelInfo = YoutubeApi.GetYoutubeChannelAsync(Vtuber.YoutubeChannelId).Retry(5).GetAwaiter()
                                      .GetResult();
                    var comments = info.GetComments().Where(comment => RecordedLiveChats.All(v => v.CommentId != comment.CommentId)).ToList();
                    if (channelInfo != null && channelInfo.LiveViewerCount > 0)
                    {
                        comments.ForEach(v => v.ViewerCount = channelInfo.LiveViewerCount);
                    }
                    if (comments.Any())
                    {
                        comments.ForEach(v => v.VideoId = VideoId);
                        try
                        {
                            _chatCollection.InsertMany(comments, new InsertManyOptions()
                            {
                                IsOrdered = false
                            });
                            RecordedLiveChats.AddRange(comments);
                            if (VtuberList != null)
                            {
                                var comment = comments.Where(v => VtuberList.Any(t => t.YoutubeChannelId == v.AuthorChannelId));
                                foreach (var chat in comment)
                                {
                                    var target = VtuberList.First(v => v.YoutubeChannelId == chat.AuthorChannelId);
                                    VtuberCommentedEvent?.Invoke(target, chat, this);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(10000);
                        }
                    }
                    if (++num % 10 == 0)
                    {
                        if (RecordedLiveChats.Count > 100)
                        {
                            RecordedLiveChats.RemoveRange(0, RecordedLiveChats.Count - 100);
                        }
                        if (!CacheManager.Manager.LastCheckYoutubeLiveStatus[Vtuber].IsLive || CacheManager.Manager.LastCheckYoutubeLiveStatus[Vtuber].VideoId != VideoId)
                        {
                            LiveStoppedEvent?.Invoke(LiveChatId, this);
                            break;
                        }
                    }
                    Thread.Sleep(info.PollingInterval < 2000 ? info.PollingInterval : info.PollingInterval - 1000);
                }
            }).Start();
        }
コード例 #25
0
        public static void Main(string[] args)
        {
            #region Generics

            Console.WriteLine("------- Starting Generics ---------");
            var number = new Nullable <int>(0);
            Console.WriteLine("Has Value: " + number.HasValue);
            Console.WriteLine("Value: " + number.GetValueOrDefault());

            #endregion

            #region Delegates

            Console.WriteLine("------- Starting Delegates ---------");
            // Use for extesibility and flexibility
            var processor    = new PhotoProcessor();
            var photoFilters = new PhotoFilters();

            Action <Photo> filterHandler = photoFilters.ApplyBrightness;
            filterHandler += photoFilters.ApplyContrast;
            filterHandler += RemoveRedEye;

            processor.Process("Photos.jpg", filterHandler);
            #endregion

            #region Lambda Expressions

            Console.WriteLine("------- Starting Lambda Expressions ---------");
            const int       factor     = 5;
            Func <int, int> multiplier = num => num * factor;
            Console.WriteLine("The result after multiplication: " + multiplier(50));

            var books      = new BookRepository().GetBooks();
            var cheapBooks = books.FindAll(b => b.Price <= 35);
            Console.WriteLine("Books having the price less than 35: ");
            foreach (var book in cheapBooks)
            {
                Console.WriteLine(book.Title);
            }

            #endregion

            #region Extension Methods

            Console.WriteLine("------- Starting Extension Methods ---------");

            string post = "This is supposed to be a very long post blah blah blah";
            //Our extension method
            var shortenedPost = post.Shorten(5);
            Console.WriteLine(shortenedPost);

            //Pre-defined extension method
            IEnumerable <int> numbers = new List <int>()
            {
                1, 5, 3, 10, 18, 9, 34, 12
            };
            Console.WriteLine("The maximum number from the list:" + numbers.Max());

            #endregion

            #region LINQ

            Console.WriteLine("------- Starting LINQ ---------");

            // LINQ Query Operators

            var cheapBooksAgain = from b in books
                                  where b.Price < 30
                                  orderby b.Title
                                  select b.Title;


            // LINQ Extension Methods
            cheapBooksAgain = books
                              .Where(b => b.Price < 30)
                              .OrderBy(b => b.Title)
                              .Select(b => b.Title);
            Console.WriteLine("Books having price less than 30$: ");
            foreach (var book in cheapBooksAgain)
            {
                Console.WriteLine(book);
            }

            var lastThreeBooks = books.Skip(2).Take(3);

            Console.WriteLine("Last three books: ");
            foreach (var book in lastThreeBooks)
            {
                Console.WriteLine(book.Title);
            }

            #endregion

            #region Events and Delegates

            Console.WriteLine("------- Starting Events and Delegates ---------");

            var video = new Video()
            {
                Title = "Video 1"
            };
            var videoEncoder   = new VideoEncoder();                    // Publisher
            var mailService    = new MailService();                     // Subscriber
            var messageService = new MessageService();                  // Subscriber

            videoEncoder.VideoEncoded += mailService.OnVideoEncoded;    // Binding the event
            videoEncoder.VideoEncoded += messageService.OnVideoEncoded; // Binding the event

            videoEncoder.Encode(video);

            #endregion

            #region Dynamic

            Console.WriteLine("------- Starting Dynamic ---------");

            //Normal way
            object obj = "Ubaid";

            //With Reflection
            //var methodInfo = obj.GetType().GetMethod("GetHashCode");
            //methodInfo.Invoke(null, null);

            //With Dynamic
            dynamic testInt = 10;
            //Although optimize is not defined, still no compile time error if you uncomment
            //excelObject.Optimize();

            dynamic testSecondInt = 20;
            object  result        = testInt + testSecondInt;
            Console.WriteLine("The result: " + result.GetType());
            #endregion

            #region Exception Handling

            Console.WriteLine("------- Starting Exception Handling ---------");
            try
            {
                var a = 1;
                var b = 0;
                //var answer = a / b;
                var api    = new YoutubeApi();
                var videos = api.GetVideos();
            }

            catch (DivideByZeroException ex)
            {
                Console.WriteLine("You can't divide by 0");
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine("Argument is out of range.");
            }

            catch (Exception ex)
            {
                Console.WriteLine("Exception Message: " + ex.Message);
                Console.WriteLine("Inner Exception Message: " + ex.InnerException.Message);
            }
            #endregion

            #region Async and Await

            var download = new Download();
            download.DownloadHtml("https://msdn.microsoft.com");

            #endregion
        }
コード例 #26
0
        static void ExceptionHandling()
        {
            // Normal Exception Handling with many Exceptions
            // try
            // {
            //     var calculator = new Calculator();
            //     var result = calculator.Divide(5, 0);
            // }
            // catch (DivideByZeroException ex)
            // {
            //     Console.WriteLine($"DivideByZeroException: {ex.Message}");
            // }
            // catch (ArithmeticException ex)
            // {
            //     Console.WriteLine($"ArithmeticException: {ex.Message}");
            // }
            // catch (Exception ex)
            // {
            //     Console.WriteLine($"Sorry, an exception error occurred - {ex.Message}");
            // }


            // Example with Finally
            // StreamReader streamReader = null;
            // try
            // {
            //     streamReader = new StreamReader("/Users/itabarino/Downloads/test123.txt");
            //     var content = streamReader.ReadToEnd();
            //     Console.WriteLine(content);
            // }
            // catch (Exception ex)
            // {
            //     Console.WriteLine($"Sorry, an exception error occurred - {ex.Message}");
            // }
            // finally
            // {
            //     if (streamReader != null)
            //     {
            //         streamReader.Dispose();
            //     }
            // }

            // Instead of using Finally, simple use the "using". It will create finally under the hook for you
            // try
            // {
            //     using (var streamReader = new StreamReader("/Users/itabarino/Downloads/test123.txt"))
            //     {
            //         var content = streamReader.ReadToEnd();
            //         Console.WriteLine(content);
            //     }
            // }
            // catch (Exception ex)
            // {
            //     Console.WriteLine($"Sorry, an exception error occurred - {ex.Message}");
            // }


            // Custom Exceptions
            try
            {
                var api = new YoutubeApi();
                api.GetVideos("TestApi");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Sorry, an exception error occurred - {ex.Message}");
                Console.WriteLine(ex.InnerException.Message);
            }
        }
コード例 #27
0
        private async void RunCreateList(string idPlaylist, string name, string idUser)
        {
            var listNameMusic = await spotifyApi.GetFullNamePlaylistFullTracksAll(idPlaylist, idUser);


            if (!listNameMusic.Any())
            {
                return;
            }


            var youtube = new YoutubeApi();

            var listCount = 0;

            Invoke(new SetStringCallback((string text) =>
            {
                lblTotal.Text        = text;
                pBarPlaylist.Value   = 0;
                pBarPlaylist.Maximum = Convert.ToInt32(text);
            }), new object[] { listNameMusic.Count().ToString() });

            var logged = await youtube.Login();

            if (!logged)
            {
                return;
            }

            var idNewPlaylist = await youtube.CreatePlaylist(name);

            var url = $"https://www.youtube.com/playlist?list={idNewPlaylist}";

            foreach (var music in listNameMusic)
            {
                listCount++;

                var returnAddItem = await youtube.AddItemPlaylist(idNewPlaylist, music);

                Invoke(new SetStringBoolCallback((string text, bool found) =>
                {
                    ltvAddItens.Items.Add(new ListViewItem()
                    {
                        Text     = text,
                        SubItems = { (found ? "Sim" : "Não") }
                    });
                }), new object[] { music, returnAddItem });

                Invoke(new SetStringCallback((string text) =>
                {
                    pBarPlaylist.PerformStep();
                    lblAtual.Text = text;
                }), new object[] { listCount.ToString() });
            }


            Invoke(new SetStringCallback((string text) =>
            {
                System.Diagnostics.Process.Start(text);
                btnExportar.Enabled = true;
                MessageBox.Show("Exportação concluída ");
            }), new object[] { url });
        }
コード例 #28
0
        public string GetYoutubeMetrics(string channelId)
        {
            YoutubeApi youtubeApi = new YoutubeApi();

            return(youtubeApi.getMetrics(channelId));
        }