diff --git a/MConnectSDK/MConnectClient.cs b/MConnectSDK/MConnectClient.cs index 5c2c17c..98e6b92 100644 --- a/MConnectSDK/MConnectClient.cs +++ b/MConnectSDK/MConnectClient.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; +using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading; @@ -49,6 +50,10 @@ namespace MConnectSDK /// protected DateTime lastRedSrvCheck; /// + /// Intervallo di default x recall successive + /// + protected int waitRecall = 1000; + /// /// URL x chaimata auth QR-code /// protected string qrAuthBaseUrl = @"https://smart.maestroconnect.com/deviceauth/{0}"; @@ -130,8 +135,11 @@ namespace MConnectSDK } set { - string serVal = JsonConvert.SerializeObject(value); - ML.setRSV(ML.redHash("TokenResponse"), serVal, value.expires_in / 1000); + if (value != null) + { + string serVal = JsonConvert.SerializeObject(value); + ML.setRSV(ML.redHash("TokenResponse"), serVal, value.expires_in); + } } } /// @@ -414,8 +422,8 @@ namespace MConnectSDK { int user_code = 0; int device_code = 0; - int refrInt = 100; - int expIn = 10000; + int refrInt = 5; + int expIn = 60; if (redServAlive) { Random r = new Random(); @@ -434,7 +442,18 @@ namespace MConnectSDK } else { - /// TBD !!!FARE!!! le vere chiamate di testing remoto... + // parametri chiamata + Uri callUri = new Uri(BaseUrl + "/oauth2/token"); + var payload = "{\"client_id\": \"test\"}"; + HttpContent callCont = new StringContent(payload, Encoding.UTF8, "application/json"); + // effettuo call effettiva + var taskRes = Task.Run(() => Utils.PostURI(callUri, callCont)); + taskRes.Wait(); + + // decodifico risposta come tokResp... + var resp = JsonConvert.DeserializeObject(taskRes.Result); + waitRecall = 1000 * resp.interval; + tokResp = resp; } } /// @@ -480,9 +499,43 @@ namespace MConnectSDK * - chiamo /verification, con client_id + device_code * - salvo e verifico retVal *-----------------------------------------*/ + + // SOLOS E ho un device code... + if (tokResp != null && tokResp.device_code != "") + { + // parametri chiamata + Uri callUri = new Uri(BaseUrl + "/oauth2/verification"); + var payload = "{\"client_id\": \"test\", \"device_code\": \"" + tokResp.device_code + "\"}"; + HttpContent callCont = new StringContent(payload, Encoding.UTF8, "application/json"); + // effettuo call effettiva + var taskRes = Task.Run(() => Utils.PostURI(callUri, callCont)); + taskRes.Wait(); + + // leggo la rispsota in var temporanea... + var resp = JsonConvert.DeserializeObject(taskRes.Result); + // verifico se esista un errore come risposta... + if (resp != null) + { + if (resp.error == "") // aggiorno... + { + //// decodifico risposta come tokResp... + //tokResp = resp; + verifResp = JsonConvert.DeserializeObject(taskRes.Result); + } + else + { + if (resp.error == "slow_down") + { + Thread.Sleep(waitRecall); + } + else if (resp.error == "authorization_pending") + { + Thread.Sleep(waitRecall); + } + } + } + } } - - } } @@ -539,8 +592,9 @@ namespace MConnectSDK { redisConn = baseConf, redisConnAdmin = baseConf + ",allowAdmin=true", - // hard coded x ora - testMode = true, + // hard coded x ora + //testMode = true, + testMode = false, module = _module, defaultDb = currDb }; @@ -632,10 +686,6 @@ namespace MConnectSDK // init output ActivationPayload answ = new ActivationPayload(); StringBuilder sb = new StringBuilder(); -#if false - // init altro - reqStatus = preCheckStatus(); -#endif var _currReq = reqStatus; // verifico autorizzazione... se non c'è TENTO auth... if (!reqStatus.IsHmiEnrolled) @@ -1259,41 +1309,44 @@ namespace MConnectSDK { await Task.Run(() => { - authData = tryEnroll(); - // recupero nuova reqStatus... - _currReq = reqStatusUpd; - - // verifico SE sia stato registrato... - if (_currReq.IsHmiEnrolled || authData.IsEnrolled) + // SOLOS E precedentemente autorizzato... + if (_currReq.IsAuth) { - sb.AppendLine(""); - sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | ENROLL DONE", DateTime.Now)); - authData.Message += sb.ToString(); - processRequest = false; - _currReq.IsAuth = true; - _currReq.IsHmiEnrolled = true; + authData = tryEnroll(); + // recupero nuova reqStatus... + _currReq = reqStatusUpd; + + // verifico SE sia stato registrato... + if (_currReq.IsHmiEnrolled || authData.IsEnrolled) + { + sb.AppendLine(""); + sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | ENROLL DONE", DateTime.Now)); + authData.Message += sb.ToString(); + processRequest = false; + _currReq.IsAuth = true; + _currReq.IsHmiEnrolled = true; + } + + // verifico se richiesta cancellazione... CHIUDO! + if (token.IsCancellationRequested) + { + // riporto richiesta cancellazione... ed esco + authData = new ActivationPayload(); + processRequest = false; + } + + + // aggiorno il payload... + _currReq.Payload = authData; + reqStatus = _currReq; + + // riporto progress... + if (progress != null) + { + progress.Report(_currReq); + } } - - // verifico se richiesta cancellazione... CHIUDO! - if (token.IsCancellationRequested) - { - // riporto richiesta cancellazione... ed esco - authData = new ActivationPayload(); - processRequest = false; - } - - - // aggiorno il payload... - _currReq.Payload = authData; - reqStatus = _currReq; - - // riporto progress... - if (progress != null) - { - progress.Report(_currReq); - } - - // mi fermo... + // attendo... Thread.Sleep(500); }); } diff --git a/MConnectSDK/Utils.cs b/MConnectSDK/Utils.cs index a5b40c9..1f2db6a 100644 --- a/MConnectSDK/Utils.cs +++ b/MConnectSDK/Utils.cs @@ -81,63 +81,36 @@ namespace MConnectSDK /// public static async Task DownloadPageAsync(string pageURL) { - string result = ""; + string answ = ""; // ... Use HttpClient. using (HttpClient client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(pageURL)) using (HttpContent content = response.Content) { // ... lettura contenuto... - result = await content.ReadAsStringAsync(); - } - return result; - } -#if false - /// - /// Effettua chaimata URL e restituisce risultato - /// - /// - /// - public static string callUrl(string URL) - { - string answ = ""; - // controllo se ho un VETO all'invio... - if (dtVetoSend < DateTime.Now) - { - var client = new WebClientWT(); - //var client = new WebClient(); - client.Headers.Add("user-agent", CRS("appName")); - try - { - answ = client.DownloadString(URL); - } - catch (Exception exc) - { - // imposto un veto per pauseSendMSec - int pauseSendMSec = CRI("pauseSendMSec"); - // aggiungo NOISE... +/- 33% - Random rnd = new Random(); - int noise = rnd.Next(1, pauseSendMSec / 3); - pauseSendMSec += noise - (pauseSendMSec / 6); - // imposto veto - dtVetoSend = DateTime.Now.AddMilliseconds(pauseSendMSec); - - // log ogni - Logger lg = LogManager.GetCurrentClassLogger(); - lg.Info("Errore in callURL: impostato attesa di {0} ms prima della prossima chiamata", pauseSendMSec); - logReduxFactor--; - if (logReduxFactor <= 0) - { - lg.Error("Eccezione in esecuzione callURL: {0}{1}{2}", URL, Environment.NewLine, exc); - logReduxFactor = 10; - } - } - // restituisco valore! + answ = await content.ReadAsStringAsync(); } return answ; - } -#endif - + } + /// + /// Chiamata POST asyncrona + /// + /// URI della chiamata + /// contenuto della chiamata + /// + public static async Task PostURI(Uri reqUri, HttpContent callCont) + { + var response = string.Empty; + using (var client = new HttpClient()) + { + HttpResponseMessage result = await client.PostAsync(reqUri, callCont); + //if (result.IsSuccessStatusCode) + //{ + response = await result.Content.ReadAsStringAsync(); + //} + } + return response; + } } @@ -187,13 +160,17 @@ namespace MConnectSDK /// public string verification_uri; /// - /// Intervallo di refresh della chiamata proposto (msec) + /// Intervallo di refresh della chiamata proposto (sec) /// - public int interval = 1000; + public int interval = 5; /// - /// Expire di validità della risposta (msec) + /// Expire di validità della risposta (sec) /// - public int expires_in = 60000; + public int expires_in = 60; + /// + /// Eventuale errore in risposta token + /// + public string error = ""; } /// diff --git a/TestClient/MainForm.cs b/TestClient/MainForm.cs index 26f3268..71cb007 100644 --- a/TestClient/MainForm.cs +++ b/TestClient/MainForm.cs @@ -422,7 +422,7 @@ namespace TestClient var currImage = pictBox.Image; //if (userData.Username != "") - if (userResult.Result.Error.Reason == Reason.AllOk) + if (userResult.Result.Error.Reason == Reason.AllOk) { List userList = ((UserPayload)userResult.Result.Payload).UserList; // controllo se ho risultato...) diff --git a/TestClient/mconnect.conf.yaml b/TestClient/mconnect.conf.yaml index 5d383cc..ebf898b 100644 --- a/TestClient/mconnect.conf.yaml +++ b/TestClient/mconnect.conf.yaml @@ -1,7 +1,7 @@ #File di conf per MConnectClientSDK conf: Client_ID: "test" - MachineID: "MCID-0009-1234-5678" + MachineID: "MCID000123456789" PingTarget: "stg.api.maestroconnect.scmgroup.com" AliveTarget: "https://stg.api.maestroconnect.scmgroup.com/health" BaseUrl: "https://stg.api.maestroconnect.scmgroup.com/api"