示例#1
0
        public async void SearchSingleVideo(string videoid)
        {
            if (IsLoadingSearchTerm)
            {
                return;
            }
            IsLoadingSearchTerm = true;

            var videoInfoRequest = YoutubeService.service.Videos.List("snippet,statistics,id,status,recordingDetails,topicDetails");

            videoInfoRequest.Id = videoid;

            try
            {
                var videoResultResponse = await videoInfoRequest.ExecuteAsync();

                if (videoResultResponse.Items.Count >= 0)
                {
                    Google.Apis.YouTube.v3.Data.Video videoNew = videoResultResponse.Items[0];

                    video = videoNew;
                }
            }
            catch { }
            IsLoadingSearchTerm = false;
        }
示例#2
0
        public UploadQueueItem(YouTubeSession session, string filename)
        {
            youtubeSession = new WeakReference <YouTubeSession> (session);

            FileName    = new Uri(filename, UriKind.Absolute);
            mediaStream = new FileStream(HttpUtility.UrlDecode(FileName.AbsolutePath), FileMode.Open, FileAccess.Read, FileShare.Read);
            if (mediaStream.Length >= 68719476736)
            {
                mediaStream.Dispose();
                mediaStream = null;
                throw new ArgumentException("File size is to big.", "filename");
            }

            video = new Google.Apis.YouTube.v3.Data.Video()
            {
                Snippet = new VideoSnippet()
                {
                    Tags = new ObservableCollection <string> ()
                },
                Status = new VideoStatus()
            };

            Title         = Path.GetFileNameWithoutExtension(filename);
            Description   = "";
            PrivacyStatus = PrivacyStatus.Public;

            Progress        = 0;
            TotalUploaded   = 0;
            UploadingStatus = UploadingStatus.Queued;
        }
示例#3
0
        public async Task <YouTubeUploadRequest> CreateUploadRequest(string FileName,
                                                                     string Title,
                                                                     string Description,
                                                                     string[] Tags = null,
                                                                     YouTubePrivacyStatus PrivacyStatus = YouTubePrivacyStatus.Unlisted)
        {
            if (_youtubeService == null)
            {
                await Init();
            }

            var video = new Google.Apis.YouTube.v3.Data.Video
            {
                Snippet = new VideoSnippet
                {
                    Title       = Title,
                    Description = Description,
                    Tags        = Tags ?? new string[0],
                    CategoryId  = "22"
                },
                Status = new VideoStatus {
                    PrivacyStatus = GetPrivacyStatus(PrivacyStatus)
                }
            };

            return(new YouTubeUploadRequest(FileName, _youtubeService, video));
        }
示例#4
0
        static void VideosInsertRequestResponseReceived(Google.Apis.YouTube.v3.Data.Video video)
        {
            string msg = "YouTube video uploaded: <a href=\"http://www.youtube.com/watch?v=" + video.Id + "\">" +
                         video.Id + "</a>";

            msg += " (" + video.Status.PrivacyStatus + ")";
            MainForm.LogMessageToFile(msg);
            _uploaded = true;
        }
示例#5
0
        public Video(Google.Apis.YouTube.v3.Data.Video youtubeVideo)
        {
            this.VideoId          = youtubeVideo.Id;
            this.Title            = youtubeVideo.Snippet?.Title;
            this.Description      = youtubeVideo.Snippet?.Description;
            this.ThumbnailDetails = youtubeVideo.Snippet?.Thumbnails;
            this.PublishedAt      = youtubeVideo.Snippet?.PublishedAt;

            DownloadImage(youtubeVideo?.Snippet?.Thumbnails?.Maxres?.Url ?? youtubeVideo?.Snippet?.Thumbnails?.Default__?.Url);
        }
示例#6
0
        private async Task Run(string localVideoPath)
        {
            UserCredential credential;

            if (!File.Exists("youtube_client_secret.json"))
            {
                Console.WriteLine($"Unable to find secrets file in current dir: {Directory.GetCurrentDirectory()}");
                return;
            }

            string creds = File.OpenText("youtube_client_secret.json").ReadToEnd();

            Console.WriteLine("Creds: " + creds);

            using (var stream = new FileStream("youtube_client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                    );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Data.Video();

            video.Snippet       = new Data.VideoSnippet();
            video.Snippet.Title = "Ski Video";
            //video.Snippet.Description = "Default Video Description";
            //video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId   = "17";       // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status               = new Data.VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = localVideoPath;           // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged  += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }
示例#7
0
        private int SaveVideoNumberCount(int videoid, Google.Apis.YouTube.v3.Data.Video video)
        {
            var             db       = new youtubeEntities();
            ObjectParameter objParam = new ObjectParameter("Id", typeof(int));

            var videoNumberCountId = db.yt_Save_Video_NumberCount(
                videoid,
                ParseData.GetLong(video.Statistics.ViewCount),
                ParseData.GetLong(video.Statistics.LikeCount),
                ParseData.GetLong(video.Statistics.DislikeCount),
                ParseData.GetLong(video.Statistics.FavoriteCount),
                ParseData.GetLong(video.Statistics.CommentCount)
                , objParam);

            return(Convert.ToInt32(objParam.Value));
        }
示例#8
0
 private VideoSearchResultViewModel CreateVideoViewModel(Google.Apis.YouTube.v3.Data.Video video)
 {
     return(new VideoSearchResultViewModel
     {
         YoutubeVideoId = video.Id,
         YoutubeChannelId = video.Snippet.ChannelId,
         Titulo = video.Snippet.Title,
         ImagemUrl = video.Snippet.Thumbnails.Default__.Url.Replace("https", "http"),
         Descricao = video.Snippet.Description,
         PublicadoEm = video.Snippet.PublishedAt,
         Definicao = video.ContentDetails.Definition,
         Idioma = video.Snippet.DefaultLanguage,
         QuantidadeLike = video.Statistics?.LikeCount,
         QuantidadeDeslike = video.Statistics?.DislikeCount,
         QuantidadeComentario = video.Statistics?.CommentCount,
         QuantidadeVisualizacao = video.Statistics?.ViewCount
     });
 }
示例#9
0
        /// <summary>
        /// Get statistics and status details about video
        /// </summary>
        /// <param name="videoId"></param>
        /// <returns></returns>
        public async Task <VideoStatusStatistics> GetVideoDetails(string videoId)
        {
            var request = _ytService.Videos.List("snippet,statistics,status");

            request.Id = videoId;

            VideoListResponse result = await request.ExecuteAsync();

            Google.Apis.YouTube.v3.Data.Video video = result?.Items.FirstOrDefault();

            return(new VideoStatusStatistics()
            {
                Comments = video.Statistics.CommentCount.GetValueOrDefault(0),
                Dislikes = video.Statistics.DislikeCount.GetValueOrDefault(0),
                Likes = video.Statistics.LikeCount.GetValueOrDefault(0),
                Views = video.Statistics.ViewCount.GetValueOrDefault(0),
                IsPrivate = video.Status.PrivacyStatus != "public",
                Tags = video.Snippet.Tags?.ToList()
            });
        }
示例#10
0
        private static void Upload(object state)
        {
            if (UploadList.Count == 0)
            {
                _uploading = false;
                return;
            }

            UserState us;

            try
            {
                var l = UploadList.ToList();
                us = l[0];
                l.RemoveAt(0);
                UploadList = l.ToList();
            }
            catch
            {
                _uploading = false;
                return;
            }


            if (Service == null)
            {
                if (!Authorise())
                {
                    _uploading = false;
                    return;
                }
            }
            if (Service != null)
            {
                var video = new Google.Apis.YouTube.v3.Data.Video
                {
                    Snippet =
                        new VideoSnippet
                    {
                        Title       = "iSpy: " + us.CameraData.name,
                        Description =
                            MainForm.Website + ": free open source surveillance software: " +
                            us.CameraData.description,
                        Tags       = us.CameraData.settings.youtube.tags.Split(','),
                        CategoryId = "22"
                    },
                    Status =
                        new VideoStatus
                    {
                        PrivacyStatus =
                            us.CameraData.settings.youtube.@public
                                        ? "public"
                                        : "private"
                    }
                };

                try
                {
                    using (var fileStream = new FileStream(us.Filename, FileMode.Open))
                    {
                        var videosInsertRequest = Service.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                        videosInsertRequest.ProgressChanged  += VideosInsertRequestProgressChanged;
                        videosInsertRequest.ResponseReceived += VideosInsertRequestResponseReceived;
                        _uploaded = false;
                        videosInsertRequest.Upload();
                        if (_uploaded)
                        {
                            Uploaded.Add(us.Filename);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MainForm.LogExceptionToFile(ex);
                }
                Upload(null);
            }
            else
            {
                _uploading = false;
            }
        }
示例#11
0
 void videosInsertRequest_ResponseReceived(Data.Video video)
 {
     Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
 }
示例#12
0
        public async Task Queue(CommandContext ctx, [Description("A search query or a direct link to the video."), RemainingText] string queryString)
        {
            if (string.IsNullOrWhiteSpace(queryString))
            {
                if (!GuildQueues.TryGetValue(ctx.Guild.Id, out List <JigglySong> resultSongs))
                {
                    await ctx.RespondAsync("There is nothing currently queued.");

                    return;
                }

                for (int i = 0; i < resultSongs.Count; i += 5)
                {
                    DiscordEmbedBuilder queueBuilder = new DiscordEmbedBuilder
                    {
                        Title = $"Current Queue {i + 1}-{i + 5}",
                        Color = DiscordColor.Aquamarine
                    };

                    string tracks = string.Empty;

                    for (int j = i; j < i + 5; j++)
                    {
                        if (j >= resultSongs.Count)
                        {
                            break;
                        }

                        JigglySong resultSong = resultSongs[j];

                        tracks += $"{j + 1}: [**{resultSong.Title}** by **{resultSong.Artist}**](https://www.youtube.com/watch?v={resultSong.Id})\n";
                    }

                    queueBuilder.Description = tracks;

                    await ctx.RespondAsync(string.Empty, false, queueBuilder.Build());
                }

                return;
            }

            if (ctx.Client.GetVoiceNext()?.GetConnection(ctx.Guild)?.Channel != null && ctx.Client.GetVoiceNext().GetConnection(ctx.Guild).Channel.Users.All(e => e.Id != ctx.User.Id))
            {
                throw new OutputException("You must join a voice channel to queue songs.");
            }

            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = Globals.BotSettings.YoutubeApiKey,
                ApplicationName = this.GetType().ToString()
            });

            try
            {
                Uri uri = new Uri(queryString);

                if (uri.Host != "youtu.be" && !uri.Host.ToLower().Contains("youtube"))
                {
                    throw new ArgumentException();
                }

                NameValueCollection query = HttpUtility.ParseQueryString(uri.Query);

                string id = query.AllKeys.Contains("v") ? query["v"] : uri.Segments.Last();

                VideosResource.ListRequest idSearch = youtubeService.Videos.List("id,snippet");
                idSearch.Id         = id;
                idSearch.MaxResults = 1;

                VideoListResponse videoListResponse = await idSearch.ExecuteAsync();

                if (videoListResponse.Items.Count == 0)
                {
                    await ctx.RespondAsync("Video link cannot be parsed.");

                    return;
                }

                if (!GuildQueues.ContainsKey(ctx.Guild.Id))
                {
                    GuildQueues.Add(ctx.Guild.Id, new List <JigglySong>());
                }

                Video parsedVideo = videoListResponse.Items.First();

                if (!string.IsNullOrWhiteSpace(parsedVideo.ContentDetails?.Duration) && XmlConvert.ToTimeSpan(parsedVideo.ContentDetails.Duration).Minutes > 15)
                {
                    await ctx.RespondAsync("This video is too long, please try to find something shorter than 15 minutes.");
                }

                Guid guid = Guid.NewGuid();

                AddSong(guid, parsedVideo.Snippet.Title, parsedVideo.Id, parsedVideo.Snippet.ChannelTitle, JigglySong.SongType.Youtube, ctx.Member);

                if (!DownloadHelper.GuildMusicTasks.ContainsKey(ctx.Guild.Id))
                {
                    DownloadHelper.GuildMusicTasks.Add(ctx.Guild.Id, new List <(Guid guid, Func <string> downloadTask)>());
                }

                DownloadHelper.GuildMusicTasks[ctx.Guild.Id].Add((guid, () => DownloadHelper.DownloadFromYouTube(ctx, queryString)));

                if (!DownloadHelper.IsDownloadLoopRunning)
                {
                    new Thread(() => DownloadHelper.DownloadQueue(ctx.Guild.Id)).Start();
                }

                DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
                {
                    Description = $"**✅ Successfully added [{parsedVideo.Snippet.Title}](https://www.youtube.com/watch?v={parsedVideo.Id}) to queue position {GuildQueues[ctx.Guild.Id].Count}**"
                };

                await ctx.RespondAsync(null, false, confirmationBuilder.Build());
            }
            catch
            {
                SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet");
                searchListRequest.Q          = queryString.Replace(" ", "+");
                searchListRequest.MaxResults = 10;
                searchListRequest.Type       = "video";

                // Call the search.list method to retrieve results matching the specified query term.
                SearchListResponse searchListResponse = await searchListRequest.ExecuteAsync();

                DiscordEmbedBuilder builder = new DiscordEmbedBuilder
                {
                    Title = "Enter the number of your selection."
                };

                List <JigglySong> videos     = new List <JigglySong>();
                string            selections = string.Empty;

                // Add each result to the appropriate list, and then display the lists of
                // matching videos, channels, and playlists.
                for (int i = 0; i < 5; i++)
                {
                    if (!searchListResponse.Items.Any())
                    {
                        await ctx.RespondAsync("No available tracks less than 15 minutes.");

                        return;
                    }

                    SearchResult searchResult = searchListResponse.Items[i];

                    VideosResource.ListRequest listRequest = youtubeService.Videos.List("snippet");
                    listRequest.Id = searchResult.Id.VideoId;

                    if (!string.IsNullOrWhiteSpace((await listRequest.ExecuteAsync()).Items.First().ContentDetails?.Duration) && XmlConvert.ToTimeSpan((await listRequest.ExecuteAsync()).Items.First().ContentDetails.Duration).Minutes > 15)
                    {
                        searchListResponse.Items.RemoveAt(i);
                        i--;
                        continue;
                    }

                    selections += $"{i + 1}: {searchResult.Snippet.Title}\n";
                    videos.Add(new JigglySong
                    {
                        Title  = searchResult.Snippet.Title,
                        Id     = searchResult.Id.VideoId,
                        Artist = searchResult.Snippet.ChannelTitle,
                        Type   = JigglySong.SongType.Youtube,
                        Queuer = ctx.Member
                    });
                }

                selections += "c: Cancel";

                builder.Description = selections;

                DiscordMessage resultsMessage = await ctx.RespondAsync(string.Empty, false, builder.Build());

                int result = -1;

                MessageContext msgContext = await ctx.Client.GetInteractivity().WaitForMessageAsync(e => e.Author.Id == ctx.Message.Author.Id && (e.Content.ToLower() == "c" || int.TryParse(e.Content, out result) && result > 0 && result <= videos.Count), TimeSpan.FromSeconds(30));

                if (msgContext == null)
                {
                    await ctx.RespondAsync($"🖍*Jigglypuff wrote on {ctx.User.Mention}'s face!*🖍\nMaybe they should have picked a song...");

                    await resultsMessage.DeleteAsync();

                    return;
                }

                result--;

                if (result >= 0)
                {
                    if ((await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id)).PermissionsIn(ctx.Channel).HasPermission(Permissions.ManageMessages))
                    {
                        await msgContext.Message.DeleteAsync();
                    }

                    if (!GuildQueues.ContainsKey(ctx.Guild.Id))
                    {
                        GuildQueues.Add(ctx.Guild.Id, new List <JigglySong>());
                    }

                    JigglySong selectedSong = videos[result];

                    DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
                    {
                        Description = $"**✅ Successfully added [{videos[result].Title}](https://www.youtube.com/watch?v={videos[result].Id}) to queue position {GuildQueues[ctx.Guild.Id].Count + 1}**"
                    };

                    if (GuildQueues[ctx.Guild.Id].Count == 0)
                    {
                        confirmationBuilder.Description += "\nPlease be patient; it takes a bit for the first song to cache.";
                    }

                    await ctx.RespondAsync(string.Empty, false, confirmationBuilder.Build());

                    if (!GuildMusicStatuses.TryGetValue(ctx.Guild.Id, out MusicStatus musicStatus))
                    {
                        GuildMusicStatuses.Add(ctx.Guild.Id, new MusicStatus
                        {
                            Skip = false
                        });
                    }

                    Guid guid = Guid.NewGuid();

                    AddSong(guid, selectedSong.Title, selectedSong.Id, selectedSong.Artist, selectedSong.Type, selectedSong.Queuer);

                    if (!DownloadHelper.GuildMusicTasks.ContainsKey(ctx.Guild.Id))
                    {
                        DownloadHelper.GuildMusicTasks.Add(ctx.Guild.Id, new List <(Guid guid, Func <string> downloadTask)>());
                    }

                    DownloadHelper.GuildMusicTasks[ctx.Guild.Id].Add((guid, () => DownloadHelper.DownloadFromYouTube(ctx, $"https://www.youtube.com/watch?v={videos[result].Id}")));

                    if (!DownloadHelper.IsDownloadLoopRunning)
                    {
                        new Thread(() => DownloadHelper.DownloadQueue(ctx.Guild.Id)).Start();
                    }
                }
                else
                {
                    DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
                    {
                        Title = "🚫 Canceled queue."
                    };

                    await ctx.RespondAsync(string.Empty, false, confirmationBuilder.Build());
                }
            }
        }
示例#13
0
        private static void Upload(object state)
        {
            if (UploadList.Count == 0)
            {
                _uploading = false;
                return;
            }

            UserState us;

            try
            {
                var l = UploadList.ToList();
                us = l[0];
                l.RemoveAt(0);
                UploadList = l.ToList();
            }
            catch
            {
                _uploading = false;
                return;
            }

            if (Service == null)
            {
                if (!Authorise())
                {
                    _uploading = false;
                    return;
                }
            }
            if (Service != null)
            {
                if (us.CameraData == null)
                    return;
                var video = new Google.Apis.YouTube.v3.Data.Video
                    {
                        Snippet =
                            new VideoSnippet
                            {
                                Title = "iSpy: " + us.CameraData.name,
                                Description =
                                    MainForm.Website + ": free open source surveillance software: " +
                                    us.CameraData.description,
                                Tags = us.CameraData.settings.youtube.tags.Split(','),
                                CategoryId = "22"
                            },
                        Status =
                            new VideoStatus
                            {
                                PrivacyStatus =
                                    us.CameraData.settings.youtube.@public
                                        ? "public"
                                        : "private"
                            }
                    };

                try
                {
                    using (var fileStream = new FileStream(us.Filename, FileMode.Open))
                    {

                        var videosInsertRequest = Service.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                        videosInsertRequest.ProgressChanged += VideosInsertRequestProgressChanged;
                        videosInsertRequest.ResponseReceived += VideosInsertRequestResponseReceived;
                        _uploaded = false;
                        videosInsertRequest.Upload();
                        if (_uploaded)
                            Uploaded.Add(us.Filename);
                    }
                }
                catch (Exception ex)
                {
                    MainForm.LogExceptionToFile(ex);
                }
                Upload(null);
            }
            else
            {
                _uploading = false;
            }
        }
示例#14
0
        public async Task <UploadResult> UploadStart(DataChunkSize dataChunkSize = DataChunkSize.ChunkSize_10MB)
        {
            youtubeSession.TryGetTarget(out YouTubeSession session);

            if (UploadingStatus == UploadingStatus.UploadCanceled)
            {
                UploadingStatus = UploadingStatus.Queued;
                video.Id        = null;
                if (mediaStream != null)
                {
                    mediaStream.Dispose();
                }
                mediaStream        = null;
                Progress           = 0;
                TotalUploaded      = 0;
                TimeRemaining      = new TimeSpan();
                videoInsertRequest = null;
                IsManuallyPaused   = false;
            }

            if (video.Id != null && (
                    UploadingStatus == UploadingStatus.UploadFailed ||
                    UploadingStatus == UploadingStatus.UploadCompleted ||
                    UploadingStatus == UploadingStatus.UpdateFailed ||
                    UploadingStatus == UploadingStatus.UpdateComplete
                    ))
            {
                UploadingStatus = UploadingStatus.UpdateStart;

                await UploadThumbnail(video.Id);

                var videoUpdateRequest = session.YouTubeService.Videos.Update(video, "snippet,status");
                var result             = await videoUpdateRequest.ExecuteAsync();

                if (result != null)
                {
                    UploadingStatus = UploadingStatus.UpdateComplete;
                    PC(nameof(UploadingStatus));
                    Completed?.Invoke(this, EventArgs.Empty);
                    return(UploadResult.Succeed);
                }
                else
                {
                    UploadingStatus = UploadingStatus.UpdateFailed;
                    PC(nameof(UploadingStatus));
                    Failed?.Invoke(this, EventArgs.Empty);
                    return(UploadResult.Succeed);
                }
            }

            if (!(UploadingStatus == UploadingStatus.Queued || UploadingStatus == UploadingStatus.UploadFailed))
            {
                return(UploadResult.AlreadyUploading);
            }

            UploadingStatus = UploadingStatus.PrepareUpload;

            bool virIsNull = videoInsertRequest == null;

            if (virIsNull)
            {
                videoInsertRequest = session.YouTubeService.Videos.Insert(video, "snippet,status", mediaStream, "video/*");
                if (videoInsertRequest == null)
                {
                    UploadingStatus = UploadingStatus.UploadFailed;
                    return(UploadResult.FailedUploadRequest);
                }

                DataChunkSize = dataChunkSize;
                videoInsertRequest.ProgressChanged += (uploadProgress) =>
                {
                    TotalUploaded = uploadProgress.BytesSent;
                    Progress      = uploadProgress.BytesSent / ( double )mediaStream.Length;
                    double percentage = (uploadProgress.BytesSent - lastSentBytes) / ( double )mediaStream.Length;
                    lastSentBytes = uploadProgress.BytesSent;
                    double totalSeconds = (DateTime.Now.TimeOfDay - startTime).TotalSeconds;
                    TimeRemaining = Progress != 0 ? TimeSpan.FromSeconds((totalSeconds / Progress) * (1 - Progress)) : TimeSpan.FromDays(999);

                    switch (uploadProgress.Status)
                    {
                    case UploadStatus.Starting:
                        startTime       = DateTime.Now.TimeOfDay;
                        UploadingStatus = UploadingStatus.UploadStart;
                        Started?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Uploading:
                        UploadingStatus = UploadingStatus.Uploading;
                        Uploading?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Failed:
                        UploadingStatus = UploadingStatus.UploadFailed;
                        Failed?.Invoke(this, EventArgs.Empty);
                        break;

                    case UploadStatus.Completed:
                        UploadingStatus = UploadingStatus.UploadCompleted;
                        Uploading?.Invoke(this, EventArgs.Empty);
                        Completed?.Invoke(this, EventArgs.Empty);
                        mediaStream.Dispose();
                        mediaStream = null;
                        break;
                    }

                    PC(nameof(Progress));
                    PC(nameof(UploadingStatus));
                    PC(nameof(TotalUploaded));
                    PC(nameof(TimeRemaining));
                };
                videoInsertRequest.ResponseReceived += async(video) =>
                {
                    await UploadThumbnail(video.Id);

                    foreach (var playlist in Playlists)
                    {
                        playlist.AddVideo(video.Id);
                    }
                };
            }

            try
            {
                startTime = DateTime.Now.TimeOfDay;
                cancellationTokenSource = new CancellationTokenSource();
                var uploadStatus = virIsNull ?
                                   await videoInsertRequest.UploadAsync(cancellationTokenSource.Token) :
                                   await videoInsertRequest.ResumeAsync(cancellationTokenSource.Token);

                cancellationTokenSource.Dispose();
                video = videoInsertRequest.ResponseBody ?? video;
                if (uploadStatus.Status == UploadStatus.NotStarted)
                {
                    UploadingStatus = UploadingStatus.UploadFailed;
                    return(UploadResult.CannotStartUpload);
                }
            }
            catch
            {
                UploadingStatus = UploadingStatus.UploadFailed;
                return(UploadResult.UploadCanceled);
            }

            return(UploadResult.Succeed);
        }
示例#15
0
        private void UploadVideos(Stream uploadedStream, String contenttype, string filename, string path)
        {
            try
            {
                String clientsecretkeypath = HttpContext.Current.Server.MapPath("~/client_secrets.json");
                //  GoogleAuthorizationCodeFlow flow;
                ////  string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                ////  credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                //  var folder = System.Web.HttpContext.Current.Server.MapPath("/App_Data/MyGoogleStorage");
                //  using (var stream = new FileStream(clientsecretkeypath, FileMode.Open, FileAccess.Read))
                //  {
                //      flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                //      {
                //          DataStore = new FileDataStore(folder),
                //          ClientSecretsStream = stream,
                //          Scopes = new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }
                //      });
                //  }
                //  var uri = Request.Url.ToString();
                //  var code = Request["code"];
                //  string userId = "sidza";
                //  var youtubeService = new YouTubeService();
                //  if (code != null)
                //  {
                //      var token = flow.ExchangeCodeForTokenAsync(userId, code,
                //          uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                //  //    Extract the right state.
                //      var oauthState = AuthWebUtility.ExtracRedirectFromState(
                //          flow.DataStore, userId, Request["state"]).Result;
                //      Response.Redirect(oauthState, false);
                //  }
                //  else
                //  {
                //      var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(userId,
                //          CancellationToken.None).Result;
                //      if (result.RedirectUri != null)
                //      {
                //    //      Redirect the user to the authorization server.
                //         Response.Redirect(result.RedirectUri, false);
                //      }
                //      else
                //      {
                //      //    The data store contains the user credential, so the user has been already authenticated.
                //         youtubeService = new YouTubeService(new BaseClientService.Initializer()
                //         {
                //             HttpClientInitializer = result.Credential,
                //             ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                //         });
                //      }
                //  }



                var cred = GetUserCredential(clientsecretkeypath);

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = cred,
                    ApplicationName       = Assembly.GetExecutingAssembly().GetName().Name
                });

                youtubeService.HttpClient.Timeout = TimeSpan.FromMinutes(15.00);
                var video = new Google.Apis.YouTube.v3.Data.Video();
                video.Snippet             = new VideoSnippet();
                video.Snippet.Title       = Session["title"].ToString();
                video.Snippet.Description = txtVidDescription.Text;
                video.Snippet.Tags        = new string[] { "Autos" };
                //video.Snippet.CategoryId = "2";
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "public";
                var       filePath         = path;
                const int KB               = 0x400;
                var       minimumChunkSize = 256 * KB;
                // tmr.Enabled = true;
                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged  += videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
                    videosInsertRequest.ChunkSize         = minimumChunkSize * 8;
                    //await  videosInsertRequest.UploadAsync();
                    videosInsertRequest.Upload();
                }
            }
            catch (Exception ex)
            {
                CreateLog err = new CreateLog();
                CreateLog.CreateLogFiles();
                err.ErrorLog(Server.MapPath("/Logs/ErrorLog.txt"), ex.Message);
            }
            finally
            {
            }
        }
示例#16
0
        void videosInsertRequest_ResponseReceived(Google.Apis.YouTube.v3.Data.Video video)
        {
            //Response.Write(String.Format("Video id '{0}' was successfully uploaded.", video.Id));

            Session["videoid"] = video.Id;
        }
示例#17
0
        public async Task QueuePlaylist(CommandContext ctx, string playlistUrl, [Description("Shuffle the playlist when adding to queue. \"true\" to enable.")] bool shuffle = false)
        {
            if (ctx.Client.GetVoiceNext()?.GetConnection(ctx.Guild)?.Channel != null && ctx.Client.GetVoiceNext().GetConnection(ctx.Guild).Channel.Users.All(e => e.Id != ctx.User.Id))
            {
                throw new OutputException("You must join a voice channel to queue songs.");
            }

            Uri playlistUri;

            try
            {
                playlistUri = new Uri(playlistUrl);
            }
            catch
            {
                throw new OutputException("Invalid url.");
            }

            NameValueCollection query = HttpUtility.ParseQueryString(playlistUri.Query);

            if (!query.AllKeys.Contains("list"))
            {
                throw new OutputException("Url must point to a YouTube playlist, specifically with a \"list=\" query.");
            }

            YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                ApiKey          = Globals.BotSettings.YoutubeApiKey,
                ApplicationName = this.GetType().ToString()
            });

            PlaylistsResource.ListRequest playlistListRequest = youtubeService.Playlists.List("snippet");
            playlistListRequest.Id         = query["list"];
            playlistListRequest.MaxResults = 1;

            PlaylistListResponse playlistListResponse = playlistListRequest.Execute();

            PlaylistItemsResource.ListRequest playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
            playlistItemsListRequest.PlaylistId = query["list"];
            playlistItemsListRequest.MaxResults = 50;

            PlaylistItemListResponse playlistItemsListResponse = playlistItemsListRequest.Execute();

            if (!playlistItemsListResponse.Items.Any())
            {
                throw new OutputException("Unable to retrieve playlist or playlist is empty.");
            }

            if (shuffle)
            {
                playlistItemsListResponse.Items.Shuffle();
            }

            int resultQueueCount = GuildQueues.ContainsKey(ctx.Guild.Id) ? GuildQueues[ctx.Guild.Id].Count + playlistItemsListResponse.Items.Count : playlistItemsListResponse.Items.Count;

            await ctx.RespondAsync($"Queuing {playlistItemsListResponse.Items.Count} songs, please be patient if this is the first items to be added to queue. " +
                                   "(If you try to play music and nothing happens most likely the first song is still pending)");

            if (!GuildMusicStatuses.TryGetValue(ctx.Guild.Id, out MusicStatus musicStatus))
            {
                GuildMusicStatuses.Add(ctx.Guild.Id, new MusicStatus
                {
                    Skip = false
                });
            }

            while (GuildMusicStatuses[ctx.Guild.Id].Queuing)
            {
            }

            GuildMusicStatuses[ctx.Guild.Id].Queuing = true;

            foreach (PlaylistItem playlistItem in playlistItemsListResponse.Items)
            {
                string id = playlistItem.Snippet.ResourceId.VideoId;

                VideosResource.ListRequest idSearch = youtubeService.Videos.List("id,snippet");
                idSearch.Id         = id;
                idSearch.MaxResults = 1;

                VideoListResponse videoListResponse = await idSearch.ExecuteAsync();

                if (videoListResponse.Items.Count == 0)
                {
                    await ctx.RespondAsync("Video link cannot be parsed.");

                    return;
                }

                if (!GuildQueues.ContainsKey(ctx.Guild.Id))
                {
                    GuildQueues.Add(ctx.Guild.Id, new List <JigglySong>());
                }

                Video parsedVideo = videoListResponse.Items.First();

                if (!string.IsNullOrWhiteSpace(parsedVideo.ContentDetails?.Duration) && XmlConvert.ToTimeSpan(parsedVideo.ContentDetails.Duration).Minutes > 15)
                {
                    await ctx.RespondAsync("This video is too long, please try to find something shorter than 15 minutes.");
                }

                Guid guid = Guid.NewGuid();

                AddSong(guid, parsedVideo.Snippet.Title, parsedVideo.Id, parsedVideo.Snippet.ChannelTitle, JigglySong.SongType.Youtube, ctx.Member);

                if (!DownloadHelper.GuildMusicTasks.ContainsKey(ctx.Guild.Id))
                {
                    DownloadHelper.GuildMusicTasks.Add(ctx.Guild.Id, new List <(Guid guid, Func <string> downloadTask)>());
                }

                DownloadHelper.GuildMusicTasks[ctx.Guild.Id].Add((guid, () => DownloadHelper.DownloadFromYouTube(ctx, $"https://www.youtube.com/watch?v={id}")));

                if (!DownloadHelper.IsDownloadLoopRunning)
                {
                    new Thread(() => DownloadHelper.DownloadQueue(ctx.Guild.Id)).Start();
                }
            }

            GuildMusicStatuses[ctx.Guild.Id].Queuing = false;

            DiscordEmbedBuilder confirmationBuilder = new DiscordEmbedBuilder
            {
                Description = $"**✅ Successfully added [{playlistListResponse.Items.First().Snippet.Title}](https://www.youtube.com/playlist?list={query["list"]}) " +
                              $"to queue positions {resultQueueCount + 1 - playlistItemsListResponse.Items.Count}-{resultQueueCount}**"
            };

            await ctx.RespondAsync(null, false, confirmationBuilder.Build());
        }