将视频文件上传到youtube时,为什么要将其上传到我的第二个Gmail帐户?

时间:2015-08-18 23:58:07

标签: c# .net winforms youtube

在我的桌面电脑上,我有一个Gmail帐户。 在我的笔记本电脑上,我有另一个不同的gnet帐户。

我的JSON文件:client_secrets包含在笔记本电脑和台式机上同一个gmail帐户在我的桌面电脑上。但是,当我从笔记本电脑上传视频文件时,它会将其上传到笔记本电脑上的我的Gmail帐户。我希望它将它上传到我桌面电脑上的gmail youtube帐户。

首先,为什么笔记本电脑上传到笔记本电脑上的gmail帐户而不是桌面电脑上的gmail? 第二,我怎么能改变它?即使在笔记本电脑和台式电脑上,我也在笔记本电脑上使用相同的client_secrets文件,然后将其上传到笔记本电脑上的gmail。

另一件事是,在我的笔记本电脑上,我已连接到我的笔记本电脑的gmail帐户和连接到台式电脑的gmail帐户的台式电脑上。 但我确信JSON文件上的gmail帐户设置了文件将上传到的位置。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Google.GData.Client;
using Google.GData.Extensions;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Net;

namespace Youtubeupload
{
    public partial class Youtube_Uploader : Form
    {
        public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

        YouTubeService service;

        string apiKey = "myapikey";
        string FileNameToUpload = "";
        string[] stringProgressReport = new string[5];
        long totalBytes = 0;
        DateTime dt;
        public static string fileuploadedsuccess = "";
        Upload upload;

        public Youtube_Uploader(string filetoupload)
        {
            InitializeComponent();

            FileNameToUpload = @"C:\Users\tester\Videos\test.mp4";
            service = AuthenticateOauth(apiKey);
            var videoCatagories = service.VideoCategories.List("snippet");
            videoCatagories.RegionCode = "IL";
            var result = videoCatagories.Execute();
            MakeRequest();
            backgroundWorker1.RunWorkerAsync();
        }

        public static string uploadstatus = "";
        Video objects = null;
        private void videosInsertRequest_ResponseReceived(Video obj)
        {
            System.Timers.Timer aTimer;
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += aTimer_Elapsed;
            aTimer.Interval = 10000;
            aTimer.Enabled = false;
            uploadstatus = obj.Status.UploadStatus;
            if (uploadstatus == "uploaded")
            {
                fileuploadedsuccess = "file uploaded successfully";
            }
            if (uploadstatus == "Completed")
            {
                fileuploadedsuccess = "completed";
            }
            objects = obj;
        }

        void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

        }

        double mbSent = 0;
        int percentComplete = 0;
        VideoProcessingDetailsProcessingProgress vp = new VideoProcessingDetailsProcessingProgress();
        private void videosInsertRequest_ProgressChanged(IUploadProgress obj)
        {            
            ulong? ul = vp.TimeLeftMs;
            stringProgressReport[1] = obj.Status.ToString();
            mbSent = ((double)obj.BytesSent) / (1 << 20);
            stringProgressReport[2] = mbSent.ToString();
            percentComplete = (int)Math.Round(((double)obj.BytesSent) / totalBytes * 100);
            stringProgressReport[3] = percentComplete.ToString();

            if (obj.BytesSent != 0)
            {
                var currentTime = DateTime.Now;
                TimeSpan diff = currentTime - dt;
                double diffSeconds = (DateTime.Now - dt).TotalSeconds;
                double averageSpeed = obj.BytesSent / diffSeconds;
                double MBunits = ConvertBytesToMegabytes((long)averageSpeed);
                stringProgressReport[4] = string.Format("{0:f2} MB/s", MBunits);
            }
        }

        public static YouTubeService AuthenticateOauth(string apiKey)
        {
            try
            {
                YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
                {
                    ApiKey = apiKey,
                    ApplicationName = "YouTube Uploader",
                });
                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;
            }
        }

        private void MakeRequest()
        {
            var searchListRequest = service.Search.List("snippet");
            searchListRequest.Q = "daniel lipman gta"; // Replace with your search term.
            searchListRequest.RegionCode = "IL";
            searchListRequest.MaxResults = 50;
            // Call the search.list method to retrieve results matching the specified query term.
            var searchListResponse = searchListRequest.Execute();

            List<string> videos = new List<string>();
            List<string> channels = new List<string>();
            List<string> playlists = new List<string>();
            // matching videos, channels, and playlists.
            foreach (var searchResult in searchListResponse.Items)
            {
                switch (searchResult.Id.Kind)
                {
                    case "youtube#video":
                        videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
                        break;

                    case "youtube#channel":
                        channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
                        break;

                    case "youtube#playlist":
                        playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
                        break;
                }
            }
        }

        static Video video = new Video();
        private void UploadVideo(string FileName, string VideoTitle, string VideoDescription)
        {
            try
            {
                UserCredential credential;
                using (FileStream stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None,
                        new FileDataStore("YouTube.Auth.Store")).Result;
                }
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                });

                video.Snippet = new VideoSnippet();
                video.Snippet.Title = VideoTitle;
                video.Snippet.Description = VideoDescription;
                video.Snippet.Tags = new string[] { "tag1", "tag2" };
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "public";
                using (var fileStream = new FileStream(FileName, FileMode.Open))
                {

                    const int KB = 0x400;
                    var minimumChunkSize = 256 * KB;

                    var videosInsertRequest = youtubeService.Videos.Insert(video,
                        "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged +=
                        videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived +=
                        videosInsertRequest_ResponseReceived;
                    // The default chunk size is 10MB, here will use 1MB.
                    videosInsertRequest.ChunkSize = minimumChunkSize * 3;
                    dt = DateTime.Now;
                    videosInsertRequest.Upload();
                }
            }
            catch (Exception errors)
            {
                string errorss = errors.ToString();
            }
        }

        static double ConvertBytesToMegabytes(long bytes)
        {
            return (bytes / 1024f) / 1024f;
        }

        private void Youtube_Uploader_Load(object sender, EventArgs e)
        {

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            UploadVideo(FileNameToUpload, "Gta v ps4", "Testing gta v ps4");
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int eventIndex = 0;
            try
            {
                eventIndex = (int)e.UserState;
            }
            catch
            {
                MessageBox.Show(e.UserState == null ? "null" : e.UserState.GetType().FullName);
                throw;
            }

            if (eventIndex == 0) // upload status.
            {
                label14.Text = stringProgressReport[0];
            }
            else if (eventIndex == 1) // obj.Status
            {
                label16.Text = stringProgressReport[1];
            }
            else if (eventIndex == 2) // mb sent so far
            {
                stringProgressReport[2];
                label5.Text = stringProgressReport[2];
            }
            else if (eventIndex == 3) // percent complete
            {
                progressBar1.Value = Int32.Parse(stringProgressReport[3]);
            }
            else if (eventIndex == 4) // percent complete
            {
                label8.Text = stringProgressReport[4];
            }
            else
            {
                throw new Exception("Invalid event index: " + eventIndex);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }
    }
}

我想要的是它会将视频文件上传到台式机上的我的Gmail帐户,即使我是从笔记本电脑上传它并且我已经连接到另一个Gmail帐户。

0 个答案:

没有答案