public async Task <WeatherDescription> GetWeatherAsync(GeoTagsEntry geoTags) { var requestUri = string.Format(RequestWeatherUri, geoTags.LatitudeValue, geoTags.LongitudeValue, InternalUtils.GetOpenWeatherApiCode()); #if DEBUG Logging.Write(requestUri); #endif using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); XDocument doc; try { doc = XDocument.Parse(data); } catch (XmlException) { Logging.Warning("response: " + data); throw; } var temperatureValue = doc.Descendants(@"temperature").FirstOrDefault()?.Attribute(@"value")?.Value; var weatherNode = doc.Descendants(@"weather").FirstOrDefault(); if (temperatureValue == null || weatherNode == null) { throw new Exception("Invalid response"); } var temperature = FlexibleParser.ParseDouble(temperatureValue); var type = OpenWeatherTypeToCommonType((OpenWeatherType)int.Parse(weatherNode.Attribute(@"number")?.Value, NumberStyles.Any, CultureInfo.InvariantCulture)); var description = weatherNode.Attribute(@"value")?.Value; var icon = weatherNode.Attribute(@"icon")?.Value; var iconUri = icon == null ? null : string.Format(IconUri, icon); return(new WeatherDescription(type, temperature, description, iconUri)); } }
public static async Task <TimeZoneInfo> DetermineTimeZoneAsync(GeoTagsEntry geoTags) { var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue, DateTime.Now.ToUnixTimestamp()); Logging.Debug(requestUri); using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var doc = XDocument.Parse(data); var zoneId = doc.Descendants(@"time_zone_id").FirstOrDefault()?.Value; if (zoneId == null) { throw new Exception("Invalid response"); } try { return(TimeZoneInfo.FindSystemTimeZoneById(zoneId)); } catch (TimeZoneNotFoundException) { var rawOffset = doc.Descendants(@"raw_offset").FirstOrDefault()?.Value; var zoneName = doc.Descendants(@"time_zone_name").FirstOrDefault()?.Value; if (rawOffset == null || zoneName == null) { throw new Exception("Invalid response"); } return(TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneName, zoneName)); } } }
public static async Task <string> UnwrapLink(string argument, CancellationToken cancellation = default(CancellationToken)) { var loader = CreateLoader(argument); using (var order = KillerOrder.Create(new CookieAwareWebClient { Headers = { [HttpRequestHeader.UserAgent] = CmApiProvider.UserAgent } }, TimeSpan.FromMinutes(10))) { var client = order.Victim; if (_proxy != null) { client.Proxy = _proxy; } if (!await loader.PrepareAsync(client, cancellation)) { throw new InformativeException("Can’t load file", "Loader preparation failed."); } return(await loader.GetDownloadLink(cancellation)); } }
private async Task <bool> EnsureConnectedAsync(bool reconnect) { if (_socket == null || !_socket.Connected) { if (!reconnect || _lastConnectionAttempt?.ElapsedMilliseconds < 3000) { return(false); } Logging.Debug("Close socket before reconnecting…"); CloseSocket(); try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _killer = KillerOrder.Create(_socket, TimeSpan.FromSeconds(1)); await _socket.ConnectTaskAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), OptionSocketPort)).ConfigureAwait(false); Logging.Debug("Connected to CM in-game app"); _killer?.Pause(); } catch (Exception e) { Logging.Warning(e); CloseSocket(); } } return(_socket != null); }
public static async Task <AcServerStatus> GetCurrentStateAsync(string ip, int port, string password) { try { using (var killer = KillerOrder.Create(new CookieAwareWebClient(), OptionTimeout)) { return(JsonConvert.DeserializeObject <AcServerStatus>(await killer.Victim.DownloadStringTaskAsync( $"http://{ip}:{port}/api/control/acserver?password={EncodePassword(password)}&_method=STATUS"))); } } catch (Exception e) when(e.IsCancelled()) { throw new WebException("Timeout exceeded", WebExceptionStatus.Timeout); } }
private static async Task <string> LoadUsingClientAsync(string uri, TimeSpan timeout) { using (var order = KillerOrder.Create(new TimeoutyWebClient(timeout) { Headers = { [HttpRequestHeader.UserAgent] = InternalUtils.GetKunosUserAgent() } }, timeout)) { return(await order.Victim.DownloadStringTaskAsync(uri)); } }
private KillerOrder <FtpWebRequest> Request([NotNull] string remoteFile, [NotNull] string method, CancellationToken cancellation) { cancellation.ThrowIfCancellationRequested(); var killer = KillerOrder.Create((FtpWebRequest)WebRequest.Create($"{_hostName}/{remoteFile}"), Timeout, cancellation); var request = killer.Victim; request.Credentials = new NetworkCredential(_userName, _password); request.UseBinary = UseBinary; request.UsePassive = UsePassive; request.KeepAlive = KeepAlive; request.Method = method; return(killer); }
public static async Task <GeoTagsEntry> LocateAsync([CanBeNull] string address) { var requestUri = string.Format(RequestLocationUri, InternalUtils.GetPositionStackApiKey().Item1, HttpUtility.UrlEncode(CleanUpRegex.Replace(address ?? "", " "))); using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var item = JObject.Parse(data)[@"data"][0]; return(new GeoTagsEntry( item.GetDoubleValueOnly("latitude") ?? throw new Exception("Invalid response: no latitude"), item.GetDoubleValueOnly("longitude") ?? throw new Exception("Invalid response: no longitude"))); } }
public async Task <string> Send([Localizable(false)] string method, string url, object data, string authToken, [CanBeNull] IProgress <AsyncProgressEntry> progress, CancellationToken cancellation, NameValueCollection extraHeaders) { try { using (var order = KillerOrder.Create(new CookieAwareWebClient { Headers = { [@"Accept"] = @"application/json" } }, TimeSpan.FromMinutes(10))) { var client = order.Victim; if (authToken != null) { client.Headers[@"Authorization"] = $@"{AuthorizationTokenType} {authToken}"; } client.SetUserAgent(InternalUtils.GetKunosUserAgent()); cancellation.Register(client.CancelAsync); if (extraHeaders != null) { foreach (string header in extraHeaders) { client.Headers[header] = extraHeaders[header]; #if DEBUG Logging.Debug($"Header: {header}: {extraHeaders[header]}"); #endif } } if (data == null) { client.SetMethod(method); client.SetDownloadProgress(progress, null, order.Delay); return((await client.DownloadDataTaskAsync(url)).ToUtf8String()); } var bytes = GetBytes(data, out var contentType); client.SetContentType(contentType); client.SetUploadProgress(progress, bytes.Length, order.Delay); return((await client.UploadDataTaskAsync(url, method, bytes)).ToUtf8String()); } } catch (Exception e) { var wrapped = ApiException.Wrap(e, cancellation); if (wrapped == null) { throw; } throw wrapped; } }
public static async Task <TimeZoneInfo> DetermineTimeZoneAsync(GeoTagsEntry geoTags) { var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue, InternalUtils.GetTimeZoneDbApiCode()); #if DEBUG Logging.Debug(requestUri); #endif using (var order = KillerOrder.Create(new CookieAwareWebClient(), 15000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var doc = JObject.Parse(data); var zoneId = doc.GetStringValueOnly("zoneName"); if (zoneId == null) { throw new Exception("Invalid response"); } Logging.Write("Returned zone ID: " + zoneId); try { Logging.Write("Parsed as: " + TZConvert.GetTimeZoneInfo(zoneId).ToSerializedString()); return(TZConvert.GetTimeZoneInfo(zoneId)); } catch (TimeZoneNotFoundException) { var rawOffset = doc.GetStringValueOnly(@"gmtOffset"); return(TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneId, zoneId)); } } /*var requestUri = string.Format(RequestTimeZoneUri, geoTags.LatitudeValue, geoTags.LongitudeValue, * DateTime.Now.ToUnixTimestamp(), InternalUtils.GetGoogleMapsApiCode()); * * using (var order = KillerOrder.Create(new WebClient(), 5000)) { * var data = await order.Victim.DownloadStringTaskAsync(requestUri); * var doc = XDocument.Parse(data); * var zoneId = doc.Descendants(@"time_zone_id").FirstOrDefault()?.Value; * if (zoneId == null) throw new Exception("Invalid response"); * * try { * return TZConvert.GetTimeZoneInfo(zoneId); * } catch (TimeZoneNotFoundException) { * var rawOffset = doc.Descendants(@"raw_offset").FirstOrDefault()?.Value; * var zoneName = doc.Descendants(@"time_zone_name").FirstOrDefault()?.Value; * if (rawOffset == null || zoneName == null) throw new Exception("Invalid response"); * return TimeZoneInfo.CreateCustomTimeZone(zoneId, TimeSpan.FromSeconds(FlexibleParser.ParseDouble(rawOffset)), zoneName, zoneName); * } * }*/ }
public static async Task <Tuple <int, TimeSpan> > TryToPingServerAsync(string ip, int port, int timeout) { using (var order = KillerOrder.Create(new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { SendTimeout = timeout, ReceiveTimeout = timeout }, timeout)) { var socket = order.Victim; var buffer = new byte[3]; try { var bytes = BitConverter.GetBytes(200); var endpoint = new IPEndPoint(IPAddress.Parse(ip), port); await Task.Factory.FromAsync(socket.BeginSendTo(bytes, 0, bytes.Length, SocketFlags.None, endpoint, null, socket), socket.EndSendTo); if (order.Killed) { return(null); } var timer = Stopwatch.StartNew(); var elapsed = TimeSpan.Zero; var begin = socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, a => { elapsed = timer.Elapsed; }, socket); if (begin == null) { return(null); } await Task.Factory.FromAsync(begin, socket.EndReceive); if (order.Killed) { return(null); } return(buffer[0] != 200 || buffer[1] + buffer[2] <= 0 ? null : new Tuple <int, TimeSpan>(BitConverter.ToInt16(buffer, 1), elapsed)); } catch (Exception) { return(null); } } }
public static async Task <GeoTagsEntry> LocateAsync([CanBeNull] string address) { var requestUri = string.Format(RequestLocationUri, HttpUtility.UrlEncode(CleanUpRegex.Replace(address ?? "", " "))); using (var order = KillerOrder.Create(new WebClient(), 5000)) { var data = await order.Victim.DownloadStringTaskAsync(requestUri); var ns = XNamespace.Get(@"http://where.yahooapis.com/v1/schema.rng"); var centroid = XDocument.Parse(data).Descendants(ns + @"centroid").FirstOrDefault(); var latitude = centroid?.Element(ns + @"latitude"); var longitude = centroid?.Element(ns + @"longitude"); if (latitude == null || longitude == null) { throw new Exception("Invalid response"); } return(new GeoTagsEntry(FlexibleParser.ParseDouble(latitude.Value), FlexibleParser.ParseDouble(longitude.Value))); } }
public static async Task <string> UnwrapLink(string argument, CancellationToken cancellation = default) { var loader = await CreateLoaderAsync(argument, cancellation) ?? throw new OperationCanceledException(); using (var order = KillerOrder.Create(new CookieAwareWebClient(), TimeSpan.FromMinutes(10))) { var client = order.Victim; if (_proxy != null) { client.Proxy = _proxy; } if (!await loader.PrepareAsync(client, cancellation)) { throw new InformativeException("Can’t load file", "Loader preparation failed."); } return(await loader.GetDownloadLink(cancellation)); } }
public static async Task <Tuple <int, TimeSpan> > TryToPingServerAsync(string ip, int port, int timeout, bool logging = false) { using (var order = KillerOrder.Create(new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { SendTimeout = timeout, ReceiveTimeout = timeout }, timeout)) { var socket = order.Victim; var buffer = new byte[3]; if (logging) { Logging.Debug("Socket created"); } try { var bytes = BitConverter.GetBytes(200); var endpoint = new IPEndPoint(await ParseIPAddressAsync(ip), port); if (logging) { Logging.Debug("Sending bytes to: " + endpoint); } await Task.Factory.FromAsync(socket.BeginSendTo(bytes, 0, bytes.Length, SocketFlags.None, endpoint, null, socket), socket.EndSendTo); if (logging) { Logging.Debug("Bytes sent"); } if (order.Killed) { if (logging) { Logging.Warning("Timeout exceeded"); } return(null); } var timer = Stopwatch.StartNew(); var elapsed = TimeSpan.Zero; if (logging) { Logging.Debug("Receiving response…"); } var begin = socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, a => { elapsed = timer.Elapsed; }, socket); if (begin == null) { if (logging) { Logging.Warning("Failed to begin receiving response"); } return(null); } if (logging) { Logging.Debug("Waiting for the end of response"); } await Task.Factory.FromAsync(begin, socket.EndReceive); if (order.Killed) { if (logging) { Logging.Warning("Timeout exceeded"); } return(null); } if (logging) { Logging.Debug("Response: " + buffer.JoinToString(", ")); } if (buffer[0] != 200 || buffer[1] + buffer[2] <= 0) { if (logging) { Logging.Warning("Invalid response, consider as an error"); } return(null); } if (logging) { Logging.Write("Pinging is a success"); } return(new Tuple <int, TimeSpan>(BitConverter.ToInt16(buffer, 1), elapsed)); } catch (Exception) { return(null); } } }
public static async Task <string> LoadAsyncTo(string argument, string destination, IProgress <AsyncProgressEntry> progress = null, Action <FlexibleLoaderMetaInformation> metaInformationCallback = null, CancellationToken cancellation = default(CancellationToken)) { var loader = CreateLoader(argument); try { using (var order = KillerOrder.Create(new CookieAwareWebClient { Headers = { [HttpRequestHeader.UserAgent] = CmApiProvider.UserAgent } }, TimeSpan.FromMinutes(10))) { var client = order.Victim; if (_proxy != null) { client.Proxy = _proxy; } progress?.Report(AsyncProgressEntry.Indetermitate); cancellation.ThrowIfCancellationRequested(); cancellation.Register(client.CancelAsync); if (!await loader.PrepareAsync(client, cancellation)) { throw new InformativeException("Can’t load file", "Loader preparation failed."); } cancellation.ThrowIfCancellationRequested(); metaInformationCallback?.Invoke(new FlexibleLoaderMetaInformation(loader.TotalSize, loader.FileName, loader.Version)); var s = Stopwatch.StartNew(); if (loader.UsesClientToDownload) { client.DownloadProgressChanged += (sender, args) => { if (s.Elapsed.TotalMilliseconds > 20) { order.Delay(); s.Restart(); } else { return; } var total = args.TotalBytesToReceive; if (total == -1 && loader.TotalSize != -1) { total = Math.Max(loader.TotalSize, args.BytesReceived); } progress?.Report(AsyncProgressEntry.CreateDownloading(args.BytesReceived, total)); }; } await loader.DownloadAsync(client, destination, loader.UsesClientToDownload?null : new Progress <double>(p => { if (s.Elapsed.TotalMilliseconds > 20) { order.Delay(); s.Restart(); } else { return; } var total = loader.TotalSize; progress?.Report(total == -1 ? new AsyncProgressEntry("Loading…", p) : AsyncProgressEntry.CreateDownloading((long)(p * total), total)); }), cancellation); cancellation.ThrowIfCancellationRequested(); } } catch (Exception) when(cancellation.IsCancellationRequested) { throw new OperationCanceledException(); } return(destination); }
private static async Task <string> LoadUsingRequestAsync(string uri, TimeSpan timeout) { using (var order = KillerOrder.Create((HttpWebRequest)WebRequest.Create(uri), timeout)) { var request = order.Victim; request.Method = "GET"; request.UserAgent = InternalUtils.GetKunosUserAgent(); request.Headers.Add("Accept-Encoding", "gzip"); if (OptionNoProxy) { request.Proxy = null; } if (OptionForceDisabledCache) { request.CachePolicy = _cachePolicy ?? (_cachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore)); } request.Timeout = (int)timeout.TotalMilliseconds; string result; using (var response = (HttpWebResponse)await request.GetResponseAsync()) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($@"StatusCode = {response.StatusCode}"); } using (var stream = response.GetResponseStream()) { if (stream == null) { throw new Exception(@"ResponseStream = null"); } if (string.Equals(response.Headers.Get("Content-Encoding"), @"gzip", StringComparison.OrdinalIgnoreCase)) { using (var deflateStream = new GZipStream(stream, CompressionMode.Decompress)) { using (var reader = new StreamReader(deflateStream, Encoding.UTF8)) { result = await reader.ReadToEndAsync(); } } } else { using (var reader = new StreamReader(stream, Encoding.UTF8)) { result = await reader.ReadToEndAsync(); } } } } if (OptionSaveResponses) { var filename = FilesStorage.Instance.GetFilename("Logs", $"Dump_{Regex.Replace(uri.Split('/').Last(), @"\W+", "_")}.json"); if (!File.Exists(filename)) { File.WriteAllText(FilesStorage.Instance.GetFilename(filename), result); } } return(result); } }
public static async Task <string> LoadAsyncTo(string argument, FlexibleLoaderGetPreferredDestinationCallback getPreferredDestination, [CanBeNull] FlexibleLoaderReportDestinationCallback reportDestination, Action <FlexibleLoaderMetaInformation> reportMetaInformation = null, Func <bool> checkIfPaused = null, IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default) { progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Finding fitting loader…")); var loader = await CreateLoaderAsync(argument, cancellation) ?? throw new OperationCanceledException(); try { using (var order = KillerOrder.Create(new CookieAwareWebClient(), TimeSpan.FromMinutes(10))) { var client = order.Victim; if (_proxy != null) { client.Proxy = _proxy; } progress?.Report(AsyncProgressEntry.Indetermitate); cancellation.ThrowIfCancellationRequested(); cancellation.Register(client.CancelAsync); if (!await loader.PrepareAsync(client, cancellation)) { throw new InformativeException("Can’t load file", "Loader preparation failed."); } cancellation.ThrowIfCancellationRequested(); reportMetaInformation?.Invoke(FlexibleLoaderMetaInformation.FromLoader(loader)); var initialProgressCallback = true; var reportStopwatch = Stopwatch.StartNew(); var progressStopwatch = new AsyncProgressBytesStopwatch(); if (loader.UsesClientToDownload) { client.DownloadProgressChanged += (sender, args) => { if (initialProgressCallback) { reportMetaInformation?.Invoke(FlexibleLoaderMetaInformation.FromLoader(loader)); initialProgressCallback = false; } if (reportStopwatch.Elapsed.TotalMilliseconds < 20) { return; } order.Delay(); reportStopwatch.Restart(); progress?.Report(AsyncProgressEntry.CreateDownloading(args.BytesReceived, args.TotalBytesToReceive == -1 && loader.TotalSize.HasValue ? Math.Max(loader.TotalSize.Value, args.BytesReceived) : args.TotalBytesToReceive, progressStopwatch)); }; } var loaded = await loader.DownloadAsync(client, getPreferredDestination, reportDestination, checkIfPaused, loader.UsesClientToDownload?null : new Progress <long>(p => { if (initialProgressCallback) { reportMetaInformation?.Invoke(FlexibleLoaderMetaInformation.FromLoader(loader)); initialProgressCallback = false; } if (reportStopwatch.Elapsed.TotalMilliseconds < 20) { return; } order.Delay(); reportStopwatch.Restart(); progress?.Report(loader.TotalSize.HasValue ? AsyncProgressEntry.CreateDownloading(p, loader.TotalSize.Value, progressStopwatch) : new AsyncProgressEntry(string.Format(UiStrings.Progress_Downloading, p.ToReadableSize(1)), null)); }), cancellation); cancellation.ThrowIfCancellationRequested(); Logging.Write("Loaded: " + loaded); return(loaded); } } catch (Exception e) when(cancellation.IsCancellationRequested || e.IsCancelled()) { Logging.Warning("Cancelled"); throw new OperationCanceledException(); } catch (Exception e) { Logging.Warning(e); throw; } }
private static async Task <IpGeoEntry> GetAsyncFn() { using (var killer = KillerOrder.Create(new CookieAwareWebClient(), 10000)) { return(JsonConvert.DeserializeObject <IpGeoEntry>(await killer.Victim.DownloadStringTaskAsync(RequestUri))); } }