public static bool IsArcadyanModem(bool waitWindow = true, bool silent = false) { try { if (waitWindow) { return((bool)ArcWaitWindow.ArcWaitWindow.Show(IsArcadyanModem, @"Verifying modem...", silent)); } //download login page var loginPage = ResourceGrab.GrabString(Endpoints.LoginHtm); //verify if it contains the correct string var validModem = loginPage.Contains(Global.VerificationString); //return result return(validModem || Global.InitToken != null); } catch (Exception ex) { if (!silent) { UiMessages.Error($"An error occurred whilst trying to verify your modem:\n\n{ex}"); } } //default return(false); }
public bool Fetch() { try { //validate URL if (Uri.TryCreate(CodeUrl, UriKind.Absolute, out var u)) { //URI valid, encode it var codeUri = HttpUtility.UrlEncode(CodeUrl); //code BackColor var codeBackColor = HttpUtility.UrlEncode("#ffffff"); //URI valid, attempt data fetch var fetchUrl = $"https://qrcode.tec-it.com/API/QRCode?data={codeUri}&backcolor={codeBackColor}&method=base64"; //fetch it using AltoHttp var codeImageBase64 = ResourceGrab.GrabString(fetchUrl); //null validation if (!string.IsNullOrWhiteSpace(codeImageBase64)) { //convert to bytes var codeImageBytes = Convert.FromBase64String(codeImageBase64); //length validation if (codeImageBytes.Length > 0) { //convert to image var bitmap = new Bitmap(new MemoryStream(codeImageBytes)); //null validation if ((bitmap.Width * bitmap.Height) > 0) { //assign image CodeImage = bitmap; //success return(true); } } } } } catch (Exception ex) { //log error LoggingHelpers.RecordException(ex.Message, @"FetchQRCodeError"); } //default return return(false); }
/// <summary> /// What's this<br /> /// This will execute a query to the modem for the specified JavaScript file /// </summary> /// <param name="waitWindow"></param> /// <returns></returns> public string GrabJS(bool waitWindow = true) { try { if (waitWindow) { return((string)ArcWaitWindow.ArcWaitWindow.Show(GrabJS, ServiceAuthInfo.ServiceMessage)); } //fetch a new httoken var newToken = new ArcToken(ServiceAuthInfo.TokeniserPage); //endpoint to call var jsUri = ServiceAuthInfo.ServiceEndpoint; //apply the httoken and related information to the endpoint jsUri = newToken.TokeniseUrl(jsUri); //apply ArcToken generated above to the global AuthenticationToken = newToken; //download result from modem var jsResult = ResourceGrab.GrabString(jsUri, ServiceAuthInfo.ReferrerPage); //ensure checks for this are made to avoid invalid content const string notFoundMsg = @"The requested page was not found on this server."; //validate (LH1000 fakes a not found on failure) if (!jsResult.Contains(notFoundMsg) && !string.IsNullOrEmpty( jsResult)) { RawJS = jsResult; return(jsResult); } else { return(@"404"); } } catch (Exception ex) { MessageBox.Show($"ScriptService error:\n\n{ex}"); } //default return(@""); }
/// <summary> /// Downloads the page from the specified URL, extracts the token and instantiates the object /// </summary> /// <param name="tokenPollUri"></param> public ArcToken(string tokenPollUri) { //download the login page for a new token var pageHtml = ResourceGrab.GrabString(tokenPollUri); //debugging //File.WriteAllText(@"latestTokenPage.log", pageHtml); //MessageBox.Show(loginHtml); //verification if (!string.IsNullOrEmpty(pageHtml)) { //create a new HTML Document for parsing var document = new HtmlDocument(); document.LoadHtml(pageHtml); //just get all image 'src' tag values var urls = document.DocumentNode.Descendants("img") .Select(e => e.GetAttributeValue("src", null)) .Where(s => !string.IsNullOrEmpty(s)); //begin parse foreach (var i in urls) { if (i.IndexOf("data:", StringComparison.Ordinal) != 0) { continue; } const int splitKey = 78; var tokenRaw = i.Substring(splitKey); TokenRaw = tokenRaw; break; } } }
/// <summary> /// Perform a new CGI login request which will emulate a user logging into the web portal /// </summary> /// <param name="auth"></param> /// <param name="waitWindow"></param> /// <param name="warningMode"></param> /// <param name="silent"></param> /// <returns></returns> public static bool DoLogin(ArcCredential auth = null, bool waitWindow = true, bool warningMode = false, bool silent = false) { //waitwindow activation if (waitWindow && !silent) { //offloads to another thread and returns the result once it's done return((bool)ArcWaitWindow.ArcWaitWindow.Show(DoLogin, @"Authenticating...", auth, warningMode)); } try { //this will trigger a secondary request var arcToken = new ArcToken(); //verify authentication token if (!string.IsNullOrWhiteSpace(arcToken.Token)) { //authentication credentials (they get hashed when loaded into the Credential object) var unEncoded = auth?.Username; var pwEncoded = auth?.Password; //data to send alongside request var requestBody = new FormUrlEncodedContent( new Dictionary <string, string> { { @"httoken", arcToken.Token }, { @"usr", unEncoded }, { @"pws", pwEncoded } }); //request handler Global.GlobalHandler = new HttpClientHandler { AutomaticDecompression = ~DecompressionMethods.None, AllowAutoRedirect = false, CookieContainer = new CookieContainer() }; //request client Global.GlobalClient = new HttpClient(Global.GlobalHandler) { Timeout = TimeSpan.FromMilliseconds(Global.RequestTimeout) }; //add request credentials var request = new HttpRequestMessage(new HttpMethod(@"POST"), Endpoints.LoginCgi) { Content = requestBody }; //create the needed headers request.Headers.TryAddWithoutValidation(@"Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); request.Headers.TryAddWithoutValidation(@"Accept-Language", @"en-US,en;q=0.5"); request.Headers.TryAddWithoutValidation(@"Connection", @"keep-alive"); request.Headers.TryAddWithoutValidation(@"Upgrade-Insecure-Requests", @"1"); request.Headers.TryAddWithoutValidation(@"Cookie", @"disableLogout=0"); request.Headers.TryAddWithoutValidation(@"User-Agent", Global.UserAgent); request.Headers.TryAddWithoutValidation(@"Referer", Endpoints.LoginHtm); request.Headers.TryAddWithoutValidation(@"Host", Endpoints.GatewayAddress); request.Headers.TryAddWithoutValidation(@"Origin", Endpoints.Origin); //receive and format response var response = Global.GlobalClient.SendAsync(request).Result; var locationHeader = response.Headers.Location != null ? response.Headers.Location.ToString() : @""; //null validation if (string.IsNullOrWhiteSpace(locationHeader)) { return(false); } //header return page validation if (locationHeader.StartsWith(@"/login.htm")) { //figure out what the error code was var parameters = ParametersFromUrl(locationHeader); //null validation if (parameters != null) { //convert NameValueCollection to generic IDictionary var dict = parameters.AllKeys.ToDictionary(t => t, t => parameters[t]); //verify if the 'err' (error code) parameter exists if (dict.ContainsKey(@"err")) { //parse out error code var err = dict[@"err"]; //ensure we can display error messages if (!silent) { //figure out what error message to display via a switch-case switch (err) { case @"4": UiMessages.Error("Modem login error:\n\nYou are not allowed to login device's GUI now,\nsince the user number had reached its limit."); break; case @"3": UiMessages.Error("Modem login error:\n\nYour session has timed out or login status has changed.\nPlease sign in again."); break; case @"2": UiMessages.Error("Modem login error:\n\nAnother user has already login."); break; case @"1": UiMessages.Error("Modem login error:\n\nInvalid Username/Password."); break; } } } } } else if (locationHeader == @"/index.htm") { //download home page var homeGrab = ResourceGrab.GrabString(Endpoints.HomeHtm, Endpoints.IndexHtm); //make sure we didn't get redirected to the login page var success = !homeGrab.Contains(@"Telstra Login") && !homeGrab.Contains(@"login.htm"); //apply global token if successful if (success) { Global.InitToken = arcToken; } //report status return(success); } } else { UiMessages.Warning(@"Authentication error; CSRF token was invalid."); } } catch (Exception ex) { if (!silent) { if (!warningMode) { UiMessages.Error($"Login error\n\n{ex}"); } else { UiMessages.Warning("We couldn't authenticate the application; this will affect your " + "ability to connect to the modem's CGI pages. Please verify if the modem is reachable."); } } } //default return(false); }
public static XmlDocument GetXmlTransaction(string uri, bool forceNoCache = false, bool silent = false, bool waitWindow = true) { //allows multi-threaded operations if (waitWindow) { //offload to another thread if specified return((XmlDocument)WaitWindow.WaitWindow.Show(GetXmlTransaction, @"Fetching from API", uri, forceNoCache, silent)); } //Create the cache folder structure CachingHelpers.CacheStructureBuilder(); //check if it's already cached if (XmlCaching.XmlInCache(uri) && !forceNoCache) { try { //load from the cache var xmlCache = XmlCaching.XmlFromCache(uri); //return the cached XML if not null, otherwise force a re-download return(xmlCache ?? GetXmlTransaction(uri, true, silent, false)); } catch (Exception ex) { //record the error LoggingHelpers.RecordException(ex.Message, "CacheLoadError"); //force a re-download return(GetXmlTransaction(uri, true, silent, false)); } } //default secret account token var secret = !string.IsNullOrWhiteSpace(ObjectProvider.Settings.ConnectionInfo.PlexAccountToken) ? ObjectProvider.Settings.ConnectionInfo.PlexAccountToken : ObjectProvider.User.authenticationToken; //allows specific server connection matching for the correct token var uriToken = string.IsNullOrEmpty(secret) ? Methods.MatchUriToToken(uri, ObjectProvider.PlexServers) : secret; //the API URI is combined with the token to yield the fully-qualified URI var fullUri = $@"{uri}{uriToken}"; try { //get the resource var xmlString = ResourceGrab.GrabString(fullUri); //validation if (!string.IsNullOrWhiteSpace(xmlString)) { //conversion var xmlResponse = xmlString.ToXmlDocument(); //log outcome LoggingHelpers.RecordTransaction(fullUri, ResourceGrab.LastStatusCode); //ensure file is cached XmlCaching.XmlToCache(xmlResponse, uri); //return XML document return(xmlResponse); } } catch (ThreadAbortException) { //literally nothing; this gets raised when a cancellation happens. } catch (Exception ex) { LoggingHelpers.RecordException(ex.Message, "XMLTransactionError"); LoggingHelpers.RecordTransaction(fullUri, "Undetermined"); if (!silent) { UIMessages.Error("Error Occurred in XML Transaction\n\n" + ex, @"Network Error"); } } //default return(new XmlDocument()); }