Upload or share video on youtube in Appcelerator Titanium

Posted By : Ajit Jati | 04-Mar-2015

In one of my recent Titanium project, there was a client requirement on Youtube upload and share. So I searched for a cross platform solution to be able to upload videos on youtube,but unfortunately there is no Titanium API available by Google or Appcelerator for such thing. So I browsed through the web and created a solution using both Google Rest APIs and Titaniums Javascript APIs.

Elements we will be using :

  • Blob of the image which I have to upload.
  • Access token required for the google api's.(You may need Google OAuth 2.0 module which will give you access token from google after authentication)
  • Google javascript API.
  • Scopes to be used . ["https://www.googleapis.com/auth/youtube",'https://www.googleapis.com/auth/youtube.upload' ].

Before you start :

  • We need a Google Account to access the Google Developers Console, request an API key, and register your application.
  • Register your application with Google in order to work with its API requests.
  • After registering the application, we need to select the YouTube Data API as one of the services that your application uses:
    1. Go to the Developers Console and select the project that you just registered.
    2.   In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the YouTube Data API v3.

Steps to achieve:

  • Create a new Titanium Project and try to authenticate with google to get access token.
  • After successful authentication call the following method.
    var uploadVideo = function() {
    	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "/extras/video.MOV");
    	InitiateUploading(file, googleAuth.getAccessToken());
    };
    
    Note : googleAuth.getAccessToken() is used to get token using the module url shared above.
  • Now the 'InitiateUploading' method would look like :
    var InitiateUploading = function(file, accessToken) {
    	var metadata = {
    		snippet : {
    			"title" : "Demo Youtube Video",
    			"description" : "This is a description of my video",
    			"tags" : ["cool", "video", "more keywords"],
    			"categoryId" : 22
    		},
    		status : {
    			"privacyStatus" : "public",
    			"embeddable" : "True",
    			"license" : "youtube"
    		},
    	};
    	var xhrList = Ti.Network.createHTTPClient({
    		// function called when the response data is available
    		onload : function(e) {
    			Ti.API.error("Success Text Raw : " + this.allResponseHeaders + "\n status :" + this.status);
    			var location = this.getResponseHeader("Location");
    			UploadFile(location, accessToken, file);
    		},
    		// function called when an error occurs, including a timeout
    		onerror : function(e) {
    			Ti.API.error("Error from upload" + this.responseText);
    		},
    		timeout : 10000,
    		autoEncodeUrl : true
    	});
    	var url = 'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=' + Object.keys(metadata).join(',');
    	xhrList.open("POST", url);
    	xhrList.setRequestHeader('Authorization', "Bearer " + accessToken);
    	xhrList.setRequestHeader('content-type', 'application/json; charset=UTF-8');
    	xhrList.setRequestHeader('content-length', 278);
    	xhrList.setRequestHeader('x-upload-content-length', file.length);
    	xhrList.setRequestHeader('x-upload-content-type', "video/*");
    	xhrList.setRequestHeader('content-type', 'application/json; charset=UTF-8');
    
    	xhrList.send(JSON.stringify(metadata));
    };
    
            
    Note : We have created a HTTP POST request based on the Resumable upload request provided by google. Additionally we need to set the video details on the metadata part.
  • The “uploadFile” method would look like
    var uploadFile = function(url, accessToken, file) {
    	var xhrList = Ti.Network.createHTTPClient({
    		// function called when the response data is available
    		onload : function(e) {
    			//Ti.API.error("ALL HEADERS  : " + this.allResponseHeaders + "\n status :" + this.status);
    			//var location = this.getResponseHeader("Location");
    			Ti.API.error("Uploaded on Youtube :: " + this.responseText);
    		},
    		onsendstream : function(e) {
    			Ti.API.error("Sending stream in upload" + e.progress);
    		},
    
    		// function called when an error occurs, including a timeout
    		onerror : function(e) {
    			Ti.API.error("Error from upload" + this.responseText);
    		},
    		timeout : 100000,
    		autoEncodeUrl : true
    	});
    	//var url = 'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=' + Object.keys(metadata).join(',');
    	Ti.API.info("url = " + url);
    	xhrList.open("POST", url);
    	xhrList.setRequestHeader('Authorization', "Bearer " + accessToken);
    	xhrList.setRequestHeader('content-length', file.lenth);
    	xhrList.setRequestHeader('content-type', "video/*");
    	xhrList.send(file.read());
    };
    
            
  • Note : Here we next post the video to the location we have recieved from the response header in  step-3.
  • We should get the upload status , video ID , error messages (if any) , thumbnail urls with the response in step-4.
  • Thats it , if we get a 201 (Created) response in step-4 then we might check for the uploaded video now on the My channel section on Youtube.

For more info , visit

https://developers.google.com/youtube/getting_started

https://developers.google.com/api-client-library/javascript/features/authentication

https://developers.google.com/accounts/docs/OAuth2

Good Luck , Cheers !!

 

About Author

Author Image
Ajit Jati

Ajit is an proficient Project Manager specializing in Mobile technologies. He possesses extensive development experience in Titanium, Android, Kotlin, Roku, and PHP. Ajit has successfully delivered various projects in the OTT, AR/VR, and Travel industries. His skill set includes developing and maintaining project plans, schedules, and budgets, ensuring timely delivery while staying within the allocated budget. He excels in collaborating closely with clients to define project scope and requirements, establish project timelines and milestones, and effectively manage expectations. He conducts regular project status meetings, ensuring effective communication and providing updates to clients and stakeholders on project progress, risks, and issues. Furthermore, Ajit takes on the role of a coach and mentor for team,offering guidance on project management best practices and assisting in their skill development.

Request for Proposal

Name is required

Comment is required

Sending message..