/// <summary> /// Saves data about a hit to a short URL /// </summary> /// <param name="hit">Hit to save</param> public async Task AddHitAsync(ShortenedUrlHit hit) { await _context.Hits.AddAsync(hit); await _context.Database.ExecuteSqlCommandAsync( $"UPDATE urls SET last_hit = {hit.Date.ToUnix()}, hits = hits + 1 WHERE id = {hit.UrlId}" ); await _context.SaveChangesAsync(); }
/// <summary> /// Saves data about a hit to a short URL /// </summary> /// <param name="hit">Hit to save</param> public async Task AddHitAsync(ShortenedUrlHit hit, CancellationToken token = default(CancellationToken)) { await _context.Hits.AddAsync(hit, token); await _context.Database.ExecuteSqlCommandAsync( $"UPDATE urls SET last_hit = {hit.Date.ToUnix()}, hits = hits + 1 WHERE id = {hit.UrlId}", token ); await _context.SaveChangesAsync(token); }
/// <summary> /// Creates a <see cref="ShortenedUrlHit"/> representing a hit to the specified URL /// </summary> /// <param name="urlId">Shortened URL that was hit</param> /// <param name="ip">IP the hit came from</param> /// <param name="userAgent">User-Agent the hit came from</param> /// <param name="referrer">HTTP Referrer the hit came from</param> /// <returns>The hit. Not saved to the database yet.</returns> private ShortenedUrlHit CreateHit(int urlId, IPAddress ip, string userAgent, string referrer) { var hit = new ShortenedUrlHit { UrlId = urlId, Date = DateTime.Now, UserAgent = userAgent, IpAddress = ip.ToString(), // DB should really take nulls for these :( ReferrerDomain = "", Browser = "", BrowserVersion = "", Country = "", }; // Parse user-agent if (!string.IsNullOrWhiteSpace(hit.UserAgent)) { var parsedUserAgent = _uaParser.ParseUserAgent(hit.UserAgent); hit.Browser = parsedUserAgent.Family; hit.BrowserVersion = parsedUserAgent.Major + "." + parsedUserAgent.Minor + "." + parsedUserAgent.Patch; } // Determine GeoIP country if (_geoIp.TryCountry(ip, out var geoIpResponse)) { hit.Country = geoIpResponse.Country.IsoCode; } // Parse domain from referrer if (Uri.TryCreate(referrer, UriKind.Absolute, out var referrerUri)) { hit.Referrer = referrerUri; hit.ReferrerDomain = referrerUri.Host.Replace("www.", string.Empty); } return(hit); }