private void AskForLogin() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] rawVerifier = new byte[32]; rng.GetBytes(rawVerifier); verifier = base64UrlEncode(rawVerifier); // Create the verifier random key byte[] rawAuthSessionID = new byte[8]; rng.GetBytes(rawAuthSessionID); authSessionID = base64UrlEncode(rawAuthSessionID); // and a random auth session id byte[] byteVerifier = Encoding.ASCII.GetBytes(verifier); byte[] hash = SHA256.Create().ComputeHash(byteVerifier); string codeChallenge = base64UrlEncode(hash); // create a SHA256 version of the verifier // issue the request to frontier with the required audience, scope, client id // code challenge, authsessioID and the URI to call back on string CALLBACK_URL = $"{URI}://auth/"; string webURL = $"{AUTH_SERVER}{AUTH_URL}" + $"?response_type=code&{AUDIENCE}&{SCOPE}&client_id={clientID}&code_challenge={codeChallenge}&code_challenge_method=S256&state={authSessionID}&redirect_uri={Uri.EscapeDataString(CALLBACK_URL)}"; Process.Start(webURL); CurrentState = State.AwaitingCallback; StatusChange?.Invoke(CurrentState); }
/// <summary> /// Generate the event if someone is listening to it /// </summary> /// <param name="sender">Event Sender</param> /// <param name="arguments">Event arguments</param> private void GenerateStatusChangeEvent(object sender, EventArgs arguments) { if (StatusChange != null) { StatusChange.Invoke(this, new EventArgs()); } }
public void Damage(float amount) { hp -= amount; if (hp <= 0) { Die(); } onDamage?.Invoke(amount); }
/// <summary> /// Idraw objects status has changed, info graphics create new /// </summary> private void Reorganize() { if (__selectedObject != null) { __selectedObject.isSelected = false; } __selectedObject = null; StatusChange?.Invoke(this, EventArgs.Empty); }
private void FireStatusChangeEvent() { if (CoreStatusChange != null) { CoreStatusChange.Invoke(); } Core.RunInGuiThread(GuiStatusChange); }
public void Heal(float amount) { if (hp + amount > maxHp) { hp = maxHp; } else { hp += amount; } onHeal?.Invoke(amount); }
// Disconnect the user from this class - credential file is unaffected. Can call before login public void Disconnect() { bool notloggedout = CurrentState != State.LoggedOut; Credentials?.Clear(); CurrentState = State.LoggedOut; cachedProfile = null; User = null; if (notloggedout) // prevent reporting if currently logged out { StatusChange?.Invoke(CurrentState); } }
private void OnStateChanged(object sender, StateChangeEventArgs e) { bool isStatusConnected; switch (e.CurrentState) { case ConnectionState.Open: case ConnectionState.Fetching: case ConnectionState.Executing: isStatusConnected = true; break; default: isStatusConnected = false; break; } if (isStatusConnected != IsStatusConnected) { IsStatusConnected = isStatusConnected; StatusChange?.Invoke(IsStatusConnected); } }
public void StartScan() { Thread oGetArgThread = new Thread(new System.Threading.ThreadStart(() => { while (true) { Thread.Sleep(100); foreach (var item in _config.List) { var tmp = Utils._ReadObject(this, item); if (ConnectionState != tmp) { ConnectionState = tmp; StatusChange?.Invoke(this, tmp); } } } })); oGetArgThread.IsBackground = true; oGetArgThread.Start(); }
private void OnStatusChange(string status) { StatusChange?.Invoke(status); }
public void ChangeState(int playerState) { stateNum += playerState; StatusChange?.Invoke(); }
private async Task ReadPackets() { try { byte[] buffer = new byte[1024]; int count = 0; while (true) { int rc = await stream.ReadAsync(buffer, count, 1024 - count); if (rc == 0) { throw new IOException("Disconnected from projector"); } count += rc; while (count > 0) { if (count >= 5 && System.Text.Encoding.ASCII.GetString(buffer, 0, 5) == "PJ_OK") { await stream.WriteAsync(System.Text.Encoding.ASCII.GetBytes("PJREQ")); count -= 5; if (count > 0) { Buffer.BlockCopy(buffer, 5, buffer, 0, count); } continue; } if (count >= 5 && System.Text.Encoding.ASCII.GetString(buffer, 0, 5) == "PJACK") { //hands have been shaked ready = true; ConnectionChange.Invoke(this, true); count -= 5; if (count > 0) { Buffer.BlockCopy(buffer, 5, buffer, 0, count); } continue; } if (count >= 5 && System.Text.Encoding.ASCII.GetString(buffer, 0, 5) == "PJ_NG") { //no udea count -= 5; if (count > 0) { Buffer.BlockCopy(buffer, 5, buffer, 0, count); } continue; } // ♠ ë P W ◙ @ ë ☺ P W 0 ◙ //status reply: 06 89 01 50 57 0a 40 89 01 50 57 30 0a if (count >= 6 && buffer[0] == 0x06 && buffer[1] == 0x89 && buffer[2] == 0x01 && buffer[3] == 0x50 && buffer[4] == 0x57 && buffer[5] == 0x0a ) { count -= 6; if (count > 0) { Buffer.BlockCopy(buffer, 6, buffer, 0, count); } continue; } if (count >= 7 && buffer[0] == 0x40 && buffer[1] == 0x89 && buffer[2] == 0x01 && buffer[3] == 0x50 && buffer[4] == 0x57 && buffer[6] == 0x0a ) { PowerStatus newStatus = PowerStatus.emergency; switch (buffer[5]) { case 0x30: newStatus = PowerStatus.standby; break; case 0x31: newStatus = PowerStatus.poweron; break; case 0x32: newStatus = PowerStatus.cooling; break; case 0x34: newStatus = PowerStatus.emergency; break; } if (newStatus != _status) { StatusChange?.Invoke(this, newStatus); _status = newStatus; } count -= 7; if (count > 0) { Buffer.BlockCopy(buffer, 7, buffer, 0, count); } continue; } break; } if (count > 0) { throw new IOException("Protocol error, unknown command"); } } } catch (IOException e) { Console.WriteLine($"ONKYO\tException when reading from socket: {e}"); } finally { await Task.Delay(1000); await Connect(address); } }
// DDE server calls this with the URL callback // NB any user can send an arbitrary URL from the Windows Run dialog, so it must be treated as untrusted public void URLCallBack(string url) { try { string CALLBACK_URL = $"{URI}://auth/"; // verify the callback url is ours, and contains parameters if (!(url.StartsWith(CALLBACK_URL) && url.Contains("?"))) { throw new EliteDangerousCompanionAppAuthenticationException("Malformed callback URL from Frontier"); } // parse out the query string into key / value pairs Dictionary <string, string> paramsDict = ParseQueryString(url); // we need an authsessionID, we need a state response, and it must be the same authsessionID if (authSessionID == null || !paramsDict.ContainsKey("state") || paramsDict["state"] != authSessionID) { throw new EliteDangerousCompanionAppAuthenticationException("Unexpected callback URL from Frontier"); } authSessionID = null; // for security, throw it away so noone can use it again (in case we get a double URL call back for some reason) // must have a code, if not, we are borked if (!paramsDict.ContainsKey("code")) { if (!paramsDict.TryGetValue("error_description", out string desc)) { paramsDict.TryGetValue("error", out desc); } desc = desc ?? "no error description"; throw new EliteDangerousCompanionAppAuthenticationException($"Negative response from Frontier: {desc}"); } string code = paramsDict["code"]; // now request frontier with the TOKEN URL to get the access token HttpWebRequest request = GetRequest(AUTH_SERVER + TOKEN_URL); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.KeepAlive = false; request.AllowAutoRedirect = true; // we send back the clientID, verifier, code and the requesturi byte[] data = Encoding.UTF8.GetBytes($"grant_type=authorization_code&client_id={clientID}&code_verifier={verifier}&code={code}&redirect_uri={Uri.EscapeDataString(CALLBACK_URL)}"); request.ContentLength = data.Length; // in the request stream, we write the data above using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(data, 0, data.Length); } // now get the response using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response?.StatusCode == null) { throw new EliteDangerousCompanionAppAuthenticationException("Failed to contact authorization server"); } else if (response.StatusCode == HttpStatusCode.OK) { string responseData = getResponseData(response); JObject json = JObject.Parse(responseData); // store the refresh token, access token and expiry time into the credential file Credentials.refreshToken = (string)json["refresh_token"]; Credentials.accessToken = (string)json["access_token"]; Credentials.tokenExpiry = DateTime.UtcNow.AddSeconds((double)json["expires_in"]); Credentials.Save(); if (Credentials.accessToken == null) { throw new EliteDangerousCompanionAppAuthenticationException("Access token not found"); } CurrentState = State.Authorized; StatusChange?.Invoke(CurrentState); } else { throw new EliteDangerousCompanionAppAuthenticationException("Invalid refresh token from authorization server"); } } } catch (Exception) { StatusChange?.Invoke(State.AuthorizationFailed); CurrentState = State.LoggedOut; } }
// throws web exception, or AuthenticationException (logs you out). Else its got the access token and your good to go private void RefreshToken() // may throw { if (Credentials.refreshToken == null) { LogOut(); throw new EliteDangerousCompanionAppAuthenticationException("Refresh token not found, need full login"); } HttpWebRequest request = GetRequest(AUTH_SERVER + TOKEN_URL); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; byte[] data = Encoding.UTF8.GetBytes($"grant_type=refresh_token&client_id={clientID}&refresh_token={Credentials.refreshToken}"); request.ContentLength = data.Length; using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(data, 0, data.Length); } try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { string responseData = getResponseData(response); JObject json = JObject.Parse(responseData); Credentials.refreshToken = (string)json["refresh_token"]; Credentials.accessToken = (string)json["access_token"]; Credentials.tokenExpiry = DateTime.UtcNow.AddSeconds((double)json["expires_in"]); Credentials.Save(); if (Credentials.accessToken == null) { LogOut(); throw new EliteDangerousCompanionAppAuthenticationException("Access token not found"); } CurrentState = State.Authorized; StatusChange?.Invoke(State.RefreshSucceeded); } else { LogOut(); throw new EliteDangerousCompanionAppAuthenticationException("Invalid refresh token"); } } } catch (WebException wex) { System.Diagnostics.Debug.WriteLine("CAPI Refresh Web exception " + wex.Status); if (wex.Status == WebExceptionStatus.ProtocolError) // seen when a bad refresh token is sent to frontier { LogOut(); throw new EliteDangerousCompanionWebException("Protocol Error"); } else { throw new EliteDangerousCompanionWebException("Failed to contact API server " + wex); } } }
private void AlertStatusChange(string message, Action <string> logAction) { StatusChange?.Invoke(message, Status); logAction(message); }
public void Start() { statusChangeHandler?.Invoke(Status.Started); }
public void SetCacheStatus(CacheStatus newStatus, string message) { _status = newStatus; StatusChange?.Invoke(_status, message); }
public void RepportStatus(string status) { Logger.Log <ProgressRepporter>(LoggerLevel.Info, status); Status = status; StatusChange?.Invoke(this, status); }