GPGSUtil.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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, relative to the plugin root directory. This is a generated file.
  77. /// </summary>
  78. private const string GameInfoRelativePath = "GameInfo.cs";
  79. /// <summary>
  80. /// The manifest path, relative to the plugin root directory.
  81. /// </summary>
  82. /// <remarks>The Games SDK requires additional metadata in the AndroidManifest.xml
  83. /// file. </remarks>
  84. private const string ManifestRelativePath =
  85. "../Plugins/Android/GooglePlayGamesManifest.androidlib/AndroidManifest.xml";
  86. private const string RootFolderName = "GooglePlayGames";
  87. /// <summary>
  88. /// The root path of the Google Play Games plugin
  89. /// </summary>
  90. public static string RootPath
  91. {
  92. get
  93. {
  94. if (string.IsNullOrEmpty(mRootPath))
  95. {
  96. string[] dirs = Directory.GetDirectories("Assets", RootFolderName, SearchOption.AllDirectories);
  97. switch (dirs.Length)
  98. {
  99. case 0:
  100. Alert("Plugin error: GooglePlayGames folder was renamed");
  101. throw new Exception("GooglePlayGames folder was renamed");
  102. case 1:
  103. mRootPath = SlashesToPlatformSeparator(dirs[0]);
  104. break;
  105. default:
  106. for (int i = 0; i < dirs.Length; i++)
  107. {
  108. if (File.Exists(SlashesToPlatformSeparator(Path.Combine(dirs[i], GameInfoRelativePath)))
  109. )
  110. {
  111. mRootPath = SlashesToPlatformSeparator(dirs[i]);
  112. break;
  113. }
  114. }
  115. if (string.IsNullOrEmpty(mRootPath))
  116. {
  117. Alert("Plugin error: GooglePlayGames folder was renamed");
  118. throw new Exception("GooglePlayGames folder was renamed");
  119. }
  120. break;
  121. }
  122. }
  123. return mRootPath;
  124. }
  125. }
  126. /// <summary>
  127. /// The game info file path. This is a generated file.
  128. /// </summary>
  129. private static string GameInfoPath
  130. {
  131. get { return SlashesToPlatformSeparator(Path.Combine(RootPath, GameInfoRelativePath)); }
  132. }
  133. /// <summary>
  134. /// The manifest path.
  135. /// </summary>
  136. /// <remarks>The Games SDK requires additional metadata in the AndroidManifest.xml
  137. /// file. </remarks>
  138. private static string ManifestPath
  139. {
  140. get { return SlashesToPlatformSeparator(Path.Combine(RootPath, ManifestRelativePath)); }
  141. }
  142. /// <summary>
  143. /// The root path of the Google Play Games plugin
  144. /// </summary>
  145. private static string mRootPath = "";
  146. /// <summary>
  147. /// The map of replacements for filling in code templates. The
  148. /// key is the string that appears in the template as a placeholder,
  149. /// the value is the key into the GPGSProjectSettings.
  150. /// </summary>
  151. private static Dictionary<string, string> replacements =
  152. new Dictionary<string, string>()
  153. {
  154. // Put this element placeholder first, since it has embedded placeholder
  155. {SERVICEID_ELEMENT_PLACEHOLDER, SERVICEID_ELEMENT_PLACEHOLDER},
  156. {SERVICEIDPLACEHOLDER, SERVICEIDKEY},
  157. {APPIDPLACEHOLDER, APPIDKEY},
  158. {CLASSNAMEPLACEHOLDER, CLASSNAMEKEY},
  159. {WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY},
  160. {PLUGINVERSIONPLACEHOLDER, PLUGINVERSIONKEY},
  161. // Causes the placeholder to be replaced with overridden value at runtime.
  162. {NEARBY_PERMISSIONS_PLACEHOLDER, NEARBY_PERMISSIONS_PLACEHOLDER}
  163. };
  164. /// <summary>
  165. /// Replaces / in file path to be the os specific separator.
  166. /// </summary>
  167. /// <returns>The path.</returns>
  168. /// <param name="path">Path with correct separators.</param>
  169. public static string SlashesToPlatformSeparator(string path)
  170. {
  171. return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
  172. }
  173. /// <summary>
  174. /// Reads the file.
  175. /// </summary>
  176. /// <returns>The file contents. The slashes are corrected.</returns>
  177. /// <param name="filePath">File path.</param>
  178. public static string ReadFile(string filePath)
  179. {
  180. filePath = SlashesToPlatformSeparator(filePath);
  181. if (!File.Exists(filePath))
  182. {
  183. Alert("Plugin error: file not found: " + filePath);
  184. return null;
  185. }
  186. StreamReader sr = new StreamReader(filePath);
  187. string body = sr.ReadToEnd();
  188. sr.Close();
  189. return body;
  190. }
  191. /// <summary>
  192. /// Reads the editor template.
  193. /// </summary>
  194. /// <returns>The editor template contents.</returns>
  195. /// <param name="name">Name of the template in the editor directory.</param>
  196. public static string ReadEditorTemplate(string name)
  197. {
  198. return ReadFile(
  199. Path.Combine(RootPath, string.Format("Editor{0}{1}.txt", Path.DirectorySeparatorChar, name)));
  200. }
  201. /// <summary>
  202. /// Writes the file.
  203. /// </summary>
  204. /// <param name="file">File path - the slashes will be corrected.</param>
  205. /// <param name="body">Body of the file to write.</param>
  206. public static void WriteFile(string file, string body)
  207. {
  208. file = SlashesToPlatformSeparator(file);
  209. DirectoryInfo dir = Directory.GetParent(file);
  210. dir.Create();
  211. using (var wr = new StreamWriter(file, false))
  212. {
  213. wr.Write(body);
  214. }
  215. }
  216. /// <summary>
  217. /// Validates the string to be a valid nearby service id.
  218. /// </summary>
  219. /// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns>
  220. /// <param name="s">string to test.</param>
  221. public static bool LooksLikeValidServiceId(string s)
  222. {
  223. if (s.Length < 3)
  224. {
  225. return false;
  226. }
  227. foreach (char c in s)
  228. {
  229. if (!char.IsLetterOrDigit(c) && c != '.')
  230. {
  231. return false;
  232. }
  233. }
  234. return true;
  235. }
  236. /// <summary>
  237. /// Looks the like valid app identifier.
  238. /// </summary>
  239. /// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns>
  240. /// <param name="s">the string to test.</param>
  241. public static bool LooksLikeValidAppId(string s)
  242. {
  243. if (s.Length < 5)
  244. {
  245. return false;
  246. }
  247. foreach (char c in s)
  248. {
  249. if (c < '0' || c > '9')
  250. {
  251. return false;
  252. }
  253. }
  254. return true;
  255. }
  256. /// <summary>
  257. /// Looks the like valid client identifier.
  258. /// </summary>
  259. /// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns>
  260. /// <param name="s">the string to test.</param>
  261. public static bool LooksLikeValidClientId(string s)
  262. {
  263. return s.EndsWith(".googleusercontent.com");
  264. }
  265. /// <summary>
  266. /// Looks the like a valid bundle identifier.
  267. /// </summary>
  268. /// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns>
  269. /// <param name="s">the string to test.</param>
  270. public static bool LooksLikeValidBundleId(string s)
  271. {
  272. return s.Length > 3;
  273. }
  274. /// <summary>
  275. /// Looks like a valid package.
  276. /// </summary>
  277. /// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns>
  278. /// <param name="s">the string to test.</param>
  279. public static bool LooksLikeValidPackageName(string s)
  280. {
  281. if (string.IsNullOrEmpty(s))
  282. {
  283. throw new Exception("cannot be empty");
  284. }
  285. string[] parts = s.Split(new char[] {'.'});
  286. foreach (string p in parts)
  287. {
  288. char[] bytes = p.ToCharArray();
  289. for (int i = 0; i < bytes.Length; i++)
  290. {
  291. if (i == 0 && !char.IsLetter(bytes[i]))
  292. {
  293. throw new Exception("each part must start with a letter");
  294. }
  295. else if (char.IsWhiteSpace(bytes[i]))
  296. {
  297. throw new Exception("cannot contain spaces");
  298. }
  299. else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_')
  300. {
  301. throw new Exception("must be alphanumeric or _");
  302. }
  303. }
  304. }
  305. return parts.Length >= 1;
  306. }
  307. /// <summary>
  308. /// Determines if is setup done.
  309. /// </summary>
  310. /// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns>
  311. public static bool IsSetupDone()
  312. {
  313. bool doneSetup = true;
  314. #if UNITY_ANDROID
  315. doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false);
  316. // check gameinfo
  317. if (File.Exists(GameInfoPath))
  318. {
  319. string contents = ReadFile(GameInfoPath);
  320. if (contents.Contains(APPIDPLACEHOLDER))
  321. {
  322. Debug.Log("GameInfo not initialized with AppId. " +
  323. "Run Window > Google Play Games > Setup > Android Setup...");
  324. return false;
  325. }
  326. }
  327. else
  328. {
  329. Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup...");
  330. return false;
  331. }
  332. #endif
  333. return doneSetup;
  334. }
  335. /// <summary>
  336. /// Makes legal identifier from string.
  337. /// Returns a legal C# identifier from the given string. The transformations are:
  338. /// - spaces => underscore _
  339. /// - punctuation => empty string
  340. /// - leading numbers are prefixed with underscore.
  341. /// </summary>
  342. /// <returns>the id</returns>
  343. /// <param name="key">Key to convert to an identifier.</param>
  344. public static string MakeIdentifier(string key)
  345. {
  346. string s;
  347. string retval = string.Empty;
  348. if (string.IsNullOrEmpty(key))
  349. {
  350. return "_";
  351. }
  352. s = key.Trim().Replace(' ', '_');
  353. foreach (char c in s)
  354. {
  355. if (char.IsLetterOrDigit(c) || c == '_')
  356. {
  357. retval += c;
  358. }
  359. }
  360. return retval;
  361. }
  362. /// <summary>
  363. /// Displays an error dialog.
  364. /// </summary>
  365. /// <param name="s">the message</param>
  366. public static void Alert(string s)
  367. {
  368. Alert(GPGSStrings.Error, s);
  369. }
  370. /// <summary>
  371. /// Displays a dialog with the given title and message.
  372. /// </summary>
  373. /// <param name="title">the title.</param>
  374. /// <param name="message">the message.</param>
  375. public static void Alert(string title, string message)
  376. {
  377. EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok);
  378. }
  379. /// <summary>
  380. /// Gets the android sdk path.
  381. /// </summary>
  382. /// <returns>The android sdk path.</returns>
  383. public static string GetAndroidSdkPath()
  384. {
  385. string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
  386. #if UNITY_2019_1_OR_NEWER
  387. // Unity 2019.x added installation of the Android SDK in the AndroidPlayer directory
  388. // so fallback to searching for it there.
  389. if (string.IsNullOrEmpty(sdkPath) || EditorPrefs.GetBool("SdkUseEmbedded"))
  390. {
  391. string androidPlayerDir = BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.Android, BuildOptions.None);
  392. if (!string.IsNullOrEmpty(androidPlayerDir))
  393. {
  394. string androidPlayerSdkDir = Path.Combine(androidPlayerDir, "SDK");
  395. if (Directory.Exists(androidPlayerSdkDir))
  396. {
  397. sdkPath = androidPlayerSdkDir;
  398. }
  399. }
  400. }
  401. #endif
  402. if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\")))
  403. {
  404. sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
  405. }
  406. return sdkPath;
  407. }
  408. /// <summary>
  409. /// Determines if the android sdk exists.
  410. /// </summary>
  411. /// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns>
  412. public static bool HasAndroidSdk()
  413. {
  414. string sdkPath = GetAndroidSdkPath();
  415. return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath);
  416. }
  417. /// <summary>
  418. /// Gets the unity major version.
  419. /// </summary>
  420. /// <returns>The unity major version.</returns>
  421. public static int GetUnityMajorVersion()
  422. {
  423. #if UNITY_5
  424. string majorVersion = Application.unityVersion.Split('.')[0];
  425. int ver;
  426. if (!int.TryParse(majorVersion, out ver))
  427. {
  428. ver = 0;
  429. }
  430. return ver;
  431. #elif UNITY_4_6
  432. return 4;
  433. #else
  434. return 0;
  435. #endif
  436. }
  437. /// <summary>
  438. /// Checks for the android manifest file exsistance.
  439. /// </summary>
  440. /// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns>
  441. public static bool AndroidManifestExists()
  442. {
  443. string destFilename = ManifestPath;
  444. return File.Exists(destFilename);
  445. }
  446. /// <summary>
  447. /// Generates the android manifest.
  448. /// </summary>
  449. public static void GenerateAndroidManifest()
  450. {
  451. string destFilename = ManifestPath;
  452. // Generate AndroidManifest.xml
  453. string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest");
  454. Dictionary<string, string> overrideValues =
  455. new Dictionary<string, string>();
  456. if (!string.IsNullOrEmpty(GPGSProjectSettings.Instance.Get(SERVICEIDKEY)))
  457. {
  458. overrideValues[NEARBY_PERMISSIONS_PLACEHOLDER] =
  459. " <!-- Required for Nearby Connections -->\n" +
  460. " <uses-permission android:name=\"android.permission.BLUETOOTH\" />\n" +
  461. " <uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\" />\n" +
  462. " <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />\n" +
  463. " <uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\n" +
  464. " <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n";
  465. overrideValues[SERVICEID_ELEMENT_PLACEHOLDER] =
  466. " <!-- Required for Nearby Connections API -->\n" +
  467. " <meta-data android:name=\"com.google.android.gms.nearby.connection.SERVICE_ID\"\n" +
  468. " android:value=\"__NEARBY_SERVICE_ID__\" />\n";
  469. }
  470. else
  471. {
  472. overrideValues[NEARBY_PERMISSIONS_PLACEHOLDER] = "";
  473. overrideValues[SERVICEID_ELEMENT_PLACEHOLDER] = "";
  474. }
  475. foreach (KeyValuePair<string, string> ent in replacements)
  476. {
  477. string value =
  478. GPGSProjectSettings.Instance.Get(ent.Value, overrideValues);
  479. manifestBody = manifestBody.Replace(ent.Key, value);
  480. }
  481. GPGSUtil.WriteFile(destFilename, manifestBody);
  482. GPGSUtil.UpdateGameInfo();
  483. }
  484. /// <summary>
  485. /// Writes the resource identifiers file. This file contains the
  486. /// resource ids copied (downloaded?) from the play game app console.
  487. /// </summary>
  488. /// <param name="classDirectory">Class directory.</param>
  489. /// <param name="className">Class name.</param>
  490. /// <param name="resourceKeys">Resource keys.</param>
  491. public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys)
  492. {
  493. string constantsValues = string.Empty;
  494. string[] parts = className.Split('.');
  495. string dirName = classDirectory;
  496. if (string.IsNullOrEmpty(dirName))
  497. {
  498. dirName = "Assets";
  499. }
  500. string nameSpace = string.Empty;
  501. for (int i = 0; i < parts.Length - 1; i++)
  502. {
  503. dirName += "/" + parts[i];
  504. if (nameSpace != string.Empty)
  505. {
  506. nameSpace += ".";
  507. }
  508. nameSpace += parts[i];
  509. }
  510. EnsureDirExists(dirName);
  511. foreach (DictionaryEntry ent in resourceKeys)
  512. {
  513. string key = MakeIdentifier((string) ent.Key);
  514. constantsValues += " public const string " +
  515. key + " = \"" + ent.Value + "\"; // <GPGSID>\n";
  516. }
  517. string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants");
  518. if (nameSpace != string.Empty)
  519. {
  520. fileBody = fileBody.Replace(
  521. NAMESPACESTARTPLACEHOLDER,
  522. "namespace " + nameSpace + "\n{");
  523. }
  524. else
  525. {
  526. fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty);
  527. }
  528. fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]);
  529. fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues);
  530. if (nameSpace != string.Empty)
  531. {
  532. fileBody = fileBody.Replace(
  533. NAMESPACEENDPLACEHOLDER,
  534. "}");
  535. }
  536. else
  537. {
  538. fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty);
  539. }
  540. WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody);
  541. }
  542. /// <summary>
  543. /// Updates the game info file. This is a generated file containing the
  544. /// app and client ids.
  545. /// </summary>
  546. public static void UpdateGameInfo()
  547. {
  548. string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo");
  549. foreach (KeyValuePair<string, string> ent in replacements)
  550. {
  551. string value =
  552. GPGSProjectSettings.Instance.Get(ent.Value);
  553. fileBody = fileBody.Replace(ent.Key, value);
  554. }
  555. GPGSUtil.WriteFile(GameInfoPath, fileBody);
  556. }
  557. /// <summary>
  558. /// Checks the dependencies file and fixes repository paths
  559. /// if they are incorrect (for example if the user moved plugin
  560. /// into some subdirectory). This is a generated file containing
  561. /// the list of dependencies that are needed for the plugin to work.
  562. /// </summary>
  563. public static void CheckAndFixDependencies()
  564. {
  565. string depPath =
  566. SlashesToPlatformSeparator(Path.Combine(GPGSUtil.RootPath,
  567. "Editor/GooglePlayGamesPluginDependencies.xml"));
  568. XmlDocument doc = new XmlDocument();
  569. doc.Load(depPath);
  570. XmlNodeList repos = doc.SelectNodes("//androidPackage[contains(@spec,'com.google.games')]//repository");
  571. foreach (XmlNode repo in repos)
  572. {
  573. if (!Directory.Exists(repo.InnerText))
  574. {
  575. int pos = repo.InnerText.IndexOf(RootFolderName);
  576. if (pos != -1)
  577. {
  578. repo.InnerText =
  579. Path.Combine(RootPath, repo.InnerText.Substring(pos + RootFolderName.Length + 1))
  580. .Replace("\\", "/");
  581. }
  582. }
  583. }
  584. doc.Save(depPath);
  585. }
  586. /// <summary>
  587. /// Checks the file containing the list of versioned assets and fixes
  588. /// paths to them if they are incorrect (for example if the user moved
  589. /// plugin into some subdirectory). This is a generated file.
  590. /// </summary>
  591. public static void CheckAndFixVersionedAssestsPaths()
  592. {
  593. string[] foundPaths =
  594. Directory.GetFiles(RootPath, "GooglePlayGamesPlugin_v*.txt", SearchOption.AllDirectories);
  595. if (foundPaths.Length == 1)
  596. {
  597. string tmpFilePath = Path.GetTempFileName();
  598. StreamWriter writer = new StreamWriter(tmpFilePath);
  599. using (StreamReader reader = new StreamReader(foundPaths[0]))
  600. {
  601. string assetPath;
  602. while ((assetPath = reader.ReadLine()) != null)
  603. {
  604. int pos = assetPath.IndexOf(RootFolderName);
  605. if (pos != -1)
  606. {
  607. assetPath = Path.Combine(RootPath, assetPath.Substring(pos + RootFolderName.Length + 1))
  608. .Replace("\\", "/");
  609. }
  610. writer.WriteLine(assetPath);
  611. }
  612. }
  613. writer.Flush();
  614. writer.Close();
  615. try
  616. {
  617. File.Copy(tmpFilePath, foundPaths[0], true);
  618. }
  619. finally
  620. {
  621. File.Delete(tmpFilePath);
  622. }
  623. }
  624. }
  625. /// <summary>
  626. /// Ensures the dir exists.
  627. /// </summary>
  628. /// <param name="dir">Directory to check.</param>
  629. public static void EnsureDirExists(string dir)
  630. {
  631. dir = SlashesToPlatformSeparator(dir);
  632. if (!Directory.Exists(dir))
  633. {
  634. Directory.CreateDirectory(dir);
  635. }
  636. }
  637. /// <summary>
  638. /// Deletes the dir if exists.
  639. /// </summary>
  640. /// <param name="dir">Directory to delete.</param>
  641. public static void DeleteDirIfExists(string dir)
  642. {
  643. dir = SlashesToPlatformSeparator(dir);
  644. if (Directory.Exists(dir))
  645. {
  646. Directory.Delete(dir, true);
  647. }
  648. }
  649. /// <summary>
  650. /// Gets the Google Play Services library version. This is only
  651. /// needed for Unity versions less than 5.
  652. /// </summary>
  653. /// <returns>The GPS version.</returns>
  654. /// <param name="libProjPath">Lib proj path.</param>
  655. private static int GetGPSVersion(string libProjPath)
  656. {
  657. string versionFile = libProjPath + "/res/values/version.xml";
  658. XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile));
  659. bool inResource = false;
  660. int version = -1;
  661. while (reader.Read())
  662. {
  663. if (reader.Name == "resources")
  664. {
  665. inResource = true;
  666. }
  667. if (inResource && reader.Name == "integer")
  668. {
  669. if ("google_play_services_version".Equals(
  670. reader.GetAttribute("name")))
  671. {
  672. reader.Read();
  673. Debug.Log("Read version string: " + reader.Value);
  674. version = Convert.ToInt32(reader.Value);
  675. }
  676. }
  677. }
  678. reader.Close();
  679. return version;
  680. }
  681. }
  682. }