private MessageType ConvertMessageType(Settings.MessageTypes msgType)
 {
     switch (msgType)
     {
         case Settings.MessageTypes.Error:
             return MessageType.Error;
         case Settings.MessageTypes.Info:
             return MessageType.Info;
         case Settings.MessageTypes.Warning:
             return MessageType.Warning;
         default:
             return MessageType.None;
     }
 }
        private static void InitAPI()
        {
            try
            {
                _settings = (Settings)Resources.Load("GameAnalytics/Settings", typeof(Settings));

                #if UNITY_EDITOR
                if(_settings == null)
                {
                    //If the settings asset doesn't exist, then create it. We require a resources folder
                    if(!Directory.Exists(Application.dataPath + "/Resources"))
                    {
                        Directory.CreateDirectory(Application.dataPath + "/Resources");
                    }
                    if(!Directory.Exists(Application.dataPath + "/Resources/GameAnalytics"))
                    {
                        Directory.CreateDirectory(Application.dataPath + "/Resources/GameAnalytics");
                        Debug.LogWarning("GameAnalytics: Resources/GameAnalytics folder is required to store settings. it was created ");
                    }

                    var asset = ScriptableObject.CreateInstance<Settings>();
                    //some hack to mave the asset around
                    string path = AssetDatabase.GetAssetPath(Selection.activeObject);
                    if(path == "")
                    {
                        path = "Assets";
                    }
                    else if(Path.GetExtension(path) != "")
                    {
                        path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
                    }
                    string uniquePath = AssetDatabase.GenerateUniqueAssetPath("Assets/Resources/GameAnalytics/Settings.asset");
                    AssetDatabase.CreateAsset(asset, uniquePath);
                    if(uniquePath != "Assets/Resources/GameAnalytics/Settings.asset")
                    {
                        Debug.LogWarning("GameAnalytics: The path Assets/Resources/GameAnalytics/Settings.asset used to save the settings file is not available.");
                    }
                    AssetDatabase.SaveAssets();
                    Debug.LogWarning("GameAnalytics: Settings file didn't exist and was created");
                    Selection.activeObject = asset;

                    //save reference
                    _settings =	asset;
                }
                #endif
            }
            catch(System.Exception e)
            {
                Debug.Log("Error getting Settings in InitAPI: " + e.Message);
            }
        }
示例#3
0
        private static void InitAPI()
        {
            try
            {
                _settings = (Settings)Resources.Load("GameAnalytics/Settings", typeof(Settings));

                #if UNITY_EDITOR
                if(_settings == null)
                {
                    //If the settings asset doesn't exist, then create it. We require a resources folder
                    if(!Directory.Exists(Application.dataPath + "/Resources"))
                    {
                        Directory.CreateDirectory(Application.dataPath + "/Resources");
                    }
                    if(!Directory.Exists(Application.dataPath + "/Resources/GameAnalytics"))
                    {
                        Directory.CreateDirectory(Application.dataPath + "/Resources/GameAnalytics");
                        Debug.LogWarning("GameAnalytics: Resources/GameAnalytics folder is required to store settings. it was created ");
                    }

                    const string path = "Assets/Resources/GameAnalytics/Settings.asset";

                    if(File.Exists(path))
                    {
                        AssetDatabase.DeleteAsset(path);
                        AssetDatabase.Refresh();
                    }

                    var asset = ScriptableObject.CreateInstance<Settings>();
                    AssetDatabase.CreateAsset(asset, path);
                    AssetDatabase.Refresh();

                    AssetDatabase.SaveAssets();
                    Debug.LogWarning("GameAnalytics: Settings file didn't exist and was created");
                    Selection.activeObject = asset;

                    //save reference
                    _settings =	asset;
                }
                #endif
            }
            catch(System.Exception e)
            {
                Debug.Log("Error getting Settings in InitAPI: " + e.Message);
            }
        }
		private static void SelectGame(int index, Settings ga, int platform)
		{
			ga.SelectedGame[platform] = index;

			if(index == 0)
			{
				ga.UpdateGameKey(platform, "");
				ga.UpdateSecretKey(platform, "");
			}
			else if(ga.IsGameKeyValid(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].GameKey) &&
			   ga.IsSecretKeyValid(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].SecretKey))
			{
				ga.SelectedPlatformStudio[platform] = ga.Studios[ga.SelectedStudio[platform] - 1].Name;
				ga.SelectedPlatformGame[platform] = ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].Name;
				ga.SelectedPlatformGameID[platform] = ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].ID;
				ga.UpdateGameKey(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].GameKey);
				ga.UpdateSecretKey(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].SecretKey);
				SetLoginStatus("Received keys. Ready to go!", ga);
			}
			else
			{
				if(!ga.IsGameKeyValid(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].GameKey))
				{
					Debug.LogError("[GameAnalytics] Game key already exists for another platform. Platforms can't use the same key.");
					ga.SelectedGame[platform] = 0;
				}
				else if(!ga.IsSecretKeyValid(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[index - 1].SecretKey))
				{
					Debug.LogError("[GameAnalytics] Secret key already exists for another platform. Platforms can't use the same key.");
					ga.SelectedGame[platform] = 0;
				}
			}
		}
		private static void SetLoginStatus(string status, Settings ga)
		{
			ga.LoginStatus = status;
			EditorUtility.SetDirty(ga);
		}
		private static IEnumerator<WWW> GetAppFiguresFrontend(WWW www, Settings ga, GA_SignUp signup, string gameName)
		{
			yield return www;
			
			try
			{
				Hashtable returnParam = null;
				string error = "";
				if(!string.IsNullOrEmpty(www.text))
				{
					returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
					if(returnParam.ContainsKey("errors"))
					{
						ArrayList errorList = (ArrayList)returnParam["errors"];
						if(errorList != null && errorList.Count > 0)
						{
							Hashtable errors = (Hashtable)errorList[0];
							if(errors.ContainsKey("msg"))
							{
								error = errors["msg"].ToString();
							}
						}
					}
				}

				if(string.IsNullOrEmpty(www.error))
				{
					if(!String.IsNullOrEmpty(error))
					{
						Debug.LogError(error);
						SetLoginStatus("Failed to get app.", ga);
					}
					else if(returnParam != null)
					{
						ArrayList resultList = (ArrayList)returnParam["results"];

						List<AppFiguresGame> appFiguresGames = new List<AppFiguresGame>();
						for(int s = 0; s < resultList.Count; s++)
						{
							Hashtable result = (Hashtable)resultList[s];

							string name = result["title"].ToString();
							string appID = result["store_id"].ToString();
							string store = result["store"].ToString();
							string developer = result["developer"].ToString();
							string iconUrl = result["image"].ToString();

							if(store.Equals("apple") || store.Equals("google_play") || store.Equals("amazon_appstore"))
							{
								appFiguresGames.Add(new AppFiguresGame(name, appID, store, developer, iconUrl, signup));
							}
						}

						signup.AppFigComplete(gameName, appFiguresGames);
					}
				}
				else
				{
					Debug.LogError("Failed to find app: " + www.error + " " + www.text);
					SetLoginStatus("Failed to find app.", ga);
				}
			}
			catch(Exception e)
			{
				Debug.LogError("Failed to find app: " + e);
				SetLoginStatus("Failed to find app.", ga);
			}
		}
		private static void SelectStudio(int index, Settings ga, int platform)
		{
			ga.SelectedStudio[platform] = index;
			if(ga.Studios[index - 1].Games.Count == 1)
			{
				if(ga.IsGameKeyValid(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[0].GameKey) &&
				   ga.IsSecretKeyValid(platform, ga.Studios[ga.SelectedStudio[platform] - 1].Games[0].SecretKey))
				{
					SelectGame(1, ga, platform);
				}
			}
			else
			{
				SetLoginStatus("Please select game..", ga);
			}
		}
		private static IEnumerator<WWW> CreateGameFrontend(WWW www, Settings ga, GA_SignUp signup, GAPlatformSignUp platform, AppFiguresGame appFiguresGame)
		{
			yield return www;
			
			try
			{
				Hashtable returnParam = null;
				string error = "";
				if(!string.IsNullOrEmpty(www.text))
				{
					returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
					if(returnParam.ContainsKey("errors"))
					{
						ArrayList errorList = (ArrayList)returnParam["errors"];
						if(errorList != null && errorList.Count > 0)
						{
							Hashtable errors = (Hashtable)errorList[0];
							if(errors.ContainsKey("msg"))
							{
								error = errors["msg"].ToString();
							}
						}
					}
				}

				if(string.IsNullOrEmpty(www.error))
				{
					if(!String.IsNullOrEmpty(error))
					{
						Debug.LogError(error);
						SetLoginStatus("Failed to create game.", ga);
						signup.CreateGameFailed();
					}
					else
					{
						ga.LastCreatedGamePlatform = (GAPlatform)((int)(platform + 1));
						GetUserData(ga);
						signup.CreateGameComplete();
					}
				}
				else
				{
					Debug.LogError("Failed to create game: " + www.error + " " + error);
					SetLoginStatus("Failed to create game.", ga);
					signup.CreateGameFailed();
				}
			}
			catch
			{
				Debug.LogError("Failed to create game");
				SetLoginStatus("Failed to create game.", ga);
				signup.CreateGameFailed();
			}
		}
		public static void GetAppFigures(Settings ga, GA_SignUp signup)
		{
			WWW www = new WWW(_gaUrl + "apps/search?query=" + WWW.EscapeURL(ga.GameName), null, GA_EditorUtilities.WWWHeadersWithAuthorization(ga.TokenGA));
			GA_ContinuationManager.StartCoroutine(GetAppFiguresFrontend(www, ga, signup, ga.GameName), () => www.isDone);

			if(ga.AmazonIcon == null)
			{
				WWW wwwAmazon = new WWW("http://public.gameanalytics.com/resources/images/sdk_doc/appstore_icons/amazon.png");
				GA_ContinuationManager.StartCoroutine(signup.GetAppStoreIconTexture(wwwAmazon, "amazon_appstore", signup), () => wwwAmazon.isDone);
			}

			if(ga.GooglePlayIcon == null)
			{
				WWW wwwGoogle = new WWW("http://public.gameanalytics.com/resources/images/sdk_doc/appstore_icons/google_play.png");
				GA_ContinuationManager.StartCoroutine(signup.GetAppStoreIconTexture(wwwGoogle, "google_play", signup), () => wwwGoogle.isDone);
			}

			if(ga.iosIcon == null)
			{
				WWW wwwIos = new WWW("http://public.gameanalytics.com/resources/images/sdk_doc/appstore_icons/ios.png");
				GA_ContinuationManager.StartCoroutine(signup.GetAppStoreIconTexture(wwwIos, "apple:ios", signup), () => wwwIos.isDone);
			}

			if(ga.macIcon == null)
			{
				WWW wwwMac = new WWW("http://public.gameanalytics.com/resources/images/sdk_doc/appstore_icons/mac.png");
				GA_ContinuationManager.StartCoroutine(signup.GetAppStoreIconTexture(wwwMac, "apple:mac", signup), () => wwwMac.isDone);
			}

			if(ga.windowsPhoneIcon == null)
			{
				WWW wwwWindowsPhone = new WWW("http://public.gameanalytics.com/resources/images/sdk_doc/appstore_icons/windows_phone.png");
				GA_ContinuationManager.StartCoroutine(signup.GetAppStoreIconTexture(wwwWindowsPhone, "windows_phone", signup), () => wwwWindowsPhone.isDone);
			}
		}
		private static IEnumerator<WWW> GetUserDataFrontend(WWW www, Settings ga)
		{
			yield return www;
			
			try
			{
				Hashtable returnParam = null;
				string error = "";
				if(!string.IsNullOrEmpty(www.text))
				{
					returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
					if(returnParam.ContainsKey("errors"))
					{
						ArrayList errorList = (ArrayList)returnParam["errors"];
						if(errorList != null && errorList.Count > 0)
						{
							Hashtable errors = (Hashtable)errorList[0];
							if(errors.ContainsKey("msg"))
							{
								error = errors["msg"].ToString();
							}
						}
					}
				}

				if(string.IsNullOrEmpty(www.error))
				{
					if(!String.IsNullOrEmpty(error))
					{
						Debug.LogError(error);
						SetLoginStatus("Failed to get data.", ga);
					}
					else if(returnParam != null)
					{
						ArrayList resultList = (ArrayList)returnParam["results"];
						Hashtable results = (Hashtable)resultList[0];
						ArrayList studioList = (ArrayList)results["studios"];
						
						List<Studio> returnStudios = new List<Studio>();
						
						for(int s = 0; s < studioList.Count; s++)
						{
							Hashtable studio = (Hashtable)studioList[s];
							if(!studio.ContainsKey("demo") || !((bool)studio["demo"]))
							{
								List<Game> returnGames = new List<Game>();
								
								ArrayList gamesList = (ArrayList)studio["games"];
								for(int g = 0; g < gamesList.Count; g++)
								{
									Hashtable games = (Hashtable)gamesList[g];
									returnGames.Add(new Game(games["name"].ToString(), int.Parse(games["id"].ToString()), games["key"].ToString(), games["secret"].ToString()));
								}
								
								returnStudios.Add(new Studio(studio["name"].ToString(), studio["id"].ToString(), returnGames));
							}
						}
						ga.Studios = returnStudios;

						if(ga.Studios.Count == 1)
						{
							for(int i = 0; i < NumberOfPlatforms; ++i)
							{
								GAPlatform platform = (GAPlatform)(i + 1);

								if(platform == ga.LastCreatedGamePlatform)
								{
									SelectStudio(1, ga, (int)platform - 1);
								}
							}
							ga.LastCreatedGamePlatform = GAPlatform.None;
						}
						else
						{
							SetLoginStatus("Received data. Select studio..", ga);
						}

						ga.CurrentInspectorState = Settings.InspectorStates.Basic;
					}
				}
				else
				{
					Debug.LogError("Failed to get user data: " + www.error + " " + error);
					SetLoginStatus("Failed to get data.", ga);
				}
			}
			catch(Exception e)
			{
				Debug.LogError("Failed to get user data: " + e);
				SetLoginStatus("Failed to get data.", ga);
			}
		}
		public static void CreateGame(Settings ga, GA_SignUp signup, int studioIndex, string gameTitle, string googlePlayPublicKey, GAPlatformSignUp platform, AppFiguresGame appFiguresGame)
		{
			Hashtable jsonTable = new Hashtable();

			if(appFiguresGame != null)
			{
				jsonTable["title"] = gameTitle;
				jsonTable["store_id"] = appFiguresGame.AppID;
				jsonTable["store"] = appFiguresGame.Store;
				jsonTable["googleplay_key"] = string.IsNullOrEmpty(googlePlayPublicKey) ? null : googlePlayPublicKey;
			}
			else
			{
				jsonTable["title"] = gameTitle;
				jsonTable["store_id"] = null;
				jsonTable["store"] = null;
				jsonTable["googleplay_key"] = string.IsNullOrEmpty(googlePlayPublicKey) ? null : googlePlayPublicKey;
			}
			byte[] data = System.Text.Encoding.UTF8.GetBytes(GA_MiniJSON.JsonEncode(jsonTable));

			string url = _gaUrl + "studios/" + ga.Studios[studioIndex].ID + "/games";
			WWW www = new WWW(url, data, GA_EditorUtilities.WWWHeadersWithAuthorization(ga.TokenGA));
			GA_ContinuationManager.StartCoroutine(CreateGameFrontend(www, ga, signup, platform, appFiguresGame), () => www.isDone);
		}
		private static void GetUserData(Settings ga)
		{
			WWW www = new WWW(_gaUrl + "user", null, GA_EditorUtilities.WWWHeadersWithAuthorization(ga.TokenGA));
			GA_ContinuationManager.StartCoroutine(GetUserDataFrontend(www, ga), () => www.isDone);
		}
		private static IEnumerator<WWW> LoginUserFrontend(WWW www, Settings ga)
		{
			yield return www;
			
			try
			{
				string error = "";
				Hashtable returnParam = null;
				if(!string.IsNullOrEmpty(www.text))
				{
					returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
                    
					if(returnParam.ContainsKey("errors"))
					{
						ArrayList errorList = (ArrayList)returnParam["errors"];
						if(errorList != null && errorList.Count > 0)
						{
							Hashtable errors = (Hashtable)errorList[0];
							if(errors.ContainsKey("msg"))
							{
								error = errors["msg"].ToString();
							}
						}
					}
				}

				if(string.IsNullOrEmpty(www.error))
				{
					if(!String.IsNullOrEmpty(error))
					{
						Debug.LogError(error);
						SetLoginStatus("Failed to login.", ga);
					}
					else if(returnParam != null)
					{
						ArrayList resultList = (ArrayList)returnParam["results"];
						Hashtable results = (Hashtable)resultList[0];
						ga.TokenGA = results["token"].ToString();
						ga.ExpireTime = results["exp"].ToString();
						
						SetLoginStatus("Logged in. Getting data.", ga);

						GetUserData(ga);
					}
				}
				else
				{
					Debug.LogError("Failed to login: "******" " + error);
					SetLoginStatus("Failed to login.", ga);
				}
			}
			catch
			{
				Debug.LogError("Failed to login");
				SetLoginStatus("Failed to login.", ga);
			}
		}
		private static void LoginUser(Settings ga)
		{
			Hashtable jsonTable = new Hashtable();
			jsonTable["email"] = ga.EmailGA;
			jsonTable["password"] = ga.PasswordGA;

			byte[] data = System.Text.Encoding.UTF8.GetBytes(GA_MiniJSON.JsonEncode(jsonTable));

			WWW www = new WWW(_gaUrl + "token", data, GA_EditorUtilities.WWWHeaders());
			GA_ContinuationManager.StartCoroutine(LoginUserFrontend(www, ga), () => www.isDone);
		}
		private static IEnumerator<WWW> SignupUserFrontend(WWW www, Settings ga, GA_SignUp signup)
		{
			yield return www;

			try
			{
				Hashtable returnParam = null;
				string error = "";
				if(!string.IsNullOrEmpty(www.text))
				{
					returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
					if(returnParam.ContainsKey("errors"))
					{
						ArrayList errorList = (ArrayList)returnParam["errors"];
						if(errorList != null && errorList.Count > 0)
						{
							Hashtable errors = (Hashtable)errorList[0];
							if(errors.ContainsKey("msg"))
							{
								error = errors["msg"].ToString();
							}
						}
					}
				}

				if(string.IsNullOrEmpty(www.error))
				{
					if(!String.IsNullOrEmpty(error))
					{
						Debug.LogError(error);
						SetLoginStatus("Failed to sign up.", ga);
						signup.SignUpFailed();
					}
					else if(returnParam != null)
					{
						ArrayList resultList = (ArrayList)returnParam["results"];
						Hashtable results = (Hashtable)resultList[0];
						ga.TokenGA = results["token"].ToString();
						ga.ExpireTime = results["exp"].ToString();

						ga.JustSignedUp = true;

						//ga.SignUpOpen = false;

						ga.Studios = null;
						SetLoginStatus("Signed up. Getting data.", ga);
						
						GetUserData(ga);
						signup.SignUpComplete();
					}
				}
				else
				{
					Debug.LogError("Failed to sign up: " + www.error + " " + error);
					SetLoginStatus("Failed to sign up.", ga);
					signup.SignUpFailed();
				}
			}
			catch
			{
				Debug.LogError("Failed to sign up");
				SetLoginStatus("Failed to sign up.", ga);
				signup.SignUpFailed();
			}
		}
		public static void SignupUser(Settings ga, GA_SignUp signup)
		{
			Hashtable jsonTable = new Hashtable();
			jsonTable["email"] = ga.EmailGA;
			jsonTable["password"] = ga.PasswordGA;
			jsonTable["password_confirm"] = ga.PasswordConfirm;
			jsonTable["first_name"] = ga.FirstName;
			jsonTable["last_name"] = ga.LastName;
			jsonTable["studio_name"] = ga.StudioName;
			jsonTable["email_opt_out"] = ga.EmailOptIn;

			byte[] data = System.Text.Encoding.UTF8.GetBytes(GA_MiniJSON.JsonEncode(jsonTable));
			
			WWW www = new WWW(_gaUrl + "user", data, GA_EditorUtilities.WWWHeaders());

			GA_ContinuationManager.StartCoroutine(SignupUserFrontend(www, ga, signup), () => www.isDone);
		}