예제 #1
0
        public DeviceInfo BuildFromEventData(string userAgent)
        {
            var dd = new DeviceDetector(userAgent);

            dd.Parse();
            var client = (BrowserMatchResult)dd.GetClient().Matches.First(r => r is BrowserMatchResult);
            var os     = dd.GetOs();

            if (!BrowserParser.GetBrowserFamily(client.ShortName, out var browserFamily))
            {
                browserFamily = client.ShortName;
            }

            if (!OperatingSystemParser.GetOsFamily(os.Match.ShortName, out var osFamily) || osFamily == "GNU/Linux")
            {
                osFamily = os.Match.ShortName;
            }
            return(new DeviceInfo
            {
                Browser = new BrowserInfo()
                {
                    Name = client.Name + " " + client.Version,
                    Type = browserFamily
                },
                DeviceType = dd.GetDeviceName(),
                OperatingSystem = new OsInfo()
                {
                    Name = os.Match.Platform + " " + os.Match.Name + " " + os.Match.Version,
                    Type = osFamily
                },
                UserAgent = userAgent
            });
        }
예제 #2
0
        /// <summary>
        ///
        /// </summary>
        public Detector(string userAgent)
        {
            DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE);

            DeviceDetector dd = new DeviceDetector(userAgent);

            // OPTIONAL: Set caching method
            // By default static cache is used, which works best within one php process (memory array caching)
            // To cache across requests use caching in files or memcache
            dd.SetCache(new DictionaryCache());

            // OPTIONAL: If called, GetBot() will only return true if a bot was detected  (speeds up detection a bit)
            dd.DiscardBotInformation();

            // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
            dd.SkipBotDetection();

            dd.Parse();

            if (dd.IsBot())
            {
                // handle bots,spiders,crawlers,...
                var botInfo = dd.GetBot();
            }
            else
            {
                var clientInfo = dd.GetClient(); // holds information about browser, feed reader, media player, ...
                var osInfo     = dd.GetOs();
                var device     = dd.GetDeviceName();
                var brand      = dd.GetBrandName();
                var model      = dd.GetModel();
            }
        }
예제 #3
0
        // Generate refresh token
        private RefreshToken GenerateRefreshToken(string ipAddress, DeviceDetector dd)
        {
            dd.Parse();
            var refreshToken = new RefreshToken
            {
                Token       = RandomTokenString(),
                Expires     = DateTime.Now.AddDays(7),
                Created     = DateTime.Now,
                CreatedByIp = ipAddress,
                LastActive  = DateTime.Now,
            };

            if (!dd.IsBot())
            {
                try
                {
                    var clientInfo = dd.GetClient().ToString().Replace(" ", "").Split("\n")[1].Split(":")[1].Replace(";", "");
                    var osInfo     = dd.GetOs().ToString().Replace(" ", "").Split("\n")[1].Split(":")[1].Replace(";", "");
                    var device     = dd.GetDeviceName();
                    var brand      = dd.GetBrandName();
                    var model      = dd.GetModel();
                    refreshToken.Device      = model + " " + brand + " " + osInfo + " " + device;
                    refreshToken.Application = clientInfo;
                }
                catch { }
            }
            return(refreshToken);
        }
예제 #4
0
        public ActionResult <IEnumerable <string> > Get(
            [FromServices] DeviceDetector detector,
            [FromServices] ILogger <SampleController> logger,
            [FromQuery] string gggg)
        {
            logger.LogError("TEST");
            var os  = detector.GetOs();
            var url = this.Request.GetDisplayUrl();

            return(new string[] { os.Match.Name, url });
        }
        public async Task <IActionResult> Get()
        {
            var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();

            if (string.IsNullOrWhiteSpace(userAgent))
            {
                return(BadRequest("User agent could not be determined."));
            }

            var dd = new DeviceDetector(userAgent);

            dd.Parse();

            var device = OrUnknown(dd.GetDeviceName(), "device");
            var brand  = OrUnknown(dd.GetBrandName(), "brand");
            var model  = OrUnknown(dd.GetModel(), "model");

            var osMatch    = dd.GetOs()?.Match;
            var osName     = OrUnknown(osMatch?.Name, "os");
            var osPlatform = OrUnknown(osMatch?.Platform, "os-platform");
            var osVersion  = OrUnknown(osMatch?.Version, "os-version");

            var clientMatch   = dd.GetClient()?.Match;
            var clientName    = OrUnknown(clientMatch?.Name, "client");
            var clientType    = OrUnknown(clientMatch?.Type, "client-type");
            var clientVersion = OrUnknown(clientMatch?.Version, "client-version");

            // var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(); // This didn't work
            var ip = HttpContext.Request.Headers["X-Forwarded-For"].ToString();

            var city = string.Empty;

            if (!string.IsNullOrWhiteSpace(ip))
            {
                var apiKey  = Environment.GetEnvironmentVariable("IPREGISTRY_KEY");
                var url     = $"https://api.ipregistry.co/{ip}?key={apiKey}";
                var client  = _clientFactory.CreateClient();
                var reponse = await client.GetAsync(url);

                var ipReponse = JsonConvert.DeserializeObject <IPResponse>(await reponse.Content.ReadAsStringAsync());
                city = ipReponse?.location?.city;
            }

            ip   = OrUnknown(ip, "ip-address");
            city = OrUnknown(city, "city");

            return(Ok($"" +
                      $"Device: {device} {brand} {model}\n" +
                      $"OS: {osName} {osPlatform} {osVersion}\n" +
                      $"Client: {clientName} {clientType} {clientVersion}\n" +
                      $"IP: {ip}, near {city}"));
        }
예제 #6
0
        /// <summary>
        /// this library get device and user related details to perform first level authentication
        /// </summary>
        /// <param name="userAgent"></param>
        /// <returns>DeviceInfo</returns>
        public static DeviceInfo Get(string userAgent)
        {
            var deviceInfo = new DeviceInfo();
            var client     = new ClientModel();
            var bot        = new BotModel();
            var os         = new OsInfo();
            var device     = new DeviceDetector(userAgent);

            device.SetCache(new DictionaryCache());
            device.Parse();
            if (device.IsBot())
            {
                // checks if the user is a bot or crawler and retrieve the info
                var botInfo = device.GetBot();
                bot.Success     = botInfo.Success;
                bot.Name        = botInfo.Matches[0].Name ?? botInfo.Match?.Name;
                bot.Producer    = botInfo.Matches[0].Producer.Name ?? botInfo.Match?.Producer.Name;
                bot.ProducerUrl = botInfo.Matches[0].Producer.Url ?? botInfo.Match?.Producer.Url;
                bot.Url         = botInfo.Matches[0].Url ?? botInfo.Match?.Url;
            }

            else
            {//if its not a bot get client info
                var clientInfo = device.GetClient();
                client.Name    = clientInfo.Matches[0]?.Name ?? clientInfo.Match?.Name;
                client.Type    = clientInfo.Matches[0]?.Type ?? clientInfo.Match?.Type;
                client.Version = clientInfo.Matches[0]?.Version ?? clientInfo.Match?.Version;
                client.Success = clientInfo.Success;


                // holds information about browser, feed reader, media player, ...
                var osInfo = device.GetOs();
                os.Name                = osInfo.Matches[0]?.Name ?? osInfo.Match?.Name;
                os.Version             = osInfo.Match?.Version ?? osInfo.Matches[0]?.Version ?? osInfo.Match?.Version;
                os.PlatForm            = osInfo.Match?.Platform ?? osInfo.Matches[0]?.Platform ?? osInfo.Match?.Platform;
                os.ShortName           = osInfo.Match?.ShortName ?? osInfo.Matches[0]?.ShortName ?? osInfo.Match?.ShortName;
                os.Success             = osInfo.Success;
                client.DeviceName      = device.GetDeviceName();
                client.DeviceBrandName = device.GetBrandName();
                client.DeviceModel     = device.GetModel();
            }

            client.IsDesktop  = device.IsDesktop();
            client.IsMobile   = device.IsMobile();
            deviceInfo.Bot    = bot;
            deviceInfo.Client = client;
            deviceInfo.OsInfo = os;
            return(deviceInfo);
        }
예제 #7
0
파일: LoggingTo.cs 프로젝트: wwwK/aceadmin
        /// <summary>
        /// 解析 User-Agent
        /// </summary>
        /// <param name="ua"></param>
        /// <param name="browserName"></param>
        /// <param name="systemName"></param>
        /// <param name="isBot"></param>
        public static void UserAgentParse(string ua, out string browserName, out string systemName, out bool isBot)
        {
            isBot = false;

            DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE);

            var bn = "Unknown";
            var sn = "Unknown";

            if (ua != null)
            {
                var dd = new DeviceDetector(ua);
                dd.Parse();
                if (dd.IsBot())
                {
                    isBot = true;

                    var botInfo = dd.GetBot();
                    if (botInfo.Success)
                    {
                        bn = botInfo.Match.Name;
                    }
                }
                else
                {
                    var clientInfo = dd.GetClient();
                    if (clientInfo.Success)
                    {
                        bn = clientInfo.Match.Name + " " + clientInfo.Match.Version;
                    }
                    var osInfo = dd.GetOs();
                    if (osInfo.Success)
                    {
                        sn = osInfo.Match.Name + " " + osInfo.Match.Version;
                    }
                }
            }

            browserName = bn;
            systemName  = sn;
        }
예제 #8
0
        /// <summary>
        /// 解析 User-Agent
        /// </summary>
        /// <param name="ua">User-Agent</param>
        public UserAgentTo(string ua)
        {
            DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE);

            if (ua != null)
            {
                var dd = new DeviceDetector(ua);
                dd.Parse();
                if (dd.IsBot())
                {
                    IsBot = true;

                    var botInfo = dd.GetBot();
                    if (botInfo.Success)
                    {
                        BrowserName = botInfo.Match.Name;
                    }
                }
                else
                {
                    var clientInfo = dd.GetClient();
                    if (clientInfo.Success)
                    {
                        BrowserName    = clientInfo.Match.Name;
                        BrowserType    = clientInfo.Match.Type;
                        BrowserVersion = clientInfo.Match.Version;
                    }
                    var osInfo = dd.GetOs();
                    if (osInfo.Success)
                    {
                        SystemName      = osInfo.Match.Name;
                        SystemShortName = osInfo.Match.ShortName;
                        SystemVersion   = osInfo.Match.Version;
                        SystemPlatform  = osInfo.Match.Platform;
                    }
                }
            }
        }
예제 #9
0
        public ParsedUA ParseUA()
        {
            string ua;

            if (string.IsNullOrEmpty(UserAgent))
            {
                ua = Request.Headers["User-Agent"].ToString();
            }
            else
            {
                ua = UserAgent;
            }

            ParsedUA result = new ParsedUA();

            var dd = new DeviceDetector(ua);

            dd.Parse();

            if (dd.IsBot())
            {
                result.IsBot = true;
                result.Bot   = dd.GetBot().Match;
            }
            else
            {
                result.Client            = dd.GetClient().Match;
                result.Os                = dd.GetOs().Match;
                result.Device.DeviceName = dd.GetDeviceName();
                result.Device.Model      = dd.GetModel();
                result.Device.IsDesktop  = dd.IsDesktop();
                result.Device.IsMobile   = dd.IsMobile();
            }

            return(result);
        }
예제 #10
0
        /// <summary>
        /// Creates the analytic entry if one is deemed to be necessary
        /// This method relies on DeviceDetector.NET. Details at https://github.com/totpero/DeviceDetector.NET
        /// It is advisable to frequently check for updates, especially to the regexes folder (situated in the Resources folder of this project)
        /// </summary>
        /// <param name="Ado"></param>
        /// <param name="requestDTO"></param>
        /// <param name="hRequest"></param>
        /// <param name="request"></param>
        internal static void Create(ADO Ado, dynamic requestDTO, HttpRequest hRequest, JSONRPC_API request)
        {
            //If this method doesn't require analytic logging then exit the function here
            if (!MethodReader.MethodHasAttribute(request.method, "Analytic"))
            {
                return;
            }

            Analytic_DTO aDto = new Analytic_DTO();


            if (hRequest.UserLanguages != null)
            {
                if (hRequest.UserLanguages.Count() > 0)
                {
                    if (hRequest.UserLanguages[0].Length >= 2)
                    {
                        aDto.EnvironmentLngIsoCode = hRequest.UserLanguages[0].Substring(0, 2);
                    }
                }
            }

            //Get a masked version of the ip address
            aDto.NltMaskedIp = getMaskedIp(request.ipAddress);

            //Get the matrix field from the calling DTO
            if (MethodReader.DynamicHasProperty(requestDTO, "jStatQueryExtension"))
            {
                aDto.matrix = requestDTO.jStatQueryExtension.extension.Matrix;
            }

            // Get the Referer
            aDto.NltReferer = hRequest.UrlReferrer == null || String.IsNullOrEmpty(hRequest.UrlReferrer.Host) ? null : hRequest.UrlReferrer.Host;

            //The m2m parameter will not be translated into a DTO property so we just read it from the request parameters if it exists
            if (MethodReader.DynamicHasProperty(requestDTO, "m2m"))
            {
                aDto.NltM2m = requestDTO.m2m;
            }
            else
            {
                aDto.NltM2m = true;
            }

            if (MethodReader.DynamicHasProperty(requestDTO, "widget"))
            {
                aDto.NltWidget = requestDTO.widget;
            }

            if (MethodReader.DynamicHasProperty(requestDTO, "user"))
            {
                aDto.NltUser = requestDTO.user;
            }

            // Get the DateTime
            aDto.NltDate = DateTime.Now;


            //Get Format information
            if (MethodReader.DynamicHasProperty(requestDTO, "jStatQueryExtension"))
            {
                if (MethodReader.DynamicHasProperty(requestDTO.jStatQueryExtension.extension.Format, "Type") && MethodReader.DynamicHasProperty(requestDTO.jStatQueryExtension.extension.Format, "Version"))
                {
                    aDto.FrmType    = requestDTO.jStatQueryExtension.extension.Format.Type;
                    aDto.FrmVersion = requestDTO.jStatQueryExtension.extension.Format.Version;
                }
            }


            //Get the device detector and populate the dto attributes
            DeviceDetector deviceDetector = GetDeviceDetector(request.userAgent);

            aDto.NltBotFlag = deviceDetector.IsBot();


            //If it's a bot, then that overrules everything else
            if (aDto.NltBotFlag)
            {
                aDto.NltM2m    = false;
                aDto.NltUser   = false;
                aDto.NltWidget = false;
            }

            if (deviceDetector.GetBrowserClient().Match != null)
            {
                aDto.NltBrowser = deviceDetector.GetBrowserClient().Match.Name;
            }

            if (deviceDetector.GetOs().Match != null)
            {
                aDto.NltOs = deviceDetector.GetOs().Match.Name;
            }


            var valids = new Analytic_VLD().Validate(aDto);

            //validate whatever has been returned
            if (!valids.IsValid)
            {
                foreach (var fail in valids.Errors)
                {
                    Log.Instance.Debug("Analytic method failed validation:" + request.method + " :" + fail.ErrorMessage);
                }
                return;
            }

            //Create the analytic entry
            Analytic_ADO ado = new Analytic_ADO(Ado);

            if (ado.Create(aDto) == 0)
            {
                Log.Instance.Debug("Failed to create Analytic:" + request.method);
                return;
            }

            return;
        }
예제 #11
0
        internal static void Create(HttpRequest hRequest, string method, string userAgent, string ipaddress, string matrixCode, bool m2m, Format_DTO_Read format)
        {
            ADO Ado = new ADO("defaultConnection");

            try
            {
                Analytic_DTO aDto = new Analytic_DTO()
                {
                    NltMaskedIp = ipaddress, matrix = matrixCode, NltM2m = m2m, NltDate = DateTime.Now, FrmType = format.FrmType, FrmVersion = format.FrmVersion
                };


                // Get the Referer
                aDto.NltReferer = hRequest.UrlReferrer == null || String.IsNullOrEmpty(hRequest.UrlReferrer.Host) ? Configuration_BSO.GetCustomConfig("analytic.referrer-not-applicable") : hRequest.UrlReferrer.Host;


                //Get the device detector and populate the dto attributes
                DeviceDetector deviceDetector = GetDeviceDetector(hRequest.UserAgent);

                aDto.NltBotFlag = deviceDetector.IsBot();

                if (deviceDetector.GetBrowserClient().Match != null)
                {
                    aDto.NltBrowser = deviceDetector.GetBrowserClient().Match.Name;
                }

                if (deviceDetector.GetOs().Match != null)
                {
                    aDto.NltOs = deviceDetector.GetOs().Match.Name;
                }


                var valids = new Analytic_VLD().Validate(aDto);

                //validate whatever has been returned
                if (!valids.IsValid)
                {
                    foreach (var fail in valids.Errors)
                    {
                        Log.Instance.Debug("Analytic method failed validation:" + method + " :" + fail.ErrorMessage);
                    }
                    return;
                }

                //Create the analytic entry
                Analytic_ADO ado = new Analytic_ADO(Ado);

                if (ado.Create(aDto) == 0)
                {
                    Log.Instance.Debug("Failed to create Analytic:" + method);
                    return;
                }

                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Ado.Dispose();
            }
        }
예제 #12
0
        [ValidateAntiForgeryToken] //protect against CSRF attacks
        public async Task <IActionResult> Kontakt(Inquiry inquiry)
        {
            var userAgent = Request.Headers["User-Agent"].ToString();

            // OPTIONAL: Set version truncation to none, so full versions will be returned
            // By default only minor versions will be returned (e.g. X.Y)
            // for other options see VERSION_TRUNCATION_* constants in DeviceParserAbstract class
            // add using DeviceDetectorNET.Parser;
            DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE);

            var dd = new DeviceDetector(userAgent);

            // OPTIONAL: Set caching method
            // By default static cache is used, which works best within one php process (memory array caching)
            // To cache across requests use caching in files or memcache
            // add using DeviceDetectorNET.Cache;
            dd.SetCache(new DictionaryCache());

            // OPTIONAL: If called, GetBot() will only return true if a bot was detected  (speeds up detection a bit)
            dd.DiscardBotInformation();

            // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
            dd.SkipBotDetection();

            dd.Parse();

            if (dd.IsBot())
            {
                // handle bots,spiders,crawlers,...
                var botInfo = dd.GetBot();
                inquiry.Browser         = "BOT";
                inquiry.OperatingSystem = "BOT";
                inquiry.Device          = "BOT";
                inquiry.Brand           = "BOT";
                inquiry.Model           = "BOT";
            }
            else
            {
                var clientInfo = dd.GetClient(); // holds information about browser, feed reader, media player, ...
                var osInfo     = dd.GetOs();
                var device     = dd.GetDeviceName();
                var brand      = dd.GetBrandName();
                var model      = dd.GetModel();

                inquiry.Browser         = $"{clientInfo.Match.Name} ({clientInfo.Match.Version})";
                inquiry.OperatingSystem = $"{osInfo.Match.Name} ({osInfo.Match.Version}) {osInfo.Match.Platform}";
                var deviceResult = device == "" ? inquiry.Device = "N/A" : inquiry.Device = device;
                var brandResult  = brand == "" ? inquiry.Brand = "N/A" : inquiry.Brand = brand;
                var modelResult  = model == "" ? inquiry.Model = "N/A" : inquiry.Model = model;
            }

            //local Environment
            //OperatingSystem os = Environment.OSVersion;
            //var platform = os.Platform.ToString();
            //var version = os.Version.ToString();
            //var servicePack = os.ServicePack.ToString();

            var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();

            inquiry.IpAddress = remoteIpAddress;

            inquiry.CreatedDate = DateTime.Now;
            inquiry.Status      = "New";
            inquiry.HoursSpend  = 0;
            inquiry.HourPrice   = 400;
            inquiry.InvoiceNo   = "N/A";
            inquiry.Payment     = "N/A";


            if (ModelState.IsValid)
            {
                var inquiryId = await contex.Inquiries.FirstOrDefaultAsync(x => x.Id == inquiry.Id);

                if (inquiryId != null)
                {
                    ModelState.AddModelError("", "Nastapil bland, ponow wpis.");
                    return(View());
                }

                //string attachmentName = "noimagecar.png";
                //if (inquiry.AttachmentUpload != null)
                //{
                //    string uploadsDir = Path.Combine(webHostEnvironment.WebRootPath, "media/cars");
                //    attachmentName = Guid.NewGuid().ToString() + "_" + inquiry.AttachmentUpload.FileName;
                //    string filePath = Path.Combine(uploadsDir, attachmentName);
                //    FileStream fs = new FileStream(filePath, FileMode.Create);
                //    await inquiry.AttachmentUpload.CopyToAsync(fs);
                //    fs.Close();
                //}
                //inquiry.Attachment = attachmentName;



                contex.Add(inquiry);
                await contex.SaveChangesAsync();

                TempData["Success"] = "Wiadomosc zostala wyslana!";

                return(RedirectToAction("Kontakt"));
            }

            return(View());
        }