Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i upload to youtube to my gmail account ? #38

Open
Csharper1972 opened this issue Aug 21, 2015 · 0 comments
Open

How can i upload to youtube to my gmail account ? #38

Csharper1972 opened this issue Aug 21, 2015 · 0 comments

Comments

@Csharper1972
Copy link

On my laptop when i surf with chrome to gmail it's getting to gmail.com to my [email protected]
But on my program in csharp in my client_secrets.JSON file the gmail account there is [email protected]

How can i make that in my csharp program it will upload the video file to [email protected] without changing the gmail account i'm surfing to in chrome ?
For some reason when i upload to the youtube it's uploading to the channel according to the gmail in chrome and not the one in the JSON file.

This is my code to upload to youtube:

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)
    {

    }
}

}

And this is my JSON file content:

{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"jfffffffflCv","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":"[email protected]","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],"client_x509_cert_url":"","client_id":"19300890668-ffffffffffffff8tr707m07maf.apps.googleusercontent.com","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"}}

The problem again instead uploading the video file to [email protected] it's uploading the video file to the account on [email protected]

How can i make it to upload it to [email protected] without disconnect or changing anything in the chrome gmail.com ?

What is the JSON file for if it dosent upload the file to the gmail account in it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant