GPGSUtil.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. // <copyright file="GPGSUtil.cs" company="Google Inc.">
  2. // Copyright (C) 2014 Google Inc. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // </copyright>
  16. // Keep this even on unsupported configurations.
  17. namespace GooglePlayGames.Editor
  18. {
  19. using System;
  20. using System.Collections;
  21. using System.Collections.Generic;
  22. using System.IO;
  23. using System.Xml;
  24. using UnityEditor;
  25. using UnityEngine;
  26. /// <summary>
  27. /// Utility class to perform various tasks in the editor.
  28. /// </summary>
  29. public static class GPGSUtil
  30. {
  31. /// <summary>Property key for project settings.</summary>
  32. public const string SERVICEIDKEY = "App.NearbdServiceId";
  33. /// <summary>Property key for project settings.</summary>
  34. public const string APPIDKEY = "proj.AppId";
  35. /// <summary>Property key for project settings.</summary>
  36. public const string CLASSDIRECTORYKEY = "proj.classDir";
  37. /// <summary>Property key for project settings.</summary>
  38. public const string CLASSNAMEKEY = "proj.ConstantsClassName";
  39. /// <summary>Property key for project settings.</summary>
  40. public const string WEBCLIENTIDKEY = "and.ClientId";
  41. /// <summary>Property key for project settings.</summary>
  42. public const string ANDROIDRESOURCEKEY = "and.ResourceData";
  43. /// <summary>Property key for project settings.</summary>
  44. public const string ANDROIDSETUPDONEKEY = "android.SetupDone";
  45. /// <summary>Property key for project settings.</summary>
  46. public const string ANDROIDBUNDLEIDKEY = "and.BundleId";
  47. /// <summary>Property key for plugin version.</summary>
  48. public const string PLUGINVERSIONKEY = "proj.pluginVersion";
  49. /// <summary>Property key for nearby settings done.</summary>
  50. public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone";
  51. /// <summary>Property key for project settings.</summary>
  52. public const string LASTUPGRADEKEY = "lastUpgrade";
  53. /// <summary>Constant for token replacement</summary>
  54. private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__";
  55. private const string SERVICEID_ELEMENT_PLACEHOLDER = "__NEARBY_SERVICE_ELEMENT__";
  56. private const string NEARBY_PERMISSIONS_PLACEHOLDER = "__NEARBY_PERMISSIONS__";
  57. /// <summary>Constant for token replacement</summary>
  58. private const string APPIDPLACEHOLDER = "__APP_ID__";
  59. /// <summary>Constant for token replacement</summary>
  60. private const string CLASSNAMEPLACEHOLDER = "__Class__";
  61. /// <summary>Constant for token replacement</summary>
  62. private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__";
  63. /// <summary>Constant for token replacement</summary>
  64. private const string PLUGINVERSIONPLACEHOLDER = "__PLUGIN_VERSION__";
  65. /// <summary>Constant for require google plus token replacement</summary>
  66. private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__";
  67. /// <summary>Property key for project settings.</summary>
  68. private const string TOKENPERMISSIONKEY = "proj.tokenPermissions";
  69. /// <summary>Constant for token replacement</summary>
  70. private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__";
  71. /// <summary>Constant for token replacement</summary>
  72. private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__";
  73. /// <summary>Constant for token replacement</summary>
  74. private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__";
  75. /// <summary>
  76. /// The game info file path. This is a generated file.
  77. /// </summary>
  78. private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs";
  79. /// <summary>
  80. /// The manifest path.
  81. /// </summary>
  82. /// <remarks>The Games SDK requires additional metadata in the AndroidManifest.xml
  83. /// file. </remarks>
  84. private const string ManifestPath =
  85. "Assets/GooglePlayGames/Plugins/Android/GooglePlayGamesManifest.plugin/AndroidManifest.xml";
  86. /// <summary>
  87. /// The map of replacements for filling in code templates. The
  88. /// key is the string that appears in the template as a placeholder,
  89. /// the value is the key into the GPGSProjectSettings.
  90. /// </summary>
  91. private static Dictionary<string, string> replacements =
  92. new Dictionary<string, string>()
  93. {
  94. // Put this element placeholder first, since it has embedded placeholder
  95. {SERVICEID_ELEMENT_PLACEHOLDER, SERVICEID_ELEMENT_PLACEHOLDER},
  96. { SERVICEIDPLACEHOLDER, SERVICEIDKEY },
  97. { APPIDPLACEHOLDER, APPIDKEY },
  98. { CLASSNAMEPLACEHOLDER, CLASSNAMEKEY },
  99. { WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY },
  100. { PLUGINVERSIONPLACEHOLDER, PLUGINVERSIONKEY},
  101. // Causes the placeholder to be replaced with overridden value at runtime.
  102. { NEARBY_PERMISSIONS_PLACEHOLDER, NEARBY_PERMISSIONS_PLACEHOLDER}
  103. };
  104. /// <summary>
  105. /// Replaces / in file path to be the os specific separator.
  106. /// </summary>
  107. /// <returns>The path.</returns>
  108. /// <param name="path">Path with correct separators.</param>
  109. public static string SlashesToPlatformSeparator(string path)
  110. {
  111. return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
  112. }
  113. /// <summary>
  114. /// Reads the file.
  115. /// </summary>
  116. /// <returns>The file contents. The slashes are corrected.</returns>
  117. /// <param name="filePath">File path.</param>
  118. public static string ReadFile(string filePath)
  119. {
  120. filePath = SlashesToPlatformSeparator(filePath);
  121. if (!File.Exists(filePath))
  122. {
  123. Alert("Plugin error: file not found: " + filePath);
  124. return null;
  125. }
  126. StreamReader sr = new StreamReader(filePath);
  127. string body = sr.ReadToEnd();
  128. sr.Close();
  129. return body;
  130. }
  131. /// <summary>
  132. /// Reads the editor template.
  133. /// </summary>
  134. /// <returns>The editor template contents.</returns>
  135. /// <param name="name">Name of the template in the editor directory.</param>
  136. public static string ReadEditorTemplate(string name)
  137. {
  138. return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt"));
  139. }
  140. /// <summary>
  141. /// Writes the file.
  142. /// </summary>
  143. /// <param name="file">File path - the slashes will be corrected.</param>
  144. /// <param name="body">Body of the file to write.</param>
  145. public static void WriteFile(string file, string body)
  146. {
  147. file = SlashesToPlatformSeparator(file);
  148. using (var wr = new StreamWriter(file, false))
  149. {
  150. wr.Write(body);
  151. }
  152. }
  153. /// <summary>
  154. /// Validates the string to be a valid nearby service id.
  155. /// </summary>
  156. /// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns>
  157. /// <param name="s">string to test.</param>
  158. public static bool LooksLikeValidServiceId(string s)
  159. {
  160. if (s.Length < 3)
  161. {
  162. return false;
  163. }
  164. foreach (char c in s)
  165. {
  166. if (!char.IsLetterOrDigit(c) && c != '.')
  167. {
  168. return false;
  169. }
  170. }
  171. return true;
  172. }
  173. /// <summary>
  174. /// Looks the like valid app identifier.
  175. /// </summary>
  176. /// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns>
  177. /// <param name="s">the string to test.</param>
  178. public static bool LooksLikeValidAppId(string s)
  179. {
  180. if (s.Length < 5)
  181. {
  182. return false;
  183. }
  184. foreach (char c in s)
  185. {
  186. if (c < '0' || c > '9')
  187. {
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. /// <summary>
  194. /// Looks the like valid client identifier.
  195. /// </summary>
  196. /// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns>
  197. /// <param name="s">the string to test.</param>
  198. public static bool LooksLikeValidClientId(string s)
  199. {
  200. return s.EndsWith(".googleusercontent.com");
  201. }
  202. /// <summary>
  203. /// Looks the like a valid bundle identifier.
  204. /// </summary>
  205. /// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns>
  206. /// <param name="s">the string to test.</param>
  207. public static bool LooksLikeValidBundleId(string s)
  208. {
  209. return s.Length > 3;
  210. }
  211. /// <summary>
  212. /// Looks like a valid package.
  213. /// </summary>
  214. /// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns>
  215. /// <param name="s">the string to test.</param>
  216. public static bool LooksLikeValidPackageName(string s)
  217. {
  218. if (string.IsNullOrEmpty(s))
  219. {
  220. throw new Exception("cannot be empty");
  221. }
  222. string[] parts = s.Split(new char[] { '.' });
  223. foreach (string p in parts)
  224. {
  225. char[] bytes = p.ToCharArray();
  226. for (int i = 0; i < bytes.Length; i++)
  227. {
  228. if (i == 0 && !char.IsLetter(bytes[i]))
  229. {
  230. throw new Exception("each part must start with a letter");
  231. }
  232. else if (char.IsWhiteSpace(bytes[i]))
  233. {
  234. throw new Exception("cannot contain spaces");
  235. }
  236. else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_')
  237. {
  238. throw new Exception("must be alphanumeric or _");
  239. }
  240. }
  241. }
  242. return parts.Length >= 1;
  243. }
  244. /// <summary>
  245. /// Determines if is setup done.
  246. /// </summary>
  247. /// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns>
  248. public static bool IsSetupDone()
  249. {
  250. bool doneSetup = true;
  251. #if UNITY_ANDROID
  252. doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false);
  253. // check gameinfo
  254. if (File.Exists(GameInfoPath))
  255. {
  256. string contents = ReadFile(GameInfoPath);
  257. if (contents.Contains(APPIDPLACEHOLDER))
  258. {
  259. Debug.Log("GameInfo not initialized with AppId. " +
  260. "Run Window > Google Play Games > Setup > Android Setup...");
  261. return false;
  262. }
  263. }
  264. else
  265. {
  266. Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup...");
  267. return false;
  268. }
  269. #endif
  270. return doneSetup;
  271. }
  272. /// <summary>
  273. /// Makes legal identifier from string.
  274. /// Returns a legal C# identifier from the given string. The transformations are:
  275. /// - spaces => underscore _
  276. /// - punctuation => empty string
  277. /// - leading numbers are prefixed with underscore.
  278. /// </summary>
  279. /// <returns>the id</returns>
  280. /// <param name="key">Key to convert to an identifier.</param>
  281. public static string MakeIdentifier(string key)
  282. {
  283. string s;
  284. string retval = string.Empty;
  285. if (string.IsNullOrEmpty(key))
  286. {
  287. return "_";
  288. }
  289. s = key.Trim().Replace(' ', '_');
  290. foreach (char c in s)
  291. {
  292. if (char.IsLetterOrDigit(c) || c == '_')
  293. {
  294. retval += c;
  295. }
  296. }
  297. return retval;
  298. }
  299. /// <summary>
  300. /// Displays an error dialog.
  301. /// </summary>
  302. /// <param name="s">the message</param>
  303. public static void Alert(string s)
  304. {
  305. Alert(GPGSStrings.Error, s);
  306. }
  307. /// <summary>
  308. /// Displays a dialog with the given title and message.
  309. /// </summary>
  310. /// <param name="title">the title.</param>
  311. /// <param name="message">the message.</param>
  312. public static void Alert(string title, string message)
  313. {
  314. EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok);
  315. }
  316. /// <summary>
  317. /// Gets the android sdk path.
  318. /// </summary>
  319. /// <returns>The android sdk path.</returns>
  320. public static string GetAndroidSdkPath()
  321. {
  322. string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
  323. if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\")))
  324. {
  325. sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
  326. }
  327. return sdkPath;
  328. }
  329. /// <summary>
  330. /// Determines if the android sdk exists.
  331. /// </summary>
  332. /// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns>
  333. public static bool HasAndroidSdk()
  334. {
  335. string sdkPath = GetAndroidSdkPath();
  336. return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath);
  337. }
  338. /// <summary>
  339. /// Gets the unity major version.
  340. /// </summary>
  341. /// <returns>The unity major version.</returns>
  342. public static int GetUnityMajorVersion()
  343. {
  344. #if UNITY_5
  345. string majorVersion = Application.unityVersion.Split('.')[0];
  346. int ver;
  347. if (!int.TryParse(majorVersion, out ver))
  348. {
  349. ver = 0;
  350. }
  351. return ver;
  352. #elif UNITY_4_6
  353. return 4;
  354. #else
  355. return 0;
  356. #endif
  357. }
  358. /// <summary>
  359. /// Checks for the android manifest file exsistance.
  360. /// </summary>
  361. /// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns>
  362. public static bool AndroidManifestExists()
  363. {
  364. string destFilename = GPGSUtil.SlashesToPlatformSeparator(ManifestPath);
  365. return File.Exists(destFilename);
  366. }
  367. /// <summary>
  368. /// Generates the android manifest.
  369. /// </summary>
  370. public static void GenerateAndroidManifest()
  371. {
  372. string destFilename = GPGSUtil.SlashesToPlatformSeparator(ManifestPath);
  373. // Generate AndroidManifest.xml
  374. string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest");
  375. Dictionary<string, string> overrideValues =
  376. new Dictionary<string, string>();
  377. if (!string.IsNullOrEmpty (GPGSProjectSettings.Instance.Get (SERVICEIDKEY)))
  378. {
  379. overrideValues [NEARBY_PERMISSIONS_PLACEHOLDER] =
  380. " <!-- Required for Nearby Connections -->\n" +
  381. " <uses-permission android:name=\"android.permission.BLUETOOTH\" />\n" +
  382. " <uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\" />\n" +
  383. " <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />\n" +
  384. " <uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\n" +
  385. " <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n";
  386. overrideValues [SERVICEID_ELEMENT_PLACEHOLDER] =
  387. " <!-- Required for Nearby Connections API -->\n" +
  388. " <meta-data android:name=\"com.google.android.gms.nearby.connection.SERVICE_ID\"\n" +
  389. " android:value=\"__NEARBY_SERVICE_ID__\" />\n";
  390. }
  391. else
  392. {
  393. overrideValues [NEARBY_PERMISSIONS_PLACEHOLDER] = "";
  394. overrideValues [SERVICEID_ELEMENT_PLACEHOLDER] = "";
  395. }
  396. foreach (KeyValuePair<string, string> ent in replacements)
  397. {
  398. string value =
  399. GPGSProjectSettings.Instance.Get(ent.Value, overrideValues);
  400. manifestBody = manifestBody.Replace(ent.Key, value);
  401. }
  402. GPGSUtil.WriteFile(destFilename, manifestBody);
  403. GPGSUtil.UpdateGameInfo();
  404. }
  405. /// <summary>
  406. /// Writes the resource identifiers file. This file contains the
  407. /// resource ids copied (downloaded?) from the play game app console.
  408. /// </summary>
  409. /// <param name="classDirectory">Class directory.</param>
  410. /// <param name="className">Class name.</param>
  411. /// <param name="resourceKeys">Resource keys.</param>
  412. public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys)
  413. {
  414. string constantsValues = string.Empty;
  415. string[] parts = className.Split('.');
  416. string dirName = classDirectory;
  417. if (string.IsNullOrEmpty(dirName))
  418. {
  419. dirName = "Assets";
  420. }
  421. string nameSpace = string.Empty;
  422. for (int i = 0; i < parts.Length - 1; i++)
  423. {
  424. dirName += "/" + parts[i];
  425. if (nameSpace != string.Empty)
  426. {
  427. nameSpace += ".";
  428. }
  429. nameSpace += parts[i];
  430. }
  431. EnsureDirExists(dirName);
  432. foreach (DictionaryEntry ent in resourceKeys)
  433. {
  434. string key = MakeIdentifier((string)ent.Key);
  435. constantsValues += " public const string " +
  436. key + " = \"" + ent.Value + "\"; // <GPGSID>\n";
  437. }
  438. string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants");
  439. if (nameSpace != string.Empty)
  440. {
  441. fileBody = fileBody.Replace(
  442. NAMESPACESTARTPLACEHOLDER,
  443. "namespace " + nameSpace + "\n{");
  444. }
  445. else
  446. {
  447. fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty);
  448. }
  449. fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]);
  450. fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues);
  451. if (nameSpace != string.Empty)
  452. {
  453. fileBody = fileBody.Replace(
  454. NAMESPACEENDPLACEHOLDER,
  455. "}");
  456. }
  457. else
  458. {
  459. fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty);
  460. }
  461. WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody);
  462. }
  463. /// <summary>
  464. /// Updates the game info file. This is a generated file containing the
  465. /// app and client ids.
  466. /// </summary>
  467. public static void UpdateGameInfo()
  468. {
  469. string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo");
  470. foreach (KeyValuePair<string, string> ent in replacements)
  471. {
  472. string value =
  473. GPGSProjectSettings.Instance.Get(ent.Value);
  474. fileBody = fileBody.Replace(ent.Key, value);
  475. }
  476. GPGSUtil.WriteFile(GameInfoPath, fileBody);
  477. }
  478. /// <summary>
  479. /// Ensures the dir exists.
  480. /// </summary>
  481. /// <param name="dir">Directory to check.</param>
  482. public static void EnsureDirExists(string dir)
  483. {
  484. dir = SlashesToPlatformSeparator(dir);
  485. if (!Directory.Exists(dir))
  486. {
  487. Directory.CreateDirectory(dir);
  488. }
  489. }
  490. /// <summary>
  491. /// Deletes the dir if exists.
  492. /// </summary>
  493. /// <param name="dir">Directory to delete.</param>
  494. public static void DeleteDirIfExists(string dir)
  495. {
  496. dir = SlashesToPlatformSeparator(dir);
  497. if (Directory.Exists(dir))
  498. {
  499. Directory.Delete(dir, true);
  500. }
  501. }
  502. /// <summary>
  503. /// Gets the Google Play Services library version. This is only
  504. /// needed for Unity versions less than 5.
  505. /// </summary>
  506. /// <returns>The GPS version.</returns>
  507. /// <param name="libProjPath">Lib proj path.</param>
  508. private static int GetGPSVersion(string libProjPath)
  509. {
  510. string versionFile = libProjPath + "/res/values/version.xml";
  511. XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile));
  512. bool inResource = false;
  513. int version = -1;
  514. while (reader.Read())
  515. {
  516. if (reader.Name == "resources")
  517. {
  518. inResource = true;
  519. }
  520. if (inResource && reader.Name == "integer")
  521. {
  522. if ("google_play_services_version".Equals(
  523. reader.GetAttribute("name")))
  524. {
  525. reader.Read();
  526. Debug.Log("Read version string: " + reader.Value);
  527. version = Convert.ToInt32(reader.Value);
  528. }
  529. }
  530. }
  531. reader.Close();
  532. return version;
  533. }
  534. }
  535. }