Google Cloud Print Plugin for Unity

Type : Unity 3D Plugin

The first plugin to use the Google Cloud Print services in Unity projects.

Comming soon on the Unity Asset Store

How to use Google Cloud Print Plugin

1.      Init a new scene

When the unity package is installed on your project, create a new scene.

In this scene create a new empty object named “Main” (for example) and attach to him the “Google Authentication” and the “Google Cloud Print Plugin” Components.

 

2.      Create your script

Create a new script named “GoogleCloudPrintTest” (for example) and attach it to your “Main” game object too.

Create some variables and on the “Start” method retrieve your components.

private static string APP_PROXY = "com.myproject"; 
private GoogleCloudPrintPlugin GCPPlugin; 
private GoogleAuthentication googleAuthentication; 
 
void Start () 
{
	// Retrieve plugin component
	googleAuthentication = GetComponent();
	GCPPlugin = GetComponent();
 
	// Init plugin
	GCPPlugin.AppProxy = APP_PROXY;
}

Now you are ready to call the Google Cloud Print services !

 

3.      Connect a user

There is several methods to connect a user with the Google services. The plugin provide you 3 methods.

  • The Client Login method
  • The OAuth2 method
  • The GetAuthTokenByFeatures method for the Android devices

 

Connect a user with the Client Login method (more informations at https://developers.google.com/accounts/docs/AuthForInstalledApps)

Just call the “ClientLogin” method on the “GoogleAuthentication” classe with a google login and password.

googleAuthentication.ClientLogin("HOSTED_OR_GOOGLE", "yourGmailEmail", "yourGmailPassword", "cloudprint", APP_PROXY, (success, message, SID, LSID, auth) => 
{
	if (success)
	{
		// For example, store the client auth
		string clientId = auth;
 
		// Do something...
 
		// Update authorization type
		GCPPlugin.AuthorizationType = GoogleCloudPrintPlugin.GCPAuthorizationType.GoogleLogin;
	}
	else
	{
		// For example, store the error message
		string errorMessage = message;
 
		// Do something...
	}
});

 

Connect a user with the OAuth2 method (more informations at https://developers.google.com/accounts/docs/OAuth2)

Just call the “OAuth2Code” and “OAuth2Token” methods on the “GoogleAuthentication” classe.

private static string AppClientId = "yourAppClientId";
private static string AppClientSecret = "yourAppClientSecret";
private static string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; // urn:ietf:wg:oauth:2.0:oob for a mobile app or another url set in your application
private static string SCOPE = "https://www.googleapis.com/auth/cloudprint";
 
// ...
 
// Open a browser and get a code for the user
googleAuthentication.OAuth2Code("code", AppClientId, REDIRECT_URI, SCOPE);
 
// ..

When the user have accepted the app and have the code you can call the other method to get a token.

// ...
 
// Retrieve an OAUth2 Token
googleAuthentication.OAuth2Token(authCode, AppClientId, AppClientSecret, REDIRECT_URI, "authorization_code", SCOPE, (success, message, accessToken, tokenType, expiresIn, refreshToken) => 
{
    if (success)
    {
        // Store the auth token
        string authToken = accessToken;
 
        // Do something...
 
        // Update authorization type
        GCPPlugin.AuthorizationType = GoogleCloudPrintPlugin.GCPAuthorizationType.OAuth;
    }
    else
    {
		// For example, store the error message
		string errorMessage = message;
 
		// Do something...
    }
});
// ...

 

Connect a user with the GetAuthTokenByFeatures (more informations at http://developer.android.com/reference/android/accounts/AccountManager.html)

Just call the “GetAuthTokenByFeatures” method on the “GoogleAuthentication” classe.

// Create a callback
#if UNITY_ANDROID
    public void AuthTokenCallback(string result)
    {
        Dictionary<string, object> requestResult = MiniJSON.Json.Deserialize(result) as Dictionary<string, object>;
        bool success  = (bool)requestResult["success"];
 
        if (success)
        {
            string authToken = (string)requestResult["authtoken"];
        }
        else
        {
            string errorMessage = (string)requestResult["message"];
        }
    }
#endif
 
// ...
 
#if UNITY_ANDROID
            // Get a OAuth2 Token for Google Cloud Print services
            googleAuthentication.GetAuthTokenByFeatures("com.google", "oauth2:" + SCOPE, "AuthTokenCallback", gameObject);
#endif

With this method on Android, a message pop to allow the user to authorize your app to access to the the Google Cloud Print services.

You must add the “USE_CREDENTIALS” permission in your “AndroidManifest.xml” to use this method. You can compile your game first on Android and copy/paste the generated Manifest file from your Temp/StagingArea/ folder to the Plugin/Android/ folder and add this permission :

<uses-permission android:name="android.permission.USE_CREDENTIALS" />

4.      Call the Google Cloud Print services (moer informations at https://developers.google.com/cloud-print/docs/appInterfaces)

With a valid token you can call all the Google Cloud Print services for a user. There is 5 services that can be called :

  • submit

The /submit service interface is used to send print jobs to the GCP service. Upon initialization, the status of the print job will be QUEUED. The print job is created and the appropriate printer is notified of its existence. The status of the print job can then be tracked using /jobs.

GCPPlugin.Submit("yourToken",
    "yourPrinterId",
    "documentName",
    "",
    texture.EncodeToPNG(), // bytes
    "image/png",
    "",
    (success, message, response) =&gt; 
{
    // Show the result message
    string resultText = message;
});
  • jobs

The /jobs interface retrieves the status of print jobs for a user.

GCPPlugin.Jobs("yourToken",
    "yourPrinterId",
    (success, message, response, jobs) =&gt; 
{
    // Show Jobs count
    string resultText = jobs.Count + " Jobs";
 
    // Store jobs
    currentJobs = jobs;
});
  • deletejob

The /deletejob interface deletes the given print job.

GCPPlugin.DeleteJob("yourToken",
    "yourJobId",
    (success, message, response) =&gt; 
{
    // Show Jobs
    string resultText = message;
 
    // clear jobs
    currentJobs.Clear();
});
  • printer

The /printer interface retrieves the capabilities of the specified printer.

GCPPlugin.Printer("yourToken",
    "yourPrinterId",
    true,
    (success, message, response, printerCapabilities) =&gt; 
{
    // Show Capicities count
    string resultText = printerCapabilities.Capabilities.Count + " Capacities";
});
  • search

The /search interface returns a list of printers accessible to the authenticated user, taking an optional search query as a parameter. Note that by default, /search will not include printers that have been offline for a long time (i.e. whose connectionStatus is DORMANT). This behavior can be overridden if ALL or DORMANT is passed as the value of the optional connection_status parameter.

GCPPlugin.Search("yourToken", 
    (success, message, response, printers) =&gt; 
{
    // Save the printers
    this.printers = printers;
});

 

5.      Example of complete project code Create 4 textures (MyTexture0.png, MyTexture1.png, MyTexture2.png and MyTexture3.png) on your project folder “Assets\Resources\Textures”.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
 
[RequireComponent(typeof(GoogleAuthentication))]
[RequireComponent(typeof(GoogleCloudPrintPlugin))]
public class GoogleCloudPrintTest : MonoBehaviour 
{
	private static string AppClientId = "yourAppId";
	private static string AppClientSecret = "yourAppSecret";
	private static string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
	private static string SCOPE = "https://www.googleapis.com/auth/cloudprint";
	private static string APP_PROXY = "com.myproject";
 
	private string resultText = "";
	private string logText = "";
	private string googleAccountLogin = "your gmail email";
	private string googleAccountPassword = "";
	private string clientId = "";
	private string authCode = "";
	private string authToken = "";
 
	private int currentTextureId = 0;
	private Texture2D texture;
 
	private GoogleCloudPrintPlugin GCPPlugin;
	private GoogleAuthentication googleAuthentication;
	private List<GoogleCloudPrinter> printers;
	private List<GoogleCloudJob> currentJobs;
 
	// Use this for initialization
	void Start () 
	{
		// Retrieve plugin component
		googleAuthentication = GetComponent<GoogleAuthentication>();
		GCPPlugin = GetComponent<GoogleCloudPrintPlugin>();
 
		// Init plugin
		GCPPlugin.AppProxy = APP_PROXY;
 
		// Init printers and jobs list
		printers = new List<GoogleCloudPrinter>();
		currentJobs = new List<GoogleCloudJob>();
 
		// Load first texture 
		texture = (Texture2D)Resources.Load("Textures/MyTexture" + currentTextureId);
	}
 
#if UNITY_ANDROID
	public void AuthTokenCallback(string result)
	{
		Dictionary<string, object> requestResult = MiniJSON.Json.Deserialize(result) as Dictionary<string, object>;
		bool success  = (bool)requestResult["success"];
 
		if (success)
		{
			authToken = (string)requestResult["authtoken"];
			resultText = result;
		}
		else
		{
			resultText = (string)requestResult["message"];
		}
	}
#endif
 
	private void OnGUI()
	{
		// Google Client Connection
		GUI.Label(new Rect(10, 10, 500, 20), "Google Client Connection");
		GUI.Label(new Rect(10, 40, 150, 20), "Login : ");
		GUI.Label(new Rect(10, 70, 150, 20), "Password : ");
		GUI.Label(new Rect(10, 100, 150, 20), "Client Id : " + (clientId.Length > 0 ? "OK" : "NO"));
 
		googleAccountLogin = GUI.TextField(new Rect(100, 30, 150, 20), googleAccountLogin);
		googleAccountPassword = GUI.PasswordField(new Rect(100, 60, 150, 20), googleAccountPassword, '*');
 
		if (GUI.Button(new Rect(10, 130, 200, 30), "GCP Get CLient Login"))
		{
			googleAuthentication.ClientLogin("HOSTED_OR_GOOGLE", googleAccountLogin, googleAccountPassword, "cloudprint", APP_PROXY, (success, message, SID, LSID, auth) => 
			{
				if (success)
				{
					// Store the client auth
					clientId = auth;
 
					// Reset the auth token
					authToken = "";
 
					// Update authorization type
					GCPPlugin.AuthorizationType = GoogleCloudPrintPlugin.GCPAuthorizationType.GoogleLogin;
				}
				else
				{
					resultText = message;
				}
			});
		}
 
		// OAuth2 Connection
		GUI.Label(new Rect(300, 10, 500, 20), "OAuth2 Connection");
 
#if !UNITY_ANDROID
		GUI.Label(new Rect(300, 40, 150, 20), "OAuth Code : ");
#endif
 
		GUI.Label(new Rect(300, 70, 150, 20), "OAuth Token : " + (authToken.Length > 0 ? "OK" : "NO"));
 
#if !UNITY_ANDROID
		authCode = GUI.TextField(new Rect(390, 40, 150, 20), authCode);
 
		if (GUI.Button(new Rect(550, 35, 140, 30), "Request Code"))
		{
			googleAuthentication.OAuth2Code("code", AppClientId, REDIRECT_URI, SCOPE);
		}
#endif
 
		if (GUI.Button(new Rect(300, 130, 200, 30), "GCP Get OAUth2 Token"))
		{
#if UNITY_ANDROID
			// Get a OAuth2 Token for Google Cloud Print services
			googleAuthentication.GetAuthTokenByFeatures("com.google", "oauth2:" + SCOPE, "AuthTokenCallback", gameObject);
#else
			googleAuthentication.OAuth2Token(authCode, AppClientId, AppClientSecret, REDIRECT_URI, "authorization_code", SCOPE, (success, message, accessToken, tokenType, expiresIn, refreshToken) => 
			{
				if (success)
				{
					// Store the auth token
					authToken = accessToken;
 
					// Reset the client auth
					clientId = "";
 
					// Update authorization type
					GCPPlugin.AuthorizationType = GoogleCloudPrintPlugin.GCPAuthorizationType.OAuth;
				}
				else
				{
					resultText = message;
				}
			});
#endif
		}
 
		if (clientId.Length > 0 || authToken.Length > 0)
		{
			if (GUI.Button(new Rect(10, 220, 200, 30), "GCP Search"))
			{
				GCPPlugin.Search(clientId.Length == 0 ? authToken : clientId, 
					(success, message, response, printers) => 
				{
					// Save the printers
					this.printers = printers;
 
					// Log response
					logText = response;
				}, true);
			}
 
			// Show Labels
			GUI.Label(new Rect(10, 255, 100, 30), "SUBMIT TO");
			GUI.Label(new Rect(10, 295, 100, 30), "JOBS FROM");
			GUI.Label(new Rect(10, 335, 100, 30), "CAPABALITIES");
 
			int i = 0;
			int printersCount = this.printers.Count;
 
			// Show printers count
			if (printersCount > 0)
			{
				GUI.Label(new Rect(250, 220, 250, 30), printersCount + " printers founded. 3 printers displayed.");
			}
 
			// Show only 3 printers
			for (; i < Mathf.Min(3, printersCount) ; ++i)
			{
				GoogleCloudPrinter printer = printers[i];
 
				for (int j = 0; j < 3; ++j)
				{
					if (GUI.Button(new Rect(110 + (170 * i), 255 + (j * 40), 160, 30), printer.Name))
					{
						if (j == 0)
						{
							GCPPlugin.Submit(clientId.Length == 0 ? authToken : clientId,
								printer.Id,
								texture.name,
								"",
								texture.EncodeToPNG(),
								"image/png",
								"",
								(success, message, response) => 
							{
								// Show the result message
								resultText = message;
 
								// Log response
								logText = response;
							}, true);
						}
						else if (j == 1)
						{
							GCPPlugin.Jobs(clientId.Length == 0 ? authToken : clientId,
								printer.Id,
								(success, message, response, jobs) => 
							{
								// Show Jobs count
								resultText = jobs.Count + " Jobs";
 
								// Store jobs
								currentJobs = jobs;
 
								// Log response
								logText = response;
							}, true);
						}
						else if (j == 2)
						{
							GCPPlugin.Printer(clientId.Length == 0 ? authToken : clientId,
								printer.Id,
								true,
								(success, message, response, printerCapabilities) => 
							{
								// Show Capicities count
								resultText = printerCapabilities.Capabilities.Count + " Capacities";
 
								// Log response
								logText = response;
							}, true);
						}
					}
				}
			}
 
			i = 0;
			foreach (GoogleCloudJob job in this.currentJobs)
			{
				if (GUI.Button(new Rect(10 + (180 * i), 380, 170, 30), "DEL JOB " + job.Title))
				{
					GCPPlugin.DeleteJob(clientId.Length == 0 ? authToken : clientId,
							job.Id,
							(success, message, response) => 
						{
							// Show Jobs
							resultText = message;
 
							// clear jobs
							currentJobs.Clear();
 
							// Log response
							logText = response;
						}, true);
				}
 
				++i;
			}
		}
 
		// Texture button
		if (GUI.Button(new Rect(10, 170, 100, 40), texture))
		{
			ChangeTexture();
		}
 
		// Result and log text
		resultText = GUI.TextArea(new Rect(10, 440, 300, 70), resultText);
		logText = GUI.TextArea(new Rect(320, 440, 300, 70), logText);
	}
 
	private void ChangeTexture()
	{
		// Load next texture
		if (currentTextureId < 3)
		{
			++currentTextureId;
		}
		else
		{
			currentTextureId = 0;
		}
 
		texture = (Texture2D)Resources.Load("Textures/MyTexture" + currentTextureId);
	}
}

Author: admin

Share This Post On