string UpdateStatusAction(string sessionID, string action) { string result = ""; try { //action = approve, deny or hold. string computerName = SecurityUtilities.GetComputerName(); string userName = SecurityUtilities.GetUserName(); Authentication auth; if (Utilities.Auth == null) { auth = SecurityUtilities.GetAuthentication(serviceName); } else { auth = Utilities.Auth; } HttpsClient client = new HttpsClient(); Uri fhirAddress = new Uri(UpdatePendingStatusUri); result = client.UpdatePendingStatus(fhirAddress, auth, sessionID, action, computerName, userName); } catch (Exception ex) { throw ex; } return(result); }
public async Task <string> GrantCustomSpace(string userId, int type, string fileids = "") { DingTalkServerAddressConfig _addressConfig = DingTalkServerAddressConfig.GetInstance(); LoginMobileController loginMobileController = new LoginMobileController(); var access_token = await loginMobileController.GetAccessToken(); HttpsClient _client = new HttpsClient(); _client.QueryString.Add("access_token", access_token); _client.QueryString.Add("type", type == 0 ? "add" : "download"); _client.QueryString.Add("userid", userId); _client.QueryString.Add("domain", "test"); if (type == 0) { _client.QueryString.Add("path", "/"); //授权访问的路径,如授权访问所有文件传"/",授权访问/doc文件夹传"/doc/",需要utf-8 urlEncode, type=add时必须传递 } else { _client.QueryString.Add("fileids", userId); } var url = _addressConfig.GetGrantCustomSpace; var result = await _client.Get(url); return(result); }
private static string Post(string method, object args) { var system = new { mac_address = CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)), ip_address = CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)), host_name = CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)), model = InitialParametersClass.ControllerPromptName, version = InitialParametersClass.FirmwareVersion, ram_free = SystemMonitor.RAMFree * 1000 }; var app = new { index = InitialParametersClass.ApplicationNumber, name = InitialParametersClass.ProgramIDTag, version = _assembly.GetName().Version.ToString(), last_start_time = _startupTime, build_date = _programInfo["App Build Date"], programmer = _programInfo["Programmer Name"], simpl_sharp_version = _programInfo["SIMPLSharp Version"], include_4_dat_version = _programInfo["Include4.dat Version"] }; var requestObject = new { method, @params = args, project_key = _projectKey, system, app }; var request = new HttpsClientRequest { RequestType = RequestType.Post, ContentSource = ContentSource.ContentString, ContentString = JsonConvert.SerializeObject(requestObject, Formatting.Indented, new IsoDateTimeConverter()), Header = { ContentType = "application/json" }, KeepAlive = false, Url = new Crestron.SimplSharp.Net.Http.UrlParser(@"https://crestroncloudlogger.appspot.com/api") }; using (var client = new HttpsClient { IncludeHeaders = false }) { var response = client.Dispatch(request); CrestronConsole.PrintLine("Logger response: {0}", response.Code); CrestronConsole.PrintLine("Logger rx:\r\n{0}", response.ContentString); return(response.ContentString); } }
/// <summary> /// gets the IP of the local bridge, currently one bridge is supported /// </summary> /// <returns></returns> public static string getIP() { try { var getBridge = new HttpsClient(); getBridge.KeepAlive = false; getBridge.Accept = "application/json"; getBridge.HostVerification = false; getBridge.PeerVerification = false; HttpsClientRequest bridgeRequest = new HttpsClientRequest(); bridgeRequest.Url.Parse("https://www.meethue.com/api/nupnp"); HttpsClientResponse lResponse = getBridge.Dispatch(bridgeRequest); String jsontext = lResponse.ContentString; /* * [{"id":"001788fffe2ad33b","internalipaddress":"172.22.131.242"}] */ JArray BridgeArray = JArray.Parse(jsontext); BridgeIp = (String)BridgeArray[0].SelectToken("internalipaddress"); //BridgeApi = "U8FEH-CRuHFGxXe59pitg6UeyqGKWnMsqHef8oMt"; CrestronConsole.PrintLine("Get IP of Bridge complete..."); } catch (Exception e) { CrestronConsole.PrintLine("Exception is {0}", e); } return(BridgeIp); }
internal static string HttpsJsonRequest(string uri, Crestron.SimplSharp.Net.Https.RequestType requestType, string key, string msg, string contentType) { HttpsClient client = new HttpsClient(); client.HostVerification = false; client.PeerVerification = false; try { HttpsClientRequest aRequest = new HttpsClientRequest(); //HttpsClientRequest aRequest = new HttpsClientRequest(); string aUrl = uri; aRequest.Url.Parse(aUrl); aRequest.Encoding = Encoding.UTF8; aRequest.RequestType = requestType; aRequest.Header.ContentType = contentType; aRequest.ContentString = msg; aRequest.Header.SetHeaderValue("Authorization", key); HttpsClientResponse myResponse = client.Dispatch(aRequest); return(myResponse.ContentString); } catch (Exception ex) { LogException(@"SyncProMethods \ GenericHttpsRequest", ex); return(null); } }
public void getStatus(string deviceID, string category) { HttpsClient client = new HttpsClient(); client.AllowAutoRedirect = true; client.PeerVerification = false; client.HostVerification = false; client.KeepAlive = true; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; //Get Switches string url = SmartThingsReceiver.InstallationURL + "/" + category + "/" + deviceID + "?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); //ErrorLog.Notice("Response = {0}", response.ContentString); string pattern = "value\":\"(.*?)\""; foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) { SignalChangeEvents.SerialValueChange(deviceID, m.Groups[1].ToString()); } }
//TODO: Update function in JavaScript and C# to postUnknownDOBExistingPatient public bool postUnknownDOBExistingpatient(string passedLocalNoID) { bool result = false; try { Authentication auth; if (Utilities.Auth == null) { auth = SecurityUtilities.GetAuthentication(serviceName); } else { auth = Utilities.Auth; } localNoID = passedLocalNoID; HttpsClient client = new HttpsClient(); Uri endpoint = new Uri(IdentityChallengeUri); string resultResponse = client.SendIdentityChallenge(endpoint, auth, passedLocalNoID, "failedchallenge", "", SecurityUtilities.GetComputerName(), ClinicArea); if (resultResponse.ToLower() == "yes") { result = true; } else if (resultResponse.ToLower().Contains("error") == true) { errorDescription = "Error in PatientBridge::postUnknownDOBExistingPatient: " + resultResponse.Substring(3); } } catch (Exception ex) { errorDescription = "Error in PatientBridge::postUnknownDOBExistingPatient: " + ex.Message; } return(result); }
private void checkPushes() { debug("checking for new data since " + lastModified); HttpsClient cli = new HttpsClient(); cli.KeepAlive = false; //cli.Verbose = true; HttpsClientRequest req = new HttpsClientRequest(); req.Url.Parse(api + "/pushes?modified_after=" + lastModified); req.Header.AddHeader(new HttpsHeader("Access-Token", apiToken)); cli.DispatchAsync(req, (resp, e) => { try { if (resp.Code != 200) { debug("Bad API Token? " + resp.Code + ": " + resp.ContentString); return; } PushesData ps = JsonConvert.DeserializeObject <PushesData>(resp.ContentString); foreach (PushData p in ps.pushes) { handlePush(p); if (p.modified > lastModified) { lastModified = p.modified; } } debug("lastModified is now " + lastModified); } catch (Exception e2) { debug("GET failed: " + e2.Message); } }); }
public void setDimmerLevel(string level, string deviceID, string category) { HttpsClient client = new HttpsClient(); //client.Verbose = true; client.PeerVerification = false; client.HostVerification = false; //Testing //client.AllowAutoRedirect = true; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; String url = ""; url = SmartThingsReceiver.InstallationURL + "/" + category + "/" + deviceID + "/" + "level/" + level + "?access_token=" + SmartThingsReceiver.AccessToken; request.KeepAlive = true; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); if (response.Code >= 200 && response.Code < 300) { //ErrorLog.Notice("Wink https response code: " + response.Code); //ErrorLog.Notice(response.ContentString.ToString() + "\n"); } else { // A reponse code outside this range means the server threw an error. ErrorLog.Notice("HTTPS response code: " + response.Code); } }
public void Doorbell() { debug("PBServer.Doorbell"); HttpsClient cli = new HttpsClient(); cli.KeepAlive = false; //cli.Verbose = true; HttpsClientRequest req = new HttpsClientRequest(); req.Url.Parse(api + "/pushes"); req.Header.AddHeader(new HttpsHeader("Access-Token", apiToken)); req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post; req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json")); PushData p = new PushData("Crestron Doorbell!", "Reply Unlock or Ignore.", "note"); req.ContentString = JsonConvert.SerializeObject(p); cli.DispatchAsync(req, (resp, e) => { try { if (resp.Code != 200) { debug("Bad API Token? " + resp.Code + ": " + resp.ContentString); return; } debug("Doorbell response: " + resp.ContentString); } catch (Exception e2) { debug("POST failed: " + e2.Message); } onEventCompleted(); }); }
private static void GetToken() { try { if (Username.Length > 0 && Password.Length > 0) { using (HttpsClient client = new HttpsClient()) { client.TimeoutEnabled = true; client.Timeout = 10; client.HostVerification = false; client.PeerVerification = false; client.AllowAutoRedirect = false; client.IncludeHeaders = false; HttpsClientRequest request = new HttpsClientRequest(); request.Url.Parse("https://wap.tplinkcloud.com"); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post; request.Header.AddHeader(new HttpsHeader("Content-Type", "application/json")); request.ContentString = "{\"method\":\"login\",\"params\":{\"appType\":\"Crestron\",\"cloudUserName\":\"" + Username + "\",\"cloudPassword\":\"" + Password + "\",\"terminalUUID\":\"3df98660-6155-4a7d-bc70-8622d41c767e\"}}"; HttpsClientResponse response = client.Dispatch(request); if (response.ContentString != null) { if (response.ContentString.Length > 0) { JObject body = JObject.Parse(response.ContentString); if (body["result"] != null) { if (body["result"]["token"] != null) { Token = body["result"]["token"].ToString().Replace("\"", string.Empty); } } } } } } else { throw new ArgumentException("Username and Password cannot be emtpy"); } } catch (SocketException se) { ErrorLog.Exception("SocketException occured in System.GetToken - ", se); } catch (HttpsException he) { ErrorLog.Exception("HttpsException occured in System.GetToken - ", he); } catch (Exception e) { ErrorLog.Exception("Exception occured in System.GetToken - ", e); } }
//Todo:Check if we can pass the returned object type and deserialze. private static HttpsClientResponse StaticDeviceRequest(string uri, RequestType requestType, string data, string contentType, string accessKey) { HttpsClient client = new HttpsClient(); client.HostVerification = false; client.PeerVerification = false; HttpsClientRequest aRequest = new HttpsClientRequest(); aRequest.Url.Parse(uri); aRequest.Encoding = Encoding.UTF8; aRequest.RequestType = requestType; aRequest.Header.ContentType = contentType; //Content cannot be null aRequest.ContentString = (data != null) ? data : ""; if (accessKey != null) { aRequest.Header.SetHeaderValue("Authorization", accessKey); } HttpsClientResponse res = client.Dispatch(aRequest); if (res.Code == 401) { throw new DeviceNotAuthorizedException("Device not authorized"); } return(res); }
//Use authorization code to retrieve a refresh token and a session token private void GetTokenAndRefreshToken() { try { using (HttpsClient client = new HttpsClient()) { client.TimeoutEnabled = true; client.Timeout = 10; client.HostVerification = false; client.PeerVerification = false; client.AllowAutoRedirect = false; client.IncludeHeaders = false; HttpsClientRequest request = new HttpsClientRequest(); request.Url.Parse("https://www.googleapis.com/oauth2/v4/token?client_id=" + ClientID + "&code=" + AuthCode + "&grant_type=authorization_code&redirect_uri=https://www.google.com&client_secret=" + ClientSecret); request.RequestType = RequestType.Post; HttpsClientResponse response = client.Dispatch(request); if (response.ContentString != null) { if (response.ContentString.Length > 0) { JObject body = JObject.Parse(response.ContentString); if (body["expires_in"] != null) { var seconds = Convert.ToInt16(body["expires_in"].ToString().Replace("\"", string.Empty)) - 10; var milliseconds = seconds * 1000; refreshTimer = new CTimer(UseRefreshToken, milliseconds); } if (body["access_token"] != null) { Token = body["access_token"].ToString().Replace("\"", string.Empty); } if (body["token_type"] != null) { TokenType = body["token_type"].ToString().Replace("\"", string.Empty); } if (body["refresh_token"] != null) { refreshToken = body["refresh_token"].ToString().Replace("\"", string.Empty); using (StreamWriter writer = new StreamWriter(File.Create(refreshTokenFilePath + refreshTokenFileName))) { writer.WriteLine(refreshToken); } } } } } } catch (Exception e) { ErrorLog.Exception("Exception ocurred in GetTokenAndRefreshToken", e); } }
public async Task <object> SendCommomMessage(CommomOaSendModel commomOaSendModel) { DingTalkServerAddressConfig _addressConfig = DingTalkServerAddressConfig.GetInstance(); HttpsClient _client = new HttpsClient(); form[] forms = new form[] { }; List <form> formList = new List <form>(); if (commomOaSendModel.msg != null) { foreach (var item in commomOaSendModel.msg) { formList.Add(new form() { key = item.Key, value = item.Value } ); } } forms = formList.ToArray(); oa oa = new oa() { message_url = commomOaSendModel.linkUrl, head = new head { bgcolor = "FFBBBBBB", text = "头部标题111222" }, body = new body { title = commomOaSendModel.title, form = forms, } }; NewOATestModel newOATestModel = new NewOATestModel() { msgtype = "oa", oa = oa }; DingTalk.Models.SendOAModel sendOAModel = new SendOAModel() { //E应用agent_id agent_id = long.Parse(DTConfig.AppAgentId), userid_list = commomOaSendModel.userId, to_all_user = false, //dept_id_list = null, msg = newOATestModel }; LoginMobileController loginMobileController = new LoginMobileController(); var access_token = await loginMobileController.GetAccessToken(); _client.QueryString.Add("access_token", access_token); var url = _addressConfig.GetWorkMsgUrl; var result = await _client.UploadModel(url, sendOAModel); return(result); }
public static string Authorize(string username, string password) { try { string authToken = string.Empty; usr = username; pass = password; if (CrestronDataStoreStatic.GetLocalStringValue("authToken", out authToken) != CrestronDataStore.CDS_ERROR.CDS_SUCCESS) { if (usr.Length > 0 && pass.Length > 0) { using (HttpsClient authServer = new HttpsClient()) { IPHostEntry entry; if ((entry = Dns.GetHostEntry("plex.tv")) != null) { HttpsClientRequest authServerRequest = new HttpsClientRequest(); HttpsClientResponse authServerResponse; authServer.TimeoutEnabled = true; authServer.Timeout = 25; authServer.AuthenticationMethod = Crestron.SimplSharp.Net.AuthMethod.BASIC; authServer.PeerVerification = false; authServer.UserName = usr; authServer.Password = pass; authServerRequest.Url.Parse("https://plex.tv/users/sign_in.json"); authServerRequest.Header.AddHeader(new HttpsHeader("X-Plex-Client-Identifier", "Crestron")); authServerRequest.RequestType = RequestType.Post; authServerResponse = authServer.Dispatch(authServerRequest); JObject response = JObject.Parse(authServerResponse.ContentString); authToken = (string)response["user"]["authToken"]; CrestronDataStoreStatic.SetLocalStringValue("authToken", authToken); } } } } return(authToken); } catch (Exception e) { if (e.Message.Contains("Unable to resolve address")) { } else { ErrorLog.Error("Error authorizing Plex: {0}", e); } return(""); } }
private static void SendJSON(Patient payload) { Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(PatentCheckinUri); HttpsClient client = new HttpsClient(); client.SendFHIRPatientProfile(endpoint, auth, payload); Console.WriteLine(client.ResponseText); }
public string GetHttpsText(string url) { var client = new HttpsClient(); client.PeerVerification = false; var response = client.GetResponse(url); return(response.ContentString); }
public static HttpsClient NewClient() { HttpsClient result = new HttpsClient(); result.KeepAlive = false; result.PeerVerification = false; return(result); }
//GetUserEmail function public void GetUserEmail() { if (User_Token != "") { HttpsClient MyHttpsConnection = new HttpsClient(); HttpsClientRequest MyHttpsRequest = new HttpsClientRequest(); HttpsClientResponse MyHttpsResponse; string HttpsUrl; string MyTempString; string[] words; string commandstring = ""; bool FoundEmail = false; MyHttpsConnection.PeerVerification = false; MyHttpsConnection.HostVerification = false; MyHttpsConnection.Verbose = false; HttpsUrl = "https://api.pushbullet.com/v2/users/me"; MyHttpsRequest.KeepAlive = true; MyHttpsRequest.Url.Parse(HttpsUrl); MyHttpsRequest.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; MyHttpsRequest.Header.SetHeaderValue("Authorization", "Bearer " + User_Token); PrintString2 = User_Token; MyHttpsRequest.ContentString = commandstring; // Dispatch will actually make the request with the server MyHttpsResponse = MyHttpsConnection.Dispatch(MyHttpsRequest); MyHttpsConnection.Abort(); MyTempString = MyHttpsResponse.ContentString.ToString(); words = MyTempString.Split(','); PrintString = ""; foreach (string word in words) { PrintString = PrintString + '+' + word; if (word.Contains("email_normalized")) { User_Email = word.Substring(20, word.Length - 21); FoundEmail = true; } } if (!FoundEmail) { User_Email = "Email Not Found!"; } } else { PrintString = "No Token Found"; } }
private HttpsConnect() { _client = new HttpsClient(); _client.KeepAlive = false; _client.HostVerification = false; _client.PeerVerification = false; _client.Accept = "application/json"; _request = new HttpsClientRequest(); }
private static void SendJSON(Media payload) { Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(SearchBiometricsUri); HttpsClient client = new HttpsClient(); client.SendFHIRMediaProfile(endpoint, auth, payload); Console.WriteLine(client.ResponseText); }
public void checkPushes() { CrestronConsole.PrintLine("Getting Previous Pushes"); HttpsClient hsc = new HttpsClient(); hsc.PeerVerification = false; hsc.HostVerification = false; HttpsClientRequest hscr = new HttpsClientRequest(); //HttpsClientResponse hscrs; hsc.KeepAlive = true; hscr.Url.Parse("https://api.pushbullet.com/v2/pushes?active=true&modified_after=" + lastModified); //hscr.Header.AddHeader(new HttpsHeader("Access-Token", token)); hscr.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; hscr.Header.AddHeader(new HttpsHeader("Content-Type", "application/json")); hscr.Header.AddHeader(new HttpsHeader("Authorization", "Bearer " + token)); //hscr.ContentString = JsonConvert.SerializeObject(hscr.ToString()); hsc.DispatchAsync(hscr, (hscrs, e) => { try { if (hscrs.Code >= 200 && hscrs.Code < 300) { // success //CrestronConsole.PrintLine("Old Pushes Requst Send."); //string s = hscrs.ContentString.ToString(); //CrestronConsole.Print("Old Push Data: " + s + "\n"); pushReturn pr = JsonConvert.DeserializeObject <pushReturn>(hscrs.ContentString); foreach (pushData pd in pr.pushes) { //CrestronConsole.Print("Json Push Data: " + pr.ToString() + "\n"); if (pd.modified > lastModified) { lastModified = pd.modified; CrestronConsole.Print("Json Push Data: " + pd.body + "\n"); if (pd.body.ToLower().StartsWith("unlock")) { OnNewResponse(new SimplSharpString(pd.body.ToLower())); } else if (pd.body.ToLower().StartsWith("ignore")) { OnNewResponse(new SimplSharpString(pd.body.ToLower())); } } } } } catch (Exception f) { CrestronConsole.PrintLine("Old Push Connection error:" + f.ToString()); } }); }
/// <summary> /// Private HTTPS submit request /// </summary> /// <param name="url"></param> /// <param name="port"></param> /// <param name="requestType"></param> /// <param name="username"></param> /// <param name="password"></param> private void SubmitRequestHttps(string url, ushort port, ushort requestType, string contentType, string username, string password) { try { HttpsClient client = new HttpsClient(); HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; client.KeepAlive = false; client.HostVerification = false; client.PeerVerification = false; var authorization = ""; if (!string.IsNullOrEmpty(username)) { authorization = EncodeBase64(username, password); } if (!string.IsNullOrEmpty(authorization)) { request.Header.SetHeaderValue("Authorization", authorization); } if (!string.IsNullOrEmpty(contentType)) { request.Header.ContentType = contentType; } request.Url.Parse(url); request.RequestType = (Crestron.SimplSharp.Net.Https.RequestType)requestType; response = client.Dispatch(request); CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString())); if (!string.IsNullOrEmpty(response.ContentString.ToString())) { OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange); } if (response.Code > 0) { OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange); } } catch (Exception e) { //var msg = string.Format("SubmitRequestHttps({0}, {1}, {2}, {3}, {4}) failed:{5}", url, port, requestType, username, password, e.Message); //CrestronConsole.PrintLine(msg); //ErrorLog.Error(msg); CrestronConsole.PrintLine(e.Message); OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange); } }
private static IList <PatientProfile> GetCheckinList() { IList <PatientProfile> PatientProfiles = null; Authentication auth = SecurityUtilities.GetAuthentication(NoIDServiceName); Uri endpoint = new Uri(PendingPatientsUri); HttpsClient client = new HttpsClient(); PatientProfiles = client.RequestPendingQueue(endpoint, auth); Console.WriteLine(client.ResponseText); return(PatientProfiles); }
//Get device info public void GetDevice() { // CrestronConsole.PrintLine("Device ID is: " + DeviceID); if (DeviceID.Length > 0) { try { using (HttpsClient client = new HttpsClient()) { client.TimeoutEnabled = true; client.Timeout = 10; client.HostVerification = false; client.PeerVerification = false; client.AllowAutoRedirect = false; client.IncludeHeaders = false; HttpsClientRequest request = new HttpsClientRequest(); request.Url.Parse("https://smartdevicemanagement.googleapis.com/v1/" + DeviceID); request.RequestType = RequestType.Get; request.Header.ContentType = "application/json"; request.Header.AddHeader(new HttpsHeader("Authorization", string.Format("{0} {1}", GoogleNestCloud.TokenType, GoogleNestCloud.Token))); HttpsClientResponse response = client.Dispatch(request); // CrestronConsole.PrintLine("GET DEVICE INFO****************** " + response.ContentString); if (response.ContentString != null) { if (response.ContentString.Length > 0) { JToken body = JToken.Parse(response.ContentString); ParseData(body); } } } } catch (Exception e) { ErrorLog.Exception("Exception ocurred in GetDevice", e); } } else { if (onErrorMsg != null) { onErrorMsg("Device not found, ensure the Label field is set in the app"); } } }
//Get all devices public void GetDevices() { try { using (HttpsClient client = new HttpsClient()) { client.TimeoutEnabled = true; client.Timeout = 10; client.HostVerification = false; client.PeerVerification = false; client.AllowAutoRedirect = false; client.IncludeHeaders = false; HttpsClientRequest request = new HttpsClientRequest(); request.Url.Parse("https://smartdevicemanagement.googleapis.com/v1/enterprises/" + ProjectID + "/devices"); request.RequestType = RequestType.Get; request.Header.ContentType = "application/json"; request.Header.AddHeader(new HttpsHeader("Authorization", string.Format("{0} {1}", TokenType, Token))); HttpsClientResponse response = client.Dispatch(request); // CrestronConsole.PrintLine("Get Devices ************ " + response.ContentString); if (response.ContentString != null) { if (response.ContentString.Length > 0) { JObject body = JObject.Parse(response.ContentString); if (body["error"] != null) { onErrorMessage(body["error"]["message"].ToString().Replace("\"", string.Empty)); } foreach (var dev in body["devices"]) { if (devices.ContainsKey(dev["traits"]["sdm.devices.traits.Info"]["customName"].ToString().Replace("\"", string.Empty))) { devices[dev["traits"]["sdm.devices.traits.Info"]["customName"].ToString().Replace("\"", string.Empty)].ParseData(dev); } } } } } } catch (Exception e) { ErrorLog.Exception("Exception ocurred in GetDevices", e); } }
/// <summary> /// Attempt to refresh the access token, return a boolean indicating success (true)/failure (false), and /// include the response code and body from the Authorization Server in the event of failure /// </summary> /// <param name="errMsg"></param> /// <param name="statusCode"></param> /// <returns></returns> bool RefreshAccessToken(out string errMsg, out int statusCode) { using (var client = new HttpsClient()) { CrestronConsole.PrintLine("Attempting to refresh Access Token..."); HttpsClientRequest req = new HttpsClientRequest(); req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post; req.Url = new UrlParser(TokenEndpoint); HttpsHeaders headers = new HttpsHeaders(); // Auth0's token endpoint expects all the necessary information to be // placed in the entity-body of the request headers.SetHeaderValue("Content-Type", "application/x-www-form-urlencoded"); req.ContentString = BuildQueryString( new NameValueCollection { { "grant_type", "refresh_token" }, { "client_id", ClientID }, { "client_secret", ClientSecret }, { "refresh_token", RefreshToken } }); // Always set the Content-Length of your POST request to indicate the length of the body, // or else the Content-Length will be set to 0 by default! headers.SetHeaderValue("Content-Length", req.ContentString.Length.ToString()); req.Header = headers; // Send the POST request to the token endpoint and wait for a response... HttpsClientResponse tokenResponse = client.Dispatch(req); if (tokenResponse.Code >= 200 && tokenResponse.Code < 300) { // Parse JSON response and securely store the token JObject resBody = JsonConvert.DeserializeObject <JObject>(tokenResponse.ContentString); accessToken = (string)resBody["access_token"]; CrestronConsole.PrintLine("Received a new \"{0}\" Access Token. It expires in {1} hours", (string)resBody["token_type"], (int)resBody["expires_in"] / 60.0 / 60.0); // Client is now authorized to access the protected resource again hasAccessToken = true; errMsg = ""; statusCode = tokenResponse.Code; return(true); } else { CrestronConsole.PrintLine("Refresh Failed"); errMsg = tokenResponse.ContentString; statusCode = tokenResponse.Code; return(false); } } }
/// <summary> /// Connect to pushbullet and make a send request /// </summary> private string PushBulletHttpRequest(string requestUrl, string accessToken, RequestType HttpRequestType, string pushBulletObject) { HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; HttpsClientRequest httpRequest = new HttpsClientRequest(); HttpsClientResponse response; try { httpRequest.KeepAlive = true; httpRequest.Url.Parse(requestUrl); httpRequest.RequestType = HttpRequestType; httpRequest.Header.SetHeaderValue("Content-Type", "application/json"); httpRequest.Header.SetHeaderValue("Access-Token", accessToken); httpRequest.ContentString = pushBulletObject; response = client.Dispatch(httpRequest); if (response.Code >= 200 && response.Code < 300) { // sucess return(response.ContentString); } else if (response.Code == 401 | response.Code == 403) { ErrorLog.Error("PushBullet Invalid Access Token"); OnDoorLockMessageReceived("PushBullet Invalid Access Token"); return("Error"); } else { // error responce ErrorLog.Error(response.ContentString.ToString()); return("Error"); } } catch (Exception e) { ErrorLog.Error("PushBulletHttpRequest Error: " + e.Message); return("Error"); } finally { client.Dispose(); } }
public void doPost(string username, string password) { string userdefault = Txt.read(Txt.path); if (userdefault != "") { JObject obj = JObject.Parse(userdefault); string expire = obj["expires_in"].ToString(); expire = expire.Substring(1, expire.Length - 2); DateTime exp = DateTime.Parse(expire); if (exp.CompareTo(DateTime.Now) > 0) { handleLogin(userdefault); return; } } string url = "https://home.nest.com/user/login"; url = url + "?username="******"&password="******"Https Data: " + s); handleLogin(s); } } catch (Exception f) { CrestronConsole.PrintLine("Connection error:" + f.ToString()); } }); }
//Use refresh token to request a session token private void UseRefreshToken(object o) { try { using (HttpsClient client = new HttpsClient()) { client.TimeoutEnabled = true; client.Timeout = 10; client.HostVerification = false; client.PeerVerification = false; client.AllowAutoRedirect = false; HttpsClientRequest request = new HttpsClientRequest(); request.Url.Parse("https://www.googleapis.com/oauth2/v4/token?client_id=" + ClientID + "&refresh_token=" + refreshToken + "&grant_type=refresh_token&redirect_uri=https://www.google.com&client_secret=" + ClientSecret); request.RequestType = RequestType.Post; HttpsClientResponse response = client.Dispatch(request); if (response.ContentString != null) { if (response.ContentString.Length > 0) { JObject body = JObject.Parse(response.ContentString); if (body["expires_in"] != null) { var seconds = Convert.ToInt16(body["expires_in"].ToString().Replace("\"", string.Empty)) - 10; var milliseconds = seconds * 1000; refreshTimer = new CTimer(UseRefreshToken, milliseconds); } if (body["access_token"] != null) { Token = body["access_token"].ToString().Replace("\"", string.Empty); } if (body["token_type"] != null) { TokenType = body["token_type"].ToString().Replace("\"", string.Empty); } } } } } catch (Exception e) { DebugLogic.Log(">>> ERROR: Exception ocurred in UseRefreshToken" + e, DebugLogic.ErrorLevel.Error, true); } }
public void getStatus(string deviceID, string category) { HttpsClient client = new HttpsClient(); client.AllowAutoRedirect = true; client.PeerVerification = false; client.HostVerification = false; client.KeepAlive = true; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; //Get Switches string url = SmartThingsReceiver.InstallationURL + "/"+category+"/"+deviceID+"?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); //ErrorLog.Notice("Response = {0}", response.ContentString); string pattern = "value\":\"(.*?)\""; foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) SignalChangeEvents.SerialValueChange(deviceID, m.Groups[1].ToString()); }
public void AuthenticateStep2() { HttpsClient client = new HttpsClient(); //client.Verbose = true; //Testing client.AllowAutoRedirect = true; client.PeerVerification = false; client.HostVerification = false; client.KeepAlive = true; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; //Get AccessToken String url = "https://graph.api.smartthings.com/oauth/token?grant_type=authorization_code&client_id=" + ClientID + "&client_secret=" + ClientSecret + "&redirect_uri=http://" + IP + ":" + Port.ToString() + "&scope=app&code=" + AuthCode; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; try { response = client.Dispatch(request); //ErrorLog.Notice("Response = {0}\n", response.ContentString); string pattern = ".*?\"([a-z0-9-]+)\""; var r = new Regex(pattern, RegexOptions.IgnoreCase); if (response.ContentString != null) { var match = r.Match(response.ContentString); if (match.Success) { SmartThingsReceiver.AccessToken = match.Groups[1].Value; //ErrorLog.Notice("AccessToken = {0}\n", SmartThingsReceiver.AccessToken); } } } catch (Exception e) { ErrorLog.Error("**Failed To Retrieve External Complete Authentication**\n"); ErrorLog.Error("URL = {0}\n", url); response = null; return; } //Get Installation ID and URL url = "https://graph.api.smartthings.com/api/smartapps/endpoints/" + SmartThingsReceiver.ClientID + "?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; try { response = client.Dispatch(request); //ErrorLog.Notice("Response = {0}\n", response.ContentString); string pattern = ".*?url\":\"(.*?)\"}"; var r = new Regex(pattern, RegexOptions.IgnoreCase); if (response.ContentString != null) { var match = r.Match(response.ContentString); if (match.Success) { SmartThingsReceiver.InstallationURL = "https://graph.api.smartthings.com" + match.Groups[1].Value; //ErrorLog.Notice("InstallationURL = {0}\n", SmartThingsReceiver.InstallationURL); } } } catch (Exception e) { ErrorLog.Error("**Failed To Retrieve External Complete Authentication**\n"); ErrorLog.Error("URL = {0}\n", url); response = null; return; } //Write Authentication Credentials to a File SmartThingsReceiver.WriteFile(); SmartThingsReceiver.Authorized = 1; }
public ushort dismissPush(string PushIden) { if (Access_Code != "") { string commandstring = ""; HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; String url = "https://api.pushbullet.com/v2/pushes/" + PushIden; request.KeepAlive = true; request.Url.Parse(url); request.Header.SetHeaderValue("Content-Type", "application/json"); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post; request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code); Dismiss dismiss = new Dismiss { dismissed = true }; commandstring = JsonConvert.SerializeObject(dismiss, Formatting.Indented); request.ContentString = commandstring; response = client.Dispatch(request); if (response.Code >= 200 && response.Code < 300) { return 1; } else { ErrorLog.Notice("Error Dismissing - " + response.Code.ToString() + "\n"); return 0; } } else return 0; }
public ushort deletePush(string PushIden) { if (Access_Code != "") { HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; client.UserName = Access_Code; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; //String url = "https://api.pushbullet.com/v2/pushes/" + PushIden; String url = "https://api-pushbullet-com-fqp420kzi8tw.runscope.net/v2/pushes/" + PushIden; //request.KeepAlive = true; request.Url.Parse(url); request.Header.SetHeaderValue("Content-Type", "application/json"); //request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Delete; request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code); response = client.Dispatch(request); string s = response.ContentString.ToString(); if (response.Code >= 200 && response.Code < 300) { //ErrorLog.Notice("Deleted\n"); return 1; } else { ErrorLog.Notice("Error Deleting - " + response.Code.ToString() + "\n"); return 0; } } else return 0; }
private void checkPushes() { debug("checking for new data since " + lastModified); HttpsClient cli = new HttpsClient(); cli.KeepAlive = false; //cli.Verbose = true; HttpsClientRequest req = new HttpsClientRequest(); req.Url.Parse(api + "/pushes?modified_after=" + lastModified); req.Header.AddHeader(new HttpsHeader("Access-Token", apiToken)); cli.DispatchAsync(req, (resp, e) => { try { if (resp.Code != 200) { debug("Bad API Token? " + resp.Code + ": " + resp.ContentString); return; } PushesData ps = JsonConvert.DeserializeObject<PushesData>(resp.ContentString); foreach (PushData p in ps.pushes) { handlePush(p); if (p.modified > lastModified) lastModified = p.modified; } debug("lastModified is now " + lastModified); } catch (Exception e2) { debug("GET failed: " + e2.Message); } }); }
/// <summary> /// This Method Will Retrieve all pushes since x. /// </summary> /// <returns></returns> public ushort getUserInfo() { string commandstring = ""; if (Access_Code != "") { HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; String url = "https://api.pushbullet.com/v2/users/me"; try { myCC.Enter(); // Will not finish, until you have the Critical Section request.KeepAlive = true; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code); request.ContentString = commandstring; // Dispatch will actually make the request with the server response = client.Dispatch(request); client.Abort(); if (response.Code >= 200 && response.Code < 300) { string s = response.ContentString.ToString(); //ErrorLog.Notice(s + "\n"); string[] words = s.Split(','); string senderEmail; foreach (string word in words) { if (word.Contains("\"email\"")) { senderEmail = word.Substring(11, word.Length - 12); setSenderEmail(senderEmail); } } //ErrorLog.Notice(response.ContentString.ToString()); // A response code between 200 and 300 means it was successful. return 1; } else { ErrorLog.Notice("Response Code = " + response.Code.ToString() + "\n"); // A reponse code outside this range means the server threw an error. return 0; } } catch (Exception e) { ErrorLog.Error("Exception in Pushbullet - GetInfo: " + e.ToString()); return 0; } finally { myCC.Leave(); } } else { return 0; } }
public void DeviceList() { HttpsClient client = new HttpsClient(); //client.Verbose = true; //Testing client.AllowAutoRedirect = true; client.PeerVerification = false; client.HostVerification = false; client.KeepAlive = true; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; //Get Switches string url = SmartThingsReceiver.InstallationURL + "/switches/?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); string pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\""; ErrorLog.Notice("**Switches**"); foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) ErrorLog.Notice("'{0}' found with ID {1}.",m.Groups[2], m.Groups[1]); ErrorLog.Notice("\n"); //Get Dimmers url = SmartThingsReceiver.InstallationURL + "/dimmers/?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\""; ErrorLog.Notice("**Dimmers**"); foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]); ErrorLog.Notice("\n"); //Get Presence url = SmartThingsReceiver.InstallationURL + "/presence/?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\""; ErrorLog.Notice("**Presence**"); foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]); ErrorLog.Notice("\n"); //Get thermostats url = SmartThingsReceiver.InstallationURL + "/thermostats/?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\""; ErrorLog.Notice("**thermostats**"); foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]); ErrorLog.Notice("\n"); //Get Locks url = SmartThingsReceiver.InstallationURL + "/locks/?access_token=" + SmartThingsReceiver.AccessToken; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; response = client.Dispatch(request); pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\""; ErrorLog.Notice("**locks**"); foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase)) ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]); ErrorLog.Notice("\n"); }
/// <summary> /// This is what actually send the push /// </summary> /// <param name="commandstring"></param> public static void Send(string commandstring) { HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; String url = "https://api.pushbullet.com/v2/pushes"; try { request.KeepAlive = true; request.Url.Parse(url); client.UserName = Access_Code; request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post; request.Header.SetHeaderValue("Content-Type", "application/json"); request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code); request.ContentString = commandstring; response = client.Dispatch(request); if (response.Code >= 200 && response.Code < 300) { // A response code between 200 and 300 means it was successful. ErrorLog.Notice(response.ContentString.ToString()); } else { // A reponse code outside this range means the server threw an error. ErrorLog.Notice("Pushbullet https response code: " + response.Code); } } catch (Exception e) { ErrorLog.Error("Exception in Pushbullet: " + e.ToString()); } }
/// <summary> /// This Method Will Retrieve all pushes since x. /// </summary> /// <returns></returns> public static ushort getPush() { string commandstring = ""; if (Access_Code != "") { HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; String url = "https://api.pushbullet.com/v2/pushes"; try { myCC.Enter(); // Will not finish, until you have the Critical Section request.KeepAlive = true; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get; request.Header.SetHeaderValue("Content-Type", "application/json"); request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code); request.ContentString = commandstring; // Dispatch will actually make the request with the server response = client.Dispatch(request); if (response.Code >= 200 && response.Code < 300) { client.Abort(); string s = response.ContentString.ToString(); string[] words = s.Split(','); string PushIden = ""; string PushTitle = ""; string PushMessage = ""; foreach (string word in words) { //ErrorLog.Notice(word + "\n"); if (word.Contains("iden")) { PushIden = word.Substring(8, word.Length - 9); } if (word.Contains("title")) { PushTitle = word.Substring(9, word.Length - 10); } if (word.Contains("message")) { PushMessage = word.Substring(11, word.Length - 12); } if (word.Contains("dismissed")) { //TODO Trigger Event To Output String to S+ PushReceived("CMD=" + PushTitle + "." + PushMessage + ";"); //ErrorLog.Notice("TX = " + PushTitle + "." + PushMessage + ";"); //TODO Delete Push.IDEN PushIden = ""; PushTitle = ""; PushMessage = ""; } } //ErrorLog.Notice(response.ContentString.ToString()); // A response code between 200 and 300 means it was successful. return 1; } else { client.Abort(); ErrorLog.Notice("Response Code = " + response.Code.ToString() + "\n"); // A reponse code outside this range means the server threw an error. return 0; } } catch (Exception e) { client.Abort(); ErrorLog.Error("Exception in Pushbullet - GetInfo: " + e.ToString()); return 0; } finally { myCC.Leave(); } } else { return 0; } }
public static void deletePush() { if (Access_Code != "") { HttpsClient client = new HttpsClient(); client.PeerVerification = false; client.HostVerification = false; client.Verbose = false; HttpsClientRequest request = new HttpsClientRequest(); HttpsClientResponse response; String url = "https://api.pushbullet.com/v2/pushes"; request.KeepAlive = true; request.Url.Parse(url); request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Delete; request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code); response = client.Dispatch(request); client.Abort(); } }