private void ThreadRun() { byte[] lenbuffer = new byte[2]; while (true) { try { byte[] d; if (_sendData.TryDequeue(out d)) { NetworkDataTools.SetUInt16(out lenbuffer[0], out lenbuffer[1], (ushort)d.Length); mmOutStream.Write(lenbuffer, 0, 2); mmOutStream.Write(d, 0, d.Length); } else { Thread.Sleep(0); } } catch (Java.IO.IOException e) { SAMLog.Warning("ABTA::ThreadSend_ConnLost", e.Message); _adapter.ThreadMessage_ConnectionLost(); break; } } }
public static string MakeTextSafeWithWarn(SpriteFont font, string s, char c) { if (font?.Characters == null) { return(""); } if (s == null) { return(""); } char[] cc = new char[s.Length]; for (int i = 0; i < s.Length; i++) { if (!font.Characters.Contains(s[i]) && s[i] != 0x0A && s[i] != 0x0D) { SAMLog.Warning("FRH::MC", $"Cant render char with font: 0x{((int)s[i]):X2}"); cc[i] = c; } else { cc[i] = s[i]; } } return(new string(cc)); }
protected override void ProcessForwardData(byte[] d) { if (Screen == null) { return; } var seq = NetworkDataTools.GetByte(d[1]); var msgSessionID = NetworkDataTools.GetSplitBits(d[2], d[3], 8, 8); var msgUserID = NetworkDataTools.GetHighBits(d[4], 4); var msgSessionSecret = NetworkDataTools.GetSplitBits(d[4], d[5], 4, 8); var msgTime = NetworkDataTools.GetSingle(d[6], d[7], d[8], d[9]); if (msgSessionID != SessionID || msgSessionSecret != SessionSecret || msgUserID == 0) { SAMLog.Warning("SNS-Server", $"Invalid server message: ({msgSessionID} != {SessionID} || {msgSessionSecret} != {SessionSecret} || {msgUserID} == {0})"); return; } if (IsSeqGreater(UserConn[msgUserID].LastRecievedSeq, seq)) { ProcessStateData(d, msgUserID); } else { SAMLog.Debug("Ignore Out-Of-Order Message"); } RecieveMsg(msgUserID, seq); }
public override void OnReceive(Context context, Intent intent) { try { SAMLog.Debug("BTScanReciever::OnRecieve(" + intent.Action + ")"); string action = intent.Action; if (action == BluetoothDevice.ActionFound) { BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice); if (device != null) { SAMLog.Debug($"BTScanReciver:ActionFound({device.Name}|{device.Type}|{device.BluetoothClass.DeviceClass}|{device.BondState})"); _adapter.ThreadMessage_DeviceFound(device); } else { SAMLog.Warning("ABTA::NULLDEVICE", "BTScanReciver:ActionFound(device == null)"); } } else if (action == BluetoothAdapter.ActionDiscoveryFinished) { _adapter.ThreadMessage_DiscoveryFinished(); } } catch (Exception e) { SAMLog.Error("ABTA::ScanRecieve", e); } }
public void StartAdapter() { CancelAllThreads(); lock (_foundDevices) { _foundDevices.Clear(); } if (Adapter.IsDiscovering) { Adapter.CancelDiscovery(); } State = BluetoothAdapterState.Created; var missingPermissions = new List <string>(); if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.AccessCoarseLocation) != Permission.Granted) { missingPermissions.Add(Manifest.Permission.AccessCoarseLocation); } if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.AccessFineLocation) != Permission.Granted) { missingPermissions.Add(Manifest.Permission.AccessFineLocation); } if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.Bluetooth) != Permission.Granted) { missingPermissions.Add(Manifest.Permission.Bluetooth); } if (_activity.CheckCallingOrSelfPermission(Manifest.Permission.BluetoothAdmin) != Permission.Granted) { missingPermissions.Add(Manifest.Permission.BluetoothAdmin); } if (missingPermissions.Any()) { SAMLog.Warning("ABTA::MissingPerms", string.Join("|", missingPermissions.Select(p => p.Split('.').Last()))); if ((int)Build.VERSION.SdkInt >= 23) { // With API>23 I can request them here // https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/ _activity.RequestPermissions(missingPermissions.ToArray(), REQUEST_ENABLE_PERM); } State = BluetoothAdapterState.PermissionNotGranted; return; } if (Adapter.IsEnabled) { State = BluetoothAdapterState.Active; } else { State = BluetoothAdapterState.RequestingEnable; Intent enableIntent = new Intent(BluetoothAdapter.ActionRequestEnable); _activity.StartActivityForResult(enableIntent, REQUEST_ENABLE_BT); } }
protected override void OnEffectError() { IsEffectsMuted = true; MainGame.Inst.Profile.SoundsEnabled = false; SAMLog.Warning("SSP::DISABLE_1", "Disable Music due to error"); MainGame.Inst.DispatchBeginInvoke(() => { MainGame.Inst.ShowToast("SSP::ERR_EFFECTS", L10N.T(L10NImpl.STR_ERR_SOUNDPLAYBACK), 32, FlatColors.Flamingo, FlatColors.Foreground, 8f); }); }
protected override void OnSongError() { IsMusicMuted = true; MainGame.Inst.Profile.MusicEnabled = false; SAMLog.Warning("SSP::DISABLE_2", "Disable Sounds due to error"); MainGame.Inst.DispatchBeginInvoke(() => { MainGame.Inst.ShowToast("SSP::ERR_SONG", L10N.T(L10NImpl.STR_ERR_MUSICPLAYBACK), 32, FlatColors.Flamingo, FlatColors.Foreground, 8f); }); }
public async Task CreateUser(PlayerProfile profile) { try { var pw = bridge.DoSHA256(Guid.NewGuid().ToString("N")); var ps = new RestParameterSet(); ps.AddParameterHash("password", pw); ps.AddParameterString("app_version", GDConstants.Version.ToString()); ps.AddParameterString("device_name", bridge.DeviceName); ps.AddParameterString("device_version", bridge.DeviceVersion); ps.AddParameterString("unlocked_worlds", profile.StrPurchasedWorlds); ps.AddParameterString("device_resolution", bridge.DeviceResolution.FormatAsResolution()); var response = await QueryAsync <QueryResultCreateUser>("create-user", ps, RETRY_CREATEUSER); if (response == null) { SAMLog.Error("Backend::CU_Null", "CreateUser returned NULL"); ShowErrorCommunication(); } else if (response.result == "success") { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.AccountType = AccountType.Anonymous; profile.OnlineUserID = response.user.ID; profile.OnlineRevisionID = response.user.RevID; profile.OnlinePasswordHash = pw; MainGame.Inst.SaveProfile(); Reupload(profile).EnsureNoError(); }); } else if (response.result == "error") { SAMLog.Error("Backend::CU_Err", $"CreateUser: Error {response.errorid}: {response.errormessage}"); ShowErrorCommunication(); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::CU_RCE", e); // probably no internet ShowErrorConnection(); } catch (Exception e) { SAMLog.Error("Backend::CU_E", e); ShowErrorCommunication(); } }
public async Task <QueryResultRanking> GetRanking(PlayerProfile profile, GraphBlueprint limit, bool multiplayer) { try { var ps = new RestParameterSet(); ps.AddParameterInt("userid", profile.OnlineUserID); if (multiplayer) { ps.AddParameterString("world_id", "@"); } else if (limit == null) { ps.AddParameterString("world_id", "*"); } else { ps.AddParameterString("world_id", limit.ID.ToString("B")); } var response = await QueryAsync <QueryResultRanking>("get-ranking", ps, RETRY_GETRANKING); if (response == null) { ShowErrorCommunication(); return(null); } else if (response.result == "success") { return(response); } else { ShowErrorCommunication(); return(null); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::GR_RCE", e); // probably no internet ShowErrorConnection(); return(null); } catch (Exception e) { SAMLog.Error("Backend::GR_E", e); ShowErrorCommunication(); return(null); } }
public void Update(SAMTime gameTime, InputState istate) { if (istate.IsExclusiveJustDown && innerBoundings.Contains(istate.GamePointerPositionOnMap)) { istate.Swallow(InputConsumer.GameEntity); OnExclusiveDown(istate); } timeSinceLastUpdate -= gameTime.ElapsedSeconds; if (timeSinceLastUpdate <= 0) { if (onlySingleUpdate) { if (Fraction.LastKiSingleCycle == MonoSAMGame.GameCycleCounter) { Fraction.KICycleWaitQueue.Enqueue(Cannon.BlueprintCannonID); return; // We want - but someone else was first } if (Fraction.KICycleWaitQueue.Count == 0) { DoUpdate(gameTime, istate); return; // We want and we don't have to wait } if (Fraction.KICycleWaitQueue.Peek() == Cannon.BlueprintCannonID) { Fraction.KICycleWaitQueue.Dequeue(); DoUpdate(gameTime, istate); return; // We want and its out turn } if (Owner.CannonMap[Fraction.KICycleWaitQueue.Peek()].Fraction != Fraction) { SAMLog.Warning("AFC::DirtyCycleQueue", $"Cycle Queue for {Fraction.Type} contains {Fraction.KICycleWaitQueue.Peek()} ({Owner.CannonMap[Fraction.KICycleWaitQueue.Peek()].Fraction.Type})"); Fraction.KICycleWaitQueue.Clear(); return; } Fraction.KICycleWaitQueue.Enqueue(Cannon.BlueprintCannonID); return; // We want - but someone else has priority } else { DoUpdate(gameTime, istate); return; } } }
public void Send(byte[] data) { if (data.Length == 0) { return; } if (_client.State != BluetoothAdapterState.Connected) { SAMLog.Warning("BNM::Send_ERR", $"Trying to send data {data[0]} while in State {_client.State}"); return; } _client.Write(data); }
public async Task DownloadHighscores(PlayerProfile profile) { try { var response = await QueryAsync <QueryResultHighscores>("get-highscores", new RestParameterSet(), RETRY_DOWNLOADHIGHSCORES); if (response == null) { SAMLog.Warning("Backend::DH_NULL", $"DownloadHighscores: Error response == null"); ShowErrorCommunication(); } else if (response.result == "success") { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { foreach (var hscore in response.highscores) { Guid id; if (Guid.TryParse(hscore.levelid, out id)) { var d = profile.GetLevelData(id, (FractionDifficulty)hscore.difficulty); d.GlobalBestTime = hscore.best_time; d.GlobalBestUserID = hscore.best_userid; d.GlobalCompletionCount = hscore.completion_count; } } MainGame.Inst.SaveProfile(); }); } else if (response.result == "error") { SAMLog.Warning("Backend::DH_ERR", $"DownloadHighscores: Error {response.errorid}: {response.errormessage}"); ShowErrorCommunication(); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::DH_RCE", e); // probably no internet ShowErrorConnection(); } catch (Exception e) { SAMLog.Error("Backend::DH_E", e); ShowErrorCommunication(); } }
public void HandleActivityResult(int requestCode, Result resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Result.Ok) { SAMLog.Debug("Bluetooth enabled"); State = BluetoothAdapterState.Active; } else { SAMLog.Warning("ABTA::BNE", "Bluetooth [[not]] enabled"); State = BluetoothAdapterState.NotEnabledByUser; } } }
private void ThreadRun() { // Always cancel discovery because it will slow down a connection _adapter.Adapter.CancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.Connect(); SAMLog.Debug("ABTA::Connect()=>true"); } catch (Java.IO.IOException e) { SAMLog.Warning("ABTA::CONNFAILED", e); _adapter.ThreadMessage_ConnectionFailed(); // Close the socket try { mmSocket.Close(); } catch (Java.IO.IOException e2) { SAMLog.Error("ABTA::NOCLOSE2", e2.Message); } return; } // Reset the ConnectThread because we're done lock (this) { _adapter.SetConnectThreadCancelled(); } // Start the connected thread _adapter.ThreadMessage_Connected(mmSocket, mmDevice); }
protected void PlaySoundeffect(SoundEffect e) { if (IsEffectsMuted) { return; } if (InitErrorState) { return; } if (_effectCounter >= MAX_EFFECTS_PER_FRAME) { return; } try { _effectCounter++; e.Play(); } catch (Exception ex) { if (ex.GetType().FullName == @"Microsoft.Xna.Framework.Audio.InstancePlayLimitException") { //ignore SAMLog.Warning("SSP::IPLE", "InstancePlayLimitException"); _effectCounter = 999; } else { OnEffectError(); SAMLog.Error("SSP::PlayEffect", ex); } } }
public async Task LogClient(UserSettings profile, SAMLogEntry entry) { try { var ps = new RestParameterSet(); //ps.AddParameterInt("userid", profile.OnlineUserID, false); //ps.AddParameterHash("password", profile.OnlinePasswordHash, false); ps.AddParameterString("app_version", SGConstants.Version.ToString(), false); ps.AddParameterString("screen_resolution", bridge.DeviceResolution.FormatAsResolution(), false); ps.AddParameterString("exception_id", entry.Type, false); ps.AddParameterCompressed("exception_message", entry.MessageShort, false); ps.AddParameterCompressed("exception_stacktrace", entry.MessageLong, false); ps.AddParameterCompressed("additional_info", bridge.FullDeviceInfoString, false); var response = await QueryAsync <QueryResultLogClient>("log-client", ps, RETRY_LOGERROR); if (response == null) { SAMLog.Warning("Log_Upload_LC_NULL", "response == null"); } else if (response.result == "error") { SAMLog.Warning("Log_Upload_LC_ERR", response.errormessage); } } catch (RestConnectionException e) { // well, that sucks // probably no internet SAMLog.Warning("Backend::LC_RCE", e); // probably no internet } catch (Exception e) { SAMLog.Error("Backend::LC_E", e); } }
protected override void ProcessForwardHostData(byte[] data) { SAMLog.Warning("GDMS::PFHD", "ProcessForwardHostData called for server"); }
protected override void ProcessForwardLobbySync(byte[] data) { SAMLog.Warning("GDMS::PFLS", "ProcessForwardLobbySync called for server"); }
public async Task <Tuple <ChangePasswordResult, string> > ChangePassword(PlayerProfile profile, string newPassword) { try { var pwHashOld = profile.OnlinePasswordHash; var pwHashNew = bridge.DoSHA256(newPassword); var ps = new RestParameterSet(); ps.AddParameterInt("userid", profile.OnlineUserID); ps.AddParameterHash("password_old", pwHashOld); ps.AddParameterString("app_version", GDConstants.Version.ToString()); ps.AddParameterHash("password_new", pwHashNew); var response = await QueryAsync <QueryResultChangePassword>("change-password", ps, RETRY_CHANGE_PW); if (response == null) { ShowErrorCommunication(); return(Tuple.Create(ChangePasswordResult.InternalError, "Internal server error")); } else if (response.result == "success") { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.AccountType = AccountType.Full; profile.OnlinePasswordHash = pwHashNew; profile.OnlineRevisionID = response.user.RevID; MainGame.Inst.SaveProfile(); }); return(Tuple.Create(ChangePasswordResult.Success, string.Empty)); } else if (response.result == "error") { if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { ShowErrorCommunication(); return(Tuple.Create(ChangePasswordResult.InternalError, response.errormessage)); } if (response.errorid == BackendCodes.WRONG_PASSWORD) { return(Tuple.Create(ChangePasswordResult.AuthError, string.Empty)); } SAMLog.Error("Backend::CP_ERR", $"ChangePassword: Error {response.errorid}: {response.errormessage}"); ShowErrorCommunication(); return(Tuple.Create(ChangePasswordResult.InternalError, response.errormessage)); } else { return(Tuple.Create(ChangePasswordResult.InternalError, "Inetrnal server error")); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::CP_RCE", e); // probably no internet ShowErrorConnection(); return(Tuple.Create(ChangePasswordResult.NoConnection, string.Empty)); } catch (Exception e) { SAMLog.Error("Backend::CP_E", e); ShowErrorCommunication(); return(Tuple.Create(ChangePasswordResult.InternalError, "Internal server error")); } }
public async Task DownloadData(PlayerProfile profile) { try { var ps = new RestParameterSet(); ps.AddParameterInt("userid", profile.OnlineUserID); ps.AddParameterHash("password", profile.OnlinePasswordHash); ps.AddParameterString("app_version", GDConstants.Version.ToString()); var response = await QueryAsync <QueryResultDownloadData>("download-data", ps, RETRY_DOWNLOADDATA); if (response == null) { return; // meh - internal server error } else if (response.result == "success") { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.OnlineRevisionID = response.user.RevID; foreach (var scdata in response.scores) { profile.SetCompleted(Guid.Parse(scdata.levelid), (FractionDifficulty)scdata.difficulty, scdata.best_time, false); } profile.MultiplayerPoints = response.user.MultiplayerScore; profile.HasMultiplayerGames |= response.user.MultiplayerScore > 0; MainGame.Inst.SaveProfile(); }); } else if (response.result == "error") { if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { return; // meh } else if (response.errorid == BackendCodes.WRONG_PASSWORD || response.errorid == BackendCodes.USER_BY_ID_NOT_FOUND) { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { SAMLog.Error("Backend::DD_INVLOGIN", $"Local user cannot login on server ({response.errorid}:{response.errormessage}). Reset local user"); // something went horribly wrong // create new user on next run profile.OnlineUserID = -1; MainGame.Inst.SaveProfile(); }); } else { SAMLog.Error("Backend::DD_ERR", $"SetScore: Error {response.errorid}: {response.errormessage}"); ShowErrorCommunication(); } } } catch (RestConnectionException e) { SAMLog.Warning("Backend::DD_RCE", e); // probably no internet ShowErrorConnection(); } catch (Exception e) { SAMLog.Error("Backend::DD_E", e); ShowErrorCommunication(); } }
protected void ProcessStateData(byte[] d, byte euid) { // [8: CMD] [8:seq] [16: SessionID] [4: UserID] [12: SessionSecret] [32:time] [~: Payload] RecieveBigSeq[euid]++; var bseq = RecieveBigSeq[euid]; var sendertime = NetworkDataTools.GetSingle(d[6], d[7], d[8], d[9]); if (sendertime - 0.05f > Screen.LevelTime) { SAMLog.Warning("GDMPC::FFWD", $"Fastforward level by {sendertime - Screen.LevelTime}s ({Screen.LevelTime} --> {sendertime})"); Screen.FastForward(sendertime); } lagBehindTime = Screen.LevelTime - sendertime; int p = PACKAGE_FORWARD_HEADER_SIZE; for (;;) { byte cmd = d[p]; p++; if (cmd == AREA_END) { break; } if (p >= MAX_PACKAGE_SIZE_BYTES) { SAMLog.Error("SNS-COMMON::OOB", "OOB: " + p); break; } else if (cmd == AREA_BULLETCANNONS) { ProcessForwardBulletCannons(ref p, d, bseq, sendertime); } else if (cmd == AREA_BULLETS) { ProcessForwardBullets(ref p, d, bseq, sendertime); } else if (cmd == AREA_LASERCANNONS) { ProcessForwardLaserCannons(ref p, d, bseq, sendertime); } else if (cmd == AREA_SHIELDPROJECTORS) { ProcessForwardShieldProjectors(ref p, d, bseq, sendertime); } else if (cmd == AREA_MINIGUNS) { ProcessForwardMiniguns(ref p, d, bseq, sendertime); } else if (cmd == AREA_TRISHOTCANNONS) { ProcessForwardTrishotCannons(ref p, d, bseq, sendertime); } else if (cmd == AREA_RELAYCANNONS) { ProcessForwardRelayCannons(ref p, d, bseq, sendertime); } else if (cmd == 0) { SAMLog.Warning("SNS-COMMON::ZA", "AREA is zero"); break; } else { SAMLog.Error("SNS-COMMON::UA", "Unknown AREA: " + cmd); break; } } }
public async Task <Tuple <VerifyResult, int, string> > Verify(string username, string password) { try { var pwHash = bridge.DoSHA256(password); var ps = new RestParameterSet(); ps.AddParameterString("username", username); ps.AddParameterHash("password", pwHash); ps.AddParameterString("app_version", GDConstants.Version.ToString()); var response = await QueryAsync <QueryResultVerify>("verify", ps, RETRY_VERIFY); if (response == null) { return(Tuple.Create(VerifyResult.InternalError, -1, "Internal server error")); } else if (response.result == "success") { if (response.user.AutoUser) { return(Tuple.Create(VerifyResult.WrongUsername, -1, string.Empty)); } return(Tuple.Create(VerifyResult.Success, response.user.ID, string.Empty)); } else if (response.result == "error") { if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { return(Tuple.Create(VerifyResult.InternalError, -1, response.errormessage)); } else if (response.errorid == BackendCodes.WRONG_PASSWORD) { return(Tuple.Create(VerifyResult.WrongPassword, -1, string.Empty)); } else if (response.errorid == BackendCodes.USER_BY_NAME_NOT_FOUND) { return(Tuple.Create(VerifyResult.WrongUsername, -1, string.Empty)); } else { ShowErrorCommunication(); SAMLog.Error("Backend::V_ERR", $"Verify: Error {response.errorid}: {response.errormessage}"); return(Tuple.Create(VerifyResult.InternalError, -1, response.errormessage)); } } else { return(Tuple.Create(VerifyResult.InternalError, -1, "Internal server exception")); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::V_RCE", e); // probably no internet ShowErrorConnection(); return(Tuple.Create(VerifyResult.NoConnection, -1, string.Empty)); } catch (Exception e) { SAMLog.Error("Backend::V_E", e); ShowErrorCommunication(); return(Tuple.Create(VerifyResult.InternalError, -1, "Internal server exception")); } }
public async Task <Tuple <VerifyResult, string> > MergeLogin(PlayerProfile profile, string username, string password) { try { var pwHash = bridge.DoSHA256(password); var ps = new RestParameterSet(); ps.AddParameterInt("old_userid", profile.OnlineUserID); ps.AddParameterHash("old_password", profile.OnlinePasswordHash); ps.AddParameterString("app_version", GDConstants.Version.ToString()); ps.AddParameterString("new_username", username); ps.AddParameterHash("new_password", pwHash); ps.AddParameterJson("merge_data", CreateScoreArray(profile)); ps.AddParameterInt("s0", profile.TotalPoints); ps.AddParameterInt("s1", profile.GetWorldPoints(Levels.WORLD_001)); ps.AddParameterInt("s2", profile.GetWorldPoints(Levels.WORLD_002)); ps.AddParameterInt("s3", profile.GetWorldPoints(Levels.WORLD_003)); ps.AddParameterInt("s4", profile.GetWorldPoints(Levels.WORLD_004)); ps.AddParameterInt("t0", profile.TotalTime); ps.AddParameterInt("t1", profile.GetWorldTime(Levels.WORLD_001)); ps.AddParameterInt("t2", profile.GetWorldTime(Levels.WORLD_002)); ps.AddParameterInt("t3", profile.GetWorldTime(Levels.WORLD_003)); ps.AddParameterInt("t4", profile.GetWorldTime(Levels.WORLD_004)); ps.AddParameterInt("sx", profile.MultiplayerPoints); var response = await QueryAsync <QueryResultMergeLogin>("merge-login", ps, RETRY_CREATEUSER); if (response == null) { return(Tuple.Create(VerifyResult.InternalError, "Internal server error")); } else if (response.result == "success") { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.AccountType = AccountType.Full; profile.OnlineUsername = response.user.Username; profile.OnlineUserID = response.user.ID; profile.OnlineRevisionID = response.user.RevID; profile.OnlinePasswordHash = pwHash; profile.AccountReminderShown = true; foreach (var scdata in response.scores) { profile.SetCompleted(Guid.Parse(scdata.levelid), (FractionDifficulty)scdata.difficulty, scdata.best_time, false); } MainGame.Inst.SaveProfile(); SetScoreAndTime(profile).EnsureNoError(); //score could have been changed - reupload }); return(Tuple.Create(VerifyResult.Success, string.Empty)); } else if (response.result == "error") { if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { return(Tuple.Create(VerifyResult.InternalError, response.errormessage)); } else if (response.errorid == BackendCodes.WRONG_PASSWORD) { return(Tuple.Create(VerifyResult.WrongPassword, string.Empty)); } else if (response.errorid == BackendCodes.USER_BY_NAME_NOT_FOUND) { return(Tuple.Create(VerifyResult.WrongUsername, string.Empty)); } else { ShowErrorCommunication(); SAMLog.Error("Backend::ML_ERR", $"Verify: Error {response.errorid}: {response.errormessage}"); return(Tuple.Create(VerifyResult.InternalError, response.errormessage)); } } else { return(Tuple.Create(VerifyResult.InternalError, "Internal server exception")); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::ML_RCE", e); // probably no internet ShowErrorConnection(); return(Tuple.Create(VerifyResult.NoConnection, string.Empty)); } catch (Exception e) { SAMLog.Error("Backend::ML_E", e); ShowErrorCommunication(); return(Tuple.Create(VerifyResult.InternalError, "Internal server exception")); } }
protected override void ProcessAfterGameData(byte[] data) { SAMLog.Warning("GDMS::PAGD", "ProcessAfterGameData called for server"); }
public async Task Reupload(PlayerProfile profile) { profile.NeedsReupload = false; try { var ps = new RestParameterSet(); ps.AddParameterInt("userid", profile.OnlineUserID); ps.AddParameterHash("password", profile.OnlinePasswordHash); ps.AddParameterString("app_version", GDConstants.Version.ToString()); ps.AddParameterJson("data", CreateScoreArray(profile)); ps.AddParameterInt("s0", profile.TotalPoints); ps.AddParameterInt("s1", profile.GetWorldPoints(Levels.WORLD_001)); ps.AddParameterInt("s2", profile.GetWorldPoints(Levels.WORLD_002)); ps.AddParameterInt("s3", profile.GetWorldPoints(Levels.WORLD_003)); ps.AddParameterInt("s4", profile.GetWorldPoints(Levels.WORLD_004)); ps.AddParameterInt("t0", profile.TotalTime); ps.AddParameterInt("t1", profile.GetWorldTime(Levels.WORLD_001)); ps.AddParameterInt("t2", profile.GetWorldTime(Levels.WORLD_002)); ps.AddParameterInt("t3", profile.GetWorldTime(Levels.WORLD_003)); ps.AddParameterInt("t4", profile.GetWorldTime(Levels.WORLD_004)); ps.AddParameterInt("sx", profile.MultiplayerPoints); var response = await QueryAsync <QueryResultSetMultiscore>("set-multiscore", ps, RETRY_DOWNLOADDATA); if (response == null) { return; // meh - internal server error } else if (response.result == "success") { if (response.update) { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.OnlineRevisionID = response.user.RevID; MainGame.Inst.SaveProfile(); if (profile.NeedsReupload) { Reupload(profile).EnsureNoError(); } }); } } else if (response.result == "error") { ShowErrorCommunication(); if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { return; // meh } else if (response.errorid == BackendCodes.WRONG_PASSWORD || response.errorid == BackendCodes.USER_BY_ID_NOT_FOUND) { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { SAMLog.Error("Backend::RU_INVLOGIN", $"Local user cannot login on server ({response.errorid}:{response.errormessage}). Reset local user"); // something went horribly wrong // create new user on next run profile.OnlineUserID = -1; MainGame.Inst.SaveProfile(); }); } else { SAMLog.Error("Backend::RU_ERR", $"SetScore: Error {response.errorid}: {response.errormessage}"); } } } catch (RestConnectionException e) { SAMLog.Warning("Backend::RU_RCE", e); // probably no internet ShowErrorConnection(); MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.NeedsReupload = true; MainGame.Inst.SaveProfile(); }); } catch (Exception e) { SAMLog.Error("Backend::RU_E", e); ShowErrorCommunication(); MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.NeedsReupload = true; MainGame.Inst.SaveProfile(); }); } }
public void Update(SAMTime gameTime, InputState istate) { if (istate.IsExclusiveJustDown && innerBoundings.Contains(istate.GamePointerPositionOnMap)) { istate.Swallow(InputConsumer.GameEntity); OnExclusiveDown(istate); } if (Fraction.KICycleWaitQueue.Any() && Owner.CannonMap[Fraction.KICycleWaitQueue.Peek()].Fraction != Fraction) { SAMLog.Warning("AFC::DirtyCycleQueue", $"Cycle Queue for {Fraction.Type} contains {Fraction.KICycleWaitQueue.Peek()} ({Owner.CannonMap[Fraction.KICycleWaitQueue.Peek()].Fraction.Type})"); Fraction.KICycleWaitQueue.Clear(); return; } bool queuePriority = false; if (Fraction.KICycleWaitQueue.Any() && Fraction.KICycleWaitQueue.Peek() == Cannon.BlueprintCannonID) { Fraction.KICycleWaitQueue.Dequeue(); queuePriority = true; } timeUntilNextUpdate -= gameTime.ElapsedSeconds; if (timeUntilNextUpdate <= 0) { if (onlySingleUpdate) { if (timeUntilNextUpdate < -KIController.MAX_UPDATE_TIME) { SAMLog.Warning("AFC::QTIMEOUT", $"Overriding SingleUpdate condition - Max wait time overstepped for cannon {Cannon.BlueprintCannonID}"); DoUpdate(gameTime, istate); return; // F**k it, we have waited long enough, now it's our turn } if (Fraction.LastKiSingleCycle == MonoSAMGame.GameCycleCounter) { if (_isWaitingForQueue) { Fraction.KICycleWaitQueue.Enqueue(Cannon.BlueprintCannonID); } _isWaitingForQueue = true; return; // We want - but someone else was first } if (Fraction.KICycleWaitQueue.Count == 0) { DoUpdate(gameTime, istate); return; // We want and we don't have to wait } if (Fraction.KICycleWaitQueue.Count > 128) { SAMLog.Warning("AFC::QFULL", $"Fraction.KICycleWaitQueue is full for cannon {Cannon.BlueprintCannonID}"); return; // Queue is full - we delay our update } if (queuePriority) { DoUpdate(gameTime, istate); return; // We want and its out turn } Fraction.KICycleWaitQueue.Enqueue(Cannon.BlueprintCannonID); _isWaitingForQueue = true; return; // We want - but someone else has priority } else { DoUpdate(gameTime, istate); return; } } }
public async Task Ping(PlayerProfile profile) { try { var ps = new RestParameterSet(); ps.AddParameterInt("userid", profile.OnlineUserID); ps.AddParameterHash("password", profile.OnlinePasswordHash); ps.AddParameterString("app_version", GDConstants.Version.ToString()); ps.AddParameterString("device_name", bridge.DeviceName); ps.AddParameterString("device_version", bridge.DeviceVersion); ps.AddParameterString("unlocked_worlds", profile.StrPurchasedWorlds); ps.AddParameterString("device_resolution", bridge.DeviceResolution.FormatAsResolution()); var response = await QueryAsync <QueryResultPing>("ping", ps, RETRY_PING); if (response == null) { return; // meh - internal server error } else if (response.result == "success") { if (response.user.RevID > profile.OnlineRevisionID) { await DownloadData(profile); } if (profile.NeedsReupload) { Reupload(profile).EnsureNoError(); } } else if (response.result == "error") { ShowErrorCommunication(); if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { return; // meh } else if (response.errorid == BackendCodes.WRONG_PASSWORD || response.errorid == BackendCodes.USER_BY_ID_NOT_FOUND) { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { SAMLog.Error("Backend::INVLOGIN", $"Local user cannot login on server ({response.errorid}:{response.errormessage}). Reset local user"); // something went horribly wrong // create new user on next run profile.OnlineUserID = -1; profile.OnlineUsername = "******"; profile.AccountType = AccountType.Local; profile.OnlinePasswordHash = ""; MainGame.Inst.SaveProfile(); MainGame.Inst.Backend.CreateUser(MainGame.Inst.Profile).EnsureNoError(); }); } else { SAMLog.Error("Backend::PingError", $"Ping: Error {response.errorid}: {response.errormessage}"); } } } catch (RestConnectionException e) { SAMLog.Warning("Backend::PingRCE", e); // probably no internet ShowErrorConnection(); } catch (Exception e) { SAMLog.Error("Backend::PingE", e); ShowErrorCommunication(); } }
private async Task <SCCMListPresenter.LoadFuncResult> QueryData(SCCMListPresenter list, int page, int reqid) { var txt = _textbox.Text; if (string.IsNullOrWhiteSpace(txt)) { return(SCCMListPresenter.LoadFuncResult.LastPage); } try { var r = await MainGame.Inst.Backend.QueryUserLevel(MainGame.Inst.Profile, QueryUserLevelCategory.Search, txt, page); if (r == null) { return(SCCMListPresenter.LoadFuncResult.Error); } else { if (r.Count == 0) { return(SCCMListPresenter.LoadFuncResult.LastPage); } else { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { if (list.IsCurrentRequest(reqid)) { foreach (var levelmeta in r) { _presenter.AddEntry(new SCCMListElementOnlinePlayable(levelmeta)); } } else { SAMLog.Warning("SCCMTS::DirtyUpdate2", "Dirty presenter update ignored (response=ok)"); } }); return(SCCMListPresenter.LoadFuncResult.Success); } } } catch (Exception e) { SAMLog.Error("SCCMTS::QD", e); MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { HUD.AddModal(new HUDFadeOutInfoBox(5, 2, 0.3f) { L10NText = L10NImpl.STR_CPP_COMERR, TextColor = FlatColors.Clouds, Background = HUDBackgroundDefinition.CreateRounded(FlatColors.Alizarin, 16), CloseOnClick = true, }, true); }); return(SCCMListPresenter.LoadFuncResult.Error); } }
public void Update(out SAMNetworkConnection.ErrorType error) { var xlastState = _lastState; _lastState = _client.State; _client.Update(); if (_client.State == BluetoothAdapterState.AdapterNotFound) { error = SAMNetworkConnection.ErrorType.BluetoothAdapterNotFound; return; } if (_client.State == BluetoothAdapterState.PermissionNotGranted) { error = SAMNetworkConnection.ErrorType.BluetoothAdapterNoPermission; return; } if (_client.State == BluetoothAdapterState.Error) { error = SAMNetworkConnection.ErrorType.NetworkMediumInternalError; return; } if (_client.State == BluetoothAdapterState.NotEnabledByUser) { error = SAMNetworkConnection.ErrorType.BluetoothNotEnabled; return; } if (_client.State == BluetoothAdapterState.ConnectionFailed) { if (_lastScanDevices.Any()) { if (_currentConnDevice != null) { SAMLog.Warning("BNM::ConnectionFailed", $"Connection to {_currentConnDevice.Name} failed"); Events.Enqueue(new BluetoothMediumEvent(BluetoothMediumEvent.BTEvent.ConnectionFailed, _currentConnDevice.Name)); } _currentConnDevice = _lastScanDevices.First(); _lastScanDevices.Remove(_currentConnDevice); _isScanning = false; SAMLog.Debug($"Try connect to {_currentConnDevice.Name} ({_currentConnDevice.Address}|{_currentConnDevice.DeviceClass}|{_currentConnDevice.Type})"); Events.Enqueue(new BluetoothMediumEvent(BluetoothMediumEvent.BTEvent.TryConnection, _currentConnDevice.Name)); _client.Connect(_currentConnDevice); error = SAMNetworkConnection.ErrorType.None; } else { _isScanning = true; _client.StartScan(); _scanStartTime = MonoSAMGame.CurrentTime.TotalElapsedSeconds; error = SAMNetworkConnection.ErrorType.None; } return; } if (_client.State == BluetoothAdapterState.ConnectionLost) { error = SAMNetworkConnection.ErrorType.P2PConnectionLost; return; } if (_client.State == BluetoothAdapterState.Active) { if (_isScanning) { _lastScanDevices = _client.FoundDevices; SAMLog.Debug($"Scanning finished {_lastScanDevices.Count} devices found"); if (_lastScanDevices.Any()) { foreach (var dd in _lastScanDevices) { SAMLog.Debug($"Device found: {dd.Name} ({dd.Address}|{dd.DeviceClass}|{dd.Type})"); } _currentConnDevice = _lastScanDevices.First(); _lastScanDevices.Remove(_currentConnDevice); SAMLog.Debug($"Try connect to {_currentConnDevice.Name} ({_currentConnDevice.Address}|{_currentConnDevice.DeviceClass}|{_currentConnDevice.Type})"); _isScanning = false; _client.Connect(_currentConnDevice); } else { _isScanning = true; _client.StartScan(); _scanStartTime = MonoSAMGame.CurrentTime.TotalElapsedSeconds; } } } if (_client.State == BluetoothAdapterState.Scanning) { if (_isScanning && !_client.IsDiscovering && MonoSAMGame.CurrentTime.TotalElapsedSeconds - _scanStartTime > 30) { error = SAMNetworkConnection.ErrorType.None; SAMLog.Warning("BNM::ForceScanCancel", "Cancel scan by force"); _client.CancelScan(); return; } } if (_client.State == BluetoothAdapterState.Listen) { error = SAMNetworkConnection.ErrorType.None; if (!_client.IsDiscoverable) { _client.ContinueWaiting(); } return; } if (_client.State == BluetoothAdapterState.Connected) { if (xlastState == BluetoothAdapterState.Connecting && _currentConnDevice != null) { Events.Enqueue(new BluetoothMediumEvent(BluetoothMediumEvent.BTEvent.ConnectionSucceeded, _currentConnDevice.Name)); } } error = SAMNetworkConnection.ErrorType.None; }
public async Task <Tuple <UpgradeResult, string> > UpgradeUser(PlayerProfile profile, string username, string password) { try { var pwHashOld = profile.OnlinePasswordHash; var pwHashNew = bridge.DoSHA256(password); var ps = new RestParameterSet(); ps.AddParameterInt("userid", profile.OnlineUserID); ps.AddParameterHash("password_old", pwHashOld); ps.AddParameterString("app_version", GDConstants.Version.ToString()); ps.AddParameterHash("password_new", pwHashNew); ps.AddParameterString("username_new", username); var response = await QueryAsync <QueryResultUpgradeUser>("upgrade-user", ps, RETRY_VERIFY); if (response == null) { ShowErrorCommunication(); return(Tuple.Create(UpgradeResult.InternalError, "Internal server error")); } else if (response.result == "success") { MonoSAMGame.CurrentInst.DispatchBeginInvoke(() => { profile.AccountType = AccountType.Full; profile.OnlineUsername = response.user.Username; profile.OnlinePasswordHash = pwHashNew; profile.OnlineRevisionID = response.user.RevID; profile.AccountReminderShown = true; MainGame.Inst.SaveProfile(); }); return(Tuple.Create(UpgradeResult.Success, string.Empty)); } else if (response.result == "error") { if (response.errorid == BackendCodes.INTERNAL_EXCEPTION) { ShowErrorCommunication(); return(Tuple.Create(UpgradeResult.InternalError, response.errormessage)); } if (response.errorid == BackendCodes.WRONG_PASSWORD) { return(Tuple.Create(UpgradeResult.AuthError, string.Empty)); } if (response.errorid == BackendCodes.UPGRADE_USER_ACCOUNT_ALREADY_SET) { return(Tuple.Create(UpgradeResult.AlreadyFullAcc, string.Empty)); } if (response.errorid == BackendCodes.UPGRADE_USER_DUPLICATE_USERNAME) { return(Tuple.Create(UpgradeResult.UsernameTaken, string.Empty)); } SAMLog.Error("Backend::UU_ERR", $"UpgradeUser: Error {response.errorid}: {response.errormessage}"); ShowErrorCommunication(); return(Tuple.Create(UpgradeResult.InternalError, response.errormessage)); } else { ShowErrorCommunication(); return(Tuple.Create(UpgradeResult.InternalError, "Internal server error")); } } catch (RestConnectionException e) { SAMLog.Warning("Backend::UU_RCE", e); // probably no internet ShowErrorConnection(); return(Tuple.Create(UpgradeResult.NoConnection, string.Empty)); } catch (Exception e) { SAMLog.Error("Backend::UU_E", e); ShowErrorCommunication(); return(Tuple.Create(UpgradeResult.InternalError, "Internal server error")); } }