diff --git a/.gitignore b/.gitignore index 20168e73..2235a2e2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ +**/.DS_Store + .gradle/ .idea/ -.vscode/ bin/ build/ *.iml diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..9c2f3c6f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,55 @@ +{ + "files.exclude": { + "**/.DS_Store": true, + "**/.git": true, + "**/.gitmodules": true, + "**/*.booproj": true, + "**/*.pidb": true, + "**/*.suo": true, + "**/*.user": true, + "**/*.userprefs": true, + "**/*.unityproj": true, + "**/*.dll": true, + "**/*.exe": true, + "**/*.pdf": true, + "**/*.mid": true, + "**/*.midi": true, + "**/*.wav": true, + "**/*.gif": true, + "**/*.ico": true, + "**/*.jpg": true, + "**/*.jpeg": true, + "**/*.png": true, + "**/*.psd": true, + "**/*.tga": true, + "**/*.tif": true, + "**/*.tiff": true, + "**/*.3ds": true, + "**/*.3DS": true, + "**/*.fbx": true, + "**/*.FBX": true, + "**/*.lxo": true, + "**/*.LXO": true, + "**/*.ma": true, + "**/*.MA": true, + "**/*.obj": true, + "**/*.OBJ": true, + "**/*.asset": true, + "**/*.cubemap": true, + "**/*.flare": true, + "**/*.mat": true, + "**/*.meta": true, + "**/*.prefab": true, + "**/*.unity": true, + "build/": true, + "Build/": true, + "Library/": true, + "library/": true, + "obj/": true, + "Obj/": true, + "ProjectSettings/": true, + "temp/": true, + "Temp/": true + }, + "dotnet.defaultSolution": "TestGoogleSignIn.sln" +} \ No newline at end of file diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.meta b/CONTRIBUTING.md.meta similarity index 55% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.meta rename to CONTRIBUTING.md.meta index 3976f6ef..83782ca2 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.meta +++ b/CONTRIBUTING.md.meta @@ -1,9 +1,5 @@ fileFormatVersion: 2 -guid: f3911d467587242978192a8723c68395 -labels: -- gvh -timeCreated: 1508956022 -licenseType: Free +guid: bf5b818b5e6f1fb4b920c2d651dd2f82 TextScriptImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository.meta b/Editor.meta similarity index 62% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository.meta rename to Editor.meta index 26cfc222..1a11891a 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository.meta +++ b/Editor.meta @@ -1,8 +1,6 @@ fileFormatVersion: 2 -guid: eefc3dc8b56e545998952bd59ab36247 +guid: b15db503f08f84da789165e1557fdd7b folderAsset: yes -timeCreated: 1508956004 -licenseType: Free DefaultImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin.meta b/Editor/iOS.meta similarity index 62% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin.meta rename to Editor/iOS.meta index 4a56a312..22b933e3 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin.meta +++ b/Editor/iOS.meta @@ -1,8 +1,6 @@ fileFormatVersion: 2 -guid: 34b86fc2e934d482ea5f9d1f5354b0f9 +guid: 71aabb773a37445bb8dcac856c8c672e folderAsset: yes -timeCreated: 1508956004 -licenseType: Free DefaultImporter: externalObjects: {} userData: diff --git a/Editor/iOS/PListImporter.cs b/Editor/iOS/PListImporter.cs new file mode 100644 index 00000000..569dbb44 --- /dev/null +++ b/Editor/iOS/PListImporter.cs @@ -0,0 +1,21 @@ +#if UNITY_EDITOR +using System.IO; + +using UnityEngine; + +using UnityEditor.AssetImporters; + +[ScriptedImporter(1, "plist")] +public class PListImporter : ScriptedImporter +{ + public override void OnImportAsset(AssetImportContext ctx) + { + if(ctx.mainObject is TextAsset) + return; + + var subAsset = new TextAsset(File.ReadAllText(ctx.assetPath)); + ctx.AddObjectToAsset("text", subAsset); + ctx.SetMainObject(subAsset); + } +} +#endif \ No newline at end of file diff --git a/Editor/iOS/PListImporter.cs.meta b/Editor/iOS/PListImporter.cs.meta new file mode 100644 index 00000000..1c45a1eb --- /dev/null +++ b/Editor/iOS/PListImporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57db1ee44933e4015a8e5b4f29a487e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/iOS/PListProcessor.cs b/Editor/iOS/PListProcessor.cs new file mode 100644 index 00000000..ded87cda --- /dev/null +++ b/Editor/iOS/PListProcessor.cs @@ -0,0 +1,67 @@ +#if UNITY_EDITOR +using UnityEngine; + +using UnityEditor; +using UnityEditor.iOS.Xcode; + +using UnityEditor.Build; +using UnityEditor.Build.Reporting; + +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; + +public class PListProcessor : IPostprocessBuildWithReport +{ + public int callbackOrder => 99999; + + public void OnPostprocessBuild(BuildReport report) + { +#if UNITY_IOS + string projectBundleId = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS); + var plistFiles = AssetDatabase.FindAssets("glob:\"**/*.plist\"").Select((guid) => { + var doc = new PlistDocument(); + doc.ReadFromFile(AssetDatabase.GUIDToAssetPath(guid)); + return doc; + }).Where((doc) => { + return doc.root.values.TryGetValue("BUNDLE_ID",out var element) && element.AsString() == projectBundleId; + }).ToArray(); + + if(!(plistFiles?.Length > 0)) + return; + + var google = plistFiles.FirstOrDefault(); + + if(!(google.root.values.TryGetValue("CLIENT_ID",out var CLIENT_ID) && CLIENT_ID?.AsString() is string clientID && clientID.EndsWith("googleusercontent.com"))) + throw new KeyNotFoundException("CLIENT_ID"); + if(!(google.root.values.TryGetValue("REVERSED_CLIENT_ID",out var REVERSED_CLIENT_ID) && REVERSED_CLIENT_ID?.AsString() is string reversedClientID && reversedClientID.StartsWith("com.googleusercontent"))) + throw new KeyNotFoundException("REVERSED_CLIENT_ID"); + + string plistPath = Path.Combine( report.summary.outputPath, "Info.plist" ); + + var info = new PlistDocument(); + info.ReadFromFile(plistPath); + + info.root.SetString("GIDClientID",clientID); + var CFBundleURLTypes = (info.root.values.TryGetValue("CFBundleURLTypes",out var element) ? element.AsArray() : null) ?? info.root.CreateArray("CFBundleURLTypes"); + if(!(CFBundleURLTypes?.values?.Count > 0 && CFBundleURLTypes.values.OfType().Select((dict) => dict.values.TryGetValue("CFBundleURLSchemes",out var value) ? value?.AsArray() : null).OfType().SelectMany((array) => array.values).Any((item) => item?.AsString() == reversedClientID))) + { + var dict = CFBundleURLTypes.AddDict(); + dict.SetString("CFBundleTypeRole","Editor"); + dict.CreateArray("CFBundleURLSchemes").AddString(reversedClientID); + } + + if(google.root.values.TryGetValue("WEB_CLIENT_ID",out var WEB_CLIENT_ID) && WEB_CLIENT_ID?.AsString() is string webClientID && !string.IsNullOrWhiteSpace(webClientID)) + { + if(webClientID.EndsWith("googleusercontent.com")) + info.root.SetString("GIDServerClientID",webClientID); + else throw new ArgumentException("WebClientID"); + } + + info.WriteToFile(plistPath); +#endif + } +} + +#endif \ No newline at end of file diff --git a/Editor/iOS/PListProcessor.cs.meta b/Editor/iOS/PListProcessor.cs.meta new file mode 100644 index 00000000..e450597e --- /dev/null +++ b/Editor/iOS/PListProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97598a1b92cb146879db81f44bfeb14d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignIn.asmdef b/GoogleSignIn.asmdef new file mode 100644 index 00000000..87028124 --- /dev/null +++ b/GoogleSignIn.asmdef @@ -0,0 +1,3 @@ +{ + "name": "GoogleSignin" +} diff --git a/GoogleSignIn.asmdef.meta b/GoogleSignIn.asmdef.meta new file mode 100644 index 00000000..af758047 --- /dev/null +++ b/GoogleSignIn.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 2a0340569ab0e1245a38e0d6c7b2529b +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn.meta b/GoogleSignIn.meta similarity index 100% rename from GoogleSignInPlugin/Assets/GoogleSignIn.meta rename to GoogleSignIn.meta diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor.meta b/GoogleSignIn/Editor.meta similarity index 100% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor.meta rename to GoogleSignIn/Editor.meta diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml b/GoogleSignIn/Editor/GoogleSignInDependencies.xml similarity index 53% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml rename to GoogleSignIn/Editor/GoogleSignInDependencies.xml index 625d2e51..49412fe3 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml +++ b/GoogleSignIn/Editor/GoogleSignInDependencies.xml @@ -3,17 +3,14 @@ - - - extra-google-m2repository - - + + + + - - + diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml.meta b/GoogleSignIn/Editor/GoogleSignInDependencies.xml.meta similarity index 78% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml.meta rename to GoogleSignIn/Editor/GoogleSignInDependencies.xml.meta index 298fa3d3..6493d604 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml.meta +++ b/GoogleSignIn/Editor/GoogleSignInDependencies.xml.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: 938014c9994164100b26d82840a88fbb labels: - gvh -timeCreated: 1507661087 -licenseType: Pro +- gvh_version-1.0.4 TextScriptImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.1.txt b/GoogleSignIn/Editor/google-signin-plugin_v1.0.4.txt similarity index 52% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.1.txt rename to GoogleSignIn/Editor/google-signin-plugin_v1.0.4.txt index f7061862..a0e24547 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.1.txt +++ b/GoogleSignIn/Editor/google-signin-plugin_v1.0.4.txt @@ -1,27 +1,33 @@ -Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml -Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.1/google-signin-support-1.0.1.aar -Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.1/google-signin-support-1.0.1.aar.md5 -Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.1/google-signin-support-1.0.1.aar.sha1 -Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.1/google-signin-support-1.0.1.pom -Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.1/google-signin-support-1.0.1.pom.md5 -Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.1/google-signin-support-1.0.1.pom.sha1 -Assets/GoogleSignIn/Future.cs -Assets/GoogleSignIn/GoogleSignIn.cs -Assets/GoogleSignIn/GoogleSignInConfiguration.cs -Assets/GoogleSignIn/GoogleSignInStatusCode.cs -Assets/GoogleSignIn/GoogleSignInUser.cs -Assets/GoogleSignIn/Impl/BaseObject.cs -Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs -Assets/GoogleSignIn/Impl/NativeFuture.cs -Assets/GoogleSignIn/Impl/SignInHelperObject.cs +Assets/PlayServicesResolver/Editor/Google.VersionHandlerImpl_v1.2.89.0.dll +Assets/PlayServicesResolver/Editor/Google.IOSResolver_v1.2.89.0.dll +Assets/PlayServicesResolver/Editor/Google.VersionHandler.dll +Assets/PlayServicesResolver/Editor/Google.JarResolver_v1.2.89.0.dll +Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm +Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h +Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h +Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm Assets/Parse/LICENSE Assets/Parse/Plugins/Unity.Compat.dll Assets/Parse/Plugins/Unity.Tasks.dll -Assets/PlayServicesResolver/Editor/Google.IOSResolver_v1.2.54.0.dll -Assets/PlayServicesResolver/Editor/Google.JarResolver_v1.2.54.0.dll -Assets/PlayServicesResolver/Editor/Google.VersionHandler.dll -Assets/PlayServicesResolver/Editor/Google.VersionHandlerImpl_v1.2.54.0.dll -Assets/PlayServicesResolver/Editor/play-services-resolver_v1.2.54.0.txt -Assets/Plugins/Android/native-googlesignin-release.aar -Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h -Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm +Assets/SignInSample/MainScene.unity +Assets/SignInSample/SigninSampleScript.cs +Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs +Assets/GoogleSignIn/Impl/SignInHelperObject.cs +Assets/GoogleSignIn/Impl/NativeFuture.cs +Assets/GoogleSignIn/Impl/BaseObject.cs +Assets/GoogleSignIn/GoogleSignIn.cs +Assets/GoogleSignIn/GoogleSignInConfiguration.cs +Assets/GoogleSignIn/Future.cs +Assets/GoogleSignIn/GoogleSignInUser.cs +Assets/GoogleSignIn/GoogleSignInStatusCode.cs +Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml +Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.md5 +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.sha1 +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.pom.md5 +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.srcaar.sha1 +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.pom.sha1 +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.srcaar +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.pom +Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/1.0.4/google-signin-support-1.0.4.srcaar.md5 diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.0.txt.meta b/GoogleSignIn/Editor/google-signin-plugin_v1.0.4.txt.meta similarity index 64% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.0.txt.meta rename to GoogleSignIn/Editor/google-signin-plugin_v1.0.4.txt.meta index 5477b554..eb7a5d66 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.0.txt.meta +++ b/GoogleSignIn/Editor/google-signin-plugin_v1.0.4.txt.meta @@ -1,10 +1,9 @@ fileFormatVersion: 2 -guid: ca932999723384cdc86087c8423332bb +guid: a67d5f0cfc09749e6b1ce13e8b8e6e1d labels: - gvh - gvh_manifest -timeCreated: 1508875148 -licenseType: Free +- gvh_version-1.0.4 TextScriptImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Future.cs b/GoogleSignIn/Future.cs similarity index 76% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Future.cs rename to GoogleSignIn/Future.cs index df469423..1784b3ea 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Future.cs +++ b/GoogleSignIn/Future.cs @@ -55,14 +55,14 @@ internal Future(FutureAPIImpl impl) { /// Gets the status. /// /// The status is set when Pending == false. - GoogleSignInStatusCode Status { get { return apiImpl.Status; } } + public GoogleSignInStatusCode Status { get { return apiImpl.Status; } } /// /// Gets the result. /// /// The result is set when Pending == false and there is no error. /// - T Result { get { return apiImpl.Result; } } + public T Result { get { return apiImpl.Result; } } /// /// Waits for result then completes the TaskCompleationSource. @@ -71,14 +71,29 @@ internal Future(FutureAPIImpl impl) { /// Tcs. internal IEnumerator WaitForResult(TaskCompletionSource tcs) { yield return new WaitUntil(() => !Pending); - if (Status == GoogleSignInStatusCode.Canceled) { + yield return null; + if (Status == GoogleSignInStatusCode.CANCELED) { tcs.SetCanceled(); - } else if (Status == GoogleSignInStatusCode.Success || - Status == GoogleSignInStatusCode.SuccessCached) { + } else if (Status == GoogleSignInStatusCode.SUCCESS || + Status == GoogleSignInStatusCode.SUCCESS_CACHE) { + tcs.SetResult(Result); + } else { + tcs.SetException(new GoogleSignIn.SignInException(Status)); + } + } + + internal async Task WaitForResultAsync(TaskCompletionSource tcs) + { + while (Pending) await Task.Yield(); + await Task.Yield(); + if (Status == GoogleSignInStatusCode.CANCELED) { + tcs.SetCanceled(); + } else if (Status == GoogleSignInStatusCode.SUCCESS || + Status == GoogleSignInStatusCode.SUCCESS_CACHE) { tcs.SetResult(Result); } else { tcs.SetException(new GoogleSignIn.SignInException(Status)); } } } -} \ No newline at end of file +} diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Future.cs.meta b/GoogleSignIn/Future.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Future.cs.meta rename to GoogleSignIn/Future.cs.meta index 3932f1d0..75a7f224 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Future.cs.meta +++ b/GoogleSignIn/Future.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: ad3b09fb652fb4ff0a68d1966f13160e labels: - gvh -timeCreated: 1495747145 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignIn.cs b/GoogleSignIn/GoogleSignIn.cs similarity index 82% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignIn.cs rename to GoogleSignIn/GoogleSignIn.cs index c59ced72..ed0a98cf 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignIn.cs +++ b/GoogleSignIn/GoogleSignIn.cs @@ -69,9 +69,7 @@ public static GoogleSignInConfiguration Configuration { if (theInstance == null || theConfiguration == value || theConfiguration == null) { theConfiguration = value; } else { - throw new SignInException(GoogleSignInStatusCode.DeveloperError, - "DefaultInstance already created. " + - " Cannot change configuration after creation."); + throw new SignInException(GoogleSignInStatusCode.DEVELOPER_ERROR,"DefaultInstance already created. Cannot change configuration after creation."); } } @@ -87,25 +85,25 @@ public static GoogleSignInConfiguration Configuration { public static GoogleSignIn DefaultInstance { get { if (theInstance == null) { -#if UNITY_ANDROID || UNITY_IOS +#if UNITY_EDITOR || UNITY_STANDALONE + theInstance = new GoogleSignIn(new GoogleSignInImplEditor(Configuration)); +#elif UNITY_ANDROID || UNITY_IOS theInstance = new GoogleSignIn(new GoogleSignInImpl(Configuration)); #else theInstance = new GoogleSignIn(null); - throw new SignInException( - GoogleSignInStatusCode.DeveloperError, - "This platform is not supported by GoogleSignIn"); + throw new SignInException(GoogleSignInStatusCode.DEVELOPER_ERROR,"This platform is not supported by GoogleSignIn"); #endif } return theInstance; } } - internal GoogleSignIn(GoogleSignInImpl impl) { + internal GoogleSignIn(ISignInImpl impl) { this.impl = impl; } public void EnableDebugLogging(bool flag) { - impl.EnableDebugLogging(flag); + impl.EnableDebugLogging(flag); } /// Starts the authentication process. @@ -116,11 +114,18 @@ public void EnableDebugLogging(bool flag) { /// public Task SignIn() { var tcs = new TaskCompletionSource(); - SignInHelperObject.Instance.StartCoroutine( - impl.SignIn().WaitForResult(tcs)); + SignInHelperObject.Instance.StartCoroutine(impl.SignIn().WaitForResult(tcs)); return tcs.Task; } + public Task SignInAsync() { + var tcs = new TaskCompletionSource(); + impl.SignIn().WaitForResultAsync(tcs).ContinueWith((task) => {}); + return tcs.Task; + } + + public Future SignInFuture() => impl.SignIn(); + /// Starts the silent authentication process. /// /// The authenication process is started and will attempt to sign in without @@ -129,11 +134,18 @@ public Task SignIn() { /// public Task SignInSilently() { var tcs = new TaskCompletionSource(); - SignInHelperObject.Instance.StartCoroutine( - impl.SignInSilently().WaitForResult(tcs)); + SignInHelperObject.Instance.StartCoroutine(impl.SignInSilently().WaitForResult(tcs)); return tcs.Task; } + public Task SignInSilentlyAsync() { + var tcs = new TaskCompletionSource(); + impl.SignInSilently().WaitForResultAsync(tcs).ContinueWith((task) => {}); + return tcs.Task; + } + + public Future SignInSilentlyFuture() => impl.SignInSilently(); + /// /// Signs out the User. /// diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignIn.cs.meta b/GoogleSignIn/GoogleSignIn.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignIn.cs.meta rename to GoogleSignIn/GoogleSignIn.cs.meta index e289fb9f..31609ffd 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignIn.cs.meta +++ b/GoogleSignIn/GoogleSignIn.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: 138b984208e394be797ce8905a44fd54 labels: - gvh -timeCreated: 1490814915 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInConfiguration.cs b/GoogleSignIn/GoogleSignInConfiguration.cs similarity index 90% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInConfiguration.cs rename to GoogleSignIn/GoogleSignInConfiguration.cs index d914c68d..e8ebce7a 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInConfiguration.cs +++ b/GoogleSignIn/GoogleSignInConfiguration.cs @@ -30,6 +30,11 @@ public class GoogleSignInConfiguration { /// See the README for more details. /// public bool UseGameSignIn = false; +#if UNITY_EDITOR || UNITY_STANDALONE + /// Client Secret for used in editor and desktop platform + /// Required for requesting auth code or id token in editor + public string ClientSecret = null; +#endif /// Web client id associated with this app. /// Required for requesting auth code or id token. public string WebClientId = null; @@ -45,7 +50,7 @@ public class GoogleSignInConfiguration { /// Request id token, requires consent. public bool RequestIdToken = false; /// Request profile information, requires consent. - public bool RequestProfile = false; + public bool RequestProfile = true; /// Hides popup UIs from games services. /// Used with games signin to show or hide the connecting popup UI /// and to associate an invisible view for other popups. This is diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInConfiguration.cs.meta b/GoogleSignIn/GoogleSignInConfiguration.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInConfiguration.cs.meta rename to GoogleSignIn/GoogleSignInConfiguration.cs.meta index 0a5774a6..943644cc 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInConfiguration.cs.meta +++ b/GoogleSignIn/GoogleSignInConfiguration.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: 0c3999c0f68f04ae08f04fb3bf2a2050 labels: - gvh -timeCreated: 1495747213 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignIn/GoogleSignInStatusCode.cs b/GoogleSignIn/GoogleSignInStatusCode.cs new file mode 100644 index 00000000..bc41fd81 --- /dev/null +++ b/GoogleSignIn/GoogleSignInStatusCode.cs @@ -0,0 +1,53 @@ +// +// Copyright (C) 2017 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace Google { + + /// + /// Status code for the SignIn operations. + /// + /// All successful status codes are less than or equal to 0. + /// + public enum GoogleSignInStatusCode { + SUCCESS_CACHE = -1, + SUCCESS = 0, + [System.Obsolete] + SERVICE_MISSING = 1, + [System.Obsolete] + SERVICE_VERSION_UPDATE_REQUIRED = 2, + [System.Obsolete] + SERVICE_DISABLED = 3, + SIGN_IN_REQUIRED = 4, + INVALID_ACCOUNT = 5, + RESOLUTION_REQUIRED = 6, + NETWORK_ERROR = 7, + INTERNAL_ERROR = 8, + SERVICE_INVALID = 9, + DEVELOPER_ERROR = 10, + LICENSE_CHECK_FAILED = 11, + ERROR = 13, + INTERRUPTED = 14, + TIMEOUT = 15, + CANCELED = 16, + API_NOT_CONNECTED = 17, + DEAD_CLIENT = 18, + REMOTE_EXCEPTION = 19, + CONNECTION_SUSPENDED_DURING_CALL = 20, + RECONNECTION_TIMED_OUT_DURING_UPDATE = 21, + RECONNECTION_TIMED_OUT = 22 + } +} // namespace GoogleSignIn + diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInStatusCode.cs.meta b/GoogleSignIn/GoogleSignInStatusCode.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInStatusCode.cs.meta rename to GoogleSignIn/GoogleSignInStatusCode.cs.meta index 9a8718dd..238e45f5 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInStatusCode.cs.meta +++ b/GoogleSignIn/GoogleSignInStatusCode.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: 077933fcaedac412d9762bf3e0a3be68 labels: - gvh -timeCreated: 1501271136 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInUser.cs b/GoogleSignIn/GoogleSignInUser.cs similarity index 100% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInUser.cs rename to GoogleSignIn/GoogleSignInUser.cs diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInUser.cs.meta b/GoogleSignIn/GoogleSignInUser.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInUser.cs.meta rename to GoogleSignIn/GoogleSignInUser.cs.meta index 757b4d0d..587c6861 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInUser.cs.meta +++ b/GoogleSignIn/GoogleSignInUser.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: c56b92217d0144af5907627d1235e0a5 labels: - gvh -timeCreated: 1495747250 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl.meta b/GoogleSignIn/Impl.meta similarity index 100% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl.meta rename to GoogleSignIn/Impl.meta diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/BaseObject.cs b/GoogleSignIn/Impl/BaseObject.cs similarity index 89% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl/BaseObject.cs rename to GoogleSignIn/Impl/BaseObject.cs index 44d65013..cacb127e 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/BaseObject.cs +++ b/GoogleSignIn/Impl/BaseObject.cs @@ -35,8 +35,7 @@ public BaseObject(IntPtr intPtr) { protected HandleRef SelfPtr() { if (selfHandleRef.Equals(nullSelf)) { - throw new InvalidOperationException( - "Attempted to use object after it was cleaned up"); + throw new InvalidOperationException("Attempted to use object after it was cleaned up"); } return selfHandleRef; } @@ -45,8 +44,7 @@ public virtual void Dispose() { selfHandleRef = nullSelf; } - internal delegate UIntPtr OutStringMethod([In, Out] byte[] out_bytes, - UIntPtr out_size); + internal delegate UIntPtr OutStringMethod([In, Out] byte[] out_bytes,UIntPtr out_size); internal static String OutParamsToString(OutStringMethod outStringMethod) { UIntPtr requiredSize = outStringMethod(null, UIntPtr.Zero); @@ -58,8 +56,7 @@ internal static String OutParamsToString(OutStringMethod outStringMethod) { try { byte[] array = new byte[requiredSize.ToUInt32()]; outStringMethod(array, requiredSize); - str = Encoding.UTF8.GetString(array, 0, - (int)requiredSize.ToUInt32() - 1); + str = Encoding.UTF8.GetString(array, 0, (int)requiredSize.ToUInt32() - 1); } catch (Exception e) { Debug.LogError("Exception creating string from char array: " + e); str = string.Empty; diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/BaseObject.cs.meta b/GoogleSignIn/Impl/BaseObject.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl/BaseObject.cs.meta rename to GoogleSignIn/Impl/BaseObject.cs.meta index 286f1c84..0e24225d 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/BaseObject.cs.meta +++ b/GoogleSignIn/Impl/BaseObject.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: fe250cda690a44cb08f8f7d26c9723b4 labels: - gvh -timeCreated: 1495748295 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignIn/Impl/GoogleSignInImpl.cs b/GoogleSignIn/Impl/GoogleSignInImpl.cs new file mode 100644 index 00000000..4a6bb728 --- /dev/null +++ b/GoogleSignIn/Impl/GoogleSignInImpl.cs @@ -0,0 +1,371 @@ +#if UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS +// +// Copyright (C) 2017 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace Google.Impl { + using System; + using System.Text; + using System.Linq; + using System.Collections.Generic; + using System.Runtime.InteropServices; + + using UnityEngine; +#if UNITY_2022_2_OR_NEWER +#else + using System.Reflection; +#endif + + internal class GoogleSignInImpl : BaseObject, ISignInImpl { + + internal GoogleSignInImpl(GoogleSignInConfiguration configuration) : base(GoogleSignIn_Create(GetPlayerActivity())) { + + if (configuration != null) { + List scopes = new List(); + if (configuration.AdditionalScopes != null) { + scopes.AddRange(configuration.AdditionalScopes); + } + GoogleSignIn_Configure(SelfPtr(), configuration.UseGameSignIn, + configuration.WebClientId, + configuration.RequestAuthCode, + configuration.ForceTokenRefresh, + configuration.RequestEmail, + configuration.RequestIdToken, + configuration.HidePopups, + scopes.ToArray(), + scopes.Count, + configuration.AccountName); + } + } + + /// Enables/Disables verbose logging to help troubleshooting + public void EnableDebugLogging(bool flag) { + GoogleSignIn_EnableDebugLogging(SelfPtr(), flag); + } + + /// + /// Starts the authentication process. + /// + /// + /// The authenication process is started and may display account picker + /// popups and consent prompts based on the state of authentication and + /// the requested elements. + /// + public Future SignIn() { + IntPtr nativeFuture = GoogleSignIn_SignIn(SelfPtr()); + return new Future(new NativeFuture(nativeFuture)); + } + + /// + /// Starts the authentication process. + /// + /// + /// The authenication process is started and may display account picker + /// popups and consent prompts based on the state of authentication and + /// the requested elements. + /// + public Future SignInSilently() { + IntPtr nativeFuture = GoogleSignIn_SignInSilently(SelfPtr()); + return new Future(new NativeFuture(nativeFuture)); + } + + /// + /// Signs out the User. + /// + public void SignOut() { + GoogleSignIn_Signout(SelfPtr()); + } + + /// + /// Disconnects the user from the application and revokes all consent. + /// + public void Disconnect() { + GoogleSignIn_Disconnect(SelfPtr()); + } + +#if UNITY_ANDROID + static AndroidJavaClass GoogleSignInHelper = new AndroidJavaClass("com.google.googlesignin.GoogleSignInHelper"); + + static IntPtr GoogleSignIn_Create(IntPtr activity) + { + return new AndroidJavaObject("com.google.googlesignin.GoogleSignInHelper").GetRawObject(); + } + + static bool GoogleSignIn_Configure(HandleRef googleSignInHelper, + bool useGameSignIn, string webClientId, + bool requestAuthCode, bool forceTokenRefresh, bool requestEmail, + bool requestIdToken, bool hidePopups, string[] additionalScopes, + int scopeCount, string accountName) + { + GoogleSignInHelper.CallStatic("configure", + useGameSignIn, + webClientId, + requestAuthCode, + forceTokenRefresh, + requestEmail, + requestIdToken, + hidePopups, + accountName, + additionalScopes, + new SignInListener()); + + return !useGameSignIn; + } + + static AndroidJavaObject googleIdTokenCredential; + static AndroidJavaObject authorizationResult; + + public class SignInListener : AndroidJavaProxy + { + public SignInListener() : base("com.google.googlesignin.IListener") { } + + public void onAuthenticated(AndroidJavaObject _googleIdTokenCredential) + { + googleIdTokenCredential?.Dispose(); + googleIdTokenCredential = _googleIdTokenCredential; + } + + public void onAuthorized(AndroidJavaObject _authorizationResult) + { + authorizationResult?.Dispose(); + authorizationResult = _authorizationResult; + } + + public void onFailure(AndroidJavaObject exception) + { + Debug.LogErrorFormat("onFailure {0} : {1}",exception?.Call("getClass").Call("toString"),exception?.Call("getMessage")); + exception.Dispose(); + } + + public void onCanceled() { + googleIdTokenCredential?.Dispose(); + authorizationResult?.Dispose(); + } + } + + static void GoogleSignIn_EnableDebugLogging(HandleRef self, bool flag) => GoogleSignInHelper.CallStatic("enableDebugLogging",flag); + + static IntPtr GoogleSignIn_SignIn(HandleRef self) + { + return GoogleSignInHelper.CallStatic("signIn").GetRawObject(); + } + + static IntPtr GoogleSignIn_SignInSilently(HandleRef self) + { + return GoogleSignInHelper.CallStatic("signInSilently").GetRawObject(); + } + + static void GoogleSignIn_Signout(HandleRef self) + { + googleIdTokenCredential?.Dispose(); + googleIdTokenCredential = null; + + authorizationResult?.Dispose(); + authorizationResult = null; + + GoogleSignInHelper.CallStatic("signOut"); + } + + static void GoogleSignIn_Disconnect(HandleRef self) => throw new NotImplementedException(); + + internal static void GoogleSignIn_DisposeFuture(HandleRef self) => GoogleSignInHelper.CallStatic("cancel"); + + internal static bool GoogleSignIn_Pending(HandleRef self) => GoogleSignInHelper.CallStatic("isPending"); + + internal static IntPtr GoogleSignIn_Result(HandleRef self) => googleIdTokenCredential.GetRawObject(); + + internal static int GoogleSignIn_Status(HandleRef self) => GoogleSignInHelper.CallStatic("getStatus"); + + internal static string GoogleSignIn_GetServerAuthCode(HandleRef self) => authorizationResult?.Call("getServerAuthCode"); + + internal static string GoogleSignIn_GetUserId(HandleRef self) + { + try + { + string idTokenFull = googleIdTokenCredential?.Call("getIdToken"); + string idTokenPart = idTokenFull?.Split('.')?.ElementAtOrDefault(1); + if(!(idTokenPart?.Length > 1)) + return null; + + // Replace URL-safe characters and fix padding + idTokenPart = idTokenPart.Replace('-', '+').Replace('_', '/'); + int mod = idTokenPart.Length % 4; + if(mod > 0) + idTokenPart += new string('=',4 - mod); + var idTokenFromBase64 = Convert.FromBase64String(idTokenPart); + var idToken = Encoding.UTF8.GetString(idTokenFromBase64); + var jobj = Newtonsoft.Json.Linq.JObject.Parse(idToken); + return jobj?["sub"]?.ToString(); + } + catch(Exception e) + { + Debug.LogException(e); + return null; + } + } + + internal static string GoogleSignIn_GetEmail(HandleRef self) => googleIdTokenCredential?.Call("getId"); + + internal static string GoogleSignIn_GetDisplayName(HandleRef self) => googleIdTokenCredential?.Call("getDisplayName"); + + internal static string GoogleSignIn_GetFamilyName(HandleRef self) => googleIdTokenCredential?.Call("getFamilyName"); + + internal static string GoogleSignIn_GetGivenName(HandleRef self) => googleIdTokenCredential?.Call("getGivenName"); + + internal static string GoogleSignIn_GetIdToken(HandleRef self) => googleIdTokenCredential?.Call("getIdToken"); + + internal static string GoogleSignIn_GetImageUrl(HandleRef self) => googleIdTokenCredential?.Call("getProfilePictureUri")?.Call("toString"); +#else + private const string DllName = "__Internal"; + + /// + /// Creates an instance of the native Google Sign-In implementation. + /// + /// + /// For Android this must be the JNI raw object for the parentActivity. + /// For iOS it is ignored. + /// + /// The pointer to the instance. + /// Data used in creating the instance. + [DllImport(DllName)] + static extern IntPtr GoogleSignIn_Create(IntPtr data); + + [DllImport(DllName)] + static extern void GoogleSignIn_EnableDebugLogging(HandleRef self, bool flag); + + [DllImport(DllName)] + static extern bool GoogleSignIn_Configure(HandleRef self, + bool useGameSignIn, string webClientId, + bool requestAuthCode, bool forceTokenRefresh, bool requestEmail, + bool requestIdToken, bool hidePopups, string[] additionalScopes, + int scopeCount, string accountName); + + [DllImport(DllName)] + static extern IntPtr GoogleSignIn_SignIn(HandleRef self); + + [DllImport(DllName)] + static extern IntPtr GoogleSignIn_SignInSilently(HandleRef self); + + [DllImport(DllName)] + static extern void GoogleSignIn_Signout(HandleRef self); + + [DllImport(DllName)] + static extern void GoogleSignIn_Disconnect(HandleRef self); + + [DllImport(DllName)] + internal static extern void GoogleSignIn_DisposeFuture(HandleRef self); + + [DllImport(DllName)] + internal static extern bool GoogleSignIn_Pending(HandleRef self); + + [DllImport(DllName)] + internal static extern IntPtr GoogleSignIn_Result(HandleRef self); + + [DllImport(DllName)] + internal static extern int GoogleSignIn_Status(HandleRef self); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetServerAuthCode( + HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetDisplayName(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetEmail(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetFamilyName(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetGivenName(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetIdToken(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetImageUrl(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + [DllImport(DllName)] + internal static extern UIntPtr GoogleSignIn_GetUserId(HandleRef self, [In, Out] byte[] bytes, UIntPtr len); + + internal static string GoogleSignIn_GetServerAuthCode(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetServerAuthCode(self, out_string, out_size)); + + internal static string GoogleSignIn_GetDisplayName(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetDisplayName(self, out_string, out_size)); + + internal static string GoogleSignIn_GetEmail(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetEmail(self, out_string, out_size)); + + internal static string GoogleSignIn_GetFamilyName(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetFamilyName(self, out_string, out_size)); + + internal static string GoogleSignIn_GetGivenName(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetGivenName(self, out_string, out_size)); + + internal static string GoogleSignIn_GetIdToken(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetIdToken(self, out_string, out_size)); + + internal static string GoogleSignIn_GetImageUrl(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetImageUrl(self, out_string, out_size)); + + internal static string GoogleSignIn_GetUserId(HandleRef self) => + OutParamsToString((out_string, out_size) => GoogleSignIn_GetUserId(self, out_string, out_size)); +#endif + + // Gets the Unity player activity. + // For iOS, this returns Zero. + private static IntPtr GetPlayerActivity() { +#if UNITY_ANDROID + var jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); + return jc.GetStatic("currentActivity").GetRawObject(); +#else + return IntPtr.Zero; +#endif + } + } + + public static class Ext + { +#if UNITY_2022_2_OR_NEWER +#else + static ConstructorInfo constructorInfo; +#endif + + public static AndroidJavaObject ToAndroidJavaObject(in this HandleRef self) => self.Handle.ToAndroidJavaObject(); + public static AndroidJavaObject ToAndroidJavaObject(in this IntPtr intPtr) + { + if (intPtr == IntPtr.Zero) + return null; + + try { +#if UNITY_2022_2_OR_NEWER + return new AndroidJavaObject(intPtr); +#else + if(constructorInfo == null) + constructorInfo = typeof(AndroidJavaObject).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,null,new[] { typeof(IntPtr) },null); + + Debug.LogFormat("constructorInfo : {0}",constructorInfo); + return constructorInfo.Invoke(new object[] { intPtr }) as AndroidJavaObject; +#endif + } catch (Exception e) { + Debug.LogError("Exception creating AndroidJavaObject: " + e); + return null; + } + } + } +} +#endif diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs.meta b/GoogleSignIn/Impl/GoogleSignInImpl.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs.meta rename to GoogleSignIn/Impl/GoogleSignInImpl.cs.meta index d4e90199..46c1d561 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs.meta +++ b/GoogleSignIn/Impl/GoogleSignInImpl.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: 9ae1f008f9f994b9c96c1a14067d7b48 labels: - gvh -timeCreated: 1502758941 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignIn/Impl/GoogleSignInImplEditor.cs b/GoogleSignIn/Impl/GoogleSignInImplEditor.cs new file mode 100644 index 00000000..eb08c2a8 --- /dev/null +++ b/GoogleSignIn/Impl/GoogleSignInImplEditor.cs @@ -0,0 +1,211 @@ +#if UNITY_EDITOR || UNITY_STANDALONE +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using System.Net; +using System.Net.NetworkInformation; + +using UnityEngine; + +using Newtonsoft.Json.Linq; + +namespace Google.Impl +{ + internal class GoogleSignInImplEditor : ISignInImpl, FutureAPIImpl + { + GoogleSignInConfiguration configuration; + + public bool Pending { get; private set; } + + public GoogleSignInStatusCode Status { get; private set; } + + public GoogleSignInUser Result { get; private set; } + + public GoogleSignInImplEditor(GoogleSignInConfiguration configuration) + { + this.configuration = configuration; + } + + public void Disconnect() + { + throw new NotImplementedException(); + } + + public void EnableDebugLogging(bool flag) + { + throw new NotImplementedException(); + } + + public Future SignIn() + { + SigningIn(); + return new Future(this); + } + + public Future SignInSilently() + { + SigningIn(); + return new Future(this); + } + + public void SignOut() + { + Debug.Log("No need on editor?"); + } + + static HttpListener BindLocalHostFirstAvailablePort() + { + ushort minPort = 49215; +#if UNITY_EDITOR_WIN + var listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); + return Enumerable.Range(minPort, ushort.MaxValue - minPort).Where((i) => !listeners.Any((x) => x.Port == i)).Select((port) => { +#elif UNITY_EDITOR_OSX + return Enumerable.Range(minPort, ushort.MaxValue - minPort).Select((port) => { +#else + return Enumerable.Range(0,10).Select((i) => UnityEngine.Random.Range(minPort,ushort.MaxValue)).Select((port) => { +#endif + try + { + var listener = new HttpListener(); + listener.Prefixes.Add($"http://localhost:{port}/"); + listener.Start(); + return listener; + } + catch(System.Exception e) + { + Debug.LogException(e); + return null; + } + }).FirstOrDefault((listener) => listener != null); + } + + void SigningIn() + { + Pending = true; + var httpListener = BindLocalHostFirstAvailablePort(); + try + { + var openURL = "https://accounts.google.com/o/oauth2/v2/auth?" + Uri.EscapeUriString("scope=openid email profile&response_type=code&redirect_uri=" + httpListener.Prefixes.FirstOrDefault() + "&client_id=" + configuration.WebClientId); + Debug.Log(openURL); + Application.OpenURL(openURL); + } + catch(Exception e) + { + Debug.LogException(e); + throw; + } + + var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); + httpListener.GetContextAsync().ContinueWith(async(task) => { + try + { + Debug.Log(task); + var context = task.Result; + var queryString = context.Request.Url.Query; + var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString); + if(queryDictionary == null || queryDictionary.Get("code") is not string code || string.IsNullOrEmpty(code)) + { + Status = GoogleSignInStatusCode.INVALID_ACCOUNT; + + context.Response.StatusCode = 404; + context.Response.OutputStream.Write(Encoding.UTF8.GetBytes("Cannot get code")); + context.Response.Close(); + return; + } + + context.Response.StatusCode = 200; + context.Response.OutputStream.Write(Encoding.UTF8.GetBytes("Can close this page")); + context.Response.Close(); + + var jobj = await HttpWebRequest.CreateHttp("https://www.googleapis.com/oauth2/v4/token").Post("application/x-www-form-urlencoded","code=" + code + "&client_id=" + configuration.WebClientId + "&client_secret=" + configuration.ClientSecret + "&redirect_uri=" + httpListener.Prefixes.FirstOrDefault() + "&grant_type=authorization_code").ContinueWith((task) => { + return JObject.Parse(task.Result); + },taskScheduler); + + var accessToken = (string)jobj.GetValue("access_token"); + var expiresIn = (int)jobj.GetValue("expires_in"); + var scope = (string)jobj.GetValue("scope"); + var tokenType = (string)jobj.GetValue("token_type"); + + var user = new GoogleSignInUser(); + if(configuration.RequestAuthCode) + user.AuthCode = code; + + if(configuration.RequestIdToken) + user.IdToken = (string)jobj.GetValue("id_token"); + + var request = HttpWebRequest.CreateHttp("https://openidconnect.googleapis.com/v1/userinfo"); + request.Method = "GET"; + request.Headers.Add("Authorization", "Bearer " + accessToken); + + var data = await request.GetResponseAsStringAsync().ContinueWith((task) => task.Result,taskScheduler); + var userInfo = JObject.Parse(data); + user.UserId = (string)userInfo.GetValue("sub"); + user.DisplayName = (string)userInfo.GetValue("name"); + + if(configuration.RequestEmail) + user.Email = (string)userInfo.GetValue("email"); + + if(configuration.RequestProfile) + { + user.GivenName = (string)userInfo.GetValue("given_name"); + user.FamilyName = (string)userInfo.GetValue("family_name"); + user.ImageUrl = Uri.TryCreate((string)userInfo.GetValue("picture"),UriKind.Absolute,out var url) ? url : null; + } + + Result = user; + + Status = GoogleSignInStatusCode.SUCCESS; + } + catch(Exception e) + { + Status = GoogleSignInStatusCode.ERROR; + + Debug.LogException(e); + if(e is AggregateException ae) + { + foreach(var inner in ae.InnerExceptions) + Debug.LogException(inner); + } + + throw; + } + finally + { + Pending = false; + } + },taskScheduler); + } + } + + public static class EditorExt + { + public static Task Post(this HttpWebRequest request,string contentType,string data,Encoding encoding = null) + { + if(encoding == null) + encoding = Encoding.UTF8; + + request.Method = "POST"; + request.ContentType = contentType; + using(var stream = request.GetRequestStream()) + stream.Write(encoding.GetBytes(data)); + + return request.GetResponseAsStringAsync(encoding); + } + + public static async Task GetResponseAsStringAsync(this HttpWebRequest request,Encoding encoding = null) + { + using(var response = await request.GetResponseAsync()) + { + using(var stream = response.GetResponseStream()) + return stream.ReadToEnd(encoding ?? Encoding.UTF8); + } + } + + public static string ReadToEnd(this Stream stream,Encoding encoding = null) => new StreamReader(stream,encoding ?? Encoding.UTF8).ReadToEnd(); + public static void Write(this Stream stream,byte[] data) => stream.Write(data,0,data.Length); + } +} +#endif \ No newline at end of file diff --git a/GoogleSignIn/Impl/GoogleSignInImplEditor.cs.meta b/GoogleSignIn/Impl/GoogleSignInImplEditor.cs.meta new file mode 100644 index 00000000..aabd98e5 --- /dev/null +++ b/GoogleSignIn/Impl/GoogleSignInImplEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fbddd2a0a0c14f84aa4aaa7efa06d1d4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignIn/Impl/NativeFuture.cs b/GoogleSignIn/Impl/NativeFuture.cs new file mode 100644 index 00000000..3bbd2833 --- /dev/null +++ b/GoogleSignIn/Impl/NativeFuture.cs @@ -0,0 +1,86 @@ +#if UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS +// +// Copyright (C) 2017 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace Google.Impl { + using System; + using System.Runtime.InteropServices; + + /// + /// Native future is an interal class that implements the FutureAPIImpl + /// by calling native methods which are implemented in the native code. + /// + internal class NativeFuture : BaseObject, FutureAPIImpl { + + internal NativeFuture(IntPtr ptr) : base(ptr) { + } + + public override void Dispose() => GoogleSignInImpl.GoogleSignIn_DisposeFuture(SelfPtr()); + + public bool Pending => GoogleSignInImpl.GoogleSignIn_Pending(SelfPtr()); + + public GoogleSignInUser Result { + get { + HandleRef self = SelfPtr(); + IntPtr ptr = GoogleSignInImpl.GoogleSignIn_Result(self); + if (ptr == IntPtr.Zero) { + return null; + } + + var user = new GoogleSignInUser(); + var userPtr = new HandleRef(user, ptr); + + user.UserId = GoogleSignInImpl.GoogleSignIn_GetUserId(userPtr); + + user.Email = GoogleSignInImpl.GoogleSignIn_GetEmail(userPtr); + + user.DisplayName = GoogleSignInImpl.GoogleSignIn_GetDisplayName(userPtr); + + user.FamilyName = GoogleSignInImpl.GoogleSignIn_GetFamilyName(userPtr); + + user.GivenName = GoogleSignInImpl.GoogleSignIn_GetGivenName(userPtr); + + user.IdToken = GoogleSignInImpl.GoogleSignIn_GetIdToken(userPtr); + + user.AuthCode = GoogleSignInImpl.GoogleSignIn_GetServerAuthCode(self); + + string url = GoogleSignInImpl.GoogleSignIn_GetImageUrl(userPtr); + if (url?.Length > 0) { + user.ImageUrl = new System.Uri(url); + } + +#pragma warning disable CS0219 // Require for no reason (tree shaking ?) + var obj = (user.UserId,user.Email,user.DisplayName,user.FamilyName,user.GivenName,user.IdToken,user.AuthCode,user.ImageUrl); +#pragma warning restore CS0219 + + return user; + } + } + + /// + /// Gets the status. + /// + /// The platform specific implementation maps the platform specific + /// code to one defined in GoogleSignStatusCode. + /// The status. + public GoogleSignInStatusCode Status { + get { + return (GoogleSignInStatusCode)GoogleSignInImpl.GoogleSignIn_Status(SelfPtr()); + } + } + } +} +#endif diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/NativeFuture.cs.meta b/GoogleSignIn/Impl/NativeFuture.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl/NativeFuture.cs.meta rename to GoogleSignIn/Impl/NativeFuture.cs.meta index 2c44becc..0cb0bd1b 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/NativeFuture.cs.meta +++ b/GoogleSignIn/Impl/NativeFuture.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: 5f1aae79b1ca4432d9d8ec382c54bf46 labels: - gvh -timeCreated: 1502759707 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/SignInHelperObject.cs b/GoogleSignIn/Impl/SignInHelperObject.cs similarity index 100% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl/SignInHelperObject.cs rename to GoogleSignIn/Impl/SignInHelperObject.cs diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/SignInHelperObject.cs.meta b/GoogleSignIn/Impl/SignInHelperObject.cs.meta similarity index 84% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Impl/SignInHelperObject.cs.meta rename to GoogleSignIn/Impl/SignInHelperObject.cs.meta index 8f90a6b2..2dd5652c 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/SignInHelperObject.cs.meta +++ b/GoogleSignIn/Impl/SignInHelperObject.cs.meta @@ -2,9 +2,9 @@ fileFormatVersion: 2 guid: ad98e5b48888e44eb81dd5884d3a1754 labels: - gvh -timeCreated: 1500486239 -licenseType: Pro +- gvh_version-1.0.4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/GoogleSignIn/link.xml b/GoogleSignIn/link.xml new file mode 100644 index 00000000..af59fefc --- /dev/null +++ b/GoogleSignIn/link.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin.txt.meta b/GoogleSignIn/link.xml.meta similarity index 51% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin.txt.meta rename to GoogleSignIn/link.xml.meta index 0bbedeb2..6c1ca62e 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin.txt.meta +++ b/GoogleSignIn/link.xml.meta @@ -1,10 +1,5 @@ fileFormatVersion: 2 -guid: 817a6673340324b8ca85e24466f60953 -labels: -- gvh -- gvh_manifest -timeCreated: 1508953127 -licenseType: Free +guid: 8d4fb89b8eb5f4d49bfdcdc4f53884e1 TextScriptImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml.meta b/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml.meta deleted file mode 100644 index fd0bf367..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/GoogleSignInSupportDependencies.xml.meta +++ /dev/null @@ -1,10 +0,0 @@ -fileFormatVersion: 2 -guid: e8689106c65f445c19cec6044d615c19 -labels: -- gvh -timeCreated: 1507661087 -licenseType: Pro -TextScriptImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.0.txt b/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.0.txt deleted file mode 100644 index b1d0d00d..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.0.txt +++ /dev/null @@ -1,21 +0,0 @@ -Assets/Parse/Plugins/Unity.Tasks.dll -Assets/Parse/Plugins/Unity.Compat.dll -Assets/Parse/LICENSE -Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h -Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm -Assets/Plugins/Android/native-googlesignin-release.aar -Assets/PlayServicesResolver/Editor/Google.IOSResolver_v1.2.54.0.dll -Assets/PlayServicesResolver/Editor/Google.VersionHandler.dll -Assets/PlayServicesResolver/Editor/play-services-resolver_v1.2.54.0.txt -Assets/PlayServicesResolver/Editor/Google.VersionHandlerImpl_v1.2.54.0.dll -Assets/PlayServicesResolver/Editor/Google.JarResolver_v1.2.54.0.dll -Assets/GoogleSignIn/GoogleSignInStatusCode.cs -Assets/GoogleSignIn/Editor/GoogleSignInDependencies.xml -Assets/GoogleSignIn/GoogleSignInUser.cs -Assets/GoogleSignIn/GoogleSignIn.cs -Assets/GoogleSignIn/Future.cs -Assets/GoogleSignIn/Impl/SignInHelperObject.cs -Assets/GoogleSignIn/Impl/BaseObject.cs -Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs -Assets/GoogleSignIn/Impl/NativeFuture.cs -Assets/GoogleSignIn/GoogleSignInConfiguration.cs diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support.meta b/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support.meta deleted file mode 100644 index 1132fbfe..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support.meta +++ /dev/null @@ -1,10 +0,0 @@ -fileFormatVersion: 2 -guid: e3becceb8680148d59e5bb93e5eb5a24 -folderAsset: yes -timeCreated: 1508956004 -licenseType: Free -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.sha1.meta b/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.sha1.meta deleted file mode 100644 index 7f0f11ac..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.sha1.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 16b8065a143bb4277af08381a56157dd -labels: -- gvh -timeCreated: 1508956004 -licenseType: Free -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInStatusCode.cs b/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInStatusCode.cs deleted file mode 100644 index 0719f2c2..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/GoogleSignInStatusCode.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace Google { - - /// - /// Status code for the SignIn operations. - /// - /// All successful status codes are less than or equal to 0. - /// - public enum GoogleSignInStatusCode { - /// The operation was successful, but used the device's cache. - /// - SuccessCached = -1, - - /// The operation was successful. - Success = 0, - - /// The client attempted to call a method from an API that - /// failed to connect. - ApiNotConnected = 1, - - /// The result was canceled either due to client disconnect - /// or cancel(). - Canceled = 2, - - /// A blocking call was interrupted while waiting and did not - /// run to completion. - Interrupted = 3, - - /// The client attempted to connect to the service with an - /// invalid account name specified. - InvalidAccount = 4, - - /// Timed out while awaiting the result. - Timeout = 5, - - /// The application is misconfigured. - /// This error is not recoverable. - /// - /// The developer should look at the logs after this to determine - /// more actionable information. - /// - DeveloperError = 6, - - /// An internal error occurred. Retrying should resolve the - /// problem. - InternalError = 7, - - /// A network error occurred. Retrying should resolve the problem. - /// - NetworkError = 8, - - /// The operation failed with no more detailed information. - /// - Error = 9, - } -} // namespace GoogleSignIn - diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs b/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs deleted file mode 100644 index 78c8081f..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/GoogleSignInImpl.cs +++ /dev/null @@ -1,187 +0,0 @@ -// -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace Google.Impl { - using System; - using System.Collections.Generic; - using System.Runtime.InteropServices; - - internal class GoogleSignInImpl : BaseObject, ISignInImpl { - -#if UNITY_ANDROID - private const string DllName = "native-googlesignin"; -#else - private const string DllName = "__Internal"; -#endif - - internal GoogleSignInImpl(GoogleSignInConfiguration configuration) - : base(GoogleSignIn_Create(GetPlayerActivity())) { - - if (configuration != null) { - List scopes = new List(); - if (configuration.AdditionalScopes != null) { - scopes.AddRange(configuration.AdditionalScopes); - } - GoogleSignIn_Configure(SelfPtr(), configuration.UseGameSignIn, - configuration.WebClientId, - configuration.RequestAuthCode, - configuration.ForceTokenRefresh, - configuration.RequestEmail, - configuration.RequestIdToken, - configuration.HidePopups, - scopes.ToArray(), - scopes.Count, - configuration.AccountName); - } - } - - /// Enables/Disables verbose logging to help troubleshooting - public void EnableDebugLogging(bool flag) { - GoogleSignIn_EnableDebugLogging(SelfPtr(), flag); - } - - /// - /// Starts the authentication process. - /// - /// - /// The authenication process is started and may display account picker - /// popups and consent prompts based on the state of authentication and - /// the requested elements. - /// - public Future SignIn() { - IntPtr nativeFuture = GoogleSignIn_SignIn(SelfPtr()); - return new Future(new NativeFuture(nativeFuture)); - } - - /// - /// Starts the authentication process. - /// - /// - /// The authenication process is started and may display account picker - /// popups and consent prompts based on the state of authentication and - /// the requested elements. - /// - public Future SignInSilently() { - IntPtr nativeFuture = GoogleSignIn_SignInSilently(SelfPtr()); - return new Future(new NativeFuture(nativeFuture)); - } - - /// - /// Signs out the User. - /// - public void SignOut() { - GoogleSignIn_Signout(SelfPtr()); - } - - /// - /// Disconnects the user from the application and revokes all consent. - /// - public void Disconnect() { - GoogleSignIn_Disconnect(SelfPtr()); - } - - /// - /// Creates an instance of the native Google Sign-In implementation. - /// - /// - /// For Android this must be the JNI raw object for the parentActivity. - /// For iOS it is ignored. - /// - /// The pointer to the instance. - /// Data used in creating the instance. - [DllImport(DllName)] - static extern IntPtr GoogleSignIn_Create(IntPtr data); - - [DllImport(DllName)] - static extern void GoogleSignIn_EnableDebugLogging(HandleRef self, bool flag); - - [DllImport(DllName)] - static extern bool GoogleSignIn_Configure(HandleRef self, - bool useGameSignIn, string webClientId, - bool requestAuthCode, bool forceTokenRefresh, bool requestEmail, - bool requestIdToken, bool hidePopups, string[] additionalScopes, - int scopeCount, string accountName); - - [DllImport(DllName)] - static extern IntPtr GoogleSignIn_SignIn(HandleRef self); - - [DllImport(DllName)] - static extern IntPtr GoogleSignIn_SignInSilently(HandleRef self); - - [DllImport(DllName)] - static extern void GoogleSignIn_Signout(HandleRef self); - - [DllImport(DllName)] - static extern void GoogleSignIn_Disconnect(HandleRef self); - - [DllImport(DllName)] - internal static extern void GoogleSignIn_DisposeFuture(HandleRef self); - - [DllImport(DllName)] - internal static extern bool GoogleSignIn_Pending(HandleRef self); - - [DllImport(DllName)] - internal static extern IntPtr GoogleSignIn_Result(HandleRef self); - - [DllImport(DllName)] - internal static extern int GoogleSignIn_Status(HandleRef self); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetServerAuthCode( - HandleRef self, [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetDisplayName(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetEmail(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetFamilyName(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetGivenName(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetIdToken(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetImageUrl(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - [DllImport(DllName)] - internal static extern UIntPtr GoogleSignIn_GetUserId(HandleRef self, - [In, Out] byte[] bytes, UIntPtr len); - - // Gets the Unity player activity. - // For iOS, this returns Zero. - private static IntPtr GetPlayerActivity() { -#if UNITY_ANDROID - UnityEngine.AndroidJavaClass jc = new UnityEngine.AndroidJavaClass( - "com.unity3d.player.UnityPlayer"); - return jc.GetStatic("currentActivity") - .GetRawObject(); -#else - return IntPtr.Zero; -#endif - } - } -} diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/NativeFuture.cs b/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/NativeFuture.cs deleted file mode 100644 index 6d460f22..00000000 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Impl/NativeFuture.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace Google.Impl { - using System; - using System.Runtime.InteropServices; - - /// - /// Native future is an interal class that implements the FutureAPIImpl - /// by calling native methods which are implemented in the native code. - /// - internal class NativeFuture : BaseObject, FutureAPIImpl { - - internal NativeFuture(IntPtr ptr) : base(ptr) { - } - - public override void Dispose() { - GoogleSignInImpl.GoogleSignIn_DisposeFuture(SelfPtr()); - base.Dispose(); - } - - public bool Pending { - get { - return GoogleSignInImpl.GoogleSignIn_Pending(SelfPtr()); - } - } - - public GoogleSignInUser Result { - get { - IntPtr ptr = GoogleSignInImpl.GoogleSignIn_Result(SelfPtr()); - if (ptr != IntPtr.Zero) { - GoogleSignInUser user = new GoogleSignInUser(); - HandleRef userPtr = new HandleRef(user, ptr); - - user.DisplayName = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetDisplayName(userPtr, - out_string, - out_size)); - user.Email = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetEmail(userPtr, out_string, - out_size)); - - user.FamilyName = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetFamilyName(userPtr, out_string, - out_size)); - - user.GivenName = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetGivenName(userPtr, out_string, - out_size)); - - user.IdToken = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetIdToken(userPtr, out_string, - out_size)); - - user.AuthCode = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetServerAuthCode(userPtr, out_string, - out_size)); - - string url = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetImageUrl(userPtr, out_string, - out_size)); - if (url.Length > 0) { - user.ImageUrl = new System.Uri(url); - } - - user.UserId = OutParamsToString((out_string, out_size) => - GoogleSignInImpl.GoogleSignIn_GetUserId(userPtr, out_string, - out_size)); - return user; - } else { - return null; - } - } - } - - /// - /// Gets the status. - /// - /// The platform specific implementation maps the platform specific - /// code to one defined in GoogleSignStatusCode. - /// The status. - public GoogleSignInStatusCode Status { - get { - return (GoogleSignInStatusCode)GoogleSignInImpl.GoogleSignIn_Status( - SelfPtr()); - } - } - } -} diff --git a/GoogleSignInPlugin/Assets/Parse.meta b/GoogleSignInPlugin/Assets/Parse.meta deleted file mode 100644 index 351c7ed2..00000000 --- a/GoogleSignInPlugin/Assets/Parse.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d1a8f2ea2fc954f4db9d55a59d097a7d -folderAsset: yes -timeCreated: 1500403331 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Parse/LICENSE b/GoogleSignInPlugin/Assets/Parse/LICENSE deleted file mode 100755 index 4abeb6e9..00000000 --- a/GoogleSignInPlugin/Assets/Parse/LICENSE +++ /dev/null @@ -1,30 +0,0 @@ -BSD License - -For Parse .NET SDK software - -Copyright (c) 2015-present, Parse, LLC. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name Parse nor the names of its contributors may be used to - endorse or promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/GoogleSignInPlugin/Assets/Parse/LICENSE.meta b/GoogleSignInPlugin/Assets/Parse/LICENSE.meta deleted file mode 100644 index f817f8d8..00000000 --- a/GoogleSignInPlugin/Assets/Parse/LICENSE.meta +++ /dev/null @@ -1,10 +0,0 @@ -fileFormatVersion: 2 -guid: 9dd0e3c9dea104831bc092afe2f6eb5e -labels: -- gvh -timeCreated: 1503959774 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Parse/Plugins.meta b/GoogleSignInPlugin/Assets/Parse/Plugins.meta deleted file mode 100644 index 2b04519c..00000000 --- a/GoogleSignInPlugin/Assets/Parse/Plugins.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: aecfff8cf5706409e93b95c9c1081553 -folderAsset: yes -timeCreated: 1500403331 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Compat.dll b/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Compat.dll deleted file mode 100644 index 4b8c275e..00000000 Binary files a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Compat.dll and /dev/null differ diff --git a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Compat.dll.meta b/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Compat.dll.meta deleted file mode 100644 index da154d38..00000000 --- a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Compat.dll.meta +++ /dev/null @@ -1,36 +0,0 @@ -fileFormatVersion: 2 -guid: 0983b695c3c6148a58a2163488772971 -labels: -- gvh -timeCreated: 1500403332 -licenseType: Pro -PluginImporter: - serializedVersion: 2 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - data: - first: - Any: - second: - enabled: 1 - settings: {} - data: - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - data: - first: - Windows Store Apps: WindowsStoreApps - second: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Tasks.dll b/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Tasks.dll deleted file mode 100644 index a3a564f3..00000000 Binary files a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Tasks.dll and /dev/null differ diff --git a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Tasks.dll.meta b/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Tasks.dll.meta deleted file mode 100644 index a141b679..00000000 --- a/GoogleSignInPlugin/Assets/Parse/Plugins/Unity.Tasks.dll.meta +++ /dev/null @@ -1,36 +0,0 @@ -fileFormatVersion: 2 -guid: af535f85bedbe4425b5153ac2087c75e -labels: -- gvh -timeCreated: 1500403332 -licenseType: Pro -PluginImporter: - serializedVersion: 2 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - data: - first: - Any: - second: - enabled: 1 - settings: {} - data: - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - data: - first: - Windows Store Apps: WindowsStoreApps - second: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/Android.meta b/GoogleSignInPlugin/Assets/Plugins/Android.meta deleted file mode 100644 index 8d4c2f5e..00000000 --- a/GoogleSignInPlugin/Assets/Plugins/Android.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 7e4ce092146284b2ab8d322170972a45 -folderAsset: yes -timeCreated: 1490826122 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn.meta b/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn.meta deleted file mode 100644 index c4ea38dc..00000000 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 07c86a3f84f494e589218ed67d10255a -folderAsset: yes -timeCreated: 1490995894 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h b/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h deleted file mode 100644 index 5e77bc10..00000000 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#import -@interface GoogleSignInHandler - : NSObject - -@end diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h.meta b/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h.meta deleted file mode 100644 index 25735784..00000000 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.h.meta +++ /dev/null @@ -1,35 +0,0 @@ -fileFormatVersion: 2 -guid: 62c129704e1ec48179ba285e1af154b8 -labels: -- gvh -timeCreated: 1510357716 -licenseType: Pro -PluginImporter: - serializedVersion: 2 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - data: - first: - Any: - second: - enabled: 0 - settings: {} - data: - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - data: - first: - iPhone: iOS - second: - enabled: 1 - settings: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm.meta b/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm.meta deleted file mode 100644 index d33a9650..00000000 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm.meta +++ /dev/null @@ -1,35 +0,0 @@ -fileFormatVersion: 2 -guid: 521784ee6b2184e0e947a8fd1508afbc -labels: -- gvh -timeCreated: 1510357716 -licenseType: Pro -PluginImporter: - serializedVersion: 2 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - data: - first: - Any: - second: - enabled: 0 - settings: {} - data: - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - data: - first: - iPhone: iOS - second: - enabled: 1 - settings: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.md5.meta b/LICENSE.meta similarity index 54% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.md5.meta rename to LICENSE.meta index 8baf9d33..3e85b64c 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google/signin/google-signin-support/maven-metadata.xml.md5.meta +++ b/LICENSE.meta @@ -1,9 +1,5 @@ fileFormatVersion: 2 -guid: c020582c1a85d47c7934908f00a0bd37 -labels: -- gvh -timeCreated: 1508956004 -licenseType: Free +guid: e8d51a67f2b0d1b4f80bf5208119f251 DefaultImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/Plugins.meta b/Plugins.meta similarity index 79% rename from GoogleSignInPlugin/Assets/Plugins.meta rename to Plugins.meta index e21f9a03..806b70fa 100644 --- a/GoogleSignInPlugin/Assets/Plugins.meta +++ b/Plugins.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 11bf9545a722341b6ba971705a514a4b +guid: b005df1f018f3154b9d2ae6312b9e417 folderAsset: yes timeCreated: 1490826122 licenseType: Pro diff --git a/Plugins/Android.meta b/Plugins/Android.meta new file mode 100644 index 00000000..5c901c39 --- /dev/null +++ b/Plugins/Android.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c3c65b0f034270e4caba2316f11faace +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/Android/src.meta b/Plugins/Android/src.meta new file mode 100644 index 00000000..641e7dd9 --- /dev/null +++ b/Plugins/Android/src.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 48773aabe4b3fb047a3fa9eb0bde5471 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/Android/src/main.meta b/Plugins/Android/src/main.meta new file mode 100644 index 00000000..af6edf97 --- /dev/null +++ b/Plugins/Android/src/main.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7d18e7e9da507324389da155a7221c46 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/Android/src/main/java.meta b/Plugins/Android/src/main/java.meta new file mode 100644 index 00000000..8b162cb9 --- /dev/null +++ b/Plugins/Android/src/main/java.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d3b660da37efb134cb3f07fc6157e014 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com.meta b/Plugins/Android/src/main/java/com.meta similarity index 62% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com.meta rename to Plugins/Android/src/main/java/com.meta index 9372f2b8..4dc5c3cc 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com.meta +++ b/Plugins/Android/src/main/java/com.meta @@ -1,8 +1,6 @@ fileFormatVersion: 2 -guid: ade49ef91c70440a0baeac322ecaa2d7 +guid: 8dbb9fb8f598ac943bcf432238355d51 folderAsset: yes -timeCreated: 1508956004 -licenseType: Free DefaultImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google.meta b/Plugins/Android/src/main/java/com/google.meta similarity index 62% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google.meta rename to Plugins/Android/src/main/java/com/google.meta index a1cf31a7..9d0c904d 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/m2repository/com/google.meta +++ b/Plugins/Android/src/main/java/com/google.meta @@ -1,8 +1,6 @@ fileFormatVersion: 2 -guid: 707de6ade212a46b1ab4bf4d42325176 +guid: 70bae88dddfd96f40840bbd280386ebe folderAsset: yes -timeCreated: 1508956004 -licenseType: Free DefaultImporter: externalObjects: {} userData: diff --git a/Plugins/Android/src/main/java/com/google/googlesignin.meta b/Plugins/Android/src/main/java/com/google/googlesignin.meta new file mode 100644 index 00000000..ffd7079e --- /dev/null +++ b/Plugins/Android/src/main/java/com/google/googlesignin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53682122783400c45bedcd332e89ae2c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/Android/src/main/java/com/google/googlesignin/GoogleSignInHelper.java b/Plugins/Android/src/main/java/com/google/googlesignin/GoogleSignInHelper.java new file mode 100644 index 00000000..d543c2e6 --- /dev/null +++ b/Plugins/Android/src/main/java/com/google/googlesignin/GoogleSignInHelper.java @@ -0,0 +1,295 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.googlesignin; + +import android.os.CancellationSignal; +import android.util.Log; + +import androidx.annotation.NonNull; +import androidx.credentials.ClearCredentialStateRequest; +import androidx.credentials.Credential; +import androidx.credentials.CredentialManager; +import androidx.credentials.CredentialManagerCallback; +import androidx.credentials.GetCredentialRequest; +import androidx.credentials.GetCredentialResponse; +import androidx.credentials.exceptions.ClearCredentialException; +import androidx.credentials.exceptions.GetCredentialException; + +import com.google.android.gms.auth.api.identity.AuthorizationRequest; +import com.google.android.gms.auth.api.identity.AuthorizationResult; +import com.google.android.gms.auth.api.identity.Identity; +import com.google.android.gms.common.Scopes; +import com.google.android.gms.common.api.CommonStatusCodes; +import com.google.android.gms.common.api.Scope; +import com.google.android.gms.common.util.Strings; +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.android.gms.tasks.SuccessContinuation; +import com.google.android.gms.tasks.Task; +import com.google.android.gms.tasks.TaskCompletionSource; +import com.google.android.gms.tasks.TaskExecutors; +import com.google.android.libraries.identity.googleid.GetGoogleIdOption; +import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption; +import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential; +import com.unity3d.player.UnityPlayer; + +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +/** + * Helper class used by the native C++ code to interact with Google Sign-in API. + * The general flow is + * Call configure, then one of signIn or signInSilently. + */ +public class GoogleSignInHelper { + + // Set to true to get more debug logging. + public static boolean loggingEnabled = false; + + /** + * Enables verbose logging + */ + public static void enableDebugLogging(boolean flag) { + loggingEnabled = flag; + } + + private static CancellationSignal cancellationSignal; + private static Task task; + private static Function> signInFunction; + public static boolean isPending() { + return task != null && !task.isComplete() && !task.isCanceled(); + } + + public static int getStatus() { + if(signInFunction == null) + return CommonStatusCodes.DEVELOPER_ERROR; + + if(task == null) + return CommonStatusCodes.SIGN_IN_REQUIRED; + + if(task.isCanceled()) + return CommonStatusCodes.CANCELED; + + if(task.isSuccessful()) + return CommonStatusCodes.SUCCESS; + + Exception e = task.getException(); + if(e != null) + { + logError("onFailure with INTERNAL_ERROR : " + e.getClass().toString() + " " + e.getMessage()); + return CommonStatusCodes.INTERNAL_ERROR; + } + + return CommonStatusCodes.ERROR; + } + + /** + * Sets the configuration of the sign-in api that should be used. + * + * @param useGamesConfig - true if the GAMES_CONFIG should be used when + * signing-in. + * @param webClientId - the web client id of the backend server + * associated with this application. + * @param requestAuthCode - true if a server auth code is needed. This also + * requires the web + * client id to be set. + * @param forceRefreshToken - true to force a refresh token when using the + * server auth code. + * @param requestEmail - true if email address of the user is requested. + * @param requestIdToken - true if an id token for the user is requested. + * @param hideUiPopups - true if the popups during sign-in from the Games + * API should be hidden. + * This only has affect if useGamesConfig is true. + * @param defaultAccountName - the account name to attempt to default to when + * signing in. + * @param additionalScopes - additional API scopes to request when + * authenticating. + * @param requestHandle - the handle to this request, created by the native + * C++ code, this is used + * to correlate the response with the request. + */ + public static void configure( + boolean useGamesConfig, + String webClientId, + boolean requestAuthCode, + boolean forceRefreshToken, + boolean requestEmail, + boolean requestIdToken, + boolean hideUiPopups, + String defaultAccountName, + String[] additionalScopes, + IListener requestHandle) { + logDebug("TokenFragment.configure called"); + + signInFunction = new Function>() { + @Override + public Task apply(@NonNull Boolean silent) { + if(isPending()) { + TaskCompletionSource source = new TaskCompletionSource<>(); + source.trySetException(new Exception("Last task still pending")); + return source.getTask(); + } + + cancellationSignal = new CancellationSignal(); + + GetCredentialRequest.Builder getCredentialRequestBuilder = new GetCredentialRequest.Builder() + .setPreferImmediatelyAvailableCredentials(hideUiPopups); + + if(silent) { + GetGoogleIdOption.Builder getGoogleIdOptionBuilder = new GetGoogleIdOption.Builder() + .setFilterByAuthorizedAccounts(hideUiPopups) + .setAutoSelectEnabled(hideUiPopups); + + if(defaultAccountName != null) + getGoogleIdOptionBuilder.setNonce(defaultAccountName); + + if(!Strings.isEmptyOrWhitespace(webClientId)) + getGoogleIdOptionBuilder.setServerClientId(webClientId); + + getCredentialRequestBuilder.addCredentialOption(getGoogleIdOptionBuilder.build()); + } + else { + GetSignInWithGoogleOption.Builder getSignInWithGoogleOptionBuilder = new GetSignInWithGoogleOption.Builder(webClientId); + getCredentialRequestBuilder.addCredentialOption(getSignInWithGoogleOptionBuilder.build()); + } + + TaskCompletionSource source = new TaskCompletionSource<>(); + + CredentialManager.create(UnityPlayer.currentActivity).getCredentialAsync(UnityPlayer.currentActivity, + getCredentialRequestBuilder.build(), + cancellationSignal, + TaskExecutors.MAIN_THREAD, + new CredentialManagerCallback() { + @Override + public void onResult(GetCredentialResponse getCredentialResponse) { + source.trySetResult(getCredentialResponse); + } + + @Override + public void onError(@NotNull GetCredentialException e) { + source.trySetException(e); + } + }); + + return source.getTask().onSuccessTask(new SuccessContinuation() { + @NonNull + @Override + public Task then(GetCredentialResponse getCredentialResponse) throws Exception { + try { + Credential credential = getCredentialResponse.getCredential(); + Log.i(TAG, "credential.getType() : " + credential.getType()); + + GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.getData()); + requestHandle.onAuthenticated(googleIdTokenCredential); + } + catch (Exception e) { + throw e; + } + + AuthorizationRequest.Builder authorizationRequestBuilder = new AuthorizationRequest.Builder(); + if (requestAuthCode && !Strings.isEmptyOrWhitespace(webClientId)) + authorizationRequestBuilder.requestOfflineAccess(webClientId, forceRefreshToken); + + int additionalCount = additionalScopes != null ? additionalScopes.length : 0; + List scopes = new ArrayList<>(2 + additionalCount); + scopes.add(new Scope(Scopes.PROFILE)); + if (requestEmail) + scopes.add(new Scope(Scopes.EMAIL)); + if (additionalCount > 0) { + for (String scope : additionalScopes) { + scopes.add(new Scope(scope)); + } + } + + if (!scopes.isEmpty()) + authorizationRequestBuilder.setRequestedScopes(scopes); + + return Identity.getAuthorizationClient(UnityPlayer.currentActivity).authorize(authorizationRequestBuilder.build()); + } + }).addOnFailureListener(requestHandle).addOnCanceledListener(requestHandle).addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(AuthorizationResult authorizationResult) { + requestHandle.onAuthorized(authorizationResult); + } + }).addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task _unused) { + cancellationSignal = null; + } + }); + } + }; + } + + public static Task signIn() { + task = signInFunction.apply(false); + return task; + } + + public static Task signInSilently() { + task = signInFunction.apply(true); + return task; + } + + public static void cancel() { + if(isPending() && cancellationSignal != null){ + cancellationSignal.cancel(); + cancellationSignal = null; + } + + task = null; + } + + public static void signOut() { + cancel(); + + CredentialManager.create(UnityPlayer.currentActivity).clearCredentialStateAsync(new ClearCredentialStateRequest(), + new CancellationSignal(), + TaskExecutors.MAIN_THREAD, + new CredentialManagerCallback() { + @Override + public void onResult(Void unused) { + logInfo("signOut"); + } + + @Override + public void onError(@NonNull ClearCredentialException e) { + logError(e.getMessage()); + } + }); + } + + static final String TAG = GoogleSignInHelper.class.getSimpleName(); + + public static void logInfo(String msg) { + if (loggingEnabled) { + Log.i(TAG, msg); + } + } + + public static void logError(String msg) { + Log.e(TAG, msg); + } + + public static void logDebug(String msg) { + if (loggingEnabled) { + Log.d(TAG, msg); + } + } +} diff --git a/Plugins/Android/src/main/java/com/google/googlesignin/GoogleSignInHelper.java.meta b/Plugins/Android/src/main/java/com/google/googlesignin/GoogleSignInHelper.java.meta new file mode 100644 index 00000000..a31fd982 --- /dev/null +++ b/Plugins/Android/src/main/java/com/google/googlesignin/GoogleSignInHelper.java.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 7f834712c6088fe4e935636c1b9960ef +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/Android/src/main/java/com/google/googlesignin/IListener.java b/Plugins/Android/src/main/java/com/google/googlesignin/IListener.java new file mode 100644 index 00000000..3ff29731 --- /dev/null +++ b/Plugins/Android/src/main/java/com/google/googlesignin/IListener.java @@ -0,0 +1,13 @@ +package com.google.googlesignin; + +import com.google.android.gms.auth.api.identity.AuthorizationResult; +import com.google.android.gms.tasks.OnCanceledListener; +import com.google.android.gms.tasks.OnFailureListener; + +import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential; + +public interface IListener extends OnCanceledListener, OnFailureListener +{ + void onAuthenticated(GoogleIdTokenCredential acct); + void onAuthorized(AuthorizationResult acct); +} \ No newline at end of file diff --git a/Plugins/Android/src/main/java/com/google/googlesignin/IListener.java.meta b/Plugins/Android/src/main/java/com/google/googlesignin/IListener.java.meta new file mode 100644 index 00000000..e545d5d3 --- /dev/null +++ b/Plugins/Android/src/main/java/com/google/googlesignin/IListener.java.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: bf5da076086ff3f42adf1c261c1794ec +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS.meta b/Plugins/iOS.meta similarity index 100% rename from GoogleSignInPlugin/Assets/Plugins/iOS.meta rename to Plugins/iOS.meta diff --git a/staging/native/src/ios/GoogleSignIn.h b/Plugins/iOS/GoogleSignIn.h similarity index 50% rename from staging/native/src/ios/GoogleSignIn.h rename to Plugins/iOS/GoogleSignIn.h index 5e77bc10..953e3350 100644 --- a/staging/native/src/ios/GoogleSignIn.h +++ b/Plugins/iOS/GoogleSignIn.h @@ -14,7 +14,26 @@ * limitations under the License. */ #import -@interface GoogleSignInHandler - : NSObject +#import + +@interface GoogleSignInHandler : NSObject +{ + @public + GIDConfiguration* signInConfiguration; + + @public + NSString* loginHint; + + @public + NSMutableArray* additionalScopes; +} + +@property(class, nonatomic, readonly) GoogleSignInHandler *sharedInstance; + +- (void)signIn:(GIDSignIn *)signIn dismissViewController:(UIViewController *)viewController; + +- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)_error; + +- (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)_error; @end diff --git a/Plugins/iOS/GoogleSignIn.h.meta b/Plugins/iOS/GoogleSignIn.h.meta new file mode 100644 index 00000000..e115ee31 --- /dev/null +++ b/Plugins/iOS/GoogleSignIn.h.meta @@ -0,0 +1,35 @@ +fileFormatVersion: 2 +guid: 62c129704e1ec48179ba285e1af154b8 +labels: +- gvh +- gvh_version-1.0.4 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm b/Plugins/iOS/GoogleSignIn.mm similarity index 77% rename from GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm rename to Plugins/iOS/GoogleSignIn.mm index 9b82a370..827972ca 100644 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignIn.mm +++ b/Plugins/iOS/GoogleSignIn.mm @@ -14,10 +14,14 @@ * limitations under the License. */ #import "GoogleSignIn.h" -#import +#import #import #import #import +#import +#import + +#import "UnityInterface.h" #import @@ -51,6 +55,7 @@ void UnpauseUnityPlayer() { struct SignInResult { int result_code; bool finished; + NSString* serverAuthCode; }; std::unique_ptr currentResult_; @@ -59,6 +64,19 @@ void UnpauseUnityPlayer() { @implementation GoogleSignInHandler +GIDConfiguration* signInConfiguration = nil; +NSString* loginHint = nil; +NSMutableArray* additionalScopes = nil; + ++ (GoogleSignInHandler *)sharedInstance { + static dispatch_once_t once; + static GoogleSignInHandler *sharedInstance; + dispatch_once(&once, ^{ + sharedInstance = [self alloc]; + }); + return sharedInstance; +} + /** * Overload the presenting of the UI so we can pause the Unity player. */ @@ -105,9 +123,6 @@ - (void)signIn:(GIDSignIn *)signIn case kGIDSignInErrorCodeKeychain: currentResult_->result_code = kStatusCodeInternalError; break; - case kGIDSignInErrorCodeNoSignInHandlersInstalled: - currentResult_->result_code = kStatusCodeDeveloperError; - break; case kGIDSignInErrorCodeHasNoAuthInKeychain: currentResult_->result_code = kStatusCodeError; break; @@ -146,6 +161,7 @@ - (void)signIn:(GIDSignIn *)signIn * The parameters are intended to be primative, easy to marshall. */ extern "C" { + /** * This method does nothing in the iOS implementation. It is here * to make the API uniform between Android and iOS. @@ -168,31 +184,29 @@ bool GoogleSignIn_Configure(void *unused, bool useGameSignIn, bool requestIdToken, bool hidePopups, const char **additionalScopes, int scopeCount, const char *accountName) { - if (webClientId) { - [GIDSignIn sharedInstance].serverClientID = - [NSString stringWithUTF8String:webClientId]; - } - - [GIDSignIn sharedInstance].shouldFetchBasicProfile = true; - - int scopeSize = scopeCount; - - if (scopeSize) { - NSMutableArray *tmpary = - [[NSMutableArray alloc] initWithCapacity:scopeSize]; - for (int i = 0; i < scopeCount; i++) { - [tmpary addObject:[NSString stringWithUTF8String:additionalScopes[i]]]; + NSString *path = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; + NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; + NSString *clientId = [dict objectForKey:@"CLIENT_ID"]; + GIDConfiguration* config = [[GIDConfiguration alloc] initWithClientID:clientId]; + if (webClientId) { + config = [[GIDConfiguration alloc] initWithClientID:clientId serverClientID:[NSString stringWithUTF8String:webClientId]]; + } + [GoogleSignInHandler sharedInstance]->signInConfiguration = config; + + int scopeSize = scopeCount; + if (scopeSize) { + NSMutableArray *tmpary = [[NSMutableArray alloc] initWithCapacity:scopeSize]; + for (int i = 0; i < scopeCount; i++) { + [tmpary addObject:[NSString stringWithUTF8String:additionalScopes[i]]]; + } + [GoogleSignInHandler sharedInstance]->additionalScopes = tmpary; } - [GIDSignIn sharedInstance].scopes = tmpary; - } - - if (accountName) { - [GIDSignIn sharedInstance].loginHint = - [NSString stringWithUTF8String:accountName]; - } + if (accountName) { + [GoogleSignInHandler sharedInstance]->loginHint = [NSString stringWithUTF8String:accountName]; + } - return !useGameSignIn; + return !useGameSignIn; } /** @@ -226,7 +240,13 @@ bool GoogleSignIn_Configure(void *unused, bool useGameSignIn, void *GoogleSignIn_SignIn() { SignInResult *result = startSignIn(); if (!result) { - [[GIDSignIn sharedInstance] signIn]; + [[GIDSignIn sharedInstance] signInWithPresentingViewController:UnityGetGLViewController() + hint:[GoogleSignInHandler sharedInstance]->loginHint + completion:^(GIDSignInResult *result, NSError *error) { + GIDGoogleUser *user = result.user; + currentResult_.get()->serverAuthCode = result.serverAuthCode; + [[GoogleSignInHandler sharedInstance] signIn:[GIDSignIn sharedInstance] didSignInForUser:user withError:error]; + }]; result = currentResult_.get(); } return result; @@ -239,7 +259,9 @@ bool GoogleSignIn_Configure(void *unused, bool useGameSignIn, void *GoogleSignIn_SignInSilently() { SignInResult *result = startSignIn(); if (!result) { - [[GIDSignIn sharedInstance] signInSilently]; + [[GIDSignIn sharedInstance] restorePreviousSignInWithCompletion:^(GIDGoogleUser *user, NSError *error) { + [[GoogleSignInHandler sharedInstance] signIn:[GIDSignIn sharedInstance] didSignInForUser:user withError:error]; + }]; result = currentResult_.get(); } return result; @@ -252,7 +274,9 @@ void GoogleSignIn_Signout() { void GoogleSignIn_Disconnect() { GIDSignIn *signIn = [GIDSignIn sharedInstance]; - [signIn disconnect]; + [signIn disconnectWithCompletion:^(NSError *error) { + [[GoogleSignInHandler sharedInstance] signIn:[GIDSignIn sharedInstance] didDisconnectWithUser:nil withError:error]; + }]; } bool GoogleSignIn_Pending(SignInResult *result) { @@ -300,10 +324,10 @@ static size_t CopyNSString(NSString *src, char *dest, size_t len) { return src ? src.length + 1 : 0; } -size_t GoogleSignIn_GetServerAuthCode(GIDGoogleUser *guser, char *buf, +size_t GoogleSignIn_GetServerAuthCode(SignInResult *result, char *buf, size_t len) { - NSString *val = [guser serverAuthCode]; - return CopyNSString(val, buf, len); + NSString *val = result->serverAuthCode; + return CopyNSString(val, buf, len); } size_t GoogleSignIn_GetDisplayName(GIDGoogleUser *guser, char *buf, @@ -328,7 +352,9 @@ size_t GoogleSignIn_GetGivenName(GIDGoogleUser *guser, char *buf, size_t len) { } size_t GoogleSignIn_GetIdToken(GIDGoogleUser *guser, char *buf, size_t len) { - NSString *val = [guser.authentication idToken]; + GIDToken *token = [guser idToken]; + NSString *val = token.tokenString; + return CopyNSString(val, buf, len); } @@ -342,4 +368,4 @@ size_t GoogleSignIn_GetUserId(GIDGoogleUser *guser, char *buf, size_t len) { NSString *val = [guser userID]; return CopyNSString(val, buf, len); } -} // extern "C" +} // extern "C" \ No newline at end of file diff --git a/Plugins/iOS/GoogleSignIn.mm.meta b/Plugins/iOS/GoogleSignIn.mm.meta new file mode 100644 index 00000000..98623911 --- /dev/null +++ b/Plugins/iOS/GoogleSignIn.mm.meta @@ -0,0 +1,35 @@ +fileFormatVersion: 2 +guid: 521784ee6b2184e0e947a8fd1508afbc +labels: +- gvh +- gvh_version-1.0.4 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h b/Plugins/iOS/GoogleSignInAppController.h similarity index 100% rename from GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h rename to Plugins/iOS/GoogleSignInAppController.h diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h.meta b/Plugins/iOS/GoogleSignInAppController.h.meta similarity index 59% rename from GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h.meta rename to Plugins/iOS/GoogleSignInAppController.h.meta index fc4d5558..1005ed81 100644 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.h.meta +++ b/Plugins/iOS/GoogleSignInAppController.h.meta @@ -2,23 +2,32 @@ fileFormatVersion: 2 guid: ce40e3e7b37a54617a4683dfc0479c71 labels: - gvh -timeCreated: 1490998272 -licenseType: Pro +- gvh_version-1.0.4 PluginImporter: - serializedVersion: 1 + externalObjects: {} + serializedVersion: 2 iconMap: {} executionOrder: {} + defineConstraints: [] isPreloaded: 0 isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 platformData: - Any: + - first: + Any: + second: enabled: 0 settings: {} - Editor: + - first: + Editor: Editor + second: enabled: 0 settings: DefaultValueInitialized: true - iOS: + - first: + iPhone: iOS + second: enabled: 1 settings: {} userData: diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm b/Plugins/iOS/GoogleSignInAppController.mm similarity index 64% rename from GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm rename to Plugins/iOS/GoogleSignInAppController.mm index 33631489..66d92c21 100644 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm +++ b/Plugins/iOS/GoogleSignInAppController.mm @@ -59,29 +59,9 @@ + (void)load { method_exchangeImplementations(original, swizzled); } -- (BOOL)GoogleSignInAppController:(UIApplication *)application - didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // IMPORTANT: IF you are not supplying a GoogleService-Info.plist in your - // project that contains the client id, you need to set the client id here. - - NSString *path = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" - ofType:@"plist"]; - NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; - NSString *clientId = [dict objectForKey:@"CLIENT_ID"]; - - gsiHandler = [GoogleSignInHandler alloc]; - - // Setup the Sign-In instance. - GIDSignIn *signIn = [GIDSignIn sharedInstance]; - signIn.clientID = clientId; - signIn.uiDelegate = gsiHandler; - signIn.delegate = gsiHandler; - - // looks like it's just calling itself, but the implementations were swapped - // so we're actually calling the original once we're done - return [self GoogleSignInAppController:application - didFinishLaunchingWithOptions:launchOptions]; +- (BOOL)GoogleSignInAppController:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + NSLog(@"GSI application:didFinishLaunchingWithOption:"); + return [self GoogleSignInAppController:application didFinishLaunchingWithOptions:launchOptions]; } /** @@ -95,11 +75,8 @@ - (BOOL)GoogleSignInAppController:(UIApplication *)application openURL:url sourceApplication:sourceApplication annotation:annotation]; - - return [[GIDSignIn sharedInstance] handleURL:url - sourceApplication:sourceApplication - annotation:annotation] || - handled; + NSLog(@"GSI application:openURL:sourceApplication:annotation: %s", [url.absoluteString UTF8String]); + return [[GIDSignIn sharedInstance] handleURL:url] || handled; } /** @@ -108,17 +85,9 @@ - (BOOL)GoogleSignInAppController:(UIApplication *)application - (BOOL)GoogleSignInAppController:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { - - BOOL handled = - [self GoogleSignInAppController:app openURL:url options:options]; - - return [[GIDSignIn sharedInstance] - handleURL:url - sourceApplication: - options[UIApplicationOpenURLOptionsSourceApplicationKey] - annotation: - options[UIApplicationOpenURLOptionsAnnotationKey]] || - handled; + BOOL handled = [self GoogleSignInAppController:app openURL:url options:options]; + NSLog(@"GSI application:openURL:options: %s", [url.absoluteString UTF8String]); + return [[GIDSignIn sharedInstance] handleURL:url] || handled; } @end diff --git a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm.meta b/Plugins/iOS/GoogleSignInAppController.mm.meta similarity index 59% rename from GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm.meta rename to Plugins/iOS/GoogleSignInAppController.mm.meta index 8e0a46a3..676c7108 100644 --- a/GoogleSignInPlugin/Assets/Plugins/iOS/GoogleSignIn/GoogleSignInAppController.mm.meta +++ b/Plugins/iOS/GoogleSignInAppController.mm.meta @@ -2,23 +2,32 @@ fileFormatVersion: 2 guid: 50b2e1c9319e4446e9dbd9b183790472 labels: - gvh -timeCreated: 1490998272 -licenseType: Pro +- gvh_version-1.0.4 PluginImporter: - serializedVersion: 1 + externalObjects: {} + serializedVersion: 2 iconMap: {} executionOrder: {} + defineConstraints: [] isPreloaded: 0 isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 platformData: - Any: + - first: + Any: + second: enabled: 0 settings: {} - Editor: + - first: + Editor: Editor + second: enabled: 0 settings: DefaultValueInitialized: true - iOS: + - first: + iPhone: iOS + second: enabled: 1 settings: {} userData: diff --git a/README.md b/README.md index f8dcabc6..cfc0b8d2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,75 @@ +# Forked to upgrade base library to newer version + +https://developer.android.com/identity/sign-in/legacy-gsi-migration +https://developers.google.com/identity/sign-in/ios/quick-migration-guide + +Thank for ios fix which was cherrypicked from this fork : https://github.com/pillsgood/google-signin-unity which came from @DulgiKim https://github.com/googlesamples/google-signin-unity/pull/205#issuecomment-1724733615 + +Android was migrated to use `CredentialManager` and `AuthorizationClient` since [GoogleSignInAccount was deprecated](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount) + +However, `GoogleIdTokenCredential` actually not provide numeric unique ID anymore and set email as userId instead, so I have to extract jwt `sub` value from idToken (which seem like the same id as userId from GoogleSignIn of other platform) + +Also, this new system seem like it did not support email hint. And now require WebClientId in addition to Android Client ID. Which need to provided at configuration initialization + +```C# + GoogleSignIn.Configuration = new GoogleSignInConfiguration() { + RequestEmail = true, + RequestProfile = true, + RequestIdToken = true, + RequestAuthCode = true, + // must be web client ID, not android client ID + WebClientId = "XXXXXXXXX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", +#if UNITY_EDITOR || UNITY_STANDALONE + ClientSecret = "XXXXXX-xxxXXXxxxXXXxxx-xxxxXXXXX" // optional for windows/macos and test in editor +#endif + }; +``` + +Tested in unity 2021.3.21 and unity 6000.0.5 + +Add UPM dependency with branch tag `https://github.com/Thaina/google-signin-unity.git#newmigration` + +```json +{ + "dependencies": { + "com.google.external-dependency-manager": "https://github.com/googlesamples/unity-jar-resolver.git?path=upm", + "com.google.signin": "https://github.com/Thaina/google-signin-unity.git#newmigration", + ... + } +} +``` + +Also, [New version of iOS recommend](https://developers.google.com/identity/sign-in/ios/quick-migration-guide#google_sign-in_sdk_v700) that we should set `GIDClientID` and `GIDServerClientID` into Info.plist + +So I have add an editor tool `PListProcessor` that look for plist files in the project, extract `CLIENT_ID` and `WEB_CLIENT_ID` property of the plist which contain the `BUNDLE_ID` with the same name as bundle identifier of the project + +The plist file in the project should be downloaded from Google Cloud Console credential page + +Select iOS credential and download at ⬇ button + +```xml + + + + + + CLIENT_ID + {YourCloudProjectID}-yyyyyYYYYyyyyYYYYYYYYYYYYYYyyyyyy.apps.googleusercontent.com + REVERSED_CLIENT_ID + com.googleusercontent.apps.{YourCloudProjectID}-yyyyyYYYYyyyyYYYYYYYYYYYYYYyyyyyy + PLIST_VERSION + 1 + BUNDLE_ID + com.{YourCompany}.{YourProductName} + + WEB_CLIENT_ID + {YourCloudProjectID}-zzzZZZZZZZZZZZZZZzzzzzzzzzzZZZzzz.apps.googleusercontent.com + + +``` + +### Document below is original README, some information might be outdated + # Google Sign-In Unity Plugin _Copyright (c) 2017 Google Inc. All rights reserved._ diff --git a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.1.txt.meta b/README.md.meta similarity index 51% rename from GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.1.txt.meta rename to README.md.meta index b6e2fd62..775de2a5 100644 --- a/GoogleSignInPlugin/Assets/GoogleSignIn/Editor/google-signin-plugin_v1.0.1.txt.meta +++ b/README.md.meta @@ -1,10 +1,5 @@ fileFormatVersion: 2 -guid: 817a6673340324b8ca85e24466f60953 -labels: -- gvh -- gvh_manifest -timeCreated: 1508875148 -licenseType: Free +guid: 31a22f492fc25314d877e5a10dc0a854 TextScriptImporter: externalObjects: {} userData: diff --git a/GoogleSignInPlugin/Assets/SignInSample.meta b/Samples~/SignInSample.meta similarity index 100% rename from GoogleSignInPlugin/Assets/SignInSample.meta rename to Samples~/SignInSample.meta diff --git a/GoogleSignInPlugin/Assets/SignInSample/MainScene.unity b/Samples~/SignInSample/MainScene.unity similarity index 100% rename from GoogleSignInPlugin/Assets/SignInSample/MainScene.unity rename to Samples~/SignInSample/MainScene.unity diff --git a/GoogleSignInPlugin/Assets/SignInSample/MainScene.unity.meta b/Samples~/SignInSample/MainScene.unity.meta similarity index 100% rename from GoogleSignInPlugin/Assets/SignInSample/MainScene.unity.meta rename to Samples~/SignInSample/MainScene.unity.meta diff --git a/GoogleSignInPlugin/Assets/SignInSample/SigninSampleScript.cs b/Samples~/SignInSample/SigninSampleScript.cs similarity index 85% rename from GoogleSignInPlugin/Assets/SignInSample/SigninSampleScript.cs rename to Samples~/SignInSample/SigninSampleScript.cs index ce38441b..d34af937 100644 --- a/GoogleSignInPlugin/Assets/SignInSample/SigninSampleScript.cs +++ b/Samples~/SignInSample/SigninSampleScript.cs @@ -26,6 +26,9 @@ public class SigninSampleScript : MonoBehaviour { public Text statusText; public string webClientId = ""; +#if UNITY_EDITOR || UNITY_STANDALONE + public string Secret; +#endif private GoogleSignInConfiguration configuration; @@ -33,6 +36,9 @@ public class SigninSampleScript : MonoBehaviour { // Can be set via the property inspector in the Editor. void Awake() { configuration = new GoogleSignInConfiguration { +#if UNITY_EDITOR || UNITY_STANDALONE + ClientSecret = Secret, +#endif WebClientId = webClientId, RequestIdToken = true }; @@ -41,11 +47,9 @@ void Awake() { public void OnSignIn() { GoogleSignIn.Configuration = configuration; GoogleSignIn.Configuration.UseGameSignIn = false; - GoogleSignIn.Configuration.RequestIdToken = true; AddStatusText("Calling SignIn"); - GoogleSignIn.DefaultInstance.SignIn().ContinueWith( - OnAuthenticationFinished); + GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnAuthenticationFinished,TaskScheduler.FromCurrentSynchronizationContext()); } public void OnSignOut() { @@ -83,8 +87,7 @@ public void OnSignInSilently() { GoogleSignIn.Configuration.RequestIdToken = true; AddStatusText("Calling SignIn Silently"); - GoogleSignIn.DefaultInstance.SignInSilently() - .ContinueWith(OnAuthenticationFinished); + GoogleSignIn.DefaultInstance.SignInSilently().ContinueWith(OnAuthenticationFinished,TaskScheduler.FromCurrentSynchronizationContext()); } @@ -95,8 +98,7 @@ public void OnGamesSignIn() { AddStatusText("Calling Games SignIn"); - GoogleSignIn.DefaultInstance.SignIn().ContinueWith( - OnAuthenticationFinished); + GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnAuthenticationFinished,TaskScheduler.FromCurrentSynchronizationContext()); } private List messages = new List(); diff --git a/GoogleSignInPlugin/Assets/SignInSample/SigninSampleScript.cs.meta b/Samples~/SignInSample/SigninSampleScript.cs.meta similarity index 100% rename from GoogleSignInPlugin/Assets/SignInSample/SigninSampleScript.cs.meta rename to Samples~/SignInSample/SigninSampleScript.cs.meta diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 50f8d7ec..00000000 --- a/build.gradle +++ /dev/null @@ -1,377 +0,0 @@ -/* Copyright (C) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Top-level build file where you can add configuration options common to all sub-projects/modules. - -import groovy.io.FileType - -buildscript { - repositories { - google() - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:3.1.4' - - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files - } -} - -allprojects { - repositories { - google() - jcenter() - } -} - -project.ext { - // Determine the current OS. - os_name = System.getProperty("os.name").toLowerCase(); - os_osx = os_name.contains("mac os x"); - os_windows = os_name.contains("windows"); - os_linux = os_name.contains("linux"); - - unity_exe = System.getProperty("UNITY_EXE") - if (unity_exe == null || unity_exe.isEmpty()) { - unity_exe = System.getenv("UNITY_EXE") - } - if (unity_exe == null || unity_exe.isEmpty()) { - if (os_osx) { - unity_exe = '/Applications/Unity/Unity.app/Contents/MacOS/Unity' - } else if (os_windows) { - unity_exe = 'c:\\program files\\unity\\editor\\unity.exe' - } else { - // Fallback to just unity, and expect it on the path. - unity_exe = 'unity' - } - } - - git_exe = System.getProperty("GIT_EXE") - if (git_exe == null || git_exe.isEmpty()) { - git_exe = System.getenv("GIT_EXE") - } - if (git_exe == null || git_exe.isEmpty()) { - // Fallback to git and expect it to be on the path. - git_exe = 'git' - } - - pluginVersion = "1.0.4" - currentPluginBasename = 'google-signin-plugin' - currentPluginName = (currentPluginBasename + '-' + pluginVersion + - '.unitypackage') - editorDir = "Assets/GoogleSignIn/Editor" - uploadDir = "${buildDir}/GoogleSignInPlugin/${editorDir}/m2repository" - exportPath = file(currentPluginName).absolutePath - samplePath = file('GoogleSignIn-sample.unitypackage').absolutePath - pluginSrcPath = file('GoogleSignInPlugin').absolutePath - pluginProjectPath = file('build/GoogleSignInPlugin').absolutePath - - resolverDir = new File('build/jarresolver').absolutePath - jarresolver_uri = System.getProperty("RESOLVER_PACKAGE_URI") - jarresolver_repos = [ - 'https://github.com/googlesamples/unity-jar-resolver.git' - ] - // Set the tag to a specific value if you want to build pinned to a - // specific version of the jar resolver (This is uncommon). - // null indicates HEAD. - jarresolver_tag = null; -} - -task clean(type: Delete) { - delete rootProject.buildDir -} - -task copy_unity_project() { - dependsOn ':native-googlesignin:uploadArchives' - doFirst { - copy { - from pluginSrcPath - into pluginProjectPath - } - } -} - -task copy_jarresolver() { - description = "Clones the jar resolver project." - doFirst { - if (file(resolverDir).exists()) { - delete resolverDir - } - } - - doLast { - // Copy the package if the direct path is given. - if (jarresolver_uri != null) { - mkdir("${resolverDir}") - def resolver = new File("${resolverDir}/resolver.unitypackage") - new URL("${jarresolver_uri}").withInputStream { - inputStream -> resolver.withOutputStream { it << inputStream } - } - return - } - - // Else, check each one of the repo addresses and stop when successful. - for (repo in jarresolver_repos) { - def result = exec { - executable "${git_exe}" - args "clone", repo, "${resolverDir}" - ignoreExitValue true - } - if (result.exitValue == 0 && jarresolver_tag != null) { - result = exec { - executable "${git_exe}" - args "checkout", "-b", "buildver", "${jarresolver_tag}" - workingDir "${resolverDir}" - } - } - - if (result.exitValue == 0) { - println "Downloaded resolver from " + repo - return - } - } - } -} - -task import_jarresolver() { - description = "Imports the jar resolver into the project" - dependsOn copy_unity_project, copy_jarresolver - - doLast { - def tree = fileTree(resolverDir) { - include "*.unitypackage" - } - def jarresolver_package = tree.getSingleFile() - def argv = [ - "-gvh_disable", - "-g.building", - "-buildTarget", - "android", - // This prevents the VersionHandler to preserve the plugin layout - "-batchmode", - "-projectPath", pluginProjectPath, - "-logFile", "build/import_jarresolver.log", - "-importPackage", jarresolver_package, - "-quit" - ] - - ext.execResult = exec { - executable "${unity_exe}" - args argv - ignoreExitValue true - } - if (ext.execResult.exitValue != 0) { - println "***Error Running Unity:" - def src = file('build/import_jarresolver.log').text - print src - throw new GradleException('error importing jarresolver plugin') - } - } -} - -task generate_dependency_xml() { - description "Generate the JarResolver dependency file for the support library" - dependsOn copy_unity_project - doFirst { - def xmlFile = file("${pluginProjectPath}/${editorDir}/GoogleSignInSupportDependencies.xml") - - xmlFile << '\n' - xmlFile << '\n' - xmlFile << '\n' - xmlFile << ' \n' - xmlFile << ' \n" - xmlFile << ' \n' - xmlFile << ' Assets/GoogleSignIn/Editor/m2repository\n' - xmlFile << ' \n' - xmlFile << ' \n' - xmlFile << ' \n' - xmlFile << '\n' - } -} - -task generate_manifest(dependsOn: [ 'inject_versionIntoMetaFiles']) { - description 'Generate a manifest for the files in the plug-in.' - doLast { - def dir = file("${pluginProjectPath}/Assets") - def list = [] - dir.eachFileRecurse(groovy.io.FileType.FILES) { filename -> - def path = filename.path - if (!(path.toLowerCase().endsWith('.meta') || - path.toLowerCase().endsWith('.txt'))) { - list << filename.path.replace("${pluginProjectPath}/", '') - } - } - def manifest = file("${pluginProjectPath}/${editorDir}/" + - versionedAssetName(currentPluginBasename + '.txt', - "${pluginVersion}")) - manifest.write(list.join('\n') + '\n') - } -} - -task copy_manifestMetadata(dependsOn: generate_manifest, type: Copy) { - def manifestBasename = versionedAssetName(currentPluginBasename + '.txt', - null) + '.meta' - description 'Copy .meta file for the plugin manifest.' - from file("${pluginSrcPath}/${editorDir}/" + manifestBasename) - into file("${pluginProjectPath}/${editorDir}/") - rename { - String fn -> - return fn.replace(manifestBasename, - versionedAssetName(currentPluginBasename + '.txt', - "${pluginVersion}") + '.meta') - } -} - -task package_plugin () { - description = "Creates and exports the Plugin unity package" - dependsOn generate_manifest, copy_manifestMetadata - - doLast { - def tree = fileTree(resolverDir) { - include "*.unitypackage" - } - def jarresolver_package = tree.getSingleFile() - def argv = [ - "-gvh_disable", - "-g.building", - "-buildTarget", - "android", - // This prevents the VersionHandler to preserve the plugin layout - "-batchmode", - "-projectPath", pluginProjectPath, - "-logFile", "build/unity.log", - "-importPackage", jarresolver_package, - "-exportPackage", - "Assets/GoogleSignIn", - "Assets/Parse", - "Assets/PlayServicesResolver", - "Assets/Plugins", - "${exportPath}", - "-quit" - ] - - ext.execResult = exec { - executable "${unity_exe}" - args argv - ignoreExitValue true - } - if (ext.execResult.exitValue != 0) { - println "***Error Running Unity:" - def src = file('build/unity.log').text - print src - throw new GradleException('error exporting plugin') - } - } -} - - -task package_sample () { - description = "Creates and exports the Google Sign-in Sample" - - doLast { - def argv = [ - "-gvh_disable", - "-g.building", - // NOTE: This doesn't target Android since we don't want to have - // dependencies on the Jar Resolver as they require the plugin to - // be enabled during the build process which would break the - // versioning process. Compilation is verified when exporting - // the sample projects. - "-batchmode", - "-projectPath", pluginProjectPath, - "-logFile", "build/unity-sample.log", - "-exportPackage", - "Assets/SignInSample", - "${samplePath}", - "-quit" - ] - - ext.execResult = exec { - executable "${unity_exe}" - args argv - ignoreExitValue true - } - if (ext.execResult.exitValue != 0) { - println "***Error Running Unity:" - def src = file('build/unity-sample.log').text - print src - throw new GradleException('error exporting sample') - } - } -} - -task inject_versionIntoMetaFiles() { - description 'Inject the version number into the plugin\'s meta files.' - dependsOn copy_unity_project, generate_dependency_xml, import_jarresolver - doLast { - for (fileobj in fileTree("${pluginProjectPath}")) { - if (fileobj.path.endsWith('.meta')) { - // Skip the manifest files for any previous versions - if (fileobj.path.contains("Editor/${currentPluginBasename}")) { - continue - } - def lines = fileobj.text.split('\n') - def outputLines = [] - def added = false - for (line in lines) { - outputLines.add(line) - if (line.contains('labels:')) { - outputLines.add("- gvh_v${pluginVersion}") - added = true - } else if (line.contains('folderAsset:') && line.contains('yes')) { - added = true - } - } - if (!added) { - outputLines.add("labels:\n- gvh_v${pluginVersion}") - } - fileobj.write(outputLines.join('\n') + '\n') - } - } - } -} - -// Construct the name of a versioned asset from the source filename and version -// // string. -// // The encoded string takes the form... -// // ${filename}_v${version}_.${extension} -// // where extension is derived from the specified filename. -def versionedAssetName(filename, version) { - def extensionIndex = filename.lastIndexOf('.') - def basename = filename.substring(0, extensionIndex) - def extension = filename.substring(extensionIndex) - // Encode the DLL version and target names into the DLL in the form... - // ${dllname}_t${hypen_separated_target_names}_v${version}.dll - def targetName = basename - if (version != null && !version.isEmpty()) { - targetName += '_v' + version - } - return targetName + extension -} - -/* - * This is a top level task that build the Unity plugin. - * It does the following: - * - copy the java/C++ library to the Plugins directory. - * - Import the latest Play Services Resolver plugin - * - Build the Google Sign-In plugin package (requires Unity). - * - Build the Google Sign-In Sample package (requires Unity). - */ -task build_all() { - dependsOn ':native-googlesignin:uploadArchives', copy_jarresolver, package_plugin, package_sample -} - diff --git a/build_all.sh b/build_all.sh deleted file mode 100755 index b1035eb2..00000000 --- a/build_all.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -readonly THIS_DIR="$(cd "$(dirname "$0")"; pwd)" -pushd ${THIS_DIR} -./gradlew -PlintAbortOnError="true" build_all -popd \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 13372aef..00000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 24eb41f2..00000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Wed Mar 29 15:27:07 PDT 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip diff --git a/gradlew b/gradlew deleted file mode 100755 index 9d82f789..00000000 --- a/gradlew +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index aec99730..00000000 --- a/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/native-googlesignin/CMakeLists.txt b/native-googlesignin/CMakeLists.txt deleted file mode 100644 index 5d865f88..00000000 --- a/native-googlesignin/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright (C) 2017 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -## - -# For more information about using CMake with Android Studio, read the -# documentation: https://d.android.com/studio/projects/add-native-code.html - -# Sets the minimum version of CMake required to build the native library. - -cmake_minimum_required(VERSION 3.4.1) - -# Creates and names a library, sets it as either STATIC -# or SHARED, and provides the relative paths to its source code. -# You can define multiple libraries, and CMake builds them for you. -# Gradle automatically packages shared libraries with your APK. - -add_library( # Sets the name of the library. - native-googlesignin - - # Sets the library as a shared library. - SHARED - - # Provides a relative path to your source file(s). - src/main/cpp/google_signin_bridge.cc - src/main/cpp/google_signin.cc - src/main/cpp/google_signin_user.cc - src/main/cpp/jni.cc) - -# Searches for a specified prebuilt library and stores the path as a -# variable. Because CMake includes system libraries in the search path by -# default, you only need to specify the name of the public NDK library -# you want to add. CMake verifies that the library exists before -# completing its build. - -find_library( # Sets the name of the path variable. - log-lib - - # Specifies the name of the NDK library that - # you want CMake to locate. - log ) - -# Specifies libraries CMake should link to your target library. You -# can link multiple libraries, such as libraries you define in this -# build script, prebuilt third-party libraries, or system libraries. - -target_link_libraries( # Specifies the target library. - native-googlesignin - - # Links the target library to the log library - # included in the NDK. - ${log-lib} ) diff --git a/native-googlesignin/build.gradle b/native-googlesignin/build.gradle deleted file mode 100644 index ba2f0d9b..00000000 --- a/native-googlesignin/build.gradle +++ /dev/null @@ -1,116 +0,0 @@ -/* Copyright (C) 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -apply plugin: 'com.android.library' -apply plugin: 'maven' - -group "com.google.signin" - -if (project.hasProperty("pluginVersion")) { - project.version = project.pluginVersion -} else { - project.version '0-SNAPSHOT' -} - -if (project.hasProperty("uploadDir")) { - project.ext.uploadDir = project.uploadDir -} else { - project.ext.uploadDir = "${buildDir}/m2repository" -} - -project.ext.baseName = "google-signin-support" - -android { - compileSdkVersion 26 - defaultConfig { - minSdkVersion 14 - targetSdkVersion 26 - versionName project.version - archivesBaseName = project.ext.baseName - externalNativeBuild { - cmake { - cppFlags "-std=c++11", "-Wall" - } - } - ndk { - abiFilters 'x86', 'armeabi-v7a', 'arm64-v8a' - } - } - lintOptions { - abortOnError (project.hasProperty("lintAbortOnError") && - (project.lintAbortOnError == "" || - project.lintAbortOnError.toBoolean())) - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt') - } - } - externalNativeBuild { - cmake { - path "CMakeLists.txt" - } - } -} - -// Rename the .aar file to be .srcaar to work around -// having the local repo in a subdirectory in a Unity project. -// The jar resolver plugin handles the changing back from .srcaar -// to .aar -// -// This is done in 2 parts, first declare the .srcaar as an -// artifact, the second is a task to rename the aar -> srcaar. - -artifacts { - archives file("build/${baseName}-${version}.srcaar") -} - -task renameLibrary() { - doFirst { - copy { - from "${buildDir}/outputs/aar/${baseName}-release.aar" - into "${buildDir}" - rename { - String fn -> - return fn.replace("release.aar", "${version}.srcaar") - } - } - } - - doLast { - configurations.archives.with { - artifacts.remove artifacts.find { it.extension == "aar"} - } - } -} - -uploadArchives { - dependsOn renameLibrary - repositories { - mavenDeployer { - repository(url: uri(project.ext.uploadDir)) - - // Remove the dependencies from the pom file to simplify the - // the resolution process. - pom.whenConfigured { - p -> p.dependencies = [] - } - } - } -} - -dependencies { - api "com.google.android.gms:play-services-auth:16.0.0" -} diff --git a/native-googlesignin/src/main/AndroidManifest.xml b/native-googlesignin/src/main/AndroidManifest.xml deleted file mode 100644 index b3147faf..00000000 --- a/native-googlesignin/src/main/AndroidManifest.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - diff --git a/native-googlesignin/src/main/cpp/future.h b/native-googlesignin/src/main/cpp/future.h deleted file mode 100644 index 59220788..00000000 --- a/native-googlesignin/src/main/cpp/future.h +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_FUTURE_H // NOLINT -#define GOOGLESIGNIN_FUTURE_H - -namespace googlesignin { - -// Provides a future promise for an asynchronous result of type -template -class Future { - public: - virtual ~Future() {} - // Returns the Status of the operation. This is set once Pending is false. - virtual int Status() const = 0; - - // Returns the Result of the operation if successful. If it is not - // successful, the error code should be retrieved using Status(). The result - // is available once Pending() is false. - virtual T* Result() const = 0; - - // Returns true while the promise has not been fulfilled by the operation. - // Once it is false, the Status and Result fields are populated. - virtual bool Pending() const = 0; -}; - -} // namespace googlesignin - -#endif // GOOGLESIGNIN_FUTURE_H NOLINT diff --git a/native-googlesignin/src/main/cpp/google_signin.cc b/native-googlesignin/src/main/cpp/google_signin.cc deleted file mode 100644 index 59848e4f..00000000 --- a/native-googlesignin/src/main/cpp/google_signin.cc +++ /dev/null @@ -1,392 +0,0 @@ -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "google_signin.h" -#include -#include -#include "google_signin_user_impl.h" -#include "jni_init.h" - -#define TAG "native-googlesignin" -#define HELPER_CLASSNAME "com/google/googlesignin/GoogleSignInHelper" - -/* -public static void enableDebugLogging(boolean flag) - */ -#define ENABLE_DEBUG_METHOD_NAME "enableDebugLogging" -#define ENABLE_DEBUG_METHOD_SIG "(Z)V" - -/* -public static void configure(Activity parentActivity, - boolean useGamesConfig, - String webClientId, - boolean requestAuthCode, - boolean forceRefreshToken, - boolean requestEmail, - boolean requestIdToken, - boolean hideUiPopups, - String defaultAccountName, - String[] additionalScopes, - long requestHandle) -*/ -#define CONFIG_METHOD_NAME "configure" -#define CONFIG_METHOD_SIG \ - "(Landroid/app/Activity;" \ - "Z" \ - "Ljava/lang/String;" \ - "ZZZZZ" \ - "Ljava/lang/String;" \ - "[Ljava/lang/String;" \ - "J)V" - -/* -public static void nativeSignIn() - */ -#define DISCONNECT_METHOD_NAME "disconnect" -#define DISCONNECT_METHOD_SIG "(Landroid/app/Activity;)V" - -/* -public static void nativeSignIn() - */ -#define SIGNIN_METHOD_NAME "signIn" -#define SIGNIN_METHOD_SIG "(Landroid/app/Activity;J)V" - -/* -public static void nativeSignIn() - */ -#define SIGNINSILENTLY_METHOD_NAME "signInSilently" -#define SIGNINSILENTLY_METHOD_SIG "(Landroid/app/Activity;J)V" - -/* -public static void nativeSignOut() - */ -#define SIGNOUT_METHOD_NAME "signOut" -#define SIGNOUT_METHOD_SIG "(Landroid/app/Activity;)V" - -/* -public static void nativeOnResult(long requestHandle, int result, - GoogleSignInAccount acct), - */ -#define NATIVEONRESULT_METHOD_NAME "nativeOnResult" -#define NATIVEONRESULT_METHOD_SIG \ - "(J" \ - "I" \ - "Lcom/google/android/gms/auth/api/signin/GoogleSignInAccount;" \ - ")V" - -namespace googlesignin { - -class GoogleSignInFuture; - -// The implementation of GoogleSignIn. This implements the JNI interface to -// call the Java helper class the handles the authentication flow within Java. -// For the public methods see google_signin.h for details. -class GoogleSignIn::GoogleSignInImpl { - public: - jobject activity_; - GoogleSignInFuture *current_result_; - Configuration *current_configuration_; - - // Constructs the implementation providing the Java activity to use when - // making calls. - GoogleSignInImpl(jobject activity); - ~GoogleSignInImpl(); - - void Configure(const Configuration &configuration); - - void EnableDebugLogging(bool flag); - - // Starts the authentication process. - Future &SignIn(); - - Future &SignInSilently(); - - // Get the result of the last sign-in. - const Future *GetLastSignInResult(); - - // Signs out. - void SignOut(); - - void Disconnect(); - - // Native method implementation for the Java class. - static void NativeOnAuthResult(JNIEnv *env, jobject obj, jlong handle, - jint result, jobject user); - - private: - void CallConfigure(); - - static const JNINativeMethod methods[]; - - static jclass helper_clazz_; - static jmethodID enable_debug_method_; - static jmethodID config_method_; - static jmethodID disconnect_method_; - static jmethodID signin_method_; - static jmethodID signinsilently_method_; - static jmethodID signout_method_; -}; - -const JNINativeMethod GoogleSignIn::GoogleSignInImpl::methods[] = { - { - NATIVEONRESULT_METHOD_NAME, - NATIVEONRESULT_METHOD_SIG, - reinterpret_cast( - GoogleSignIn::GoogleSignInImpl::NativeOnAuthResult), - }, -}; - -jclass GoogleSignIn::GoogleSignInImpl::helper_clazz_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::enable_debug_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::config_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::disconnect_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::signin_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::signinsilently_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::signout_method_ = 0; - -// Implementation of the SignIn future. -class GoogleSignInFuture : public Future { - virtual int Status() const { - return result_ ? result_->StatusCode - : GoogleSignIn::StatusCode::kStatusCodeUninitialized; - } - virtual GoogleSignIn::SignInResult *Result() const { return result_; } - virtual bool Pending() const { - return (!result_) || result_->StatusCode == - GoogleSignIn::StatusCode::kStatusCodeUninitialized; - } - - public: - GoogleSignInFuture() : result_(nullptr) {} - void SetResult(GoogleSignIn::SignInResult *result) { result_ = result; } - - private: - GoogleSignIn::SignInResult *result_; -}; - -// Constructs a new instance. The static members are initialized if need-be. -GoogleSignIn::GoogleSignInImpl::GoogleSignInImpl(jobject activity) - : current_result_(nullptr), current_configuration_(nullptr) { - JNIEnv *env = GetJniEnv(); - - activity_ = env->NewGlobalRef(activity); - - if (!helper_clazz_) { - // Find the java helper class and initialize it. - helper_clazz_ = FindClass(HELPER_CLASSNAME, activity); - - assert(helper_clazz_); - - if (helper_clazz_) { - helper_clazz_ = (jclass)env->NewGlobalRef(helper_clazz_); - env->RegisterNatives(helper_clazz_, methods, - sizeof(methods) / sizeof(methods[0])); - enable_debug_method_ = env->GetStaticMethodID(helper_clazz_, ENABLE_DEBUG_METHOD_NAME, - ENABLE_DEBUG_METHOD_SIG); - config_method_ = env->GetStaticMethodID(helper_clazz_, CONFIG_METHOD_NAME, - CONFIG_METHOD_SIG); - disconnect_method_ = env->GetStaticMethodID( - helper_clazz_, DISCONNECT_METHOD_NAME, DISCONNECT_METHOD_SIG); - signin_method_ = env->GetStaticMethodID(helper_clazz_, SIGNIN_METHOD_NAME, - SIGNIN_METHOD_SIG); - signinsilently_method_ = env->GetStaticMethodID( - helper_clazz_, SIGNINSILENTLY_METHOD_NAME, SIGNINSILENTLY_METHOD_SIG); - signout_method_ = env->GetStaticMethodID( - helper_clazz_, SIGNOUT_METHOD_NAME, SIGNOUT_METHOD_SIG); - } - } -} - -GoogleSignIn::GoogleSignInImpl::~GoogleSignInImpl() { - JNIEnv *env = GetJniEnv(); - - env->DeleteGlobalRef(activity_); - activity_ = nullptr; - delete current_result_; - current_result_ = nullptr; -} - -void GoogleSignIn::GoogleSignInImpl::EnableDebugLogging(bool flag) { - JNIEnv *env = GetJniEnv(); - - env->CallStaticVoidMethod(helper_clazz_, enable_debug_method_, flag); - -} - -void GoogleSignIn::GoogleSignInImpl::Configure( - const Configuration &configuration) { - delete current_configuration_; - current_configuration_ = new Configuration(configuration); - - delete current_result_; - current_result_ = new GoogleSignInFuture(); - - CallConfigure(); -} - -void GoogleSignIn::GoogleSignInImpl::CallConfigure() { - JNIEnv *env = GetJniEnv(); - - if (!current_configuration_) { - __android_log_print(ANDROID_LOG_ERROR, TAG, "configuration is null!?"); - return; - } - jstring j_web_client_id = - current_configuration_->web_client_id.empty() ? nullptr - : env->NewStringUTF(current_configuration_->web_client_id.c_str()); - - jstring j_account_name = - current_configuration_->account_name.empty() ? nullptr - : env->NewStringUTF(current_configuration_->account_name.c_str()); - - jobjectArray j_auth_scopes = nullptr; - - if (current_configuration_->additional_scopes.size() > 0) { - jclass string_clazz = FindClass("java/lang/String", activity_); - j_auth_scopes = env->NewObjectArray( - current_configuration_->additional_scopes.size(), string_clazz, nullptr); - - for (int i = 0; i < current_configuration_->additional_scopes.size(); i++) { - env->SetObjectArrayElement( - j_auth_scopes, i, - env->NewStringUTF(current_configuration_->additional_scopes[i].c_str())); - } - env->DeleteLocalRef(string_clazz); - } - - env->CallStaticVoidMethod( - helper_clazz_, config_method_, activity_, - current_configuration_->use_game_signin, j_web_client_id, - current_configuration_->request_auth_code, - current_configuration_->force_token_refresh, - current_configuration_->request_email, - current_configuration_->request_id_token, - current_configuration_->hide_ui_popups, j_account_name, j_auth_scopes, - reinterpret_cast(current_result_)); - - if (j_web_client_id) { - env->DeleteLocalRef(j_web_client_id); - } - - if (j_account_name) { - env->DeleteLocalRef(j_account_name); - } - - if (j_auth_scopes) { - env->DeleteLocalRef(j_auth_scopes); - } -} - -Future &GoogleSignIn::GoogleSignInImpl::SignIn() { - JNIEnv *env = GetJniEnv(); - - if (current_result_) { - current_result_->SetResult(nullptr); - } - - CallConfigure(); - - env->CallStaticVoidMethod(helper_clazz_, signin_method_, activity_, - (jlong)current_result_); - - return *current_result_; -} - -Future - &GoogleSignIn::GoogleSignInImpl::SignInSilently() { - JNIEnv *env = GetJniEnv(); - - if (current_result_) { - current_result_->SetResult(nullptr); - } - - CallConfigure(); - - env->CallStaticVoidMethod(helper_clazz_, signinsilently_method_, activity_, - (jlong)current_result_); - - return *current_result_; -} - -// Get the result of the last sign-in. -const Future - *GoogleSignIn::GoogleSignInImpl::GetLastSignInResult() { - return current_result_; -} - -// Signs out. -void GoogleSignIn::GoogleSignInImpl::SignOut() { - JNIEnv *env = GetJniEnv(); - - __android_log_print(ANDROID_LOG_INFO, TAG, - "helper: %x method: %x activity: %x", - (uintptr_t)helper_clazz_, (uintptr_t)signin_method_, - (uintptr_t)activity_); - - env->CallStaticVoidMethod(helper_clazz_, signout_method_, activity_); -} - -// Signs out. -void GoogleSignIn::GoogleSignInImpl::Disconnect() { - JNIEnv *env = GetJniEnv(); - - env->CallStaticVoidMethod(helper_clazz_, disconnect_method_, activity_); -} - -void GoogleSignIn::GoogleSignInImpl::NativeOnAuthResult( - JNIEnv *env, jobject obj, jlong handle, jint result, jobject user) { - GoogleSignInFuture *future = reinterpret_cast(handle); - if (future) { - SignInResult *rc = new GoogleSignIn::SignInResult(); - rc->StatusCode = result; - rc->User = GoogleSignInUserImpl::UserFromAccount(user); - - if (rc->User) { - __android_log_print(ANDROID_LOG_INFO, TAG, "User Display Name is %s", - rc->User->GetDisplayName()); - } - future->SetResult(rc); - } -} - -// Public class implementation. These are called by external callers to use the -// Google Sign-in API. -GoogleSignIn::GoogleSignIn(jobject activity) - : impl_(new GoogleSignInImpl(activity)) {} - -void GoogleSignIn::EnableDebugLogging(bool flag) { - impl_->EnableDebugLogging(flag); -} - -void GoogleSignIn::Configure(const Configuration &configuration) { - impl_->Configure(configuration); -} - -Future &GoogleSignIn::SignIn() { - return impl_->SignIn(); -} - -Future &GoogleSignIn::SignInSilently() { - return impl_->SignInSilently(); -} - -const Future *GoogleSignIn::GetLastSignInResult() { - return impl_->GetLastSignInResult(); -} - -void GoogleSignIn::SignOut() { impl_->SignOut(); } - -void GoogleSignIn::Disconnect() { impl_->Disconnect(); } - -} // namespace googlesignin diff --git a/native-googlesignin/src/main/cpp/google_signin.h b/native-googlesignin/src/main/cpp/google_signin.h deleted file mode 100644 index 8086c06b..00000000 --- a/native-googlesignin/src/main/cpp/google_signin.h +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_GOOGLESIGNIN_H // NOLINT -#define GOOGLESIGNIN_GOOGLESIGNIN_H - -#if !defined(__ANDROID__) -#error "This class is for Android only." -#endif - -#include -#include -#include - -#include "future.h" // NOLINT -#include "google_signin_user.h" // NOLINT - -namespace googlesignin { - -class GoogleSignIn { - public: - /// StatusCode - /// These are based on - /// https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes - /// and consistent with what is returned by the Google Sign-In API on both iOS - /// and Android. - /// - enum StatusCode { - /// The result is uninitialized. - kStatusCodeUninitialized = 100, - - /// The client attempted to call a method from an API that - /// failed to connect. - kStatusCodeApiNotConnected = 17, - - /// The result was canceled either due to client disconnect - /// or cancel(). - kStatusCodeCanceled = 16, - - /// The application is misconfigured. - /// This error is not recoverable. - /// - /// The developer should look at the logs after this to determine - /// more actionable information. - /// - kStatusCodeDeveloperError = 10, - - /// The operation failed with no more detailed - /// information. - kStatusCodeError = 13, - - /// An internal error occurred. Retrying should resolve the - /// problem. - kStatusCodeInternalError = 8, - - /// A blocking call was interrupted while waiting and did not - /// run to completion. - kStatusCodeInterrupted = 14, - - /// The client attempted to connect to the service with an - /// invalid account name specified. - kStatusCodeInvalidAccount = 5, - - /// A network error occurred. Retrying should resolve the problem. - /// - kStatusCodeNetworkError = 7, - - /// The operation was successful. - kStatusCodeSuccess = 0, - - /// The operation was successful, but was used the device's cache. - /// - kStatusCodeSuccessCached = -1, - - /// Timed out while awaiting the result. - kStatusCodeTimeout = 15, - }; - - // Defines the configuration for the sign-in process. - struct Configuration { - /// true to use games signin, false for default signin. - bool use_game_signin; - /// web client id associated with this app. - std::string web_client_id; - /// true for getting an auth code when authenticating. - /// Note: This may trigger re-consent on iOS. Ideally, this - /// is set to true once, and the result sent to the server where the - /// token is managed forever. - bool request_auth_code; - /// true to request to reset the refresh token. Causes re-consent. - bool force_token_refresh; - /// request email address, requires consent. - bool request_email; - /// request id token, requires consent. - bool request_id_token; - /// used with games signin to show or hide the connecting popup UI. - /// and to associate an invisible view for other popups. This is - /// recommended for VR applications. - bool hide_ui_popups; - /// account name to use when authenticating, null indicates use default. - std::string account_name; - /// additional scopes to request, requires consent. - std::vector additional_scopes; - - Configuration() = default; - ~Configuration() = default; - Configuration(Configuration const ©) = default; - Configuration(Configuration &&move) = delete; - Configuration &operator=(Configuration const ©) = delete; - Configuration &operator=(Configuration &&move) = delete; - }; - - // Holds the result of the sign-in process. - struct SignInResult { - GoogleSignInUser *User; - int StatusCode; - SignInResult() = default; - ~SignInResult() = default; - SignInResult(SignInResult const ©) = default; - SignInResult(SignInResult &&move) = delete; - SignInResult &operator=(SignInResult const ©) = delete; - SignInResult &operator=(SignInResult &&move) = delete; - }; - - // Constructs a new instance. The activity parameter is needed to - // add a fragment to the activity which performs the sign-in operation. - GoogleSignIn(jobject activity); - - // Enables verbose logging. - void EnableDebugLogging(bool flag); - - // Sets the configuration for the sign-in. This must be called before - // calling SignIn(). Calling this invalidates the current sign-in result. - void Configure(const Configuration &configuration); - - // Starts the authentication process. - Future &SignIn(); - - // Attempts to sign in silently. - Future &SignInSilently(); - - // Get the result of the last sign-in. - const Future *GetLastSignInResult(); - - // Signs out the local user. Any server side tokens are still valid. - void SignOut(); - - // Disconnects this user from the application. Invalidates all tokens and - // consent. - void Disconnect(); - - private: - class GoogleSignInImpl; - GoogleSignInImpl *impl_; -}; -} // namespace googlesignin - -#endif // GOOGLESIGNIN_GOOGLESIGNIN_H NOLINT diff --git a/native-googlesignin/src/main/cpp/google_signin_bridge.cc b/native-googlesignin/src/main/cpp/google_signin_bridge.cc deleted file mode 100644 index e8a287ef..00000000 --- a/native-googlesignin/src/main/cpp/google_signin_bridge.cc +++ /dev/null @@ -1,227 +0,0 @@ -// -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "google_signin_bridge.h" - -#include -#include - -#include "google_signin.h" - -// Wrapper for the GoogleSignIn object when returning it via the extern -// "C" interface. -struct GoogleSignInHolder { - std::unique_ptr wrapped_; - - GoogleSignInHolder() : wrapped_(nullptr) {} - - GoogleSignInHolder(googlesignin::GoogleSignIn *ptr) : wrapped_(ptr) {} - - ~GoogleSignInHolder() = default; - - GoogleSignInHolder(GoogleSignInHolder const ©) = default; - - GoogleSignInHolder(GoogleSignInHolder &&move) = delete; - - GoogleSignInHolder &operator=(GoogleSignInHolder const ©) = delete; - - GoogleSignInHolder &operator=(GoogleSignInHolder &&move) = delete; -}; - -// Wrapper for the Future result from calling SignIn(). -struct GoogleSignInFuture { - std::unique_ptr< - googlesignin::Future> - wrapped_; - - GoogleSignInFuture() : wrapped_(nullptr) {} - - GoogleSignInFuture( - googlesignin::Future *ptr) - : wrapped_(ptr) {} - - ~GoogleSignInFuture() = default; - - GoogleSignInFuture(GoogleSignInFuture const ©) = default; - - GoogleSignInFuture(GoogleSignInFuture &&move) = delete; - - GoogleSignInFuture &operator=(GoogleSignInFuture const ©) = delete; - - GoogleSignInFuture &operator=(GoogleSignInFuture &&move) = delete; -}; - -// Wrapper for the signed in user object. -struct GoogleSignInUser { - googlesignin::GoogleSignInUser *wrapped_; - - GoogleSignInUser() : wrapped_() {} - - GoogleSignInUser(googlesignin::GoogleSignInUser *ref) : wrapped_(ref) { - __android_log_print(ANDROID_LOG_INFO, "native-googlesignin", - "In Wrapper display name is %s", - ref->GetDisplayName()); - } - - ~GoogleSignInUser() = default; - - GoogleSignInUser(GoogleSignInUser const ©) = delete; - - GoogleSignInUser(GoogleSignInUser &&move) = delete; - - GoogleSignInUser &operator=(GoogleSignInUser const ©) = delete; - - GoogleSignInUser &operator=(GoogleSignInUser &&move) = delete; -}; - -GoogleSignIn_t GoogleSignIn_Create(jobject activity) { - return new GoogleSignInHolder(new googlesignin::GoogleSignIn(activity)); -} - -void GoogleSignIn_Dispose(GoogleSignIn_t self) { delete self; } - -void GoogleSignIn_EnableDebugLogging(GoogleSignIn_t self, bool flag) { - self->wrapped_->EnableDebugLogging(flag); -} - -void GoogleSignIn_Configure(GoogleSignIn_t self, bool useGameSignIn, - const char *webClientId, bool requestAuthCode, - bool forceTokenRefresh, bool requestEmail, - bool requestIdToken, bool hidePopups, - const char **additional_scopes, int scopes_count, - const char *accountName) { - googlesignin::GoogleSignIn::Configuration configuration; - - configuration.use_game_signin = useGameSignIn; - if (webClientId) { - configuration.web_client_id = webClientId; - } - configuration.request_auth_code = requestAuthCode; - configuration.force_token_refresh = forceTokenRefresh; - configuration.request_email = requestEmail; - configuration.request_id_token = requestIdToken; - configuration.hide_ui_popups = hidePopups; - if (accountName) { - configuration.account_name = accountName; - } - if (scopes_count) { - for(int i=0;iwrapped_->Configure(configuration); -} - -GoogleSignInFuture_t GoogleSignIn_SignIn(GoogleSignIn_t self) { - return new GoogleSignInFuture(&self->wrapped_->SignIn()); -} - -GoogleSignInFuture_t GoogleSignIn_SignInSilently(GoogleSignIn_t self) { - return new GoogleSignInFuture(&self->wrapped_->SignInSilently()); -} - -void GoogleSignIn_Signout(GoogleSignIn_t self) { self->wrapped_->SignOut(); } - -void GoogleSignIn_Disconnect(GoogleSignIn_t self) { - self->wrapped_->Disconnect(); -} - -bool GoogleSignIn_Pending(GoogleSignInFuture_t self) { - return self->wrapped_->Pending(); -} - -int GoogleSignIn_Status(GoogleSignInFuture_t self) { - // Map the Android status code onto the Unity plugin enum. - switch (self->wrapped_->Status()) { - case googlesignin::GoogleSignIn::kStatusCodeApiNotConnected: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeApiNotConnected; - case googlesignin::GoogleSignIn::kStatusCodeCanceled: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeCanceled; - case googlesignin::GoogleSignIn::kStatusCodeDeveloperError: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeDeveloperError; - case googlesignin::GoogleSignIn::kStatusCodeInternalError: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeInternalError; - case googlesignin::GoogleSignIn::kStatusCodeInterrupted: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeInterrupted; - case googlesignin::GoogleSignIn::kStatusCodeInvalidAccount: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeInvalidAccount; - case googlesignin::GoogleSignIn::kStatusCodeNetworkError: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeNetworkError; - case googlesignin::GoogleSignIn::kStatusCodeTimeout: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeInternalError; - case googlesignin::GoogleSignIn::kStatusCodeSuccessCached: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeSuccessCached; - case googlesignin::GoogleSignIn::kStatusCodeSuccess: - return googlesignin::GoogleSignUnityStatusCode::kUnityStatusCodeSuccess; - case googlesignin::GoogleSignIn::kStatusCodeError: - // fall through to default case - default: - return googlesignin::GoogleSignUnityStatusCode ::kUnityStatusCodeError; - } -} - -GoogleSignInUser_t GoogleSignIn_Result(GoogleSignInFuture_t self) { - return (self->wrapped_->Result() && self->wrapped_->Result()->User) - ? new GoogleSignInUser(self->wrapped_->Result()->User) - : nullptr; -} - -static size_t ReturnCopiedString(const char *src, char *dest, size_t len) { - if (dest && src && len) { - strncpy(dest, src, len); - return len; - } - return src ? strlen(src) + 1 : 0; -} - -size_t GoogleSignIn_GetServerAuthCode(GoogleSignInUser_t self, char *buf, - size_t len) { - return ReturnCopiedString(self->wrapped_->GetServerAuthCode(), buf, len); -} - -size_t GoogleSignIn_GetDisplayName(GoogleSignInUser_t self, char *buf, - size_t len) { - return ReturnCopiedString(self->wrapped_->GetDisplayName(), buf, len); -} - -size_t GoogleSignIn_GetEmail(const GoogleSignInUser_t self, char *buf, - size_t len) { - return ReturnCopiedString(self->wrapped_->GetEmail(), buf, len); -} - -size_t GoogleSignIn_GetFamilyName(GoogleSignInUser_t self, char *buf, - size_t len) { - return ReturnCopiedString(self->wrapped_->GetFamilyName(), buf, len); -} - -size_t GoogleSignIn_GetGivenName(GoogleSignInUser_t self, char *buf, - size_t len) { - return ReturnCopiedString(self->wrapped_->GetGivenName(), buf, len); -} - -size_t GoogleSignIn_GetIdToken(GoogleSignInUser_t self, char *buf, size_t len) { - return ReturnCopiedString(self->wrapped_->GetIdToken(), buf, len); -} - -size_t GoogleSignIn_GetImageUrl(GoogleSignInUser_t self, char *buf, - size_t len) { - return ReturnCopiedString(self->wrapped_->GetImageUrl(), buf, len); -} - -size_t GoogleSignIn_GetUserId(GoogleSignInUser_t self, char *buf, size_t len) { - return ReturnCopiedString(self->wrapped_->GetUserId(), buf, len); -} diff --git a/native-googlesignin/src/main/cpp/google_signin_bridge.h b/native-googlesignin/src/main/cpp/google_signin_bridge.h deleted file mode 100644 index 6095ade2..00000000 --- a/native-googlesignin/src/main/cpp/google_signin_bridge.h +++ /dev/null @@ -1,172 +0,0 @@ -// -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#ifndef GOOGLESIGNIN_GOOGLESIGNINBRIDGE_H -#define GOOGLESIGNIN_GOOGLESIGNINBRIDGE_H - -// Definition of the extern "C" interface. This is used -// primarily by the Unity plugin. - -#include -#include - -struct GoogleSignInHolder; -typedef GoogleSignInHolder* GoogleSignIn_t; - -struct GoogleSignInFuture; -typedef GoogleSignInFuture* GoogleSignInFuture_t; - -struct GoogleSignInUser; -typedef GoogleSignInUser* GoogleSignInUser_t; - -namespace googlesignin { -//Enum of the status codes used in the Unity plugin. The -// Android specific codes are mapped onto this when returning status via -// GoogleSignIn_Status(). -enum GoogleSignUnityStatusCode { - kUnityStatusCodeSuccessCached = -1, - kUnityStatusCodeSuccess = 0, - kUnityStatusCodeApiNotConnected = 1, - kUnityStatusCodeCanceled = 2, - kUnityStatusCodeInterrupted = 3, - kUnityStatusCodeInvalidAccount = 4, - kUnityStatusCodeTimeout = 5, - kUnityStatusCodeDeveloperError = 6, - kUnityStatusCodeInternalError = 7, - kUnityStatusCodeNetworkError = 8, - kUnityStatusCodeError = 9 -}; -} - -extern "C" { - -// Create a new instance of the GoogleSignIn class. -GoogleSignIn_t GoogleSignIn_Create(jobject activity); - -// Dispose the instance created by GoogleSignIn_Create(). -void GoogleSignIn_Dispose(GoogleSignIn_t self); - -// Enable verbose debugging -void GoogleSignIn_EnableDebugLogging(GoogleSignIn_t self, bool flag); - -// Configure the sign-in process. See GoogleSignIn::Configuration for details. -void GoogleSignIn_Configure(GoogleSignIn_t self, bool useGameSignIn, - const char* webClientId, bool requestAuthCode, - bool forceTokenRefresh, bool requestEmail, - bool requestIdToken, bool hidePopups, - const char** additional_scopes, int scopes_count, - const char* accountName); - -// Start the sign-in process. Returns a Future to use to get the result. -GoogleSignInFuture_t GoogleSignIn_SignIn(GoogleSignIn_t self); - -// Attempts to sign in silently. This method should be attempted first when -// when signing in "automatically". -GoogleSignInFuture_t GoogleSignIn_SignInSilently(GoogleSignIn_t self); - -// Signs out. This affects the local state. -void GoogleSignIn_Signout(GoogleSignIn_t self); - -// Disconnect from the app. This revokes all tokens for the user both locally -// and on the server. -void GoogleSignIn_Disconnect(GoogleSignIn_t self); - -// Accesses the Pending() method of the Future. This avoids -// having to marshal classes and structures between C and other languages -// (i.e. C#). -bool GoogleSignIn_Pending(GoogleSignInFuture_t self); - -// Accesses the Status() method of the Future. This avoids -// having to marshal classes and structures between C and other languages -// (i.e. C#). -int GoogleSignIn_Status(GoogleSignInFuture_t self); - -// Accesses the Result() method of the Future. This avoids -// having to marshal classes and structures between C and other languages -// (i.e. C#). -GoogleSignInUser_t GoogleSignIn_Result(GoogleSignInFuture_t self); - -// Accesses the AuthCode() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -size_t GoogleSignIn_GetServerAuthCode(GoogleSignInUser_t self, char* buf, - size_t len); - -// Accesses the DisplayName() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -size_t GoogleSignIn_GetDisplayName(GoogleSignInUser_t self, char* buf, - size_t len); - -// Accesses the Email() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -// -// Depending on the requested scopes and fields, this may return null. -size_t GoogleSignIn_GetEmail(GoogleSignInUser_t self, char* buf, size_t len); - -// Accesses the FamilyName() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -size_t GoogleSignIn_GetFamilyName(GoogleSignInUser_t self, char* buf, - size_t len); - -// Accesses the GiveName() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -size_t GoogleSignIn_GetGivenName(GoogleSignInUser_t self, char* buf, - size_t len); - -// Accesses the IdToken() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -size_t GoogleSignIn_GetIdToken(GoogleSignInUser_t self, char* buf, size_t len); - -// Accesses the ImageUrl() method of the GoogleSignInUser. -// This avoids having to marshal classes and structures between C and other -// languages (i.e. C#). -// -// The value is copied into buf up to len-1 characters. If buf is null, then -// nothing is copied. The return value is the length needed to copy the -// complete value. -size_t GoogleSignIn_GetImageUrl(GoogleSignInUser_t self, char* buf, size_t len); - -size_t GoogleSignIn_GetUserId(GoogleSignInUser_t self, char* buf, size_t len); -} // extern "C" -#endif // GOOGLESIGNIN_GOOGLESIGNINBRIDGE_H diff --git a/native-googlesignin/src/main/cpp/google_signin_user.cc b/native-googlesignin/src/main/cpp/google_signin_user.cc deleted file mode 100644 index 715a2da4..00000000 --- a/native-googlesignin/src/main/cpp/google_signin_user.cc +++ /dev/null @@ -1,206 +0,0 @@ -// -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "google_signin_user.h" // NOLINT -#include - -#include "google_signin_user_impl.h" // NOLINT -#include "jni_init.h" // NOLINT - -#define GOOGLESIGNINACCOUNT_NAME \ - "com/google/android/gms/auth/api/signin/GoogleSignInAccount" - -// String getDisplayName() -#define GETDISPLAYNAME_METHOD_NAME "getDisplayName" -#define GETDISPLAYNAME_METHOD_SIG "()Ljava/lang/String;" - -// String getEmail() -#define GETEMAIL_METHOD_NAME "getEmail" -#define GETEMAIL_METHOD_SIG "()Ljava/lang/String;" - -// String getFamilyName() -#define GETFAMILYNAME_METHOD_NAME "getFamilyName" -#define GETFAMILYNAME_METHOD_SIG "()Ljava/lang/String;" - -// String getGivenName() -#define GETGIVENNAME_METHOD_NAME "getGivenName" -#define GETGIVENNAME_METHOD_SIG "()Ljava/lang/String;" - -// String getId() -#define GETID_METHOD_NAME "getId" -#define GETID_METHOD_SIG "()Ljava/lang/String;" - -// String getIdToken() -#define GETIDTOKEN_METHOD_NAME "getIdToken" -#define GETIDTOKEN_METHOD_SIG "()Ljava/lang/String;" - -// String getServerAuthCode() -#define GETSERVERAUTHCODE_METHOD_NAME "getServerAuthCode" -#define GETSERVERAUTHCODE_METHOD_SIG "()Ljava/lang/String;" - -// Uri getPhotoUrl() -#define GETPHOTOURL_METHOD_NAME "getPhotoUrl" -#define GETPHOTOURL_METHOD_SIG "()Landroid/net/Uri;" - -#define URI_NAME "android/net/Uri" -#define TOSTRING_METHOD_NAME "toString" -#define TOSTRING_METHOD_SIG "()Ljava/lang/String;" - -namespace googlesignin { - -jmethodID GoogleSignInUserImpl::method_getDisplayName = 0; -jmethodID GoogleSignInUserImpl::method_getEmail = 0; -jmethodID GoogleSignInUserImpl::method_getFamilyName = 0; -jmethodID GoogleSignInUserImpl::method_getGivenName = 0; -jmethodID GoogleSignInUserImpl::method_getId = 0; -jmethodID GoogleSignInUserImpl::method_getIdToken = 0; -jmethodID GoogleSignInUserImpl::method_getPhotoUrl = 0; -jmethodID GoogleSignInUserImpl::method_getServerAuthCode = 0; -jmethodID GoogleSignInUserImpl::method_uri_toString = 0; - -void GoogleSignInUserImpl::Initialize(jobject obj) { - JNIEnv* env = GetJniEnv(); - - if (!method_getDisplayName) { - jclass google_acct_class = FindClass(GOOGLESIGNINACCOUNT_NAME, obj); - - method_getDisplayName = - env->GetMethodID(google_acct_class, GETDISPLAYNAME_METHOD_NAME, - GETDISPLAYNAME_METHOD_SIG); - - method_getEmail = env->GetMethodID(google_acct_class, GETEMAIL_METHOD_NAME, - GETEMAIL_METHOD_SIG); - - method_getFamilyName = env->GetMethodID( - google_acct_class, GETFAMILYNAME_METHOD_NAME, GETFAMILYNAME_METHOD_SIG); - - method_getGivenName = env->GetMethodID( - google_acct_class, GETGIVENNAME_METHOD_NAME, GETGIVENNAME_METHOD_SIG); - - method_getId = env->GetMethodID(google_acct_class, GETID_METHOD_NAME, - GETID_METHOD_SIG); - - method_getIdToken = env->GetMethodID( - google_acct_class, GETIDTOKEN_METHOD_NAME, GETIDTOKEN_METHOD_SIG); - - method_getPhotoUrl = env->GetMethodID( - google_acct_class, GETPHOTOURL_METHOD_NAME, GETPHOTOURL_METHOD_SIG); - - jclass uri_class = FindClass(URI_NAME, obj); - method_uri_toString = env->GetMethodID( - uri_class, TOSTRING_METHOD_NAME, TOSTRING_METHOD_SIG); - - method_getServerAuthCode = - env->GetMethodID(google_acct_class, GETSERVERAUTHCODE_METHOD_NAME, - GETSERVERAUTHCODE_METHOD_SIG); - } -} - -GoogleSignInUser::GoogleSignInUser() : impl_(new GoogleSignInUserImpl()) {} -GoogleSignInUser::~GoogleSignInUser() { delete impl_; } - -const char* GoogleSignInUser::GetDisplayName() const { - return impl_->display_name.c_str(); -} -const char* GoogleSignInUser::GetEmail() const { return impl_->email.c_str(); } -const char* GoogleSignInUser::GetFamilyName() const { - return impl_->family_name.c_str(); -} -const char* GoogleSignInUser::GetGivenName() const { - return impl_->given_name.c_str(); -} -const char* GoogleSignInUser::GetIdToken() const { - return impl_->id_token.c_str(); -} -const char* GoogleSignInUser::GetImageUrl() const { - return impl_->image_url.c_str(); -} -const char* GoogleSignInUser::GetServerAuthCode() const { - return impl_->server_auth_code.c_str(); -} -const char* GoogleSignInUser::GetUserId() const { - return impl_->user_id.c_str(); -} - -void StringFromJava(jstring j_str, std::string* dest) { - if (!j_str) { - dest->clear(); - return; - } - JNIEnv* env = GetJniEnv(); - const char* buf = env->GetStringUTFChars(j_str, nullptr); - - *dest = buf; - - __android_log_print(ANDROID_LOG_INFO, "native-googlesignin", - "StringFromJava %s == %s", dest->c_str(), buf); - - env->ReleaseStringUTFChars(j_str, buf); -} - -GoogleSignInUser* GoogleSignInUserImpl::UserFromAccount(jobject user_account) { - if (!user_account) { - return nullptr; - } - JNIEnv* env = GetJniEnv(); - GoogleSignInUserImpl* user_impl = new GoogleSignInUserImpl(); - - if (!GoogleSignInUserImpl::method_getDisplayName) { - GoogleSignInUserImpl::Initialize(user_account); - } - - jstring val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getDisplayName)); - StringFromJava(val, &user_impl->display_name); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getEmail)); - StringFromJava(val, &user_impl->email); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getFamilyName)); - StringFromJava(val, &user_impl->family_name); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getGivenName)); - StringFromJava(val, &user_impl->given_name); - - val = static_cast( - env->CallObjectMethod(user_account, GoogleSignInUserImpl::method_getId)); - StringFromJava(val, &user_impl->user_id); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getIdToken)); - StringFromJava(val, &user_impl->id_token); - - jobject uri = env->CallObjectMethod(user_account, - GoogleSignInUserImpl::method_getPhotoUrl); - if (uri) { - val = static_cast( - env->CallObjectMethod(uri, GoogleSignInUserImpl::method_uri_toString)); - } else { - val = nullptr; - } - StringFromJava(val, &user_impl->image_url); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getServerAuthCode)); - StringFromJava(val, &user_impl->server_auth_code); - - return new GoogleSignInUser(user_impl); -} - -} // namespace googlesignin diff --git a/native-googlesignin/src/main/cpp/google_signin_user.h b/native-googlesignin/src/main/cpp/google_signin_user.h deleted file mode 100644 index dfddb137..00000000 --- a/native-googlesignin/src/main/cpp/google_signin_user.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_GOOGLE_SIGNIN_USER_H -#define GOOGLESIGNIN_GOOGLE_SIGNIN_USER_H - -namespace googlesignin { - -class GoogleSignInUserImpl; - -// Represents the currently signed in user. -class GoogleSignInUser { - public: - ~GoogleSignInUser(); - - const char* GetDisplayName() const; - const char* GetEmail() const; - const char* GetFamilyName() const; - const char* GetGivenName() const; - const char* GetIdToken() const; - const char* GetImageUrl() const; - const char* GetServerAuthCode() const; - const char* GetUserId() const; - - private: - friend class GoogleSignInUserImpl; - GoogleSignInUser(); - GoogleSignInUser(GoogleSignInUserImpl* impl) : impl_(impl) {} - GoogleSignInUserImpl* impl_; -}; - -} // namespace googlesignin - -#endif // GOOGLESIGNIN_GOOGLE_SIGNIN_USER_H diff --git a/native-googlesignin/src/main/cpp/google_signin_user_impl.h b/native-googlesignin/src/main/cpp/google_signin_user_impl.h deleted file mode 100644 index 5c1047ce..00000000 --- a/native-googlesignin/src/main/cpp/google_signin_user_impl.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_GOOGLE_SIGNIN_USER_IMPL_H -#define GOOGLESIGNIN_GOOGLE_SIGNIN_USER_IMPL_H - -#include -#include - -namespace googlesignin { -class GoogleSignInUserImpl { - public: - std::string display_name; - std::string email; - std::string family_name; - std::string given_name; - std::string id_token; - std::string image_url; - std::string user_id; - std::string server_auth_code; - static jmethodID method_getDisplayName; - static jmethodID method_getEmail; - static jmethodID method_getFamilyName; - static jmethodID method_getGivenName; - static jmethodID method_getId; - static jmethodID method_getIdToken; - static jmethodID method_getPhotoUrl; - static jmethodID method_getServerAuthCode; - static jmethodID method_uri_toString; - - static void Initialize(jobject obj); - static GoogleSignInUser *UserFromAccount(jobject user_account); -}; -} // namespace googlesignin -#endif // GOOGLESIGNIN_GOOGLE_SIGNIN_USER_IMPL_H diff --git a/native-googlesignin/src/main/cpp/jni.cc b/native-googlesignin/src/main/cpp/jni.cc deleted file mode 100644 index 74ea9449..00000000 --- a/native-googlesignin/src/main/cpp/jni.cc +++ /dev/null @@ -1,104 +0,0 @@ -// -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include -#include -#include "jni_init.h" - -// static pointer to access the JVM. -static JavaVM *g_vm; - -/// Called when the library is loaded by a Java VM. -extern "C" jint JNI_OnLoad(JavaVM *vm, void *reserved) { - JNIEnv *env; - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { - return -1; - } - - g_vm = vm; - - return JNI_VERSION_1_6; -} - -namespace googlesignin { - -// Static variables used in tracking thread initialization and cleanup. -pthread_key_t jni_env_key; -pthread_once_t pthread_key_initialized = PTHREAD_ONCE_INIT; - -void DetachJVMThreads(void *stored_java_vm) { - assert(stored_java_vm); - JNIEnv *jni_env; - JavaVM *java_vm = static_cast(stored_java_vm); - // AttachCurrentThread does nothing if we're already attached, but - // calling it ensures that the DetachCurrentThread doesn't fail. - java_vm->AttachCurrentThread(&jni_env, nullptr); - java_vm->DetachCurrentThread(); -} - -// Called the first time GetJNIEnv is invoked. -// Ensures that jni_env_key is created and that the destructor is in place. -void SetupJvmDetachOnThreadDestruction() { - pthread_key_create(&jni_env_key, DetachJVMThreads); -} - -// Helper function used to access the jni environment on the current thread. -JNIEnv *GetJniEnv() { - // Set up the thread key and destructor the first time this is called: - (void)pthread_once(&pthread_key_initialized, - SetupJvmDetachOnThreadDestruction); - pthread_setspecific(jni_env_key, g_vm); - - JNIEnv *env; - jint result = g_vm->AttachCurrentThread(&env, nullptr); - return result == JNI_OK ? env : nullptr; -} - -// Find a class, attempting to load the class if it's not found. -jclass FindClass(const char *class_name, jobject activity) { - JNIEnv *env = GetJniEnv(); - jclass class_object = env->FindClass(class_name); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - // If the class isn't found it's possible NativeActivity is being used by - // the application which means the class path is set to only load system - // classes. The following falls back to loading the class using the - // Activity before retrieving a reference to it. - jclass activity_class = env->FindClass("android/app/Activity"); - jmethodID activity_get_class_loader = env->GetMethodID( - activity_class, "getClassLoader", "()Ljava/lang/ClassLoader;"); - - jobject class_loader_object = - env->CallObjectMethod(activity, activity_get_class_loader); - - jclass class_loader_class = env->FindClass("java/lang/ClassLoader"); - jmethodID class_loader_load_class = - env->GetMethodID(class_loader_class, "loadClass", - "(Ljava/lang/String;)Ljava/lang/Class;"); - jstring class_name_object = env->NewStringUTF(class_name); - - class_object = static_cast(env->CallObjectMethod( - class_loader_object, class_loader_load_class, class_name_object)); - - if (env->ExceptionCheck()) { - env->ExceptionClear(); - class_object = nullptr; - } - env->DeleteLocalRef(class_name_object); - env->DeleteLocalRef(class_loader_object); - } - return class_object; -} -} // namespace googlesignin diff --git a/native-googlesignin/src/main/cpp/jni_init.h b/native-googlesignin/src/main/cpp/jni_init.h deleted file mode 100644 index cffccedd..00000000 --- a/native-googlesignin/src/main/cpp/jni_init.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_JNI_INIT_H -#define GOOGLESIGNIN_JNI_INIT_H - -#include - -namespace googlesignin { - -JNIEnv *GetJniEnv(); -jclass FindClass(const char *class_name, jobject activity); - -} // namespace googlesignin - -#endif // GOOGLESIGNIN_JNI_INIT_H diff --git a/native-googlesignin/src/main/java/com/google/googlesignin/GoogleSignInFragment.java b/native-googlesignin/src/main/java/com/google/googlesignin/GoogleSignInFragment.java deleted file mode 100644 index e844c03c..00000000 --- a/native-googlesignin/src/main/java/com/google/googlesignin/GoogleSignInFragment.java +++ /dev/null @@ -1,554 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import android.app.Activity; -import android.app.Fragment; -import android.app.FragmentTransaction; -import android.content.Intent; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.View; -import com.google.android.gms.auth.api.Auth; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.auth.api.signin.GoogleSignInOptions; -import com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension; -import com.google.android.gms.auth.api.signin.GoogleSignInResult; -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.Api; -import com.google.android.gms.common.api.CommonStatusCodes; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.common.api.ResultCallback; -import com.google.android.gms.common.api.Scope; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Locale; - -/** - * Activity fragment with no UI added to the parent activity in order to manage the accessing of the - * player's email address and tokens. - */ -public class GoogleSignInFragment extends Fragment implements - GoogleApiClient.ConnectionCallbacks, - GoogleApiClient.OnConnectionFailedListener { - - // Tag uniquely identifying this fragment. - public static final String FRAGMENT_TAG = "signin.SignInFragment"; - private static final int RC_SIGNIN = 9009; - - /** - * Handle the Google API Client connection being connected. - * - * @param connectionHint - is not used. - */ - @Override - public void onConnected(@Nullable Bundle connectionHint) { - GoogleSignInHelper.logDebug("onConnected!"); - if (mGoogleApiClient.hasConnectedApi(Auth.GOOGLE_SIGN_IN_API)) { - GoogleSignInHelper.logDebug("has connected auth!"); - Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient) - .setResultCallback( - new ResultCallback() { - @Override - public void onResult(@NonNull GoogleSignInResult googleSignInResult) { - if (googleSignInResult.isSuccess()) { - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } else { - GoogleSignInHelper.logError( - "Error with " + "silentSignIn: " + googleSignInResult.getStatus()); - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } - } - }); - } else { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGNIN); - } - } - - @Override - public void onConnectionSuspended(int cause) { - GoogleSignInHelper.logDebug("onConnectionSuspended() called: " + cause); - } - - - @Override - public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { - // Handle errors during connection, such as Play Store not installed. - GoogleSignInHelper.logError("Connection failed: " + - connectionResult.getErrorCode()); - // if there is a resolution, just start the sign-in intent, which handles - // the resolution logic. - if (connectionResult.hasResolution()) { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGNIN); - } else { - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - connectionResult.getErrorCode(), - null); - } - } - - public void disconnect() { - - if (mGoogleApiClient != null) { - mGoogleApiClient.disconnect(); - } - } - - /** - * The state of the fragment. It can only handle one sign-in request at a time, so we use these - * values to keep track of the request lifecycle. - */ - private enum State { - NEW, - READY, - PENDING, - PENDING_SILENT, - BUSY - } - - private State state; - - /** - * The request to sign-in. This contains the configuration for the API client/Sign-in options and - * the callback information used to communicate the result. - */ - private TokenRequest request = null; - - private GoogleApiClient mGoogleApiClient; - - // TODO: make config async. - private static GoogleSignInFragment theFragment; - - /** - * Gets the instance of the fragment. - * - * @param parentActivity - the activity to attach the fragment to. - * @return the instance. - */ - public static GoogleSignInFragment getInstance(Activity parentActivity) { - GoogleSignInFragment fragment = - (GoogleSignInFragment) parentActivity.getFragmentManager().findFragmentByTag(FRAGMENT_TAG); - - fragment = (fragment != null) ? fragment : theFragment; - if (fragment == null) { - GoogleSignInHelper.logDebug("Creating fragment"); - fragment = new GoogleSignInFragment(); - FragmentTransaction trans = parentActivity.getFragmentManager().beginTransaction(); - trans.add(fragment, FRAGMENT_TAG); - trans.commitAllowingStateLoss(); - theFragment = fragment; - } - return fragment; - } - - public synchronized boolean submitRequest(TokenRequest request) { - if (this.request == null || this.state == State.READY) { - this.request = request; - return true; - } - GoogleSignInHelper.logError(String.format(Locale.getDefault(), - "Existing request: %s ignoring %s. State = %s", this.request, request, this.state)); - return false; - } - - private synchronized State getState() { - return state; - } - - private synchronized void setState(State state) { - this.state = state; - } - - /** - * Signs out and disconnects the client. NOTE: if you are using the Games API, you **MUST** call - * Games.signout() before this method. Failure to do so will result in not being able to access - * Games API until the application is restarted. - */ - public void signOut() { - clearRequest(true); - if (mGoogleApiClient != null) { - Auth.GoogleSignInApi.signOut(mGoogleApiClient); - } - } - - /** - * Starts the sign-in process using the Sign-in UI, if any UI is needed. This is in contrast to - * startSignInSilently, which does not use any UI. - * - * @return true if the sign-in flow was started. - */ - public boolean startSignIn() { - if (request == null) { - GoogleSignInHelper.logError("Request not configured! Failing authenticate"); - return false; - } - if (getState() == State.BUSY) { - GoogleSignInHelper.logError("There is already a pending callback" + " configured."); - } else if (getState() == State.READY) { - processRequest(false); - } else { - processWhenReady(false); - } - return true; - } - - /** - * Starts the sign-in silently flow. - * - * @return true if the flow was started successfully. - */ - public boolean startSignInSilently() { - if (request == null) { - GoogleSignInHelper.logError("Request not configured! Failing authenticate"); - return false; - } - if (getState() == State.BUSY) { - GoogleSignInHelper.logError("There is already a pending callback" + " configured."); - } else if (getState() == State.READY) { - processRequest(true); - } else { - processWhenReady(true); - } - return true; - } - - /** - * Indicates that the token request has been set and it is ready to be processed. The processing - * can start once the fragment is attached to the activity and initialized. - * - * @param silent - true if the sign-in should be silent. - */ - private void processWhenReady(boolean silent) { - GoogleSignInHelper.logInfo("Fragment not initialized yet, " + "waiting to authenticate"); - setState(silent ? State.PENDING_SILENT : State.PENDING); - } - - /** - * Processes the token requests that are queued up. First checking that the google api client is - * connected. - */ - private void processRequest(final boolean silent) { - try { - if (request != null) { - setState(State.BUSY); - } else { - GoogleSignInHelper.logInfo("No pending configuration, returning"); - return; - } - - request - .getPendingResponse() - .setResultCallback( - new ResultCallback() { - @Override - public void onResult(@NonNull TokenResult tokenResult) { - GoogleSignInHelper.logDebug( - String.format( - Locale.getDefault(), - "Calling nativeOnResult: handle: %s, status: %d acct: %s", - tokenResult.getHandle(), - tokenResult.getStatus().getStatusCode(), - tokenResult.getAccount())); - GoogleSignInHelper.nativeOnResult( - tokenResult.getHandle(), - tokenResult.getStatus().getStatusCode(), - tokenResult.getAccount()); - clearRequest(false); - } - }); - - // Build the GoogleAPIClient - buildClient(request); - - GoogleSignInHelper.logDebug( - " Has connected == " + mGoogleApiClient.hasConnectedApi(Auth.GOOGLE_SIGN_IN_API)); - if (!mGoogleApiClient.hasConnectedApi(Auth.GOOGLE_SIGN_IN_API)) { - - if (!silent) { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGNIN); - } else { - Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient) - .setResultCallback( - new ResultCallback() { - @Override - public void onResult(@NonNull GoogleSignInResult googleSignInResult) { - if (googleSignInResult.isSuccess()) { - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } else { - GoogleSignInHelper.logError( - "Error with " + "silentSignIn: " + googleSignInResult.getStatus()); - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } - } - }); - } - } - } catch (Throwable throwable) { - GoogleSignInHelper.logError("Exception caught! " + throwable.getMessage()); - request.setResult(CommonStatusCodes.INTERNAL_ERROR, null); - return; - } - - GoogleSignInHelper.logDebug("Done with processRequest!"); - } - - /** - * Builds the Google API Client based on the configuration in the request. - * - * @param request - the request for a token. - */ - private void buildClient(TokenRequest request) { - GoogleSignInOptions.Builder builder; - - if (request.getUseGamesConfig()) { - GoogleSignInHelper.logDebug("Using DEFAULT_GAMES_SIGN_IN"); - builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); - } else { - GoogleSignInHelper.logDebug("Using DEFAULT_SIGN_IN"); - builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN); - } - - if (request.getDoAuthCode()) { - if (!request.getWebClientId().isEmpty()) { - GoogleSignInHelper.logDebug( - "Requesting AuthCode force = " - + request.getForceRefresh() - + "client: " - + request.getWebClientId()); - builder.requestServerAuthCode(request.getWebClientId(), request.getForceRefresh()); - } else { - GoogleSignInHelper.logError("Web client ID is needed for Auth Code"); - request.setResult(CommonStatusCodes.DEVELOPER_ERROR, null); - throw new IllegalStateException("Web client ID is needed for Auth Code"); - } - } - - if (request.getDoEmail()) { - GoogleSignInHelper.logDebug("Requesting email"); - builder.requestEmail(); - } - - if (request.getDoIdToken()) { - if (!request.getWebClientId().isEmpty()) { - GoogleSignInHelper.logDebug("Requesting IDToken client: " + request.getWebClientId()); - - builder.requestIdToken(request.getWebClientId()); - } else { - GoogleSignInHelper.logError("Web client ID is needed for ID Token"); - request.setResult(CommonStatusCodes.DEVELOPER_ERROR, null); - throw new IllegalStateException("Web client ID is needed for Auth Code"); - } - } - if (request.getScopes() != null) { - for (String s : request.getScopes()) { - GoogleSignInHelper.logDebug("Adding scope: " + s); - - builder.requestScopes(new Scope(s)); - } - } - - if (request.getHidePopups() && request.getUseGamesConfig()) { - GoogleSignInHelper.logDebug("hiding popup views for games API"); - // Use reflection to build the extension, so we don't force - // a dependency on Games. - - builder.addExtension(getGamesExtension()); - } - - if (request.getAccountName() != null) { - GoogleSignInHelper.logDebug("Setting accountName: " + request.getAccountName()); - - builder.setAccountName(request.getAccountName()); - } - - GoogleSignInOptions options = builder.build(); - - GoogleApiClient.Builder clientBuilder = - new GoogleApiClient.Builder(getActivity()).addApi(Auth.GOOGLE_SIGN_IN_API, options); - if (request.getUseGamesConfig()) { - GoogleSignInHelper.logDebug("Adding games API"); - - try { - clientBuilder.addApi(getGamesAPI()); - } catch (Exception e) { - GoogleSignInHelper.logError("Exception getting Games API: " + e.getMessage()); - request.setResult(CommonStatusCodes.DEVELOPER_ERROR, null); - return; - } - } - if (request.getHidePopups()) { - View invisible = new View(getActivity()); - invisible.setVisibility(View.INVISIBLE); - invisible.setClickable(false); - clientBuilder.setViewForPopups(invisible); - } - mGoogleApiClient = clientBuilder.build(); - mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL); - } - - private Api getGamesAPI() { - try { - Class gamesClass = Class.forName("com" + ".google.android.gms.games.Games"); - Field apiField = gamesClass.getField("API"); - return (Api) apiField.get(null); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Games API requested, but " + "can't load Games class", e); - } catch (NoSuchFieldException e) { - throw new IllegalArgumentException( - "Games API requested, but " + "can't load Games API field", e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException( - "Games API requested, but " + "can't load Games API field", e); - } - } - - /** - * Builds the games extension to hide popups using Reflection. This avoids the hard dependency on - * Games. - * - * @return the extension, or throws InvalidArgumentException if games is requested, but not found. - */ - private GoogleSignInOptionsExtension getGamesExtension() { - try { - Class gamesClass = Class.forName("com" + ".google.android.gms.games.Games$GamesOptions"); - - Method builderMethod = gamesClass.getMethod("builder()"); - - Object builder = builderMethod.invoke(null); - - Method setter = builder.getClass().getMethod("setShowConnectingPopup", boolean.class); - - setter.invoke(builder, false); - - Method buildMethod = builder.getClass().getMethod("build"); - return (GoogleSignInOptionsExtension) buildMethod.invoke(builder); - - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't load Games$GamesOptions class", e); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't find builder() static method.", e); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't invoke builder() static method.", e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't invoke builder() static method.", e); - } - } - - @Override - public void onStart() { - super.onStart(); - - // This just connects the client. If there is no user signed in, you - // still need to call Auth.GoogleSignInApi.getSignInIntent() to start - // the sign-in process. - if (mGoogleApiClient != null) { - mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL); - } - } - - /** - * Called when the fragment is visible to the user and actively running. This is generally tied to - * {@link Activity#onResume() Activity.onResume} of the containing Activity's lifecycle. - */ - @Override - public void onResume() { - GoogleSignInHelper.logDebug("onResume called"); - if (theFragment != this) { - theFragment = this; - } - super.onResume(); - if (getState() == State.PENDING) { - GoogleSignInHelper.logDebug("State is pending, calling processRequest(false)"); - processRequest(false); - } else if (getState() == State.PENDING_SILENT) { - GoogleSignInHelper.logDebug("State is pending_silent, calling processRequest(true)"); - processRequest(true); - } else { - GoogleSignInHelper.logDebug("State is now ready"); - setState(State.READY); - } - } - - /** - * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. This - * follows the related Activity API as described there in {@link Activity#onActivityResult(int, - * int, Intent)}. - * - * @param requestCode The integer request code originally supplied to startActivityForResult(), - * allowing you to identify who this result came from. - * @param resultCode The integer result code returned by the child activity through its - * setResult(). - * @param data An Intent, which can return result data to the caller - */ - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - GoogleSignInHelper.logDebug("onActivityResult: " + requestCode + " " + resultCode); - if (requestCode == RC_SIGNIN) { - GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); - TokenRequest request = this.request; - if (request != null) { - if (result == null) { - // This usually indicates a problem with Google Play Services not working correctly. - int returnCode = resultCode >= 0 ? CommonStatusCodes.ERROR : resultCode; - request.setResult( returnCode, null); - GoogleSignInHelper.logError("GoogleSignIn result is null, returning error."); - } else { - GoogleSignInAccount acct = result.getSignInAccount(); - request.setResult(result.getStatus().getStatusCode(), acct); - } - } else { - GoogleSignInHelper.logError("Pending request is null, can't " + "return result!"); - } - return; - } - super.onActivityResult(requestCode, resultCode, data); - } - - private synchronized void clearRequest(boolean cancel) { - if (cancel && request != null) { - // Cancel request. - request.cancel(); - } - request = null; - setState(getActivity() != null ? State.READY : State.NEW); - } -} diff --git a/native-googlesignin/src/main/java/com/google/googlesignin/GoogleSignInHelper.java b/native-googlesignin/src/main/java/com/google/googlesignin/GoogleSignInHelper.java deleted file mode 100644 index fd251b30..00000000 --- a/native-googlesignin/src/main/java/com/google/googlesignin/GoogleSignInHelper.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import android.app.Activity; -import android.util.Log; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.CommonStatusCodes; - -/** - * Helper class used by the native C++ code to interact with Google Sign-in API. The general flow is - * Call configure, then one of signIn or signInSilently. - */ -public class GoogleSignInHelper { - - // Set to true to get more debug logging. - public static boolean loggingEnabled = false; - private static final String TAG = "SignInFragment"; - - /** - * Enables verbose logging - */ - public static void enableDebugLogging(boolean flag) { - loggingEnabled = flag; - } - - /** - * Sets the configuration of the sign-in api that should be used. - * - * @param parentActivity - the parent activity. This API creates a fragment that is attached to - * this activity. - * @param useGamesConfig - true if the GAMES_CONFIG should be used when signing-in. - * @param webClientId - the web client id of the backend server associated with this application. - * @param requestAuthCode - true if a server auth code is needed. This also requires the web - * client id to be set. - * @param forceRefreshToken - true to force a refresh token when using the server auth code. - * @param requestEmail - true if email address of the user is requested. - * @param requestIdToken - true if an id token for the user is requested. - * @param hideUiPopups - true if the popups during sign-in from the Games API should be hidden. - * This only has affect if useGamesConfig is true. - * @param defaultAccountName - the account name to attempt to default to when signing in. - * @param additionalScopes - additional API scopes to request when authenticating. - * @param requestHandle - the handle to this request, created by the native C++ code, this is used - * to correlate the response with the request. - */ - public static void configure( - Activity parentActivity, - boolean useGamesConfig, - String webClientId, - boolean requestAuthCode, - boolean forceRefreshToken, - boolean requestEmail, - boolean requestIdToken, - boolean hideUiPopups, - String defaultAccountName, - String[] additionalScopes, - long requestHandle) { - logDebug("TokenFragment.configure called"); - TokenRequest request = - new TokenRequest( - useGamesConfig, - webClientId, - requestAuthCode, - forceRefreshToken, - requestEmail, - requestIdToken, - hideUiPopups, - defaultAccountName, - additionalScopes, - requestHandle); - - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(parentActivity); - - if (request.isValid()) { - if (!fragment.submitRequest(request)) { - logError("There is already a pending" + " authentication token request!"); - } - } else { - nativeOnResult(requestHandle, CommonStatusCodes.DEVELOPER_ERROR, null); - } - } - - public static void signIn(Activity activity, long requestHandle) { - logDebug("AuthHelperFragment.authenticate called!"); - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - - if (!fragment.startSignIn()) { - nativeOnResult(requestHandle, CommonStatusCodes.DEVELOPER_ERROR, null); - } - } - - public static void signInSilently(Activity activity, long requestHandle) { - logDebug("AuthHelperFragment.signinSilently called!"); - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - - if (!fragment.startSignInSilently()) { - nativeOnResult(requestHandle, CommonStatusCodes.DEVELOPER_ERROR, null); - } - } - - public static void signOut(Activity activity) { - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - fragment.signOut(); - } - - public static void disconnect(Activity activity) { - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - fragment.disconnect(); - } - - public static void logInfo(String msg) { - if (loggingEnabled) { - Log.i(TAG, msg); - } - } - - public static void logError(String msg) { - Log.e(TAG, msg); - } - - public static void logDebug(String msg) { - if (loggingEnabled) { - Log.d(TAG, msg); - } - } - - /** - * Native callback for the authentication result. - * - * @param handle Identifies the request. - * @param result Authentication result. - * @param acct The account that is signed in, if successful. - */ - public static native void nativeOnResult(long handle, int result, GoogleSignInAccount acct); -} diff --git a/native-googlesignin/src/main/java/com/google/googlesignin/TokenPendingResult.java b/native-googlesignin/src/main/java/com/google/googlesignin/TokenPendingResult.java deleted file mode 100644 index 7f8389d0..00000000 --- a/native-googlesignin/src/main/java/com/google/googlesignin/TokenPendingResult.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import android.util.Log; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.CommonStatusCodes; -import com.google.android.gms.common.api.PendingResult; -import com.google.android.gms.common.api.ResultCallback; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Pending result class for TokenResult. This allows the pending result to be returned to the - * caller, and then updated when available, simplifying the handling of callbacks. - */ -public class TokenPendingResult extends PendingResult { - - private static final String TAG = "TokenPendingResult"; - private final long requestHandle; - - private CountDownLatch latch = new CountDownLatch(1); - private TokenResult result; - private ResultCallback resultCallback; - - public TokenPendingResult(long requestHandle) { - this.requestHandle = requestHandle; - result = new TokenResult(); - result.setHandle(requestHandle); - } - - @Override - public TokenResult await() { - - try { - latch.await(); - } catch (InterruptedException e) { - setResult(null, CommonStatusCodes.INTERRUPTED); - } - - return getResult(); - } - - @Override - public TokenResult await(long l, TimeUnit timeUnit) { - try { - if (!latch.await(l, timeUnit)) { - setResult(null, CommonStatusCodes.TIMEOUT); - } - } catch (InterruptedException e) { - setResult(null, CommonStatusCodes.INTERRUPTED); - } - return getResult(); - } - - @Override - public void cancel() { - setResult(null, CommonStatusCodes.CANCELED); - latch.countDown(); - } - - @Override - public boolean isCanceled() { - return getResult() != null && getResult().getStatus().isCanceled(); - } - - @Override - public void setResultCallback(ResultCallback resultCallback) { - - // Handle adding the callback when the latch has already counted down. This - // can happen if there is an error right away. - if (latch.getCount() == 0) { - resultCallback.onResult(getResult()); - } else { - setCallback(resultCallback); - } - } - - @Override - public void setResultCallback( - ResultCallback resultCallback, long l, TimeUnit timeUnit) { - try { - if (!latch.await(l, timeUnit)) { - setResult(null, CommonStatusCodes.TIMEOUT); - } - } catch (InterruptedException e) { - setResult(null, CommonStatusCodes.INTERRUPTED); - } - - resultCallback.onResult(getResult()); - } - - private synchronized void setCallback(ResultCallback callback) { - this.resultCallback = callback; - } - - private synchronized ResultCallback getCallback() { - return this.resultCallback; - } - - /** - * Set the result. If any of the values are null, and a previous non-null value was set, the - * non-null value is retained. - * - * @param account - the signin account, if any. - * @param resultCode - the result code. - */ - public synchronized void setResult(GoogleSignInAccount account, int resultCode) { - result = new TokenResult(account, resultCode); - result.setHandle(requestHandle); - } - - private synchronized TokenResult getResult() { - return result; - } - - /** - * Sets the result status and releases the latch and/or calls the callback. - * - * @param status - the result status. - */ - public void setStatus(int status) { - result.setStatus(status); - latch.countDown(); - ResultCallback cb = getCallback(); - TokenResult res = getResult(); - if (cb != null) { - Log.d(TAG, " Calling onResult for callback. result: " + res); - getCallback().onResult(res); - } - } -} diff --git a/native-googlesignin/src/main/java/com/google/googlesignin/TokenRequest.java b/native-googlesignin/src/main/java/com/google/googlesignin/TokenRequest.java deleted file mode 100644 index 35335024..00000000 --- a/native-googlesignin/src/main/java/com/google/googlesignin/TokenRequest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.PendingResult; -import java.util.Locale; - -/** Helper class containing the request for information. */ -public class TokenRequest { - private TokenPendingResult pendingResponse; - private boolean useGamesConfig; - private boolean doAuthCode; - private boolean doEmail; - private boolean doIdToken; - private String webClientId; - private boolean forceRefresh; - private boolean hidePopups; - private String accountName; - private String[] scopes; - private long handle; - - /** - * Constructs a token request. - * - * @param useGamesConfig - true if the GAMES_CONFIG should be used when signing-in. - * @param webClientId - the web client id of the backend server associated with this application. - * @param requestAuthCode - true if a server auth code is needed. This also requires the web - * client id to be set. - * @param forceRefreshToken - true to force a refresh token when using the server auth code. - * @param requestEmail - true if email address of the user is requested. - * @param requestIdToken - true if an id token for the user is requested. - * @param hideUiPopups - true if the popups during sign-in from the Games API should be hidden. - * This only has affect if useGamesConfig is true. - * @param defaultAccountName - the account name to attempt to default to when signing in. - * @param additionalScopes - additional API scopes to request when authenticating. - * @param requestHandle - the handle to this request, created by the native C++ code, this is used - * to correlate the response with the request. - */ - public TokenRequest( - boolean useGamesConfig, - String webClientId, - boolean requestAuthCode, - boolean forceRefreshToken, - boolean requestEmail, - boolean requestIdToken, - boolean hideUiPopups, - String defaultAccountName, - String[] additionalScopes, - long requestHandle) { - pendingResponse = new TokenPendingResult(requestHandle); - this.useGamesConfig = useGamesConfig; - this.webClientId = webClientId; - this.doAuthCode = requestAuthCode; - this.forceRefresh = forceRefreshToken; - this.doEmail = requestEmail; - this.doIdToken = requestIdToken; - this.hidePopups = hideUiPopups; - this.accountName = defaultAccountName; - this.handle = requestHandle; - if (additionalScopes != null && additionalScopes.length > 0) { - scopes = new String[additionalScopes.length]; - System.arraycopy(additionalScopes, 0, scopes, 0, additionalScopes.length); - } else { - scopes = null; - } - } - - /** - * Returns the pending response object for this request. - * - * @return the pending response. - */ - public PendingResult getPendingResponse() { - return pendingResponse; - } - - /** - * Sets the result of the reuquest. - * - * @param code - the status code of the request. - * @param account - the GoogleSignInAccount if successful. - */ - public void setResult(int code, GoogleSignInAccount account) { - pendingResponse.setResult(account, code); - pendingResponse.setStatus(code); - } - - /** Cancels the request and notifies the pending response. */ - public void cancel() { - pendingResponse.cancel(); - } - - @Override - public String toString() { - return String.format( - Locale.getDefault(), - "%s(a:%b:e:%b:i:%b)", - Integer.toHexString(hashCode()), - doAuthCode, - doEmail, - doIdToken); - } - - public String getWebClientId() { - return webClientId == null ? "" : webClientId; - } - - public boolean getForceRefresh() { - return forceRefresh; - } - - public boolean isValid() { - if (webClientId == null || webClientId.isEmpty()) { - if (doAuthCode) { - GoogleSignInHelper.logError( - "Invalid configuration, auth code" + " requires web " + "client id"); - return false; - } else if (doIdToken) { - GoogleSignInHelper.logError("Invalid configuration, id token requires web " + "client id"); - return false; - } - } - return true; - } - - public long getHandle() { - return handle; - } - - public boolean getUseGamesConfig() { - return useGamesConfig; - } - - public boolean getDoAuthCode() { - return doAuthCode; - } - - public boolean getDoEmail() { - return doEmail; - } - - public boolean getDoIdToken() { - return doIdToken; - } - - public String[] getScopes() { - return scopes; - } - - public String getAccountName() { - return accountName; - } - - public boolean getHidePopups() { - return hidePopups; - } -} diff --git a/native-googlesignin/src/main/java/com/google/googlesignin/TokenResult.java b/native-googlesignin/src/main/java/com/google/googlesignin/TokenResult.java deleted file mode 100644 index db85d96b..00000000 --- a/native-googlesignin/src/main/java/com/google/googlesignin/TokenResult.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.CommonStatusCodes; -import com.google.android.gms.common.api.Result; -import com.google.android.gms.common.api.Status; -import java.util.Locale; - -/** Class for returning the tokens to a native caller. */ -public class TokenResult implements Result { - private Status status; - private GoogleSignInAccount account; - private long handle; - - TokenResult() { - status = new Status(CommonStatusCodes.SIGN_IN_REQUIRED); - account = null; - } - - TokenResult(GoogleSignInAccount account, int resultCode) { - status = new Status(resultCode); - this.account = account; - } - - @Override - public String toString() { - return String.format( - Locale.getDefault(), "Status: %s %s", status, (account == null) ? "" : account); - } - - @Override - public Status getStatus() { - return status; - } - - public GoogleSignInAccount getAccount() { - return account; - } - - public void setStatus(int status) { - this.status = new Status(status); - } - - public long getHandle() { - return handle; - } - - public void setHandle(long handle) { - this.handle = handle; - } -} diff --git a/package.json b/package.json new file mode 100644 index 00000000..0c987933 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "com.google.signin", + "displayName": "Google Signin", + "version": "0.9.0", + "unity": "2021.3", + "description": "Google Signin for android, ios ,desktop", + "keywords": [ + "google", + "signin" + ], + "dependencies": { + "com.unity.nuget.newtonsoft-json": "3.2.1", + "com.google.external-dependency-manager": "1.2.175" + }, + "samples": [ + { + "displayName": "SignIn Sample", + "description": "Simple SignIn Sample", + "path": "Samples~/SignInSample" + } + ] +} diff --git a/package.json.meta b/package.json.meta new file mode 100644 index 00000000..5171498e --- /dev/null +++ b/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d0144d8f7992f134a87074b63d2c169e +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index e47e0e32..00000000 --- a/settings.gradle +++ /dev/null @@ -1,15 +0,0 @@ -/* Copyright (C) 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -include ':native-googlesignin' diff --git a/staging/DIR_README.md b/staging/DIR_README.md deleted file mode 100644 index e5273932..00000000 --- a/staging/DIR_README.md +++ /dev/null @@ -1,4 +0,0 @@ -This directory is a temporary staging area for reassembling the native C++ API. - -When done, the contents of this folder will be merged into the parent folder, -and replace the existing native wrappers. \ No newline at end of file diff --git a/staging/native/GoogleSignInCpp.podspec b/staging/native/GoogleSignInCpp.podspec deleted file mode 100644 index 5583f0eb..00000000 --- a/staging/native/GoogleSignInCpp.podspec +++ /dev/null @@ -1,40 +0,0 @@ -# -# Be sure to run `pod lib lint GoogleSignInCpp.podspec' to ensure this is a -# valid spec before submitting. -# -# Any lines starting with a # are optional, but their use is encouraged -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# - -Pod::Spec.new do |s| - s.name = 'GoogleSignInCpp' - s.version = '0.1.0' - s.summary = 'Google Sign In C++ SDK for iOS' - - s.description = <<-DESC -Google Sign-In is a secure authentication system that reduces the burden of login for your users, by enabling them to sign in with their Google account—the same account they already use with Gmail, Play, Google+, and other Google services. -This C++ SDK wraps the iOS SDK, as well as the android SDK, providing a platform agnostic API. - DESC - - s.homepage = 'https://developers.google.com/identity/' - s.license = { :type => 'Apache', :file => 'LICENSE' } - s.authors = 'Google, Inc.' - - s.source = { :git => 'https://github.com/TBD/GoogleSignInCpp.git', :tag => s.version.to_s } - # s.social_media_url = 'https://twitter.com/' - - s.ios.deployment_target = '7.0' - - s.cocoapods_version = '>= 1.4.0.beta.2' - s.static_framework = true - s.prefix_header_file = false - - s.source_files = 'src/ios/*' - s.source_files = 'src/include/*' - s.requires_arc = 'src/ios/*' - s.public_header_files = 'src/include/*.h' - - s.ios.dependency 'GoogleSignIn', '~> 4.1' - - s.library = 'c++' -end \ No newline at end of file diff --git a/staging/native/LICENSE b/staging/native/LICENSE deleted file mode 100644 index 25e29461..00000000 --- a/staging/native/LICENSE +++ /dev/null @@ -1,215 +0,0 @@ -Copyright (C) 2017 Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/staging/native/README.md b/staging/native/README.md deleted file mode 100644 index 9fb32a97..00000000 --- a/staging/native/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# Google Sign-In C++ SDK -_Copyright (c) 2018 Google Inc. All rights reserved._ - - -## Overview - -This is the Google Sign-In C++ API, for Android and iOS. The intent is to unify -the iOS (Objective-C) and Android (Java) native interfaces into a single common -C++ interface that abstracts all of the platform specific details, however -currently only the Android implementation is supported. - -This is intended for projects that require OAuth ID tokens for server auth -codes. - -### Getting Started - -See -[Google Sign-In for Android](https://developers.google.com/identity/sign-in/android/start) -for information on getting started. - -### Dependencies - -On Android you'll need to add the dependency -`com.google.android.gms:play-services-auth`, based on the -[setup guide](https://developers.google.com/identity/sign-in/android/start-integrating). - - -## Configuring the application on the API Console - -To authenticate you need to create credentials on the -API console for your application. The steps to do this are available on -[Google Sign-In for Android](https://developers.google.com/identity/sign-in/android/start). -In order to access ID tokens or server auth codes, you also need to configure a -*web* client ID. From the -[Credentials Page on the API Console](https://console.developers.google.com/apis/credentials) -select the "Create credentials" dropdown, and choose OAuth Client ID. On the -next page choose Web Application, name the client whatever you like, and then -click "Create". - - -## How to build the sample - -First be sure to edit the sample source configuration: - -In testapp/src/common_main.cpp, replace "YOUR_WEB_CLIENT_ID_HERE" with your web -client id, from the configuration step above. - -### Building for Android - -The android build is setup using gradle. - -Navigate to the testapp directory, and build using the "build" target: - -cd testapp -./gradlew build diff --git a/staging/native/build.gradle b/staging/native/build.gradle deleted file mode 100644 index 97040265..00000000 --- a/staging/native/build.gradle +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (C) 2018 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -buildscript { - repositories { - jcenter() - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:2.3.3' - } -} - -allprojects { - repositories { - jcenter() - maven { - url "https://maven.google.com" - } - } -} - -apply plugin: 'com.android.library' - -group "com.google.signin" - -if (project.hasProperty("pluginVersion")) { - project.version = project.pluginVersion -} else { - project.version '1.0.0' -} - -project.ext.baseName = "google-signin-cpp" - -android { - compileSdkVersion 26 - buildToolsVersion "25.0.3" - defaultConfig { - minSdkVersion 14 - targetSdkVersion 26 - versionName project.version - archivesBaseName = project.ext.baseName - externalNativeBuild { - cmake { - targets 'google-signin-cpp' - cppFlags "-std=c++11", "-Wall" - } - } - ndk { - abiFilters 'x86', 'armeabi-v7a' - } - } - lintOptions { - abortOnError (project.hasProperty("lintAbortOnError") && - (project.lintAbortOnError == "" || - project.lintAbortOnError.toBoolean())) - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt') - } - } - externalNativeBuild { - cmake { - path "src/android/CMakeLists.txt" - } - } - sourceSets { - main { - java.srcDirs = ['src/android/java'] - manifest.srcFile 'src/android/AndroidManifest.xml' - } - } -} - -task copy_aar() { - description = "Copies the local java dependency as an aar to the packaging folder." - doLast { - copy { - from('build/outputs/aar') { - include '*.aar' - } - into 'google-signin-cpp/' - } - } -} - -project.afterEvaluate { - assembleRelease.doLast { - copy { - from('build/outputs/aar') { - include '*-release.aar' - } - into 'google-signin-cpp/' - } - } - assembleDebug.doLast { - copy { - from('build/outputs/aar') { - include '*-debug.aar' - } - into 'google-signin-cpp/' - } - } -} - -dependencies { - compile 'com.google.android.gms:play-services-auth:11.8.0' -} diff --git a/staging/native/gradle/wrapper/gradle-wrapper.jar b/staging/native/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e9ac3e27..00000000 Binary files a/staging/native/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/staging/native/gradle/wrapper/gradle-wrapper.properties b/staging/native/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 84de8b98..00000000 --- a/staging/native/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Fri Feb 23 19:03:43 PST 2018 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip diff --git a/staging/native/gradlew b/staging/native/gradlew deleted file mode 100755 index 4453ccea..00000000 --- a/staging/native/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save ( ) { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/staging/native/gradlew.bat b/staging/native/gradlew.bat deleted file mode 100644 index e95643d6..00000000 --- a/staging/native/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/staging/native/src/android/AndroidManifest.xml b/staging/native/src/android/AndroidManifest.xml deleted file mode 100644 index c714f9ee..00000000 --- a/staging/native/src/android/AndroidManifest.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - diff --git a/staging/native/src/android/CMakeLists.txt b/staging/native/src/android/CMakeLists.txt deleted file mode 100644 index aba96c85..00000000 --- a/staging/native/src/android/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2018 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# For more information about using CMake with Android Studio, read the -# documentation: https://d.android.com/studio/projects/add-native-code.html - -# Sets the minimum version of CMake required to build the native library. - -cmake_minimum_required(VERSION 3.4.1) - -include_directories( ../include ) - -# Creates and names a library, sets it as either STATIC -# or SHARED, and provides the relative paths to its source code. -# You can define multiple libraries, and CMake builds them for you. -# Gradle automatically packages shared libraries with your APK. - -add_library( # Sets the name of the library. - google-signin-cpp - - # Sets the library as a shared library. - STATIC - - # Provides a relative path to your source file(s). - google_signin.cc - google_signin_user.cc - jni.cc) - -set(PACKAGE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../google-signin-cpp) -MAKE_DIRECTORY("${PACKAGE_DIR}/include") -set_target_properties(google-signin-cpp - PROPERTIES - ARCHIVE_OUTPUT_DIRECTORY - "${PACKAGE_DIR}/lib/${ANDROID_ABI}") - -add_custom_command(TARGET google-signin-cpp POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E - copy "${CMAKE_CURRENT_SOURCE_DIR}/../include/*.h" - "${PACKAGE_DIR}/include" - COMMENT "Copying public headers to output package") \ No newline at end of file diff --git a/staging/native/src/android/google_signin.cc b/staging/native/src/android/google_signin.cc deleted file mode 100644 index f266d402..00000000 --- a/staging/native/src/android/google_signin.cc +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "google_signin.h" -#include -#include -#include "google_signin_user_impl.h" -#include "jni_context.h" - -#define TAG "native-googlesignin" -#define HELPER_CLASSNAME "com/google/googlesignin/GoogleSignInHelper" - -/* -public static void enableDebugLogging(boolean flag) - */ -#define ENABLE_DEBUG_METHOD_NAME "enableDebugLogging" -#define ENABLE_DEBUG_METHOD_SIG "(Z)V" - -/* -public static void configure(Activity parentActivity, - boolean useGamesConfig, - String webClientId, - boolean requestAuthCode, - boolean forceRefreshToken, - boolean requestEmail, - boolean requestIdToken, - boolean hideUiPopups, - String defaultAccountName, - String[] additionalScopes, - long requestHandle) -*/ -#define CONFIG_METHOD_NAME "configure" -#define CONFIG_METHOD_SIG \ - "(Landroid/app/Activity;" \ - "Z" \ - "Ljava/lang/String;" \ - "ZZZZZ" \ - "Ljava/lang/String;" \ - "[Ljava/lang/String;" \ - "J)V" - -/* -public static void nativeSignIn() - */ -#define DISCONNECT_METHOD_NAME "disconnect" -#define DISCONNECT_METHOD_SIG "(Landroid/app/Activity;)V" - -/* -public static void nativeSignIn() - */ -#define SIGNIN_METHOD_NAME "signIn" -#define SIGNIN_METHOD_SIG "(Landroid/app/Activity;J)V" - -/* -public static void nativeSignIn() - */ -#define SIGNINSILENTLY_METHOD_NAME "signInSilently" -#define SIGNINSILENTLY_METHOD_SIG "(Landroid/app/Activity;J)V" - -/* -public static void nativeSignOut() - */ -#define SIGNOUT_METHOD_NAME "signOut" -#define SIGNOUT_METHOD_SIG "(Landroid/app/Activity;)V" - -/* -public static void nativeOnResult(long requestHandle, int result, - GoogleSignInAccount acct), - */ -#define NATIVEONRESULT_METHOD_NAME "nativeOnResult" -#define NATIVEONRESULT_METHOD_SIG \ - "(J" \ - "I" \ - "Lcom/google/android/gms/auth/api/signin/GoogleSignInAccount;" \ - ")V" - -namespace google { -namespace signin { - -class GoogleSignInFuture; - -// The implementation of GoogleSignIn. This implements the JNI interface to -// call the Java helper class the handles the authentication flow within Java. -// For the public methods see google_signin.h for details. -class GoogleSignIn::GoogleSignInImpl { - public: - JNIContext jni_; - GoogleSignInFuture *current_result_; - Configuration *current_configuration_; - - // Constructs the implementation providing the Java activity to use when - // making calls. - GoogleSignInImpl(jobject activity, JavaVM *vm); - ~GoogleSignInImpl(); - - void Configure(const Configuration &configuration); - - void EnableDebugLogging(bool flag); - - // Starts the authentication process. - Future &SignIn(); - - Future &SignInSilently(); - - // Get the result of the last sign-in. - const Future *GetLastSignInResult(); - - // Signs out. - void SignOut(); - - void Disconnect(); - - // Native method implementation for the Java class. - static void NativeOnAuthResult(JNIContext &jni_context, jobject obj, - jlong handle, jint result, jobject user); - - private: - void CallConfigure(); - - static const JNINativeMethod methods[]; - - static jclass helper_clazz_; - static jmethodID enable_debug_method_; - static jmethodID config_method_; - static jmethodID disconnect_method_; - static jmethodID signin_method_; - static jmethodID signinsilently_method_; - static jmethodID signout_method_; -}; - -const JNINativeMethod GoogleSignIn::GoogleSignInImpl::methods[] = { - { - NATIVEONRESULT_METHOD_NAME, - NATIVEONRESULT_METHOD_SIG, - reinterpret_cast( - GoogleSignIn::GoogleSignInImpl::NativeOnAuthResult), - }, -}; - -jclass GoogleSignIn::GoogleSignInImpl::helper_clazz_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::enable_debug_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::config_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::disconnect_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::signin_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::signinsilently_method_ = 0; -jmethodID GoogleSignIn::GoogleSignInImpl::signout_method_ = 0; - -// Implementation of the SignIn future. -class GoogleSignInFuture : public Future { - virtual int Status() const { - return result_ ? result_->StatusCode - : GoogleSignIn::StatusCode::kStatusCodeUninitialized; - } - virtual GoogleSignIn::SignInResult *Result() const { return result_; } - virtual bool Pending() const { - return (!result_) || result_->StatusCode == - GoogleSignIn::StatusCode::kStatusCodeUninitialized; - } - - public: - GoogleSignInFuture() : result_(nullptr) {} - void SetResult(GoogleSignIn::SignInResult *result) { result_ = result; } - - private: - GoogleSignIn::SignInResult *result_; -}; - -// Constructs a new instance. The static members are initialized if need-be. -GoogleSignIn::GoogleSignInImpl::GoogleSignInImpl(jobject activity, JavaVM *vm) - : jni_(activity, vm), current_result_(nullptr), - current_configuration_(nullptr) { - JNIEnv *env = jni_.GetJniEnv(); - - if (!helper_clazz_) { - // Find the java helper class and initialize it. - helper_clazz_ = jni_.FindClass(HELPER_CLASSNAME); - - assert(helper_clazz_); - if (helper_clazz_) { - helper_clazz_ = (jclass)env->NewGlobalRef(helper_clazz_); - env->RegisterNatives(helper_clazz_, methods, - sizeof(methods) / sizeof(methods[0])); - enable_debug_method_ = env->GetStaticMethodID(helper_clazz_, ENABLE_DEBUG_METHOD_NAME, - ENABLE_DEBUG_METHOD_SIG); - config_method_ = env->GetStaticMethodID(helper_clazz_, CONFIG_METHOD_NAME, - CONFIG_METHOD_SIG); - disconnect_method_ = env->GetStaticMethodID( - helper_clazz_, DISCONNECT_METHOD_NAME, DISCONNECT_METHOD_SIG); - signin_method_ = env->GetStaticMethodID(helper_clazz_, SIGNIN_METHOD_NAME, - SIGNIN_METHOD_SIG); - signinsilently_method_ = env->GetStaticMethodID( - helper_clazz_, SIGNINSILENTLY_METHOD_NAME, SIGNINSILENTLY_METHOD_SIG); - signout_method_ = env->GetStaticMethodID( - helper_clazz_, SIGNOUT_METHOD_NAME, SIGNOUT_METHOD_SIG); - } - } -} - -GoogleSignIn::GoogleSignInImpl::~GoogleSignInImpl() { - delete current_result_; - current_result_ = nullptr; -} - -void GoogleSignIn::GoogleSignInImpl::EnableDebugLogging(bool flag) { - JNIEnv *env = jni_.GetJniEnv(); - - env->CallStaticVoidMethod(helper_clazz_, enable_debug_method_, flag); -} - -void GoogleSignIn::GoogleSignInImpl::Configure( - const Configuration &configuration) { - delete current_configuration_; - current_configuration_ = new Configuration(configuration); - - delete current_result_; - current_result_ = new GoogleSignInFuture(); - - CallConfigure(); -} - -void GoogleSignIn::GoogleSignInImpl::CallConfigure() { - JNIEnv *env = jni_.GetJniEnv(); - - if (!current_configuration_) { - __android_log_print(ANDROID_LOG_ERROR, TAG, "configuration is null!?"); - return; - } - jstring j_web_client_id = - current_configuration_->web_client_id.empty() ? nullptr - : env->NewStringUTF(current_configuration_->web_client_id.c_str()); - - jstring j_account_name = - current_configuration_->account_name.empty() ? nullptr - : env->NewStringUTF(current_configuration_->account_name.c_str()); - - jobjectArray j_auth_scopes = nullptr; - - if (current_configuration_->additional_scopes.size() > 0) { - jclass string_clazz = jni_.FindClass("java/lang/String"); - j_auth_scopes = env->NewObjectArray( - current_configuration_->additional_scopes.size(), string_clazz, nullptr); - - for (int i = 0; i < current_configuration_->additional_scopes.size(); i++) { - env->SetObjectArrayElement( - j_auth_scopes, i, - env->NewStringUTF(current_configuration_->additional_scopes[i].c_str())); - } - env->DeleteLocalRef(string_clazz); - } - - jobject j_activity = jni_.GetActivity(); - env->CallStaticVoidMethod( - helper_clazz_, config_method_, j_activity, - current_configuration_->use_game_signin, j_web_client_id, - current_configuration_->request_auth_code, - current_configuration_->force_token_refresh, - current_configuration_->request_email, - current_configuration_->request_id_token, - current_configuration_->hide_ui_popups, j_account_name, j_auth_scopes, - reinterpret_cast(current_result_)); - env->DeleteLocalRef(j_activity); - - if (j_web_client_id) { - env->DeleteLocalRef(j_web_client_id); - } - - if (j_account_name) { - env->DeleteLocalRef(j_account_name); - } - - if (j_auth_scopes) { - env->DeleteLocalRef(j_auth_scopes); - } -} - -Future &GoogleSignIn::GoogleSignInImpl::SignIn() { - JNIEnv *env = jni_.GetJniEnv(); - - if (current_result_) { - current_result_->SetResult(nullptr); - } - - CallConfigure(); - - jobject j_activity = jni_.GetActivity(); - env->CallStaticVoidMethod(helper_clazz_, signin_method_, j_activity, - (jlong)current_result_); - env->DeleteLocalRef(j_activity); - - return *current_result_; -} - -Future - &GoogleSignIn::GoogleSignInImpl::SignInSilently() { - JNIEnv *env = jni_.GetJniEnv(); - - if (current_result_) { - current_result_->SetResult(nullptr); - } - - CallConfigure(); - - jobject j_activity = jni_.GetActivity(); - env->CallStaticVoidMethod(helper_clazz_, signinsilently_method_, j_activity, - (jlong)current_result_); - env->DeleteLocalRef(j_activity); - - return *current_result_; -} - -// Get the result of the last sign-in. -const Future - *GoogleSignIn::GoogleSignInImpl::GetLastSignInResult() { - return current_result_; -} - -// Signs out. -void GoogleSignIn::GoogleSignInImpl::SignOut() { - JNIEnv *env = jni_.GetJniEnv(); - - jobject j_activity = jni_.GetActivity(); - __android_log_print(ANDROID_LOG_INFO, TAG, - "helper: %x method: %x activity: %x", - (uintptr_t)helper_clazz_, (uintptr_t)signin_method_, - (uintptr_t)j_activity); - - env->CallStaticVoidMethod(helper_clazz_, signout_method_, j_activity); - env->DeleteLocalRef(j_activity); -} - -// Signs out. -void GoogleSignIn::GoogleSignInImpl::Disconnect() { - JNIEnv *env = jni_.GetJniEnv(); - - jobject j_activity = jni_.GetActivity(); - env->CallStaticVoidMethod(helper_clazz_, disconnect_method_, j_activity); - env->DeleteLocalRef(j_activity); -} - -void GoogleSignIn::GoogleSignInImpl::NativeOnAuthResult(JNIContext &jni_context, - jobject obj, jlong handle, jint result, jobject user) { - GoogleSignInFuture *future = reinterpret_cast(handle); - if (future) { - SignInResult *rc = new GoogleSignIn::SignInResult(); - rc->StatusCode = result; - rc->User = GoogleSignInUserImpl::UserFromAccount(jni_context, user); - - if (rc->User) { - __android_log_print(ANDROID_LOG_INFO, TAG, "User Display Name is %s", - rc->User->GetDisplayName()); - } - future->SetResult(rc); - } -} - -// Public class implementation. These are called by external callers to use the -// Google Sign-in API. - -GoogleSignIn::GoogleSignIn(jobject activity, JavaVM *vm) - : impl_(new GoogleSignInImpl(activity, vm)) {} - -void GoogleSignIn::EnableDebugLogging(bool flag) { - impl_->EnableDebugLogging(flag); -} - -void GoogleSignIn::Configure(const Configuration &configuration) { - impl_->Configure(configuration); -} - -Future &GoogleSignIn::SignIn() { - return impl_->SignIn(); -} - -Future &GoogleSignIn::SignInSilently() { - return impl_->SignInSilently(); -} - -const Future *GoogleSignIn::GetLastSignInResult() { - return impl_->GetLastSignInResult(); -} - -void GoogleSignIn::SignOut() { impl_->SignOut(); } - -void GoogleSignIn::Disconnect() { impl_->Disconnect(); } - -} // namespace signin -} // namespace google diff --git a/staging/native/src/android/google_signin_user.cc b/staging/native/src/android/google_signin_user.cc deleted file mode 100644 index 198afda9..00000000 --- a/staging/native/src/android/google_signin_user.cc +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "google_signin_user.h" // NOLINT -#include - -#include "google_signin_user_impl.h" // NOLINT -#include "jni_context.h" // NOLINT - -#define GOOGLESIGNINACCOUNT_NAME \ - "com/google/android/gms/auth/api/signin/GoogleSignInAccount" - -// String getDisplayName() -#define GETDISPLAYNAME_METHOD_NAME "getDisplayName" -#define GETDISPLAYNAME_METHOD_SIG "()Ljava/lang/String;" - -// String getEmail() -#define GETEMAIL_METHOD_NAME "getEmail" -#define GETEMAIL_METHOD_SIG "()Ljava/lang/String;" - -// String getFamilyName() -#define GETFAMILYNAME_METHOD_NAME "getFamilyName" -#define GETFAMILYNAME_METHOD_SIG "()Ljava/lang/String;" - -// String getGivenName() -#define GETGIVENNAME_METHOD_NAME "getGivenName" -#define GETGIVENNAME_METHOD_SIG "()Ljava/lang/String;" - -// String getId() -#define GETID_METHOD_NAME "getId" -#define GETID_METHOD_SIG "()Ljava/lang/String;" - -// String getIdToken() -#define GETIDTOKEN_METHOD_NAME "getIdToken" -#define GETIDTOKEN_METHOD_SIG "()Ljava/lang/String;" - -// String getServerAuthCode() -#define GETSERVERAUTHCODE_METHOD_NAME "getServerAuthCode" -#define GETSERVERAUTHCODE_METHOD_SIG "()Ljava/lang/String;" - -// Uri getPhotoUrl() -#define GETPHOTOURL_METHOD_NAME "getPhotoUrl" -#define GETPHOTOURL_METHOD_SIG "()Landroid/net/Uri;" - -#define URI_NAME "android/net/Uri" -#define TOSTRING_METHOD_NAME "toString" -#define TOSTRING_METHOD_SIG "()Ljava/lang/String;" - -namespace google { -namespace signin { - -jmethodID GoogleSignInUserImpl::method_getDisplayName = 0; -jmethodID GoogleSignInUserImpl::method_getEmail = 0; -jmethodID GoogleSignInUserImpl::method_getFamilyName = 0; -jmethodID GoogleSignInUserImpl::method_getGivenName = 0; -jmethodID GoogleSignInUserImpl::method_getId = 0; -jmethodID GoogleSignInUserImpl::method_getIdToken = 0; -jmethodID GoogleSignInUserImpl::method_getPhotoUrl = 0; -jmethodID GoogleSignInUserImpl::method_getServerAuthCode = 0; -jmethodID GoogleSignInUserImpl::method_uri_toString = 0; - -void GoogleSignInUserImpl::Initialize(JNIContext &jni_context) { - JNIEnv* env = jni_context.GetJniEnv(); - - if (!method_getDisplayName) { - jclass google_acct_class = jni_context.FindClass(GOOGLESIGNINACCOUNT_NAME); - - method_getDisplayName = - env->GetMethodID(google_acct_class, GETDISPLAYNAME_METHOD_NAME, - GETDISPLAYNAME_METHOD_SIG); - - method_getEmail = env->GetMethodID(google_acct_class, GETEMAIL_METHOD_NAME, - GETEMAIL_METHOD_SIG); - - method_getFamilyName = env->GetMethodID( - google_acct_class, GETFAMILYNAME_METHOD_NAME, GETFAMILYNAME_METHOD_SIG); - - method_getGivenName = env->GetMethodID( - google_acct_class, GETGIVENNAME_METHOD_NAME, GETGIVENNAME_METHOD_SIG); - - method_getId = env->GetMethodID(google_acct_class, GETID_METHOD_NAME, - GETID_METHOD_SIG); - - method_getIdToken = env->GetMethodID( - google_acct_class, GETIDTOKEN_METHOD_NAME, GETIDTOKEN_METHOD_SIG); - - method_getPhotoUrl = env->GetMethodID( - google_acct_class, GETPHOTOURL_METHOD_NAME, GETPHOTOURL_METHOD_SIG); - - jclass uri_class = jni_context.FindClass(URI_NAME); - method_uri_toString = env->GetMethodID( - uri_class, TOSTRING_METHOD_NAME, TOSTRING_METHOD_SIG); - - method_getServerAuthCode = - env->GetMethodID(google_acct_class, GETSERVERAUTHCODE_METHOD_NAME, - GETSERVERAUTHCODE_METHOD_SIG); - } -} - -GoogleSignInUser::GoogleSignInUser() : impl_(new GoogleSignInUserImpl()) {} -GoogleSignInUser::~GoogleSignInUser() { delete impl_; } - -const char* GoogleSignInUser::GetDisplayName() const { - return impl_->display_name.c_str(); -} -const char* GoogleSignInUser::GetEmail() const { return impl_->email.c_str(); } -const char* GoogleSignInUser::GetFamilyName() const { - return impl_->family_name.c_str(); -} -const char* GoogleSignInUser::GetGivenName() const { - return impl_->given_name.c_str(); -} -const char* GoogleSignInUser::GetIdToken() const { - return impl_->id_token.c_str(); -} -const char* GoogleSignInUser::GetImageUrl() const { - return impl_->image_url.c_str(); -} -const char* GoogleSignInUser::GetServerAuthCode() const { - return impl_->server_auth_code.c_str(); -} -const char* GoogleSignInUser::GetUserId() const { - return impl_->user_id.c_str(); -} - -GoogleSignInUser* GoogleSignInUserImpl::UserFromAccount(JNIContext &jni_context, - jobject user_account) { - if (!user_account) { - return nullptr; - } - JNIEnv* env = jni_context.GetJniEnv(); - GoogleSignInUserImpl* user_impl = new GoogleSignInUserImpl(); - - if (!GoogleSignInUserImpl::method_getDisplayName) { - GoogleSignInUserImpl::Initialize(jni_context); - } - - jstring val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getDisplayName)); - user_impl->display_name = jni_context.JStringToString(val); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getEmail)); - user_impl->email = jni_context.JStringToString(val); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getFamilyName)); - user_impl->family_name = jni_context.JStringToString(val); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getGivenName)); - user_impl->given_name = jni_context.JStringToString(val); - - val = static_cast( - env->CallObjectMethod(user_account, GoogleSignInUserImpl::method_getId)); - user_impl->user_id = jni_context.JStringToString(val); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getIdToken)); - user_impl->id_token = jni_context.JStringToString(val); - - jobject uri = env->CallObjectMethod(user_account, - GoogleSignInUserImpl::method_getPhotoUrl); - if (uri) { - val = static_cast( - env->CallObjectMethod(uri, GoogleSignInUserImpl::method_uri_toString)); - } else { - val = nullptr; - } - user_impl->image_url = jni_context.JStringToString(val); - - val = static_cast(env->CallObjectMethod( - user_account, GoogleSignInUserImpl::method_getServerAuthCode)); - user_impl->server_auth_code = jni_context.JStringToString(val); - - return new GoogleSignInUser(user_impl); -} - -} // namespace signin -} // namespace google diff --git a/staging/native/src/android/google_signin_user_impl.h b/staging/native/src/android/google_signin_user_impl.h deleted file mode 100644 index 5eef60a7..00000000 --- a/staging/native/src/android/google_signin_user_impl.h +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_GOOGLE_SIGNIN_USER_IMPL_H -#define GOOGLESIGNIN_GOOGLE_SIGNIN_USER_IMPL_H - -#include -#include - -namespace google { -namespace signin { - -class JNIContext; - -class GoogleSignInUserImpl { - public: - std::string display_name; - std::string email; - std::string family_name; - std::string given_name; - std::string id_token; - std::string image_url; - std::string user_id; - std::string server_auth_code; - static jmethodID method_getDisplayName; - static jmethodID method_getEmail; - static jmethodID method_getFamilyName; - static jmethodID method_getGivenName; - static jmethodID method_getId; - static jmethodID method_getIdToken; - static jmethodID method_getPhotoUrl; - static jmethodID method_getServerAuthCode; - static jmethodID method_uri_toString; - - static void Initialize(JNIContext &jni_context); - static GoogleSignInUser *UserFromAccount(JNIContext &jni_context, - jobject user_account); -}; - -} // namespace signin -} // namespace google -#endif // GOOGLESIGNIN_GOOGLE_SIGNIN_USER_IMPL_H diff --git a/staging/native/src/android/java/com/google/googlesignin/GoogleSignInFragment.java b/staging/native/src/android/java/com/google/googlesignin/GoogleSignInFragment.java deleted file mode 100644 index 9356426a..00000000 --- a/staging/native/src/android/java/com/google/googlesignin/GoogleSignInFragment.java +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright 2018 Google Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import android.app.Activity; -import android.app.Fragment; -import android.app.FragmentTransaction; -import android.content.Intent; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.View; -import com.google.android.gms.auth.api.Auth; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.auth.api.signin.GoogleSignInOptions; -import com.google.android.gms.auth.api.signin.GoogleSignInOptionsExtension; -import com.google.android.gms.auth.api.signin.GoogleSignInResult; -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.Api; -import com.google.android.gms.common.api.CommonStatusCodes; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.common.api.ResultCallback; -import com.google.android.gms.common.api.Scope; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Locale; - -/** - * Activity fragment with no UI added to the parent activity in order to manage the accessing of the - * player's email address and tokens. - */ -public class GoogleSignInFragment extends Fragment implements - GoogleApiClient.ConnectionCallbacks, - GoogleApiClient.OnConnectionFailedListener { - - // Tag uniquely identifying this fragment. - public static final String FRAGMENT_TAG = "signin.SignInFragment"; - private static final int RC_SIGNIN = 9009; - - /** - * Handle the Google API Client connection being connected. - * - * @param connectionHint - is not used. - */ - @Override - public void onConnected(@Nullable Bundle connectionHint) { - GoogleSignInHelper.logDebug("onConnected!"); - if (mGoogleApiClient.hasConnectedApi(Auth.GOOGLE_SIGN_IN_API)) { - GoogleSignInHelper.logDebug("has connected auth!"); - Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient) - .setResultCallback( - new ResultCallback() { - @Override - public void onResult(@NonNull GoogleSignInResult googleSignInResult) { - if (googleSignInResult.isSuccess()) { - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } else { - GoogleSignInHelper.logError( - "Error with " + "silentSignIn: " + googleSignInResult.getStatus()); - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } - } - }); - } else { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGNIN); - } - } - - @Override - public void onConnectionSuspended(int cause) { - GoogleSignInHelper.logDebug("onConnectionSuspended() called: " + cause); - } - - - @Override - public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { - // Handle errors during connection, such as Play Store not installed. - GoogleSignInHelper.logError("Connection failed: " + - connectionResult.getErrorCode()); - // if there is a resolution, just start the sign-in intent, which handles - // the resolution logic. - if (connectionResult.hasResolution()) { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGNIN); - } else { - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - connectionResult.getErrorCode(), - null); - } - } - - public void disconnect() { - - if (mGoogleApiClient != null) { - mGoogleApiClient.disconnect(); - } - } - - /** - * The state of the fragment. It can only handle one sign-in request at a time, so we use these - * values to keep track of the request lifecycle. - */ - private enum State { - NEW, - READY, - PENDING, - PENDING_SILENT, - BUSY - } - - private State state; - - /** - * The request to sign-in. This contains the configuration for the API client/Sign-in options and - * the callback information used to communicate the result. - */ - private TokenRequest request = null; - - private GoogleApiClient mGoogleApiClient; - - // TODO: make config async. - private static GoogleSignInFragment theFragment; - - /** - * Gets the instance of the fragment. - * - * @param parentActivity - the activity to attach the fragment to. - * @return the instance. - */ - public static GoogleSignInFragment getInstance(Activity parentActivity) { - GoogleSignInFragment fragment = - (GoogleSignInFragment) parentActivity.getFragmentManager().findFragmentByTag(FRAGMENT_TAG); - - fragment = (fragment != null) ? fragment : theFragment; - if (fragment == null) { - GoogleSignInHelper.logDebug("Creating fragment"); - fragment = new GoogleSignInFragment(); - FragmentTransaction trans = parentActivity.getFragmentManager().beginTransaction(); - trans.add(fragment, FRAGMENT_TAG); - trans.commitAllowingStateLoss(); - theFragment = fragment; - } - return fragment; - } - - public synchronized boolean submitRequest(TokenRequest request) { - if (this.request == null || this.state == State.READY) { - this.request = request; - return true; - } - GoogleSignInHelper.logError(String.format(Locale.getDefault(), - "Existing request: %s ignoring %s. State = %s", this.request, request, this.state)); - return false; - } - - private synchronized State getState() { - return state; - } - - private synchronized void setState(State state) { - this.state = state; - } - - /** - * Signs out and disconnects the client. NOTE: if you are using the Games API, you **MUST** call - * Games.signout() before this method. Failure to do so will result in not being able to access - * Games API until the application is restarted. - */ - public void signOut() { - clearRequest(true); - if (mGoogleApiClient != null) { - Auth.GoogleSignInApi.signOut(mGoogleApiClient); - } - } - - /** - * Starts the sign-in process using the Sign-in UI, if any UI is needed. This is in contrast to - * startSignInSilently, which does not use any UI. - * - * @return true if the sign-in flow was started. - */ - public boolean startSignIn() { - if (request == null) { - GoogleSignInHelper.logError("Request not configured! Failing authenticate"); - return false; - } - if (getState() == State.BUSY) { - GoogleSignInHelper.logError("There is already a pending callback" + " configured."); - } else if (getState() == State.READY) { - processRequest(false); - } else { - processWhenReady(false); - } - return true; - } - - /** - * Starts the sign-in silently flow. - * - * @return true if the flow was started successfully. - */ - public boolean startSignInSilently() { - if (request == null) { - GoogleSignInHelper.logError("Request not configured! Failing authenticate"); - return false; - } - if (getState() == State.BUSY) { - GoogleSignInHelper.logError("There is already a pending callback" + " configured."); - } else if (getState() == State.READY) { - processRequest(true); - } else { - processWhenReady(true); - } - return true; - } - - /** - * Indicates that the token request has been set and it is ready to be processed. The processing - * can start once the fragment is attached to the activity and initialized. - * - * @param silent - true if the sign-in should be silent. - */ - private void processWhenReady(boolean silent) { - GoogleSignInHelper.logInfo("Fragment not initialized yet, " + "waiting to authenticate"); - setState(silent ? State.PENDING_SILENT : State.PENDING); - } - - /** - * Processes the token requests that are queued up. First checking that the google api client is - * connected. - */ - private void processRequest(final boolean silent) { - try { - if (request != null) { - setState(State.BUSY); - } else { - GoogleSignInHelper.logInfo("No pending configuration, returning"); - return; - } - - request - .getPendingResponse() - .setResultCallback( - new ResultCallback() { - @Override - public void onResult(@NonNull TokenResult tokenResult) { - GoogleSignInHelper.logDebug( - String.format( - Locale.getDefault(), - "Calling nativeOnResult: handle: %s, status: %d acct: %s", - tokenResult.getHandle(), - tokenResult.getStatus().getStatusCode(), - tokenResult.getAccount())); - GoogleSignInHelper.nativeOnResult( - tokenResult.getHandle(), - tokenResult.getStatus().getStatusCode(), - tokenResult.getAccount()); - clearRequest(false); - } - }); - - // Build the GoogleAPIClient - buildClient(request); - - GoogleSignInHelper.logDebug( - " Has connected == " + mGoogleApiClient.hasConnectedApi(Auth.GOOGLE_SIGN_IN_API)); - if (!mGoogleApiClient.hasConnectedApi(Auth.GOOGLE_SIGN_IN_API)) { - - if (!silent) { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGNIN); - } else { - Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient) - .setResultCallback( - new ResultCallback() { - @Override - public void onResult(@NonNull GoogleSignInResult googleSignInResult) { - if (googleSignInResult.isSuccess()) { - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } else { - GoogleSignInHelper.logError( - "Error with " + "silentSignIn: " + googleSignInResult.getStatus()); - GoogleSignInHelper.nativeOnResult( - request.getHandle(), - googleSignInResult.getStatus().getStatusCode(), - googleSignInResult.getSignInAccount()); - setState(State.READY); - } - } - }); - } - } - } catch (Throwable throwable) { - GoogleSignInHelper.logError("Exception caught! " + throwable.getMessage()); - request.setResult(CommonStatusCodes.INTERNAL_ERROR, null); - return; - } - - GoogleSignInHelper.logDebug("Done with processRequest!"); - } - - /** - * Builds the Google API Client based on the configuration in the request. - * - * @param request - the request for a token. - */ - private void buildClient(TokenRequest request) { - GoogleSignInOptions.Builder builder; - - if (request.getUseGamesConfig()) { - GoogleSignInHelper.logDebug("Using DEFAULT_GAMES_SIGN_IN"); - builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); - } else { - GoogleSignInHelper.logDebug("Using DEFAULT_SIGN_IN"); - builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN); - } - - if (request.getDoAuthCode()) { - if (!request.getWebClientId().isEmpty()) { - GoogleSignInHelper.logDebug( - "Requesting AuthCode force = " - + request.getForceRefresh() - + "client: " - + request.getWebClientId()); - builder.requestServerAuthCode(request.getWebClientId(), request.getForceRefresh()); - } else { - GoogleSignInHelper.logError("Web client ID is needed for Auth Code"); - request.setResult(CommonStatusCodes.DEVELOPER_ERROR, null); - throw new IllegalStateException("Web client ID is needed for Auth Code"); - } - } - - if (request.getDoEmail()) { - GoogleSignInHelper.logDebug("Requesting email"); - builder.requestEmail(); - } - - if (request.getDoIdToken()) { - if (!request.getWebClientId().isEmpty()) { - GoogleSignInHelper.logDebug("Requesting IDToken client: " + request.getWebClientId()); - - builder.requestIdToken(request.getWebClientId()); - } else { - GoogleSignInHelper.logError("Web client ID is needed for ID Token"); - request.setResult(CommonStatusCodes.DEVELOPER_ERROR, null); - throw new IllegalStateException("Web client ID is needed for Auth Code"); - } - } - if (request.getScopes() != null) { - for (String s : request.getScopes()) { - GoogleSignInHelper.logDebug("Adding scope: " + s); - - builder.requestScopes(new Scope(s)); - } - } - - if (request.getHidePopups() && request.getUseGamesConfig()) { - GoogleSignInHelper.logDebug("hiding popup views for games API"); - // Use reflection to build the extension, so we don't force - // a dependency on Games. - - builder.addExtension(getGamesExtension()); - } - - if (request.getAccountName() != null) { - GoogleSignInHelper.logDebug("Setting accountName: " + request.getAccountName()); - - builder.setAccountName(request.getAccountName()); - } - - GoogleSignInOptions options = builder.build(); - - GoogleApiClient.Builder clientBuilder = - new GoogleApiClient.Builder(getActivity()).addApi(Auth.GOOGLE_SIGN_IN_API, options); - if (request.getUseGamesConfig()) { - GoogleSignInHelper.logDebug("Adding games API"); - - try { - clientBuilder.addApi(getGamesAPI()); - } catch (Exception e) { - GoogleSignInHelper.logError("Exception getting Games API: " + e.getMessage()); - request.setResult(CommonStatusCodes.DEVELOPER_ERROR, null); - return; - } - } - if (request.getHidePopups()) { - View invisible = new View(getContext()); - invisible.setVisibility(View.INVISIBLE); - invisible.setClickable(false); - clientBuilder.setViewForPopups(invisible); - } - mGoogleApiClient = clientBuilder.build(); - mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL); - } - - private Api getGamesAPI() { - try { - Class gamesClass = Class.forName("com" + ".google.android.gms.games.Games"); - Field apiField = gamesClass.getField("API"); - return (Api) apiField.get(null); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Games API requested, but " + "can't load Games class", e); - } catch (NoSuchFieldException e) { - throw new IllegalArgumentException( - "Games API requested, but " + "can't load Games API field", e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException( - "Games API requested, but " + "can't load Games API field", e); - } - } - - /** - * Builds the games extension to hide popups using Reflection. This avoids the hard dependency on - * Games. - * - * @return the extension, or throws InvalidArgumentException if games is requested, but not found. - */ - private GoogleSignInOptionsExtension getGamesExtension() { - try { - Class gamesClass = Class.forName("com" + ".google.android.gms.games.Games$GamesOptions"); - - Method builderMethod = gamesClass.getMethod("builder()"); - - Object builder = builderMethod.invoke(null); - - Method setter = builder.getClass().getMethod("setShowConnectingPopup", boolean.class); - - setter.invoke(builder, false); - - Method buildMethod = builder.getClass().getMethod("build"); - return (GoogleSignInOptionsExtension) builderMethod.invoke(builder); - - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't load Games$GamesOptions class", e); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't find builder() static method.", e); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't invoke builder() static method.", e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException( - "Games API requested, but" + "can't invoke builder() static method.", e); - } - } - - @Override - public void onStart() { - super.onStart(); - - // This just connects the client. If there is no user signed in, you - // still need to call Auth.GoogleSignInApi.getSignInIntent() to start - // the sign-in process. - if (mGoogleApiClient != null) { - mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL); - } - } - - /** - * Called when the fragment is visible to the user and actively running. This is generally tied to - * {@link Activity#onResume() Activity.onResume} of the containing Activity's lifecycle. - */ - @Override - public void onResume() { - GoogleSignInHelper.logDebug("onResume called"); - if (theFragment != this) { - theFragment = this; - } - super.onResume(); - if (getState() == State.PENDING) { - GoogleSignInHelper.logDebug("State is pending, calling processRequest(false)"); - processRequest(false); - } else if (getState() == State.PENDING_SILENT) { - GoogleSignInHelper.logDebug("State is pending_silent, calling processRequest(true)"); - processRequest(true); - } else { - GoogleSignInHelper.logDebug("State is now ready"); - setState(State.READY); - } - } - - /** - * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. This - * follows the related Activity API as described there in {@link Activity#onActivityResult(int, - * int, Intent)}. - * - * @param requestCode The integer request code originally supplied to startActivityForResult(), - * allowing you to identify who this result came from. - * @param resultCode The integer result code returned by the child activity through its - * setResult(). - * @param data An Intent, which can return result data to the caller - */ - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - GoogleSignInHelper.logDebug("onActivityResult: " + requestCode + " " + resultCode); - if (requestCode == RC_SIGNIN) { - GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); - TokenRequest request = this.request; - if (request != null) { - GoogleSignInAccount acct = result.getSignInAccount(); - request.setResult(result.getStatus().getStatusCode(), acct); - } else { - GoogleSignInHelper.logError("Pending request is null, can't " + "return result!"); - } - return; - } - super.onActivityResult(requestCode, resultCode, data); - } - - private synchronized void clearRequest(boolean cancel) { - if (cancel && request != null) { - // Cancel request. - request.cancel(); - } - request = null; - setState(getActivity() != null ? State.READY : State.NEW); - } -} diff --git a/staging/native/src/android/java/com/google/googlesignin/GoogleSignInHelper.java b/staging/native/src/android/java/com/google/googlesignin/GoogleSignInHelper.java deleted file mode 100644 index a1cdafab..00000000 --- a/staging/native/src/android/java/com/google/googlesignin/GoogleSignInHelper.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2018 Google Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import android.app.Activity; -import android.util.Log; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.CommonStatusCodes; - -/** - * Helper class used by the native C++ code to interact with Google Sign-in API. The general flow is - * Call configure, then one of signIn or signInSilently. - */ -public class GoogleSignInHelper { - - // Set to true to get more debug logging. - public static boolean loggingEnabled = false; - private static final String TAG = "SignInFragment"; - - /** - * Enables verbose logging - */ - public static void enableDebugLogging(boolean flag) { - loggingEnabled = flag; - } - - /** - * Sets the configuration of the sign-in api that should be used. - * - * @param parentActivity - the parent activity. This API creates a fragment that is attached to - * this activity. - * @param useGamesConfig - true if the GAMES_CONFIG should be used when signing-in. - * @param webClientId - the web client id of the backend server associated with this application. - * @param requestAuthCode - true if a server auth code is needed. This also requires the web - * client id to be set. - * @param forceRefreshToken - true to force a refresh token when using the server auth code. - * @param requestEmail - true if email address of the user is requested. - * @param requestIdToken - true if an id token for the user is requested. - * @param hideUiPopups - true if the popups during sign-in from the Games API should be hidden. - * This only has affect if useGamesConfig is true. - * @param defaultAccountName - the account name to attempt to default to when signing in. - * @param additionalScopes - additional API scopes to request when authenticating. - * @param requestHandle - the handle to this request, created by the native C++ code, this is used - * to correlate the response with the request. - */ - public static void configure( - Activity parentActivity, - boolean useGamesConfig, - String webClientId, - boolean requestAuthCode, - boolean forceRefreshToken, - boolean requestEmail, - boolean requestIdToken, - boolean hideUiPopups, - String defaultAccountName, - String[] additionalScopes, - long requestHandle) { - logDebug("TokenFragment.configure called"); - TokenRequest request = - new TokenRequest( - useGamesConfig, - webClientId, - requestAuthCode, - forceRefreshToken, - requestEmail, - requestIdToken, - hideUiPopups, - defaultAccountName, - additionalScopes, - requestHandle); - - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(parentActivity); - - if (request.isValid()) { - if (!fragment.submitRequest(request)) { - logError("There is already a pending" + " authentication token request!"); - } - } else { - nativeOnResult(requestHandle, CommonStatusCodes.DEVELOPER_ERROR, null); - } - } - - public static void signIn(Activity activity, long requestHandle) { - logDebug("AuthHelperFragment.authenticate called!"); - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - - if (!fragment.startSignIn()) { - nativeOnResult(requestHandle, CommonStatusCodes.DEVELOPER_ERROR, null); - } - } - - public static void signInSilently(Activity activity, long requestHandle) { - logDebug("AuthHelperFragment.signinSilently called!"); - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - - if (!fragment.startSignInSilently()) { - nativeOnResult(requestHandle, CommonStatusCodes.DEVELOPER_ERROR, null); - } - } - - public static void signOut(Activity activity) { - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - fragment.signOut(); - } - - public static void disconnect(Activity activity) { - GoogleSignInFragment fragment = GoogleSignInFragment.getInstance(activity); - fragment.disconnect(); - } - - public static void logInfo(String msg) { - if (loggingEnabled) { - Log.i(TAG, msg); - } - } - - public static void logError(String msg) { - Log.e(TAG, msg); - } - - public static void logDebug(String msg) { - if (loggingEnabled) { - Log.d(TAG, msg); - } - } - - /** - * Native callback for the authentication result. - * - * @param handle Identifies the request. - * @param result Authentication result. - * @param acct The account that is signed in, if successful. - */ - public static native void nativeOnResult(long handle, int result, GoogleSignInAccount acct); -} diff --git a/staging/native/src/android/java/com/google/googlesignin/TokenPendingResult.java b/staging/native/src/android/java/com/google/googlesignin/TokenPendingResult.java deleted file mode 100644 index 5d305aba..00000000 --- a/staging/native/src/android/java/com/google/googlesignin/TokenPendingResult.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2018 Google Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import android.util.Log; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.CommonStatusCodes; -import com.google.android.gms.common.api.PendingResult; -import com.google.android.gms.common.api.ResultCallback; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Pending result class for TokenResult. This allows the pending result to be returned to the - * caller, and then updated when available, simplifying the handling of callbacks. - */ -public class TokenPendingResult extends PendingResult { - - private static final String TAG = "TokenPendingResult"; - private final long requestHandle; - - private CountDownLatch latch = new CountDownLatch(1); - private TokenResult result; - private ResultCallback resultCallback; - - public TokenPendingResult(long requestHandle) { - this.requestHandle = requestHandle; - result = new TokenResult(); - result.setHandle(requestHandle); - } - - @Override - public TokenResult await() { - - try { - latch.await(); - } catch (InterruptedException e) { - setResult(null, CommonStatusCodes.INTERRUPTED); - } - - return getResult(); - } - - @Override - public TokenResult await(long l, TimeUnit timeUnit) { - try { - if (!latch.await(l, timeUnit)) { - setResult(null, CommonStatusCodes.TIMEOUT); - } - } catch (InterruptedException e) { - setResult(null, CommonStatusCodes.INTERRUPTED); - } - return getResult(); - } - - @Override - public void cancel() { - setResult(null, CommonStatusCodes.CANCELED); - latch.countDown(); - } - - @Override - public boolean isCanceled() { - return getResult() != null && getResult().getStatus().isCanceled(); - } - - @Override - public void setResultCallback(ResultCallback resultCallback) { - - // Handle adding the callback when the latch has already counted down. This - // can happen if there is an error right away. - if (latch.getCount() == 0) { - resultCallback.onResult(getResult()); - } else { - setCallback(resultCallback); - } - } - - @Override - public void setResultCallback( - ResultCallback resultCallback, long l, TimeUnit timeUnit) { - try { - if (!latch.await(l, timeUnit)) { - setResult(null, CommonStatusCodes.TIMEOUT); - } - } catch (InterruptedException e) { - setResult(null, CommonStatusCodes.INTERRUPTED); - } - - resultCallback.onResult(getResult()); - } - - private synchronized void setCallback(ResultCallback callback) { - this.resultCallback = callback; - } - - private synchronized ResultCallback getCallback() { - return this.resultCallback; - } - - /** - * Set the result. If any of the values are null, and a previous non-null value was set, the - * non-null value is retained. - * - * @param account - the signin account, if any. - * @param resultCode - the result code. - */ - public synchronized void setResult(GoogleSignInAccount account, int resultCode) { - result = new TokenResult(account, resultCode); - result.setHandle(requestHandle); - } - - private synchronized TokenResult getResult() { - return result; - } - - /** - * Sets the result status and releases the latch and/or calls the callback. - * - * @param status - the result status. - */ - public void setStatus(int status) { - result.setStatus(status); - latch.countDown(); - ResultCallback cb = getCallback(); - TokenResult res = getResult(); - if (cb != null) { - Log.d(TAG, " Calling onResult for callback. result: " + res); - getCallback().onResult(res); - } - } -} diff --git a/staging/native/src/android/java/com/google/googlesignin/TokenRequest.java b/staging/native/src/android/java/com/google/googlesignin/TokenRequest.java deleted file mode 100644 index e987d8ec..00000000 --- a/staging/native/src/android/java/com/google/googlesignin/TokenRequest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2018 Google Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.PendingResult; -import java.util.Locale; - -/** Helper class containing the request for information. */ -public class TokenRequest { - private TokenPendingResult pendingResponse; - private boolean useGamesConfig; - private boolean doAuthCode; - private boolean doEmail; - private boolean doIdToken; - private String webClientId; - private boolean forceRefresh; - private boolean hidePopups; - private String accountName; - private String[] scopes; - private long handle; - - /** - * Constructs a token request. - * - * @param useGamesConfig - true if the GAMES_CONFIG should be used when signing-in. - * @param webClientId - the web client id of the backend server associated with this application. - * @param requestAuthCode - true if a server auth code is needed. This also requires the web - * client id to be set. - * @param forceRefreshToken - true to force a refresh token when using the server auth code. - * @param requestEmail - true if email address of the user is requested. - * @param requestIdToken - true if an id token for the user is requested. - * @param hideUiPopups - true if the popups during sign-in from the Games API should be hidden. - * This only has affect if useGamesConfig is true. - * @param defaultAccountName - the account name to attempt to default to when signing in. - * @param additionalScopes - additional API scopes to request when authenticating. - * @param requestHandle - the handle to this request, created by the native C++ code, this is used - * to correlate the response with the request. - */ - public TokenRequest( - boolean useGamesConfig, - String webClientId, - boolean requestAuthCode, - boolean forceRefreshToken, - boolean requestEmail, - boolean requestIdToken, - boolean hideUiPopups, - String defaultAccountName, - String[] additionalScopes, - long requestHandle) { - pendingResponse = new TokenPendingResult(requestHandle); - this.useGamesConfig = useGamesConfig; - this.webClientId = webClientId; - this.doAuthCode = requestAuthCode; - this.forceRefresh = forceRefreshToken; - this.doEmail = requestEmail; - this.doIdToken = requestIdToken; - this.hidePopups = hideUiPopups; - this.accountName = defaultAccountName; - this.handle = requestHandle; - if (additionalScopes != null && additionalScopes.length > 0) { - scopes = new String[additionalScopes.length]; - System.arraycopy(additionalScopes, 0, scopes, 0, additionalScopes.length); - } else { - scopes = null; - } - } - - /** - * Returns the pending response object for this request. - * - * @return the pending response. - */ - public PendingResult getPendingResponse() { - return pendingResponse; - } - - /** - * Sets the result of the reuquest. - * - * @param code - the status code of the request. - * @param account - the GoogleSignInAccount if successful. - */ - public void setResult(int code, GoogleSignInAccount account) { - pendingResponse.setResult(account, code); - pendingResponse.setStatus(code); - } - - /** Cancels the request and notifies the pending response. */ - public void cancel() { - pendingResponse.cancel(); - } - - @Override - public String toString() { - return String.format( - Locale.getDefault(), - "%s(a:%b:e:%b:i:%b)", - Integer.toHexString(hashCode()), - doAuthCode, - doEmail, - doIdToken); - } - - public String getWebClientId() { - return webClientId == null ? "" : webClientId; - } - - public boolean getForceRefresh() { - return forceRefresh; - } - - public boolean isValid() { - if (webClientId == null || webClientId.isEmpty()) { - if (doAuthCode) { - GoogleSignInHelper.logError( - "Invalid configuration, auth code" + " requires web " + "client id"); - return false; - } else if (doIdToken) { - GoogleSignInHelper.logError("Invalid configuration, id token requires web " + "client id"); - return false; - } - } - return true; - } - - public long getHandle() { - return handle; - } - - public boolean getUseGamesConfig() { - return useGamesConfig; - } - - public boolean getDoAuthCode() { - return doAuthCode; - } - - public boolean getDoEmail() { - return doEmail; - } - - public boolean getDoIdToken() { - return doIdToken; - } - - public String[] getScopes() { - return scopes; - } - - public String getAccountName() { - return accountName; - } - - public boolean getHidePopups() { - return hidePopups; - } -} diff --git a/staging/native/src/android/java/com/google/googlesignin/TokenResult.java b/staging/native/src/android/java/com/google/googlesignin/TokenResult.java deleted file mode 100644 index 80e36c5a..00000000 --- a/staging/native/src/android/java/com/google/googlesignin/TokenResult.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2018 Google Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.googlesignin; - -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.common.api.CommonStatusCodes; -import com.google.android.gms.common.api.Result; -import com.google.android.gms.common.api.Status; -import java.util.Locale; - -/** Class for returning the tokens to a native caller. */ -public class TokenResult implements Result { - private Status status; - private GoogleSignInAccount account; - private long handle; - - TokenResult() { - status = new Status(CommonStatusCodes.SIGN_IN_REQUIRED); - account = null; - } - - TokenResult(GoogleSignInAccount account, int resultCode) { - status = new Status(resultCode); - this.account = account; - } - - @Override - public String toString() { - return String.format( - Locale.getDefault(), "Status: %s %s", status, (account == null) ? "" : account); - } - - @Override - public Status getStatus() { - return status; - } - - public GoogleSignInAccount getAccount() { - return account; - } - - public void setStatus(int status) { - this.status = new Status(status); - } - - public long getHandle() { - return handle; - } - - public void setHandle(long handle) { - this.handle = handle; - } -} diff --git a/staging/native/src/android/jni.cc b/staging/native/src/android/jni.cc deleted file mode 100644 index 37334671..00000000 --- a/staging/native/src/android/jni.cc +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// This file isolates some of the JNI boilerplate for managing the JNI -// environment, dealing with class loaders and keeping track of threads that -// have been bound to the JavaVM. - -#include -#include -#include -#include "jni_context.h" - -namespace google { -namespace signin { - -JavaVM* JNIContext::vm_ = nullptr; -static pthread_key_t jni_env_key; -static pthread_once_t pthread_key_initialized = PTHREAD_ONCE_INIT; - -// This will be called by any thread that's attached to the JVM when it exits. -extern "C" { -static void DetachJVMThreads(void* stored_java_vm) { - assert(stored_java_vm); - JavaVM* java_vm = static_cast(stored_java_vm); - - // AttachCurrentThread does nothing if we're already attached, but - // calling it ensures that the DetachCurrentThread doesn't fail. - JNIEnv* jni_env; - java_vm->AttachCurrentThread(&jni_env, nullptr); - java_vm->DetachCurrentThread(); -} - -// Called the first time GetJNIEnv is invoked. -// Ensures that jni_env_key is created and that the destructor is in place. -static void SetupJvmThreadStorage() { - // Set up the thread destructor when the JavaVM is first known. - // This creates a key for a thread local value. The destructor is then - // called for any thread (when it exits), which has assigned a value - // to this key, using setspecific. - pthread_key_create(&jni_env_key, DetachJVMThreads); -} -} - -JNIContext::JNIContext(jobject activity, JavaVM *vm) { - vm_ = vm; - (void)pthread_once(&pthread_key_initialized, - SetupJvmThreadStorage); - - JNIEnv* env = GetJniEnv(); - activity_ = env->NewGlobalRef(activity); -} - -JNIContext::~JNIContext() { - JNIEnv* env = GetJniEnv(); - env->DeleteGlobalRef(activity_); - activity_ = nullptr; - - // we don't clear the vm_ in case there are multiple contexts. -} - -// This could be static, but it should never be called before at least one -// instance is constructed. -JNIEnv* JNIContext::GetJniEnv() { - assert(vm_); - // This call allows us to set a thread-local value. Even though there will - // only ever be one JavaVM, and every thread will store the same value, - // this ensures any thread attaching to the JVM will call the thread - // destructor to detach before exiting. - pthread_setspecific(jni_env_key, vm_); - JNIEnv* env; - jint result = vm_->AttachCurrentThread(&env, nullptr); - return result == JNI_OK ? env : nullptr; -} - -// Returns a local reference to the activity used to construct this class. -// The user is expected to call DeleteLocalRef to avoid leaking. -jobject JNIContext::GetActivity() { - assert(activity_); - JNIEnv* env = GetJniEnv(); - return env->NewLocalRef(activity_); -} - -// Find a class, attempting to load the class if it's not found. -jclass JNIContext::FindClass(const char *class_name) { - JNIEnv *env = GetJniEnv(); - jclass class_object = env->FindClass(class_name); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - // If the class isn't found it's possible NativeActivity is being used by - // the application which means the class path is set to only load system - // classes. The following falls back to loading the class using the - // Activity before retrieving a reference to it. - - jclass activity_class = env->FindClass("android/app/Activity"); - jmethodID activity_get_class_loader = env->GetMethodID( - activity_class, "getClassLoader", "()Ljava/lang/ClassLoader;"); - - jobject activity_instance = GetActivity(); - jobject class_loader_object = - env->CallObjectMethod(activity_instance, activity_get_class_loader); - - jclass class_loader_class = env->FindClass("java/lang/ClassLoader"); - jmethodID class_loader_load_class = - env->GetMethodID(class_loader_class, "loadClass", - "(Ljava/lang/String;)Ljava/lang/Class;"); - jstring class_name_object = env->NewStringUTF(class_name); - - class_object = static_cast(env->CallObjectMethod( - class_loader_object, class_loader_load_class, class_name_object)); - - if (env->ExceptionCheck()) { - env->ExceptionClear(); - class_object = nullptr; - } - env->DeleteLocalRef(activity_instance); - env->DeleteLocalRef(class_name_object); - env->DeleteLocalRef(class_loader_object); - } - return class_object; -} - -std::string JNIContext::JStringAsString(jstring j_str) { - if (!j_str) { - return ""; - } - JNIEnv* env = GetJniEnv(); - const char* buf = env->GetStringUTFChars(j_str, nullptr); - std::string return_string(buf); - env->ReleaseStringUTFChars(j_str, buf); - return return_string; -} - -std::string JNIContext::JStringToString(jstring j_str) { - JNIEnv* env = GetJniEnv(); - std::string return_string = JStringAsString(j_str); - env->DeleteLocalRef(j_str); - return return_string; -} - -} // namespace signin -} // namespace google diff --git a/staging/native/src/android/jni_context.h b/staging/native/src/android/jni_context.h deleted file mode 100644 index 8ce6d6c6..00000000 --- a/staging/native/src/android/jni_context.h +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_JNI_INIT_H -#define GOOGLESIGNIN_JNI_INIT_H - -// All methods in this header are meant for Android only. - -#include -#include -#include - -namespace google { -namespace signin { - -// This stores the JavaVM, assuming there's only ever one, and a global -// reference to an Activity. You can instantiate this for each activity, though -// any activity will work for all cases as it's just used to get access to -// non-system class loaders when using the FindClass method. -// Any thread that calls GetJniEnv is bound to the JavaVM and will -// automatically be detached when that thread exits. -class JNIContext { -public: - JNIContext(jobject activity, JavaVM *vm); - ~JNIContext(); - - // This could be static, but it should never be called before at least one - // instance is constructed. - JNIEnv* GetJniEnv(); - - // Returns a local reference to the activity used to construct this class. - // The user is expected to call DeleteLocalRef to avoid leaking. - jobject GetActivity(); - - // Find a class, attempting to load the class if it's not found. - jclass FindClass(const char *class_name); - - // Copies a Java String to an std::string. This does not delete the local - // reference to the jstring. - std::string JStringAsString(jstring j_str); - - // Like JStringAsString, but will also delete the local reference to the - // java string. - std::string JStringToString(jstring j_str); - -private: - // The docs say this has to be a c function. - // not sure if that means we cannot have it as a static. - // But, if there's a problem move this outside the class and use: - // extern "C" void DetachJVMThreads(void* thread_set_jvm); - static void DetachJVMThreads(void* stored_java_vm); - - static JavaVM *vm_; - jobject activity_; -}; - -} // namespace signin -} // namespace google - -#endif // GOOGLESIGNIN_JNI_INIT_H \ No newline at end of file diff --git a/staging/native/src/include/future.h b/staging/native/src/include/future.h deleted file mode 100644 index fd8e8799..00000000 --- a/staging/native/src/include/future.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_FUTURE_H // NOLINT -#define GOOGLESIGNIN_FUTURE_H - -namespace google { -namespace signin { - -// Provides a future promise for an asynchronous result of type -template -class Future { - public: - virtual ~Future() {} - // Returns the Status of the operation. This is set once Pending is false. - virtual int Status() const = 0; - - // Returns the Result of the operation if successful. If it is not - // successful, the error code should be retrieved using Status(). The result - // is available once Pending() is false. - virtual T* Result() const = 0; - - // Returns true while the promise has not been fulfilled by the operation. - // Once it is false, the Status and Result fields are populated. - virtual bool Pending() const = 0; -}; - -} // namespace signin -} // namespace google -#endif // GOOGLESIGNIN_FUTURE_H NOLINT diff --git a/staging/native/src/include/google_signin.h b/staging/native/src/include/google_signin.h deleted file mode 100644 index abd45072..00000000 --- a/staging/native/src/include/google_signin.h +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_SIGNIN_GOOGLESIGNIN_H // NOLINT -#define GOOGLE_SIGNIN_GOOGLESIGNIN_H - -#include -#include - -#include "future.h" // NOLINT -#include "google_signin_user.h" // NOLINT - -#if defined(__ANDROID__) -#include -#endif - -namespace google { -namespace signin { - -class GoogleSignIn { - public: - /// StatusCode - /// These are based on - /// https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes - /// and consistent with what is returned by the Google Sign-In API on both iOS - /// and Android. - /// - enum StatusCode { - /// The operation was successful, but used the device's cache. - /// - kStatusCodeSuccessCached = -1, - - /// The operation was successful. - kStatusCodeSuccess = 0, - - /// The result is uninitialized. - kStatusCodeUninitialized = 100, - - - /// The client attempted to connect to the service with an - /// invalid account name specified. - kStatusCodeInvalidAccount = 5, - - /// A network error occurred. Retrying should resolve the problem. - /// - kStatusCodeNetworkError = 7, - - /// An internal error occurred. Retrying should resolve the - /// problem. - kStatusCodeInternalError = 8, - - /// The application is misconfigured. - /// This error is not recoverable. - /// - /// The developer should look at the logs after this to determine - /// more actionable information. - /// - kStatusCodeDeveloperError = 10, - - /// The operation failed with no more detailed - /// information. - kStatusCodeError = 13, - - /// A blocking call was interrupted while waiting and did not - /// run to completion. - kStatusCodeInterrupted = 14, - - /// Timed out while awaiting the result. - kStatusCodeTimeout = 15, - - /// The result was canceled either due to client disconnect - /// or cancel(). - kStatusCodeCanceled = 16, - - /// The client attempted to call a method from an API that - /// failed to connect. - kStatusCodeApiNotConnected = 17, - }; - - // Defines the configuration for the sign-in process. - struct Configuration { - /// true to use games signin, false for default signin. - /// games signing only works on Android. - bool use_game_signin; - /// Web client id associated with this app. - std::string web_client_id; - /// true for getting an auth code when authenticating. - /// Note: This may trigger re-consent on iOS. Ideally, this - /// is set to true once, and the result sent to the server where the - /// token is managed forever. - bool request_auth_code; - /// true to request to reset the refresh token. Causes re-consent. - bool force_token_refresh; - /// request email address, requires consent. - bool request_email; - /// request id token, requires consent. - bool request_id_token; - /// used with games signin to show or hide the connecting popup UI. - /// and to associate an invisible view for other popups. This is - /// recommended for VR applications. - bool hide_ui_popups; - /// account name to use when authenticating, null indicates use default. - std::string account_name; - /// additional scopes to request, requires consent. - std::vector additional_scopes; - int additional_scope_count; - - Configuration(Configuration const ©) = default; - Configuration(Configuration &&move) = delete; - ~Configuration() = default; - - Configuration &operator=(Configuration const ©) = delete; - Configuration &operator=(Configuration &&move) = delete; - }; - - // Holds the result of the sign-in process. - struct SignInResult { - GoogleSignInUser *User; - int StatusCode; - - SignInResult() = default; - SignInResult(SignInResult const ©) = default; - SignInResult(SignInResult &&move) = delete; - ~SignInResult() = default; - - SignInResult &operator=(SignInResult const ©) = delete; - SignInResult &operator=(SignInResult &&move) = delete; - }; - - // Constructs a new instance. -#if defined(__ANDROID__) - GoogleSignIn(jobject activity, JavaVM *vm); -#else - GoogleSignIn(); -#endif - - // Enables verbose logging. - void EnableDebugLogging(bool flag); - - // Sets the configuration for the sign-in. This must be called before - // calling SignIn(). Calling this invalidates the current sign-in result. - void Configure(const Configuration &configuration); - - // Starts the authentication process. - Future &SignIn(); - - // Attempts to sign in silently. - Future &SignInSilently(); - - // Get the result of the last sign-in. - const Future *GetLastSignInResult(); - - // Signs out the local user. Any server side tokens are still valid. - void SignOut(); - - // Disconnects this user from the application. Invalidates all tokens and - // consent. - void Disconnect(); - - private: - class GoogleSignInImpl; - GoogleSignInImpl *impl_; -}; - -} // namespace signin -} // namespace google - -#endif // GOOGLESIGNIN_GOOGLESIGNIN_H NOLINT diff --git a/staging/native/src/include/google_signin_user.h b/staging/native/src/include/google_signin_user.h deleted file mode 100644 index c2f81ead..00000000 --- a/staging/native/src/include/google_signin_user.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLESIGNIN_GOOGLE_SIGNIN_USER_H -#define GOOGLESIGNIN_GOOGLE_SIGNIN_USER_H - -namespace google { -namespace signin { - -class GoogleSignInUserImpl; - -// Represents the currently signed in user. -class GoogleSignInUser { - public: - ~GoogleSignInUser(); - - const char* GetDisplayName() const; - const char* GetEmail() const; - const char* GetFamilyName() const; - const char* GetGivenName() const; - const char* GetIdToken() const; - const char* GetImageUrl() const; - const char* GetServerAuthCode() const; - const char* GetUserId() const; - - private: - friend class GoogleSignInUserImpl; - GoogleSignInUser(); - GoogleSignInUser(GoogleSignInUserImpl* impl) : impl_(impl) {} - GoogleSignInUserImpl* impl_; -}; - -} // namespace signin -} // namespace google -#endif // GOOGLESIGNIN_GOOGLE_SIGNIN_USER_H diff --git a/staging/native/src/ios/GoogleSignIn.mm b/staging/native/src/ios/GoogleSignIn.mm deleted file mode 100644 index b6c30357..00000000 --- a/staging/native/src/ios/GoogleSignIn.mm +++ /dev/null @@ -1,314 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#import "GoogleSignIn.h" -#import -#import -#import -#import - -#import - -// These values are in the Unity plugin code. The iOS specific -// codes are mapped to these. -static const int kStatusCodeSuccessCached = -1; -static const int kStatusCodeSuccess = 0; -static const int kStatusCodeApiNotConnected = 1; -static const int kStatusCodeCanceled = 2; -static const int kStatusCodeInterrupted = 3; -static const int kStatusCodeInvalidAccount = 4; -static const int kStatusCodeTimeout = 5; -static const int kStatusCodeDeveloperError = 6; -static const int kStatusCodeInternalError = 7; -static const int kStatusCodeNetworkError = 8; -static const int kStatusCodeError = 9; - - -// result for pending operation. Access to this should be protected using the -// resultLock. -struct SignInResult { - int result_code; - bool finished; -}; - -std::unique_ptr currentResult_; - -NSRecursiveLock *resultLock = [NSRecursiveLock alloc]; - -@implementation GoogleSignInHandler - -/** - * The sign-in flow has finished and was successful if |error| is |nil|. - * Map the errors from the iOS SDK back to the Android values for consistency's - * sake in the Unity layer. - */ -- (void)signIn:(GIDSignIn *)signIn - didSignInForUser:(GIDGoogleUser *)user - withError:(NSError *)_error { - if (_error == nil) { - if (currentResult_) { - currentResult_->result_code = kStatusCodeSuccess; - currentResult_->finished = true; - } else { - NSLog(@"No currentResult to set status on!"); - } - NSLog(@"didSignInForUser: SUCCESS"); - } else { - NSLog(@"didSignInForUser: %@", _error.localizedDescription); - if (currentResult_) { - switch (_error.code) { - case kGIDSignInErrorCodeUnknown: - currentResult_->result_code = kStatusCodeError; - break; - case kGIDSignInErrorCodeKeychain: - currentResult_->result_code = kStatusCodeInternalError; - break; - case kGIDSignInErrorCodeNoSignInHandlersInstalled: - currentResult_->result_code = kStatusCodeDeveloperError; - break; - case kGIDSignInErrorCodeHasNoAuthInKeychain: - currentResult_->result_code = kStatusCodeError; - break; - case kGIDSignInErrorCodeCanceled: - currentResult_->result_code = kStatusCodeCanceled; - break; - default: - NSLog(@"Unmapped error code: %ld, returning Error", - static_cast(_error.code)); - currentResult_->result_code = kStatusCodeError; - } - - currentResult_->finished = true; - } else { - NSLog(@"No currentResult to set status on!"); - } - } -} - -// Finished disconnecting |user| from the app successfully if |error| is |nil|. -- (void)signIn:(GIDSignIn *)signIn - didDisconnectWithUser:(GIDGoogleUser *)user - withError:(NSError *)_error { - if (_error == nil) { - NSLog(@"didDisconnectWithUser: SUCCESS"); - } else { - NSLog(@"didDisconnectWithUser: %@", _error); - } -} - -@end - -/** - * These are the external "C" methods that are imported by the Unity C# code. - * The parameters are intended to be primative, easy to marshall. - */ -extern "C" { -/** - * This method does nothing in the iOS implementation. It is here - * to make the API uniform between Android and iOS. - */ -void *GoogleSignIn_Create(void *data) { return NULL; } - -void GoogleSignIn_EnableDebugLogging(void *unused, bool flag) { - if (flag) { - NSLog(@"GoogleSignIn: No optional logging available on iOS"); - } -} - -/** - * Configures the GIDSignIn instance. The first parameter is unused in iOS. - * It is here to make the API between Android and iOS uniform. - */ -bool GoogleSignIn_Configure(void *unused, bool useGameSignIn, - const char *webClientId, bool requestAuthCode, - bool forceTokenRefresh, bool requestEmail, - bool requestIdToken, bool hidePopups, - const char **additionalScopes, int scopeCount, - const char *accountName) { - if (webClientId) { - [GIDSignIn sharedInstance].serverClientID = - [NSString stringWithUTF8String:webClientId]; - } - - [GIDSignIn sharedInstance].shouldFetchBasicProfile = true; - - int scopeSize = scopeCount; - - if (scopeSize) { - NSMutableArray *tmpary = - [[NSMutableArray alloc] initWithCapacity:scopeSize]; - for (int i = 0; i < scopeCount; i++) { - [tmpary addObject:[NSString stringWithUTF8String:additionalScopes[i]]]; - } - - [GIDSignIn sharedInstance].scopes = tmpary; - } - - if (accountName) { - [GIDSignIn sharedInstance].loginHint = - [NSString stringWithUTF8String:accountName]; - } - - return !useGameSignIn; -} - -/** - Starts the sign-in process. Returns and error result if error, null otherwise. - */ -static SignInResult *startSignIn() { - bool busy = false; - [resultLock lock]; - if (!currentResult_ || currentResult_->finished) { - currentResult_.reset(new SignInResult()); - currentResult_->result_code = 0; - currentResult_->finished = false; - } else { - busy = true; - } - [resultLock unlock]; - - if (busy) { - NSLog(@"ERROR: There is already a pending sign-in operation."); - // Returned to the caller, should be deleted by calling - // GoogleSignIn_DisposeFuture(). - return new SignInResult{.result_code = kStatusCodeDeveloperError, - .finished = true}; - } - return nullptr; -} - -/** - * Sign-In. The return value is a pointer to the currentResult object. - */ -void *GoogleSignIn_SignIn() { - SignInResult *result = startSignIn(); - if (!result) { - [[GIDSignIn sharedInstance] signIn]; - result = currentResult_.get(); - } - return result; -} - -/** - * Attempt a silent sign-in. Return value is the pointer to the currentResult - * object. - */ -void *GoogleSignIn_SignInSilently() { - SignInResult *result = startSignIn(); - if (!result) { - [[GIDSignIn sharedInstance] signInSilently]; - result = currentResult_.get(); - } - return result; -} - -void GoogleSignIn_Signout() { - GIDSignIn *signIn = [GIDSignIn sharedInstance]; - [signIn signOut]; -} - -void GoogleSignIn_Disconnect() { - GIDSignIn *signIn = [GIDSignIn sharedInstance]; - [signIn disconnect]; -} - -bool GoogleSignIn_Pending(SignInResult *result) { - volatile bool ret; - [resultLock lock]; - ret = !result->finished; - [resultLock unlock]; - return ret; -} - -GIDGoogleUser *GoogleSignIn_Result(SignInResult *result) { - if (result && result->finished) { - GIDGoogleUser *guser = [GIDSignIn sharedInstance].currentUser; - return guser; - } - return nullptr; -} - -int GoogleSignIn_Status(SignInResult *result) { - if (result) { - return result->result_code; - } - return kStatusCodeDeveloperError; -} - -void GoogleSignIn_DisposeFuture(SignInResult *result) { - if (result == currentResult_.get()) { - currentResult_.reset(nullptr); - } else { - delete result; - } -} - -/** - * Private helper function to copy NSString to char*. If the destination is - * non-null, the contents of src are copied up to len bytes (using strncpy). The - * then len is returned. Otherwise returns length of the string to copy + 1. - */ -static size_t CopyNSString(NSString *src, char *dest, size_t len) { - if (dest && src && len) { - const char *string = [src UTF8String]; - strncpy(dest, string, len); - return len; - } - return src ? src.length + 1 : 0; -} - -size_t GoogleSignIn_GetServerAuthCode(GIDGoogleUser *guser, char *buf, - size_t len) { - NSString *val = [guser serverAuthCode]; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetDisplayName(GIDGoogleUser *guser, char *buf, - size_t len) { - NSString *val = [guser.profile name]; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetEmail(GIDGoogleUser *guser, char *buf, size_t len) { - NSString *val = [guser.profile email]; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetFamilyName(GIDGoogleUser *guser, char *buf, size_t len) { - NSString *val = [guser.profile familyName]; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetGivenName(GIDGoogleUser *guser, char *buf, size_t len) { - NSString *val = [guser.profile givenName]; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetIdToken(GIDGoogleUser *guser, char *buf, size_t len) { - NSString *val = [guser.authentication idToken]; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetImageUrl(GIDGoogleUser *guser, char *buf, size_t len) { - NSURL *url = [guser.profile imageURLWithDimension:128]; - NSString *val = url ? [url absoluteString] : nullptr; - return CopyNSString(val, buf, len); -} - -size_t GoogleSignIn_GetUserId(GIDGoogleUser *guser, char *buf, size_t len) { - NSString *val = [guser userID]; - return CopyNSString(val, buf, len); -} -} // extern "C" diff --git a/staging/native/testapp/LaunchScreen.storyboard b/staging/native/testapp/LaunchScreen.storyboard deleted file mode 100644 index 673e0f7e..00000000 --- a/staging/native/testapp/LaunchScreen.storyboard +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/staging/native/testapp/Podfile b/staging/native/testapp/Podfile deleted file mode 100644 index b115e020..00000000 --- a/staging/native/testapp/Podfile +++ /dev/null @@ -1,7 +0,0 @@ -use_frameworks! -platform :ios, '8.0' - -target 'testapp' do - pod 'GoogleSignInCpp', :path => '../' - -end diff --git a/staging/native/testapp/build.gradle b/staging/native/testapp/build.gradle deleted file mode 100644 index 40da1bd8..00000000 --- a/staging/native/testapp/build.gradle +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (C) 2018 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:2.3.3' - } -} - -allprojects { - repositories { - jcenter() - maven { - url "https://maven.google.com" - } - flatDir { - // Add the path to the google sign in library so the local AAR - // can be found. 'Compile' referencing a relative file doesn't work - // with AAR files, so we need to use this method instead. - dirs '../google-signin-cpp' - } - } -} - -apply plugin: 'com.android.application' - -project.ext { - ndk_dir = project.android.ndkDirectory - if (ndk_dir == null || !ndk_dir.exists()) { - ndk_dir = System.getenv('ANDROID_NDK_HOME') - if (ndk_dir == null || ndk_dir.isEmpty()) { - throw new StopActionException( - 'Android NDK directory should be specified using the ndk.dir ' + - 'property or ANDROID_NDK_HOME environment variable.') - } - } - - if (project.hasProperty("pluginVersion")) { - version = project.pluginVersion - } else { - version '1.0.0' - } - - baseName = "signin-testapp" -} - -android { - compileSdkVersion 26 - buildToolsVersion '26.0.3' - - sourceSets { - main { - manifest.srcFile 'src/android/AndroidManifest.xml' - java.srcDirs = ['src/android/java'] - jniLibs.srcDirs = ['../plugin/libs'] - res.srcDirs = ['src/android/res'] - } - } - lintOptions { - abortOnError false - } - defaultConfig { - applicationId 'com.google.signin.testapp' - minSdkVersion 14 - targetSdkVersion 26 - versionName project.version - archivesBaseName = project.ext.baseName - externalNativeBuild { - cmake { - cppFlags "-std=c++11", "-Wall" - } - } - ndk { - abiFilters 'x86', 'armeabi-v7a' - } - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt') - } - } - externalNativeBuild { - cmake { - path "src/android/CMakeLists.txt" - } - } -} - -dependencies { - compile 'com.google.android.gms:play-services-auth:11.8.0' - // Depend on the AAR built with the google sign in library in order to add - // the java helper classes which are used by the c++ library. - compile(name:'google-signin-cpp-release', ext:'aar') -} - diff --git a/staging/native/testapp/gradle/wrapper/gradle-wrapper.jar b/staging/native/testapp/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 463732c9..00000000 Binary files a/staging/native/testapp/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/staging/native/testapp/gradle/wrapper/gradle-wrapper.properties b/staging/native/testapp/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 4ab7834d..00000000 --- a/staging/native/testapp/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Fri Feb 23 19:11:21 PST 2018 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip diff --git a/staging/native/testapp/gradlew b/staging/native/testapp/gradlew deleted file mode 100755 index 4453ccea..00000000 --- a/staging/native/testapp/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save ( ) { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/staging/native/testapp/gradlew.bat b/staging/native/testapp/gradlew.bat deleted file mode 100644 index e95643d6..00000000 --- a/staging/native/testapp/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/staging/native/testapp/src/android/AndroidManifest.xml b/staging/native/testapp/src/android/AndroidManifest.xml deleted file mode 100644 index 7ed7551d..00000000 --- a/staging/native/testapp/src/android/AndroidManifest.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/staging/native/testapp/src/android/CMakeLists.txt b/staging/native/testapp/src/android/CMakeLists.txt deleted file mode 100644 index 48ca1d81..00000000 --- a/staging/native/testapp/src/android/CMakeLists.txt +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright 2018 Google Inc. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# For more information about using CMake with Android Studio, read the -# documentation: https://d.android.com/studio/projects/add-native-code.html - -# Sets the minimum version of CMake required to build the native library. -cmake_minimum_required(VERSION 3.4.1) - -add_library(native-app-glue - STATIC - ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c) - -# now build app's shared lib -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11 -Wall -Werror") - -set(GSI_PACKAGE_DIR "${CMAKE_SOURCE_DIR}/../../../google-signin-cpp") -add_library(lib-google-signin-cpp STATIC IMPORTED) -set_target_properties(lib-google-signin-cpp PROPERTIES IMPORTED_LOCATION - ${GSI_PACKAGE_DIR}/lib/${ANDROID_ABI}/libgoogle-signin-cpp.a ) - -# Our testapp is an SO the native app loads. -add_library(signin-testapp - SHARED - ../common_main.cpp - android_main.cpp) - -# Export ANativeActivity_onCreate(), -# Refer to: https://github.com/android-ndk/ndk/issues/381. -set(CMAKE_SHARED_LINKER_FLAGS - "${CMAKE_SHARED_LINKER_FLAGS} -u ANativeActivity_onCreate") - -# Add lib inlcudes -target_include_directories(signin-testapp - PRIVATE - ${ANDROID_NDK}/sources/android/native_app_glue - ${GSI_PACKAGE_DIR}/include - ..) - -# add lib dependencies -target_link_libraries(signin-testapp - android - lib-google-signin-cpp - native-app-glue - log) diff --git a/staging/native/testapp/src/android/android_main.cpp b/staging/native/testapp/src/android/android_main.cpp deleted file mode 100644 index 242e6f0f..00000000 --- a/staging/native/testapp/src/android/android_main.cpp +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include -#include - -#include -#include -#include -#include - -#include "main.h" // NOLINT - -// This implementation is derived from http://github.com/google/fplutil - -extern "C" int common_main(int argc, const char* argv[]); - -static struct android_app* g_app_state = nullptr; -static bool g_destroy_requested = false; -static bool g_started = false; -static bool g_restarted = false; -static pthread_mutex_t g_started_mutex; - -// Handle state changes from via native app glue. -static void OnAppCmd(struct android_app* app, int32_t cmd) { - g_destroy_requested |= cmd == APP_CMD_DESTROY; -} - -// Process events pending on the main thread. -// Returns true when the app receives an event requesting exit. -bool ProcessEvents(int msec) { - struct android_poll_source* source = nullptr; - int events; - int looperId = ALooper_pollAll(msec, nullptr, &events, - reinterpret_cast(&source)); - if (looperId >= 0 && source) { - source->process(g_app_state, source); - } - return g_destroy_requested | g_restarted; -} - -JNIEnv* GetJniEnv() { - JavaVM* vm = g_app_state->activity->vm; - JNIEnv* env; - jint result = vm->AttachCurrentThread(&env, nullptr); - return result == JNI_OK ? env : nullptr; -} - -jobject GetActivity() { return g_app_state->activity->clazz; } -JavaVM* GetJavaVM() { return g_app_state->activity->vm; } - -// Get the window context. For Android, it's a jobject pointing to the Activity. -jobject GetWindowContext() { return g_app_state->activity->clazz; } - -// Find a class, attempting to load the class if it's not found. -jclass FindClass(JNIEnv* env, jobject activity_object, const char* class_name) { - jclass class_object = env->FindClass(class_name); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - // If the class isn't found it's possible NativeActivity is being used by - // the application which means the class path is set to only load system - // classes. The following falls back to loading the class using the - // Activity before retrieving a reference to it. - jclass activity_class = env->FindClass("android/app/Activity"); - jmethodID activity_get_class_loader = env->GetMethodID( - activity_class, "getClassLoader", "()Ljava/lang/ClassLoader;"); - - jobject class_loader_object = - env->CallObjectMethod(activity_object, activity_get_class_loader); - - jclass class_loader_class = env->FindClass("java/lang/ClassLoader"); - jmethodID class_loader_load_class = - env->GetMethodID(class_loader_class, "loadClass", - "(Ljava/lang/String;)Ljava/lang/Class;"); - jstring class_name_object = env->NewStringUTF(class_name); - - class_object = static_cast(env->CallObjectMethod( - class_loader_object, class_loader_load_class, class_name_object)); - - if (env->ExceptionCheck()) { - env->ExceptionClear(); - class_object = nullptr; - } - env->DeleteLocalRef(class_name_object); - env->DeleteLocalRef(class_loader_object); - } - return class_object; -} - -// Vars that we need available for appending text to the log window: -class LoggingUtilsData { - public: - LoggingUtilsData() - : logging_utils_class_(nullptr), - logging_utils_add_log_text_(0), - logging_utils_init_log_window_(0) {} - - ~LoggingUtilsData() { - JNIEnv* env = GetJniEnv(); - assert(env); - if (logging_utils_class_) { - env->DeleteGlobalRef(logging_utils_class_); - } - } - - void Init() { - JNIEnv* env = GetJniEnv(); - assert(env); - - jclass logging_utils_class = FindClass( - env, GetActivity(), "com/google/signin/testapp/LoggingUtils"); - assert(logging_utils_class != 0); - - // Need to store as global references so it don't get moved during garbage - // collection. - logging_utils_class_ = - static_cast(env->NewGlobalRef(logging_utils_class)); - env->DeleteLocalRef(logging_utils_class); - - logging_utils_init_log_window_ = env->GetStaticMethodID( - logging_utils_class_, "initLogWindow", "(Landroid/app/Activity;)V"); - logging_utils_add_log_text_ = env->GetStaticMethodID( - logging_utils_class_, "addLogText", "(Ljava/lang/String;)V"); - - env->CallStaticVoidMethod(logging_utils_class_, - logging_utils_init_log_window_, GetActivity()); - } - - void AppendText(const char* text) { - if (logging_utils_class_ == 0) return; // haven't been initted yet - JNIEnv* env = GetJniEnv(); - assert(env); - jstring text_string = env->NewStringUTF(text); - env->CallStaticVoidMethod(logging_utils_class_, logging_utils_add_log_text_, - text_string); - env->DeleteLocalRef(text_string); - } - - private: - jclass logging_utils_class_; - jmethodID logging_utils_add_log_text_; - jmethodID logging_utils_init_log_window_; -}; - -LoggingUtilsData* g_logging_utils_data; - -// Checks if a JNI exception has happened, and if so, logs it to the console. -void CheckJNIException() { - JNIEnv* env = GetJniEnv(); - if (env->ExceptionCheck()) { - // Get the exception text. - jthrowable exception = env->ExceptionOccurred(); - env->ExceptionClear(); - - // Convert the exception to a string. - jclass object_class = env->FindClass("java/lang/Object"); - jmethodID toString = - env->GetMethodID(object_class, "toString", "()Ljava/lang/String;"); - jstring s = (jstring)env->CallObjectMethod(exception, toString); - const char* exception_text = env->GetStringUTFChars(s, nullptr); - - // Log the exception text. - __android_log_print(ANDROID_LOG_INFO, APP_NAME, - "-------------------JNI exception:"); - __android_log_print(ANDROID_LOG_INFO, APP_NAME, "%s", - exception_text); - __android_log_print(ANDROID_LOG_INFO, APP_NAME, - "-------------------"); - - // Also, assert fail. - assert(false); - - // In the event we didn't assert fail, clean up. - env->ReleaseStringUTFChars(s, exception_text); - env->DeleteLocalRef(s); - env->DeleteLocalRef(exception); - } -} - -// Log a message that can be viewed in "adb logcat". -void LogMessage(const char* format, ...) { - static const int kLineBufferSize = 100; - char buffer[kLineBufferSize + 2]; - - va_list list; - va_start(list, format); - int string_len = vsnprintf(buffer, kLineBufferSize, format, list); - string_len = string_len < kLineBufferSize ? string_len : kLineBufferSize; - // append a linebreak to the buffer: - buffer[string_len] = '\n'; - buffer[string_len + 1] = '\0'; - - __android_log_vprint(ANDROID_LOG_INFO, APP_NAME, format, list); - g_logging_utils_data->AppendText(buffer); - CheckJNIException(); - va_end(list); -} - -// Execute common_main(), flush pending events and finish the activity. -extern "C" void android_main(struct android_app* state) { - // native_app_glue spawns a new thread, calling android_main() when the - // activity onStart() or onRestart() methods are called. This code handles - // the case where we're re-entering this method on a different thread by - // signalling the existing thread to exit, waiting for it to complete before - // reinitializing the application. - if (g_started) { - g_restarted = true; - // Wait for the existing thread to exit. - pthread_mutex_lock(&g_started_mutex); - pthread_mutex_unlock(&g_started_mutex); - } else { - g_started_mutex = PTHREAD_MUTEX_INITIALIZER; - } - pthread_mutex_lock(&g_started_mutex); - g_started = true; - - // Save native app glue state and setup a callback to track the state. - g_destroy_requested = false; - g_app_state = state; - g_app_state->onAppCmd = OnAppCmd; - - // Create the logging display. - g_logging_utils_data = new LoggingUtilsData(); - g_logging_utils_data->Init(); - - // Execute cross platform entry point. - static const char* argv[] = {APP_NAME}; - int return_value = common_main(1, argv); - (void)return_value; // Ignore the return value. - ProcessEvents(10); - - // Clean up logging display. - delete g_logging_utils_data; - g_logging_utils_data = nullptr; - - // Finish the activity. - if (!g_restarted) ANativeActivity_finish(state->activity); - - g_app_state->activity->vm->DetachCurrentThread(); - g_started = false; - g_restarted = false; - pthread_mutex_unlock(&g_started_mutex); -} \ No newline at end of file diff --git a/staging/native/testapp/src/android/java/com/google/signin/testapp/LoggingUtils.java b/staging/native/testapp/src/android/java/com/google/signin/testapp/LoggingUtils.java deleted file mode 100644 index dc1f4c06..00000000 --- a/staging/native/testapp/src/android/java/com/google/signin/testapp/LoggingUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.signin.testapp; - -import android.app.Activity; -import android.os.Handler; -import android.os.Looper; -import android.view.Window; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.TextView; - -/** - * A utility class, encapsulating the data and methods required to log arbitrary - * text to the screen, via a non-editable TextView. - */ -public class LoggingUtils { - public static TextView sTextView = null; - - public static void initLogWindow(Activity activity) { - LinearLayout linearLayout = new LinearLayout(activity); - ScrollView scrollView = new ScrollView(activity); - TextView textView = new TextView(activity); - textView.setTag("Logger"); - linearLayout.addView(scrollView); - scrollView.addView(textView); - Window window = activity.getWindow(); - window.takeSurface(null); - window.setContentView(linearLayout); - sTextView = textView; - } - - public static void addLogText(final String text) { - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - if (sTextView != null) { - sTextView.append(text); - } - } - }); - } -} diff --git a/staging/native/testapp/src/android/java/com/google/signin/testapp/TextEntryField.java b/staging/native/testapp/src/android/java/com/google/signin/testapp/TextEntryField.java deleted file mode 100644 index e6ea7542..00000000 --- a/staging/native/testapp/src/android/java/com/google/signin/testapp/TextEntryField.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.signin.testapp; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.widget.EditText; - -/** - * A utility class, with a method to prompt the user to enter a line of text, and a native method to - * sleep for a given number of milliseconds. - */ -public class TextEntryField { - private static Object lock = new Object(); - private static String resultText = null; - - /** - * Prompt the user with a text field, blocking until the user fills it out, then returns the text - * they entered. If the user cancels, returns an empty string. - */ - public static String readText( - final Activity activity, final String title, final String message, final String placeholder) { - resultText = null; - // Show the alert dialog on the main thread. - activity.runOnUiThread( - new Runnable() { - @Override - public void run() { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity); - alertBuilder.setTitle(title); - alertBuilder.setMessage(message); - - // Set up and add the text field. - final EditText textField = new EditText(activity); - textField.setHint(placeholder); - alertBuilder.setView(textField); - - alertBuilder.setPositiveButton( - "OK", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - synchronized (lock) { - resultText = textField.getText().toString(); - } - } - }); - - alertBuilder.setNegativeButton( - "Cancel", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - synchronized (lock) { - resultText = ""; - } - } - }); - - alertBuilder.setOnCancelListener( - new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - synchronized (lock) { - resultText = ""; - } - } - }); - alertBuilder.show(); - } - }); - - // In our original thread, wait for the dialog to finish, then return its result. - while (true) { - // Pause a second, waiting for the user to enter text. - if (nativeSleep(1000)) { - // If this returns true, an exit was requested. - return ""; - } - synchronized (lock) { - if (resultText != null) { - // resultText will be set to non-null when a dialog button is clicked, or the dialog - // is canceled. - String result = resultText; - resultText = null; // Consume the result. - return result; - } - } - } - } - - private static native boolean nativeSleep(int milliseconds); -} diff --git a/staging/native/testapp/src/android/res/layout/main.xml b/staging/native/testapp/src/android/res/layout/main.xml deleted file mode 100644 index d0ffcb82..00000000 --- a/staging/native/testapp/src/android/res/layout/main.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/staging/native/testapp/src/android/res/values/strings.xml b/staging/native/testapp/src/android/res/values/strings.xml deleted file mode 100644 index 8c8e1ed3..00000000 --- a/staging/native/testapp/src/android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - Google Signin Testapp - diff --git a/staging/native/testapp/src/common_main.cpp b/staging/native/testapp/src/common_main.cpp deleted file mode 100644 index 74ffa9dc..00000000 --- a/staging/native/testapp/src/common_main.cpp +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -// This is platform agnostic test code of the C++ GSI API. -// The platform specific bootstraps are in android/ and ios/ respectively, -// and those call into this to do the API calls. - -#include "main.h" - -#include "google_signin.h" -#include "future.h" - -using namespace google::signin; - -// Don't return until `future` is complete. -// Print a message for whether the result mathes our expectations. -// Returns true if the application should exit. -template -bool WaitForFuture(Future &future, const char* fn, - GoogleSignIn::StatusCode expected_error, - bool log_error = true) { - // Wait for future to complete. - LogMessage(" Calling %s...", fn); - while (future.Pending()) { - if (ProcessEvents(100)) return true; - } - - // Log error result. - if (log_error) { - const GoogleSignIn::StatusCode error = - static_cast(future.Status()); - if (error == expected_error) { - LogMessage("%s completed as expected", fn); - } else { - LogMessage("ERROR: %s completed with error: %d", fn, error); - } - } - return false; -} - -extern "C" int common_main(int argc, const char* argv[]) { - - LogMessage("GSI Testapp Initialized!"); - - GoogleSignIn::Configuration config = {}; - config.web_client_id = "64192632067-d37vn8fg59u8pvdgc7lc8jeve9mbbd7o.apps.googleusercontent.com"; // "YOUR_WEB_CLIENT_ID_HERE"; - config.request_id_token = true; - config.use_game_signin = false; - config.request_auth_code = false; - - LogMessage("Constructing..."); -#if defined(__ANDROID__) - GoogleSignIn gsi = GoogleSignIn(GetActivity(), GetJavaVM()); -#else - GoogleSignIn gsi = GoogleSignIn(); -#endif // defined(__ANDROID__) - - LogMessage("Calling Configure..."); - gsi.Configure(config); - - LogMessage("Calling SignIn..."); - Future &future = gsi.SignIn(); - WaitForFuture(future, "GoogleSignIn::SignIn()", GoogleSignIn::kStatusCodeSuccess); - - while (!ProcessEvents(1000)) { - } - - return 0; -} diff --git a/staging/native/testapp/src/ios/ios_main.mm b/staging/native/testapp/src/ios/ios_main.mm deleted file mode 100644 index 57fc138e..00000000 --- a/staging/native/testapp/src/ios/ios_main.mm +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#import - -#include -#include - -#include "main.h" - -extern "C" int common_main(int argc, const char* argv[]); - -@interface AppDelegate : UIResponder - -@property(nonatomic, strong) UIWindow *window; - -@end - -@interface FTAViewController : UIViewController - -@property(atomic, strong) NSString *textEntryResult; - -@end - -static int g_exit_status = 0; -static bool g_shutdown = false; -static NSCondition *g_shutdown_complete; -static NSCondition *g_shutdown_signal; -static UITextView *g_text_view; -static UIView *g_parent_view; -static FTAViewController *g_view_controller; - -@implementation FTAViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - g_parent_view = self.view; - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - const char *argv[] = {"FIREBASE_TESTAPP_NAME"}; - [g_shutdown_signal lock]; - g_exit_status = common_main(1, argv); - [g_shutdown_complete signal]; - }); -} - -@end - -bool ProcessEvents(int msec) { - [g_shutdown_signal - waitUntilDate:[NSDate dateWithTimeIntervalSinceNow:static_cast(msec) / 1000.0f]]; - return g_shutdown; -} - -WindowContext GetWindowContext() { - return g_parent_view; -} - -// Log a message that can be viewed in the console. -void LogMessage(const char* format, ...) { - va_list args; - NSString *formatString = @(format); - - va_start(args, format); - NSString *message = [[NSString alloc] initWithFormat:formatString arguments:args]; - va_end(args); - - NSLog(@"%@", message); - message = [message stringByAppendingString:@"\n"]; - - dispatch_async(dispatch_get_main_queue(), ^{ - g_text_view.text = [g_text_view.text stringByAppendingString:message]; - }); -} - -int main(int argc, char* argv[]) { - @autoreleasepool { - UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } - return g_exit_status; -} - -// Create an alert dialog via UIAlertController, and prompt the user to enter a line of text. -// This function spins until the text has been entered (or the alert dialog was canceled). -// If the user cancels, returns an empty string. -std::string ReadTextInput(const char *title, const char *message, const char *placeholder) { - assert(g_view_controller); - // This should only be called from a background thread, as it blocks, which will mess up the main - // thread. - assert(![NSThread isMainThread]); - - g_view_controller.textEntryResult = nil; - - dispatch_async(dispatch_get_main_queue(), ^{ - UIAlertController *alertController = - [UIAlertController alertControllerWithTitle:@(title) - message:@(message) - preferredStyle:UIAlertControllerStyleAlert]; - [alertController addTextFieldWithConfigurationHandler:^(UITextField *_Nonnull textField) { - textField.placeholder = @(placeholder); - }]; - UIAlertAction *confirmAction = [UIAlertAction - actionWithTitle:@"OK" - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *_Nonnull action) { - g_view_controller.textEntryResult = alertController.textFields.firstObject.text; - }]; - [alertController addAction:confirmAction]; - UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" - style:UIAlertActionStyleCancel - handler:^(UIAlertAction *_Nonnull action) { - g_view_controller.textEntryResult = @""; - }]; - [alertController addAction:cancelAction]; - [g_view_controller presentViewController:alertController animated:YES completion:nil]; - }); - - while (true) { - // Pause a second, waiting for the user to enter text. - if (ProcessEvents(1000)) { - // If this returns true, an exit was requested. - return ""; - } - if (g_view_controller.textEntryResult != nil) { - // textEntryResult will be set to non-nil when a dialog button is clicked. - std::string result = g_view_controller.textEntryResult.UTF8String; - g_view_controller.textEntryResult = nil; // Consume the result. - return result; - } - } -} - -@implementation AppDelegate - -- (BOOL)application:(UIApplication*)application - didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { - g_shutdown_complete = [[NSCondition alloc] init]; - g_shutdown_signal = [[NSCondition alloc] init]; - [g_shutdown_complete lock]; - - self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; - g_view_controller = [[FTAViewController alloc] init]; - self.window.rootViewController = g_view_controller; - [self.window makeKeyAndVisible]; - - g_text_view = [[UITextView alloc] initWithFrame:g_view_controller.view.bounds]; - - g_text_view.editable = NO; - g_text_view.scrollEnabled = YES; - g_text_view.userInteractionEnabled = YES; - - [g_view_controller.view addSubview:g_text_view]; - - return YES; -} - -- (void)applicationWillTerminate:(UIApplication *)application { - g_view_controller = nil; - g_shutdown = true; - [g_shutdown_signal signal]; - [g_shutdown_complete wait]; -} - -@end diff --git a/staging/native/testapp/src/main.h b/staging/native/testapp/src/main.h deleted file mode 100644 index a3b98f17..00000000 --- a/staging/native/testapp/src/main.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef TESTAPP_MAIN_H -#define TESTAPP_MAIN_H - -#if defined(__ANDROID__) -#include -#include -jobject GetActivity(); -JavaVM* GetJavaVM(); -#elif defined(__APPLE__) -extern "C" { -#include -} // extern "C" -#endif // __ANDROID__ - -// Fallback, if not defined using -DAPP_NAME=some_app_name when compiling -// this file. -#ifndef APP_NAME -#define APP_NAME "gsi_testapp" -#endif // APP_NAME - -// WindowContext represents the handle to the parent window. It's type -// (and usage) vary based on the OS. -#if defined(__ANDROID__) -typedef jobject WindowContext; // A jobject to the Java Activity. -#elif defined(__APPLE__) -typedef id WindowContext; // A pointer to an iOS UIView. -#else -typedef void* WindowContext; // A void* for any other environments. -#endif - -// Cross platform logging method. -// Implemented by android/android_main.cc or ios/ios_main.mm. -extern "C" void LogMessage(const char* format, ...); - -// Cross platform method to flush pending events for the main thread. -// Implemented by android/android_main.cc or ios/ios_main.mm. -// Returns true when an event requesting program-exit is received. -bool ProcessEvents(int msec); - -#endif // TESTAPP_MAIN_H \ No newline at end of file diff --git a/staging/native/testapp/testapp.xcodeproj/project.pbxproj b/staging/native/testapp/testapp.xcodeproj/project.pbxproj deleted file mode 100644 index 36c938a1..00000000 --- a/staging/native/testapp/testapp.xcodeproj/project.pbxproj +++ /dev/null @@ -1,378 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 4C3C7DCC2033BACC0077B58E /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4C3C7DCB2033BACC0077B58E /* LaunchScreen.storyboard */; }; - 4C3C7DCF2033BAF60077B58E /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4C3C7DCD2033BAF60077B58E /* Images.xcassets */; }; - 4CE59BEA2033B47E00A73A92 /* common_main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4CE59BE72033B47E00A73A92 /* common_main.cpp */; }; - 4CE59BEF2033B69300A73A92 /* ios_main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4CE59BEE2033B69300A73A92 /* ios_main.mm */; }; - 6003F58E195388D20070C39A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58D195388D20070C39A /* Foundation.framework */; }; - 6003F590195388D20070C39A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58F195388D20070C39A /* CoreGraphics.framework */; }; - 6003F592195388D20070C39A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F591195388D20070C39A /* UIKit.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 0167588598B78EAA2D036D67 /* GoogleSignInCpp.podspec */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = GoogleSignInCpp.podspec; path = ../GoogleSignInCpp.podspec; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 4C3C7DCB2033BACC0077B58E /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; - 4C3C7DCD2033BAF60077B58E /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = testapp/Images.xcassets; sourceTree = ""; }; - 4C3C7DCE2033BAF60077B58E /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = testapp/Info.plist; sourceTree = ""; }; - 4CE59BE72033B47E00A73A92 /* common_main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = common_main.cpp; sourceTree = ""; }; - 4CE59BE82033B47E00A73A92 /* main.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = main.h; sourceTree = ""; }; - 4CE59BEB2033B65100A73A92 /* Podfile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Podfile; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 4CE59BEE2033B69300A73A92 /* ios_main.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = ios_main.mm; path = src/ios/ios_main.mm; sourceTree = SOURCE_ROOT; }; - 6003F58A195388D20070C39A /* testapp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = testapp.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 6003F58D195388D20070C39A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - 6003F58F195388D20070C39A /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; - 6003F591195388D20070C39A /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; - 7A126461E42F7806F61A588A /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = ../README.md; sourceTree = ""; }; - BF63353FEBAEFDC384526617 /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = LICENSE; path = ../LICENSE; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 6003F587195388D20070C39A /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 6003F590195388D20070C39A /* CoreGraphics.framework in Frameworks */, - 6003F592195388D20070C39A /* UIKit.framework in Frameworks */, - 6003F58E195388D20070C39A /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 4CE59BED2033B66E00A73A92 /* ios */ = { - isa = PBXGroup; - children = ( - 4CE59BEE2033B69300A73A92 /* ios_main.mm */, - ); - path = ios; - sourceTree = ""; - }; - 6003F581195388D10070C39A = { - isa = PBXGroup; - children = ( - 4C3C7DCD2033BAF60077B58E /* Images.xcassets */, - 4C3C7DCE2033BAF60077B58E /* Info.plist */, - 4C3C7DCB2033BACC0077B58E /* LaunchScreen.storyboard */, - 60FF7A9C1954A5C5007DD14C /* Podspec Metadata */, - 6003F593195388D20070C39A /* src */, - 6003F58C195388D20070C39A /* Frameworks */, - 6003F58B195388D20070C39A /* Products */, - ); - sourceTree = ""; - }; - 6003F58B195388D20070C39A /* Products */ = { - isa = PBXGroup; - children = ( - 6003F58A195388D20070C39A /* testapp.app */, - ); - name = Products; - sourceTree = ""; - }; - 6003F58C195388D20070C39A /* Frameworks */ = { - isa = PBXGroup; - children = ( - 6003F58D195388D20070C39A /* Foundation.framework */, - 6003F58F195388D20070C39A /* CoreGraphics.framework */, - 6003F591195388D20070C39A /* UIKit.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 6003F593195388D20070C39A /* src */ = { - isa = PBXGroup; - children = ( - 4CE59BE72033B47E00A73A92 /* common_main.cpp */, - 4CE59BE82033B47E00A73A92 /* main.h */, - 4CE59BED2033B66E00A73A92 /* ios */, - ); - path = src; - sourceTree = ""; - }; - 60FF7A9C1954A5C5007DD14C /* Podspec Metadata */ = { - isa = PBXGroup; - children = ( - 4CE59BEB2033B65100A73A92 /* Podfile */, - 0167588598B78EAA2D036D67 /* GoogleSignInCpp.podspec */, - 7A126461E42F7806F61A588A /* README.md */, - BF63353FEBAEFDC384526617 /* LICENSE */, - ); - name = "Podspec Metadata"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 6003F589195388D20070C39A /* testapp */ = { - isa = PBXNativeTarget; - buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "testapp" */; - buildPhases = ( - 3CFAC7B749210A2C53CA2CA6 /* [CP] Check Pods Manifest.lock */, - 6003F586195388D20070C39A /* Sources */, - 6003F587195388D20070C39A /* Frameworks */, - 6003F588195388D20070C39A /* Resources */, - AEAE3DFAF96D6BF95BB0395C /* [CP] Embed Pods Frameworks */, - FAD69C6CC584AB1F1E027745 /* [CP] Copy Pods Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = testapp; - productName = GoogleSignInCpp; - productReference = 6003F58A195388D20070C39A /* testapp.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 6003F582195388D10070C39A /* Project object */ = { - isa = PBXProject; - attributes = { - CLASSPREFIX = ""; - LastUpgradeCheck = 0720; - ORGANIZATIONNAME = Google; - }; - buildConfigurationList = 6003F585195388D10070C39A /* Build configuration list for PBXProject "testapp" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 6003F581195388D10070C39A; - productRefGroup = 6003F58B195388D20070C39A /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 6003F589195388D20070C39A /* testapp */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 6003F588195388D20070C39A /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4C3C7DCF2033BAF60077B58E /* Images.xcassets in Resources */, - 4C3C7DCC2033BACC0077B58E /* LaunchScreen.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3CFAC7B749210A2C53CA2CA6 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-testapp-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - AEAE3DFAF96D6BF95BB0395C /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${SRCROOT}/Pods/Target Support Files/Pods-testapp/Pods-testapp-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/GTMOAuth2/GTMOAuth2.framework", - "${BUILT_PRODUCTS_DIR}/GTMSessionFetcher/GTMSessionFetcher.framework", - "${BUILT_PRODUCTS_DIR}/GoogleToolboxForMac/GoogleToolboxForMac.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GTMOAuth2.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GTMSessionFetcher.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GoogleToolboxForMac.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-testapp/Pods-testapp-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - FAD69C6CC584AB1F1E027745 /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${SRCROOT}/Pods/Target Support Files/Pods-testapp/Pods-testapp-resources.sh", - "${PODS_ROOT}/GoogleSignIn/Resources/GoogleSignIn.bundle", - ); - name = "[CP] Copy Pods Resources"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/GoogleSignIn.bundle", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-testapp/Pods-testapp-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 6003F586195388D20070C39A /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CE59BEF2033B69300A73A92 /* ios_main.mm in Sources */, - 4CE59BEA2033B47E00A73A92 /* common_main.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 6003F5BD195388D20070C39A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.4; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 6003F5BE195388D20070C39A /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.4; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 6003F5C0195388D20070C39A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; - GCC_PRECOMPILE_PREFIX_HEADER = NO; - GCC_PREFIX_HEADER = ""; - INFOPLIST_FILE = "$(SRCROOT)/testapp/Info.plist"; - MODULE_NAME = testapp; - PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = app; - }; - name = Debug; - }; - 6003F5C1195388D20070C39A /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; - GCC_PRECOMPILE_PREFIX_HEADER = NO; - GCC_PREFIX_HEADER = ""; - INFOPLIST_FILE = "$(SRCROOT)/testapp/Info.plist"; - MODULE_NAME = testapp; - PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = app; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 6003F585195388D10070C39A /* Build configuration list for PBXProject "testapp" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 6003F5BD195388D20070C39A /* Debug */, - 6003F5BE195388D20070C39A /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "testapp" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 6003F5C0195388D20070C39A /* Debug */, - 6003F5C1195388D20070C39A /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 6003F582195388D10070C39A /* Project object */; -} diff --git a/staging/native/testapp/testapp.xcodeproj/xcshareddata/xcschemes/testapp.xcscheme b/staging/native/testapp/testapp.xcodeproj/xcshareddata/xcschemes/testapp.xcscheme deleted file mode 100644 index 42407bae..00000000 --- a/staging/native/testapp/testapp.xcodeproj/xcshareddata/xcschemes/testapp.xcscheme +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/staging/native/testapp/testapp/Images.xcassets/AppIcon.appiconset/Contents.json b/staging/native/testapp/testapp/Images.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d8db8d65..00000000 --- a/staging/native/testapp/testapp/Images.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "83.5x83.5", - "scale" : "2x" - }, - { - "idiom" : "ios-marketing", - "size" : "1024x1024", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/staging/native/testapp/testapp/Images.xcassets/LaunchImage.launchimage/Contents.json b/staging/native/testapp/testapp/Images.xcassets/LaunchImage.launchimage/Contents.json deleted file mode 100644 index 6f870a46..00000000 --- a/staging/native/testapp/testapp/Images.xcassets/LaunchImage.launchimage/Contents.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "images" : [ - { - "orientation" : "portrait", - "idiom" : "iphone", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "2x" - }, - { - "orientation" : "portrait", - "idiom" : "iphone", - "subtype" : "retina4", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "2x" - }, - { - "orientation" : "portrait", - "idiom" : "ipad", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "1x" - }, - { - "orientation" : "landscape", - "idiom" : "ipad", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "1x" - }, - { - "orientation" : "portrait", - "idiom" : "ipad", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "2x" - }, - { - "orientation" : "landscape", - "idiom" : "ipad", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/staging/native/testapp/testapp/Info.plist b/staging/native/testapp/testapp/Info.plist deleted file mode 100644 index 7d1be075..00000000 --- a/staging/native/testapp/testapp/Info.plist +++ /dev/null @@ -1,39 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - com.google.ios.signin.testapp - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleURLTypes - - - CFBundleTypeRole - Editor - CFBundleURLName - com.google.ios.signin.testapp - CFBundleURLSchemes - - com.google.ios.signin.testapp - - - - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - -