public async Task <IActionResult> FormData()
        {
            Config.ConStr = _configuration.GetConnectionString("Db");
            var model = new FormDataModel();

            try
            {
                DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE);
                BotParser botParser = new BotParser();
                var       userAgent = Request.Headers["User-Agent"];
                var       result    = DeviceDetector.GetInfoFromUserAgent(userAgent);

                if (string.IsNullOrEmpty(HttpContext.Session.GetString("_UserId")))
                {
                    var model2 = new alertLogin();
                    return(await Task.Run(() => RedirectToAction("SignIn", "Home", model2)));
                }
                else
                {
                    ViewBag.UserId = HttpContext.Session.GetString("_UserId");
                    ViewBag.Device = result.Match.DeviceType.ToString();
                    Console.WriteLine(ViewBag.Device);
                    model.ListData = await f.FormData_Get();

                    return(await Task.Run(() => View(model)));
                }
            }
            catch (Exception ex)
            {
                var Error = new ErrorViewModel();
                Error.MessageContent = ex.ToString();
                Error.MessageTitle   = "Error ";
                Error.RequestId      = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
                model.Error          = Error;
                return(await Task.Run(() => View(model)));
            }
        }
Beispiel #2
0
 void RefreshAll(DirectInput manager, DeviceDetector detector)
 {
     lock (DiUpdatesLock)
     {
         var game = SettingsManager.CurrentGame;
         // If game is not selected.
         if (game != null)
         {
             var getXInputStates = SettingsManager.Options.GetXInputStates;
             // Best place to unload XInput DLL is at the start, because
             // UpdateDiStates(...) function will try to acquire new devices exclusively for force feedback information and control.
             CheckAndUnloadXInputLibrarry(game, getXInputStates);
             // Update information about connected devices.
             UpdateDiDevices(manager);
             // Update JoystickStates from devices.
             UpdateDiStates(manager, game, detector);
             // Update XInput states from Custom DirectInput states.
             UpdateXiStates();
             // Combine XInput states of controllers.
             CombineXiStates();
             // Update virtual devices from combined states.
             UpdateVirtualDevices(game);
             // Load XInput library before retrieving XInput states.
             CheckAndLoadXInputLibrary(game, getXInputStates);
             // Retrieve XInput states from XInput controllers.
             RetrieveXiStates(game, getXInputStates);
         }
         // Update pool frequency value every second.
         UpdateDelayFrequency();
         // Fire event.
         var ev = UpdateCompleted;
         if (ev != null)
         {
             ev(this, new DInputEventArgs());
         }
     }
 }
Beispiel #3
0
        public Task Invoke(HttpContext httpContext)
        {
            var userAgent = httpContext.Request.Headers["User-Agent"].FirstOrDefault();

            try
            {
                var userAgentInfo = DeviceDetector.GetInfoFromUserAgent(userAgent);

                _requestMeta.Ip = httpContext.Connection.RemoteIpAddress.ToString();

                if (userAgentInfo.Match.BrowserFamily != "Unknown")
                {
                    _requestMeta.Browser   = userAgentInfo.Match.Client.Name;
                    _requestMeta.Os        = userAgentInfo.Match.Os.Name;
                    _requestMeta.Device    = userAgentInfo.Match.DeviceType;
                    _requestMeta.UserAgent = userAgent;
                }
                else
                {
                    _requestMeta.Browser   = "";
                    _requestMeta.Os        = "";
                    _requestMeta.Device    = "";
                    _requestMeta.UserAgent = userAgent;
                }
            }
            catch (Exception)
            {
                _requestMeta.Browser   = "";
                _requestMeta.Os        = "";
                _requestMeta.Device    = "";
                _requestMeta.UserAgent = userAgent;
            }


            return(_next(httpContext));
        }
Beispiel #4
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);
        }
Beispiel #5
0
		void UpdateForm1()
		{
			detector = new DeviceDetector(false);
			detector.DeviceChanged += new DeviceDetector.DeviceDetectorEventHandler(detector_DeviceChanged);
			BusyLoadingCircle.Visible = false;
			BusyLoadingCircle.Top = HeaderPictureBox.Top;
			BusyLoadingCircle.Left = HeaderPictureBox.Left;
			defaultBody = HelpBodyLabel.Text;
			//if (DesignMode) return;
			OptionsPanel.InitOptions();
			// Set status.
			StatusSaveLabel.Visible = false;
			StatusEventsLabel.Visible = false;
			// Load Tab pages.
			ControlPages = new TabPage[4];
			ControlPages[0] = Pad1TabPage;
			ControlPages[1] = Pad2TabPage;
			ControlPages[2] = Pad3TabPage;
			ControlPages[3] = Pad4TabPage;
			//BuletImageList.Images.Add("bullet_square_glass_blue.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_blue.png")));
			//BuletImageList.Images.Add("bullet_square_glass_green.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_green.png")));
			//BuletImageList.Images.Add("bullet_square_glass_grey.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_grey.png")));
			//BuletImageList.Images.Add("bullet_square_glass_red.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_red.png")));
			//BuletImageList.Images.Add("bullet_square_glass_yellow.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_yellow.png")));
			foreach (var item in ControlPages) item.ImageKey = "bullet_square_glass_grey.png";
			// Hide status values.
			StatusDllLabel.Text = "";
			MainStatusStrip.Visible = false;
			// Check if INI and DLL is on disk.
			WarningsForm.CheckAndOpen();
		}
        /// <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;
        }
        void UpdateDiStates(UserGame game, DeviceDetector detector)
        {
            // Get all mapped user devices.
            var userDevices = SettingsManager.GetMappedDevices(game?.FileName);
            // Acquire copy of feedbacks for processing.
            var feedbacks = CopyAndClearFeedbacks();

            for (int i = 0; i < userDevices.Count(); i++)
            {
                // Update direct input form and return actions (pressed Buttons/DPads, turned Axis/Sliders).
                var ud = userDevices[i];
                //JoystickState state = null;
                CustomDiState    newState   = null;
                CustomDiUpdate[] newUpdates = null;
                // Allow if not testing or testing with option enabled.
                var o     = SettingsManager.Options;
                var allow = !o.TestEnabled || o.TestGetDInputStates;
                // Note: manager.IsDeviceAttached() use a lot of CPU resources.
                var isAttached = ud != null && ud.IsOnline;                 // && manager.IsDeviceAttached(ud.InstanceGuid);
                if (isAttached && allow)
                {
                    var useData = false;
                    var device  = ud.Device;
                    if (device != null)
                    {
                        var exceptionData = new System.Text.StringBuilder();
                        try
                        {
                            if (o.UseDeviceBufferedData && device.Properties.BufferSize == 0)
                            {
                                // Set BufferSize in order to use buffered data.
                                device.Properties.BufferSize = 128;
                                useData = true;
                            }
                            var isVirtual        = ((EmulationType)game.EmulationType).HasFlag(EmulationType.Virtual);
                            var hasForceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback);
                            // Original device will be hidden from the game when acquired in exclusive mode.
                            var acquireMappedDevicesInExclusiveMode = false;
                            // If device is not keyboard or mouse then apply AcquireMappedDevicesInExclusiveMode option.
                            if (device.Information.Type != SharpDX.DirectInput.DeviceType.Keyboard && device.Information.Type != SharpDX.DirectInput.DeviceType.Mouse)
                            {
                                acquireMappedDevicesInExclusiveMode = o.AcquireMappedDevicesInExclusiveMode;
                            }
                            // Exclusive mode required only if force feedback is available and device is virtual there are no info about effects.
                            var exclusiveRequired = acquireMappedDevicesInExclusiveMode || hasForceFeedback && (isVirtual || ud.DeviceEffects == null);
                            // If exclusive mode is required and mode is unknown or not exclusive then...
                            if (exclusiveRequired && (!ud.IsExclusiveMode.HasValue || !ud.IsExclusiveMode.Value))
                            {
                                var flags = CooperativeLevel.Background | CooperativeLevel.Exclusive;
                                // Reacquire device in exclusive mode.
                                exceptionData.AppendLine("UnAcquire (Exclusive)...");
                                device.Unacquire();
                                exceptionData.AppendLine("SetCooperativeLevel (Exclusive)...");
                                device.SetCooperativeLevel(detector.DetectorForm.Handle, flags);
                                exceptionData.AppendLine("Acquire (Exclusive)...");
                                device.Acquire();
                                ud.IsExclusiveMode = true;
                            }
                            // If current mode must be non exclusive and mode is unknown or exclusive then...
                            else if (!exclusiveRequired && (!ud.IsExclusiveMode.HasValue || ud.IsExclusiveMode.Value))
                            {
                                var flags = CooperativeLevel.Background | CooperativeLevel.NonExclusive;
                                // Reacquire device in non exclusive mode so that xinput.dll can control force feedback.
                                exceptionData.AppendLine("UnAcquire (NonExclusive)...");
                                device.Unacquire();
                                exceptionData.AppendLine("SetCooperativeLevel (Exclusive)...");
                                device.SetCooperativeLevel(detector.DetectorForm.Handle, flags);
                                exceptionData.AppendLine("Acquire (Acquire)...");
                                device.Acquire();
                                ud.IsExclusiveMode = false;
                            }
                            exceptionData.AppendFormat("device.GetCurrentState() // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                            // Polling - Retrieves data from polled objects on a DirectInput device.
                            // Some devices require pooling (For example original "XBOX Controller S" with XBCD drivers).
                            // If the device does not require polling, calling this method has no effect.
                            // If a device that requires polling is not polled periodically, no new data is received from the device.
                            // Calling this method causes DirectInput to update the device state, generate input
                            // events (if buffered data is enabled), and set notification events (if notification is enabled).
                            device.Poll();
                            // Get device states as buffered data.
                            if (device is Mouse mDevice)
                            {
                                if (useData)
                                {
                                    var data = mDevice.GetBufferedData();
                                    newUpdates = data?.Select(x => new CustomDiUpdate(x)).ToArray();
                                }
                                var state = mDevice.GetCurrentState();
                                newState       = new CustomDiState(state);
                                ud.DeviceState = state;
                            }
                            else if (device is Keyboard kDevice)
                            {
                                if (useData)
                                {
                                    var data = kDevice.GetBufferedData();
                                    newUpdates = data?.Select(x => new CustomDiUpdate(x)).ToArray();
                                }
                                var state = kDevice.GetCurrentState();
                                newState       = new CustomDiState(state);
                                ud.DeviceState = state;
                            }
                            else if (device is Joystick jDevice)
                            {
                                if (useData)
                                {
                                    var data = jDevice.GetBufferedData();
                                    newUpdates = data?.Select(x => new CustomDiUpdate(x)).ToArray();
                                }
                                var state = jDevice.GetCurrentState();
                                newState       = new CustomDiState(state);
                                ud.DeviceState = state;
                            }
                            else
                            {
                                throw new Exception(string.Format("Unknown device: {0}", device));
                            }
                            // Fill device objects.
                            if (ud.DeviceObjects == null)
                            {
                                exceptionData.AppendFormat("AppHelper.GetDeviceObjects(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                var dos = AppHelper.GetDeviceObjects(device);
                                ud.DeviceObjects = dos;
                                // Update masks.
                                int axisMask      = 0;
                                int actuatorMask  = 0;
                                int actuatorCount = 0;
                                if (device is Mouse mDevice2)
                                {
                                    CustomDiState.GetMouseAxisMask(dos, mDevice2, out axisMask);
                                }
                                else if (device is Joystick jDevice)
                                {
                                    CustomDiState.GetJoystickAxisMask(dos, jDevice, out axisMask, out actuatorMask, out actuatorCount);
                                    //CustomDiState.GetJoystickSlidersMask(dos, (Joystick) device, out slidersMask);
                                }
                                ud.DiAxeMask = axisMask;
                                // Contains information about which axis have force feedback actuator attached.
                                ud.DiActuatorMask  = actuatorMask;
                                ud.DiActuatorCount = actuatorCount;
                            }
                            if (ud.DeviceEffects == null)
                            {
                                exceptionData.AppendFormat("AppHelper.GetDeviceEffects(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                ud.DeviceEffects = AppHelper.GetDeviceEffects(device);
                            }
                            // If device support force feedback then...
                            if (hasForceFeedback)
                            {
                                // Get setting related to user device.
                                var setting = SettingsManager.UserSettings.ItemsToArraySynchronized()
                                              .FirstOrDefault(x => x.InstanceGuid == ud.InstanceGuid);
                                // If device is mapped to controller then...
                                if (setting != null && setting.MapTo > (int)MapTo.None)
                                {
                                    // Get pad setting attached to device.
                                    var ps = SettingsManager.GetPadSetting(setting.PadSettingChecksum);
                                    if (ps != null)
                                    {
                                        // If force is enabled then...
                                        if (ps.ForceEnable == "1")
                                        {
                                            if (ud.FFState == null)
                                            {
                                                ud.FFState = new Engine.ForceFeedbackState();
                                            }
                                            // If force update supplied then...
                                            var force = feedbacks[setting.MapTo - 1];
                                            if (force != null || ud.FFState.Changed(ps))
                                            {
                                                var v = new Vibration();
                                                if (force == null)
                                                {
                                                    v.LeftMotorSpeed  = short.MinValue;
                                                    v.RightMotorSpeed = short.MinValue;
                                                }
                                                else
                                                {
                                                    v.LeftMotorSpeed  = (short)ConvertHelper.ConvertRange(byte.MinValue, byte.MaxValue, short.MinValue, short.MaxValue, force.LargeMotor);
                                                    v.RightMotorSpeed = (short)ConvertHelper.ConvertRange(byte.MinValue, byte.MaxValue, short.MinValue, short.MaxValue, force.SmallMotor);
                                                }
                                                // For the future: Investigate device states if force feedback is not working.
                                                // var st = ud.Device.GetForceFeedbackState();
                                                //st == SharpDX.DirectInput.ForceFeedbackState
                                                // ud.Device.SendForceFeedbackCommand(ForceFeedbackCommand.SetActuatorsOn);
                                                exceptionData.AppendFormat("ud.FFState.SetDeviceForces(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                                ud.FFState.SetDeviceForces(ud, device, ps, v);
                                            }
                                        }
                                        // If force state was created then...
                                        else if (ud.FFState != null)
                                        {
                                            // Stop device forces.
                                            exceptionData.AppendFormat("ud.FFState.StopDeviceForces(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                            ud.FFState.StopDeviceForces(device);
                                            ud.FFState = null;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var dex = ex as SharpDXException;
                            if (dex != null && dex.ResultCode == SharpDX.DirectInput.ResultCode.InputLost)
                            {
                                // Ignore error.
                            }
                            else if (dex != null && dex.ResultCode == SharpDX.DirectInput.ResultCode.NotAcquired)
                            {
                                // Ignore error
                            }
                            else if (dex != null && dex.ResultCode == SharpDX.DirectInput.ResultCode.Unplugged)
                            {
                                // Ignore error
                            }
                            else
                            {
                                var cx = new DInputException("UpdateDiStates Exception", ex);
                                cx.Data.Add("FFInfo", exceptionData.ToString());
                                JocysCom.ClassLibrary.Runtime.LogHelper.Current.WriteException(cx);
                            }
                            ud.IsExclusiveMode = null;
                        }
                    }
                    // If this is test device then...
                    else if (TestDeviceHelper.ProductGuid.Equals(ud.ProductGuid))
                    {
                        // Fill device objects.
                        if (ud.DeviceObjects == null)
                        {
                            var dos = TestDeviceHelper.GetDeviceObjects();
                            ud.DeviceObjects = dos;
                            // Update masks.
                            ud.DiAxeMask    = 0x1 | 0x2 | 0x4 | 0x8;
                            ud.DiSliderMask = 0;
                        }
                        if (ud.DeviceEffects == null)
                        {
                            ud.DeviceEffects = new DeviceEffectItem[0];
                        }
                        var state = TestDeviceHelper.GetCurrentState(ud);
                        newState       = new CustomDiState(state);
                        ud.DeviceState = state;
                    }
                }
                if (newState != null)
                {
                    // If updates from buffer supplied and old state is available then...
                    if (newUpdates != null && newUpdates.Count(x => x.Type == MapType.Button) > 1 && ud.DiState != null)
                    {
                        // Analyse if state must be modified.
                        for (int b = 0; b < newState.Buttons.Length; b++)
                        {
                            var oldPresseed = ud.DiState.Buttons[b];
                            var newPresseed = newState.Buttons[b];
                            // If button state was not changed.
                            if (oldPresseed == newPresseed)
                            {
                                // But buffer contains press then...
                                var wasPressed = newUpdates.Count(x => x.Type == MapType.Button && x.Index == b) > 1;
                                if (wasPressed)
                                {
                                    // Invert state and give chance for the game to recognize the press.
                                    newState.Buttons[b] = !newState.Buttons[b];
                                }
                            }
                        }
                    }
                    var newTime = watch.ElapsedTicks;
                    // Remember old state.
                    ud.OldDiState     = ud.DiState;
                    ud.OldDiUpdates   = ud.DiUpdates;
                    ud.OldDiStateTime = ud.DiStateTime;
                    // Update state.
                    ud.DiState     = newState;
                    ud.DiUpdates   = newUpdates;
                    ud.DiStateTime = newTime;
                    // Mouse needs special update.
                    if (ud.Device != null && ud.Device.Information.Type == SharpDX.DirectInput.DeviceType.Mouse)
                    {
                        // If original state is missing then...
                        if (ud.OrgDiState == null)
                        {
                            // Store current values.
                            ud.OrgDiState     = newState;
                            ud.OrgDiStateTime = newTime;
                            // Make sure new states have zero values.
                            for (int a = 0; a < newState.Axis.Length; a++)
                            {
                                newState.Axis[a] = -short.MinValue;
                            }
                            for (int s = 0; s < newState.Sliders.Length; s++)
                            {
                                newState.Sliders[s] = -short.MinValue;
                            }
                        }
                        var mouseState = new CustomDiState(new JoystickState());
                        // Clone button values.
                        Array.Copy(newState.Buttons, mouseState.Buttons, mouseState.Buttons.Length);

                        //	//--------------------------------------------------------
                        //	// Map mouse acceleration to axis position. Good for FPS control.
                        //	//--------------------------------------------------------

                        //	// This parts needs to be worked on.
                        //	//var ticks = (int)(newTime - ud.DiStateTime);
                        //	// Update axis with delta.
                        //	//for (int a = 0; a < newState.Axis.Length; a++)
                        //	//	mouseState.Axis[a] = ticks * (newState.Axis[a] - ud.OldDiState.Axis[a]) - short.MinValue;
                        //	// Update sliders with delta.
                        //	//for (int s = 0; s < newState.Sliders.Length; s++)
                        //	//	mouseState.Sliders[s] = ticks * (newState.Sliders[s] - ud.OldDiState.Sliders[s]) - short.MinValue;

                        //--------------------------------------------------------
                        // Map mouse position to axis position. Good for car wheel controls.
                        //--------------------------------------------------------
                        Calc(ud.OrgDiState.Axis, newState.Axis, mouseState.Axis);
                        Calc(ud.OrgDiState.Sliders, newState.Sliders, mouseState.Sliders);
                        ud.DiState = mouseState;
                    }
                }
            }
        }
        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();
            }
        }
Beispiel #9
0
 // Detector will be initialized on a separate thread.
 public void InitDeviceDetector()
 {
     UpdateDevicesEnabled = true;
     detector             = new DeviceDetector(false);
 }
 public void InitDeviceDetector()
 {
     UpdateDevicesEnabled    = true;
     detector                = new DeviceDetector(false);
     detector.DeviceChanged += detector_DeviceChanged;
 }
Beispiel #11
0
 public static bool IsMobileOnDesktop(this HttpContextBase httpContext)
 {
     return(DeviceDetector.IsMobileOnDesktop(httpContext));
 }
Beispiel #12
0
        void UpdateDiStates(UserGame game, DeviceDetector detector)
        {
            // Get all mapped user instances.
            var instanceGuids = SettingsManager.Settings.Items
                                .Where(x => x.MapTo > (int)MapTo.None)
                                .Select(x => x.InstanceGuid).ToArray();
            // Get all connected devices.
            var userDevices = SettingsManager.UserDevices.Items
                              .Where(x => instanceGuids.Contains(x.InstanceGuid) && x.IsOnline)
                              .ToArray();

            // Acquire copy of feedbacks for processing.
            var feedbacks = CopyAndClearFeedbacks();

            for (int i = 0; i < userDevices.Count(); i++)
            {
                // Update direct input form and return actions (pressed Buttons/DPads, turned Axis/Sliders).
                var           ud    = userDevices[i];
                JoystickState state = null;
                // Allow if not testing or testing with option enabled.
                var o        = SettingsManager.Options;
                var allow    = !o.TestEnabled || o.TestGetDInputStates;
                var isOnline = ud != null && ud.IsOnline;
                if (isOnline && allow)
                {
                    var device = ud.Device;
                    if (device != null)
                    {
                        var exceptionData = new System.Text.StringBuilder();
                        try
                        {
                            var isVirtual        = ((EmulationType)game.EmulationType).HasFlag(EmulationType.Virtual);
                            var hasForceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback);
                            // Exclusive mode required only if force feedback is available and device is virtual there are no info about effects.
                            var exclusiveRequired = hasForceFeedback && (isVirtual || ud.DeviceEffects == null);
                            // If exclusive mode is required and mode is unknown or not exclusive then...
                            if (exclusiveRequired && (!ud.IsExclusiveMode.HasValue || !ud.IsExclusiveMode.Value))
                            {
                                var flags = CooperativeLevel.Background | CooperativeLevel.Exclusive;
                                // Reacquire device in exclusive mode.
                                exceptionData.AppendLine("Unacquire (Exclusive)...");
                                device.Unacquire();
                                exceptionData.AppendLine("SetCooperativeLevel (Exclusive)...");
                                device.SetCooperativeLevel(detector.DetectorForm.Handle, flags);
                                exceptionData.AppendLine("Acquire (Exclusive)...");
                                device.Acquire();
                                ud.IsExclusiveMode = true;
                            }
                            // If current mode must be non exclusive and mode is unknown or exclusive then...
                            else if (!exclusiveRequired && (!ud.IsExclusiveMode.HasValue || ud.IsExclusiveMode.Value))
                            {
                                var flags = CooperativeLevel.Background | CooperativeLevel.NonExclusive;
                                // Reacquire device in non exclusive mode so that xinput.dll can control force feedback.
                                exceptionData.AppendLine("Unacquire (NonExclusive)...");
                                device.Unacquire();
                                exceptionData.AppendLine("SetCooperativeLevel (Exclusive)...");
                                device.SetCooperativeLevel(detector.DetectorForm.Handle, flags);
                                exceptionData.AppendLine("Acquire (Acquire)...");
                                device.Acquire();
                                ud.IsExclusiveMode = false;
                            }
                            exceptionData.AppendFormat("device.GetCurrentState() // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                            // Polling - Retrieves data from polled objects on a DirectInput device.
                            // Some devices require pooling (For example original "Xbox Controller S" with XBCD drivers).
                            // If the device does not require polling, calling this method has no effect.
                            // If a device that requires polling is not polled periodically, no new data is received from the device.
                            // Calling this method causes DirectInput to update the device state, generate input
                            // events (if buffered data is enabled), and set notification events (if notification is enabled).
                            device.Poll();
                            // Get device state.
                            state = device.GetCurrentState();
                            // Fill device objects.
                            if (ud.DeviceObjects == null)
                            {
                                exceptionData.AppendFormat("AppHelper.GetDeviceObjects(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                var dos = AppHelper.GetDeviceObjects(device);
                                ud.DeviceObjects = dos;
                                // Update masks.
                                int axisMask      = 0;
                                int actuatorMask  = 0;
                                int actuatorCount = 0;
                                if (ud.CapType == (int)SharpDX.DirectInput.DeviceType.Mouse)
                                {
                                    CustomDiState.GetMouseAxisMask(dos, device, out axisMask);
                                }
                                else
                                {
                                    CustomDiState.GetJoystickAxisMask(dos, device, out axisMask, out actuatorMask, out actuatorCount);
                                }
                                ud.DiAxeMask = axisMask;
                                // Contains information about which axis have force feedback actuator attached.
                                ud.DiActuatorMask  = actuatorMask;
                                ud.DiActuatorCount = actuatorCount;
                                CustomDiState.GetJoystickSlidersMask(dos, device);
                            }
                            if (ud.DeviceEffects == null)
                            {
                                exceptionData.AppendFormat("AppHelper.GetDeviceEffects(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                ud.DeviceEffects = AppHelper.GetDeviceEffects(device);
                            }
                            // Get PAD index this device is mapped to.
                            var userIndex = SettingsManager.Settings.Items
                                            .Where(x => x.MapTo > (int)MapTo.None)
                                            .Where(x => x.InstanceGuid == ud.InstanceGuid)
                                            .Select(x => x.MapTo).First();
                            // If device support force feedback then...
                            if (hasForceFeedback)
                            {
                                // Get setting related to user device.
                                var setting = SettingsManager.Settings.Items
                                              .FirstOrDefault(x => x.MapTo == userIndex && x.InstanceGuid == ud.InstanceGuid);
                                if (setting != null)
                                {
                                    // Get pad setting attached to device.
                                    var ps = SettingsManager.GetPadSetting(setting.PadSettingChecksum);
                                    if (ps != null)
                                    {
                                        // If force is enabled then...
                                        if (ps.ForceEnable == "1")
                                        {
                                            if (ud.FFState == null)
                                            {
                                                ud.FFState = new Engine.ForceFeedbackState();
                                            }
                                            // If force update supplied then...
                                            var force = feedbacks[userIndex - 1];
                                            if (force != null || ud.FFState.Changed(ps))
                                            {
                                                var v = new Vibration();
                                                if (force == null)
                                                {
                                                    v.LeftMotorSpeed  = short.MinValue;
                                                    v.RightMotorSpeed = short.MinValue;
                                                }
                                                else
                                                {
                                                    v.LeftMotorSpeed  = (short)ConvertHelper.ConvertRange(byte.MinValue, byte.MaxValue, short.MinValue, short.MaxValue, force.LargeMotor);
                                                    v.RightMotorSpeed = (short)ConvertHelper.ConvertRange(byte.MinValue, byte.MaxValue, short.MinValue, short.MaxValue, force.SmallMotor);
                                                }
                                                // For the future: Investigate device states if force feedback is not working.
                                                // var st = ud.Device.GetForceFeedbackState();
                                                //st == SharpDX.DirectInput.ForceFeedbackState
                                                // ud.Device.SendForceFeedbackCommand(ForceFeedbackCommand.SetActuatorsOn);
                                                exceptionData.AppendFormat("ud.FFState.SetDeviceForces(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                                ud.FFState.SetDeviceForces(ud, device, ps, v);
                                            }
                                        }
                                        // If force state was created then...
                                        else if (ud.FFState != null)
                                        {
                                            // Stop device forces.
                                            exceptionData.AppendFormat("ud.FFState.StopDeviceForces(device) // ud.IsExclusiveMode = {0}", ud.IsExclusiveMode).AppendLine();
                                            ud.FFState.StopDeviceForces(device);
                                            ud.FFState = null;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var cx = new DInputException("UpdateDiStates Exception", ex);
                            cx.Data.Add("FFInfo", exceptionData.ToString());
                            JocysCom.ClassLibrary.Runtime.LogHelper.Current.WriteException(cx);
                            ud.IsExclusiveMode = null;
                        }
                    }
                    // If this is test device then...
                    else if (TestDeviceHelper.ProductGuid.Equals(ud.ProductGuid))
                    {
                        // Fill device objects.
                        if (ud.DeviceObjects == null)
                        {
                            var dos = TestDeviceHelper.GetDeviceObjects();
                            ud.DeviceObjects = dos;
                            // Update masks.
                            ud.DiAxeMask    = 0x1 | 0x2 | 0x4 | 0x8;
                            ud.DiSliderMask = 0;
                        }
                        if (ud.DeviceEffects == null)
                        {
                            ud.DeviceEffects = new DeviceEffectItem[0];
                        }
                        state = TestDeviceHelper.GetCurrentState(ud);
                    }
                }
                ud.JoState = state ?? new JoystickState();
                var newState = new CustomDiState(ud.JoState);
                var newTime  = watch.ElapsedTicks;
                // Mouse needs special update.
                if (ud.Device != null && ud.Device.Information.Type == SharpDX.DirectInput.DeviceType.Mouse)
                {
                    if (ud.DiState == null)
                    {
                        ud.DiState = new CustomDiState(new JoystickState());
                    }
                    var mouseState = ud.DiState;
                    if (ud.OldDiState == null)
                    {
                        ud.DiState = mouseState;
                        // Make sure new state have zero values.
                        for (int a = 0; a < newState.Axis.Length; a++)
                        {
                            mouseState.Axis[a] = -short.MinValue;
                        }
                        // Update sliders with delta.
                        for (int s = 0; s < newState.Sliders.Length; s++)
                        {
                            mouseState.Sliders[s] = -short.MinValue;
                        }
                    }
                    else
                    {
                        //--------------------------------------------------------
                        // Map mouse acceleration to axis position. Good for FPS control.
                        //--------------------------------------------------------

                        // This parts needs to be worked on.
                        //var ticks = (int)(newTime - ud.DiStateTime);
                        // Update axis with delta.
                        //for (int a = 0; a < newState.Axis.Length; a++)
                        //	mouseState.Axis[a] = ticks * (newState.Axis[a] - ud.OldDiState.Axis[a]) - short.MinValue;
                        // Update sliders with delta.
                        //for (int s = 0; s < newState.Sliders.Length; s++)
                        //	mouseState.Sliders[s] = ticks * (newState.Sliders[s] - ud.OldDiState.Sliders[s]) - short.MinValue;

                        //--------------------------------------------------------
                        // Map mouse position to axis position. Good for car wheel controls.
                        //--------------------------------------------------------
                        var sensitivity = 10;

                        for (int a = 0; a < newState.Axis.Length; a++)
                        {
                            // Get delta from last state.
                            var delta    = newState.Axis[a] - ud.OldDiState.Axis[a];
                            var newValue = mouseState.Axis[a] + (delta * sensitivity);
                            newValue           = Math.Min(newValue, ushort.MaxValue);
                            newValue           = Math.Max(newValue, ushort.MinValue);
                            mouseState.Axis[a] = newValue;
                        }
                        for (int a = 0; a < newState.Sliders.Length; a++)
                        {
                            // Get delta from last state.
                            var delta    = newState.Sliders[a] - ud.OldDiState.Sliders[a];
                            var newValue = mouseState.Sliders[a] + (delta * sensitivity);
                            newValue = Math.Min(newValue, ushort.MaxValue);
                            newValue = Math.Max(newValue, ushort.MinValue);
                            mouseState.Sliders[a] = newValue;
                        }
                    }
                    // Assign unmodified state.
                    ud.OldDiState     = newState;
                    ud.OldDiStateTime = ud.DiStateTime;
                }
                else
                {
                    // Update state.
                    ud.DiState = newState;
                }
                ud.DiStateTime = newTime;
            }
        }
Beispiel #13
0
 void InitDevices()
 {
     detector = new DeviceDetector(false);
     UpdateDevices();
     detector.DeviceChanged += new DeviceDetector.DeviceDetectorEventHandler(detector_DeviceChanged);
 }
Beispiel #14
0
        public static SP_DRVINFO_DATA GetHidGuardianDriverInfo()
        {
            var driver = DeviceDetector.GetDrivers(DEVCLASS.SYSTEM, DIGCF.DIGCF_PRESENT, SPDIT.SPDIT_COMPATDRIVER, null, HidGuardianHardwareId).FirstOrDefault();

            return(driver);
        }
Beispiel #15
0
 /// <summary>
 /// Clean up any 
 /// being used.
 /// </summary>
 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing && (components != null))
     {
         if (_Mutex != null)
         {
             _Mutex.Dispose();
         }
         DisposeWarnigForm();
         DisposeDeviceForm();
         if (detector != null)
         {
             detector.Dispose();
             detector = null;
         }
         Manager.Dispose();
         Manager = null;
         components.Dispose();
         //lock (checkTimerLock)
         //{
         //	// If timer is disposed then return;
         //	if (checkTimer == null) return;
         //	CheckAll();
         //}
     }
     base.Dispose(disposing);
 }
Beispiel #16
0
 public static IBrowserCaps GetBrowserCaps(this HttpContextBase httpContext)
 {
     return(DeviceDetector.GetBrowserCaps(httpContext));
 }
Beispiel #17
0
        void UpdateDiDevices()
        {
            if (!UpdateDevicesEnabled)
            {
                return;
            }
            UpdateDevicesEnabled = false;
            // Make sure that interface handle is created, before starting device updates.
            UserDevice[] deleteDevices;
            // Add connected devices.
            var insertDevices = new List <UserDevice>();
            var updateDevices = new List <KeyValuePair <UserDevice, DeviceInstance> >();
            // List of connected devices (can be a very long operation).
            var devices = new List <DeviceInstance>();
            // Controllers.
            var controllerInstances = Manager.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in controllerInstances)
            {
                devices.Add(item);
            }
            // Pointers.
            var pointerInstances = Manager.GetDevices(DeviceClass.Pointer, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in pointerInstances)
            {
                devices.Add(item);
            }
            // Keyboards.
            var keyboardInstances = Manager.GetDevices(DeviceClass.Keyboard, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in keyboardInstances)
            {
                devices.Add(item);
            }
            if (Program.IsClosing)
            {
                return;
            }
            // List of connected devices.
            var deviceInstanceGuid = devices.Select(x => x.InstanceGuid).ToList();
            // List of current devices.
            var currentInstanceGuids = SettingsManager.UserDevices.Items.Select(x => x.InstanceGuid).ToArray();

            deleteDevices = SettingsManager.UserDevices.Items.Where(x => !deviceInstanceGuid.Contains(x.InstanceGuid)).ToArray();
            var addedDevices   = devices.Where(x => !currentInstanceGuids.Contains(x.InstanceGuid)).ToArray();
            var updatedDevices = devices.Where(x => currentInstanceGuids.Contains(x.InstanceGuid)).ToArray();

            // Must find better way to find Device than by Vendor ID and Product ID.
            if (addedDevices.Length > 0)
            {
                //Joystick    = new Guid("6f1d2b70-d5a0-11cf-bfc7-444553540000");
                //SysMouse    = new Guid("6f1d2b60-d5a0-11cf-bfc7-444553540000");
                //SysKeyboard = new Guid("6f1d2b61-d5a0-11cf-bfc7-444553540000");
                DeviceInfo[] devInfos = DeviceDetector.GetDevices();
                DeviceInfo[] intInfos = null;
                // Controllers.
                var controllers = addedDevices
                                  .Where(x => x.Type != SharpDX.DirectInput.DeviceType.Mouse && x.Type != SharpDX.DirectInput.DeviceType.Keyboard)
                                  .Select(x => new Joystick(Manager, x.InstanceGuid)).ToArray();
                // Get interfaces.
                var interfacePaths = controllers.Select(x => x.Properties.InterfacePath).ToArray();
                intInfos = DeviceDetector.GetInterfaces(interfacePaths);
                for (int i = 0; i < addedDevices.Length; i++)
                {
                    var device = addedDevices[i];
                    var ud     = new UserDevice();
                    RefreshDevice(ud, device);
                    DeviceInfo hid = null;
                    DeviceInfo dev = null;
                    if (device.IsHumanInterfaceDevice)
                    {
                        // Get interface info for added devices.
                        hid = intInfos.FirstOrDefault(x => x.DevicePath == ud.Device.Properties.InterfacePath);
                        // Get device info for added devices.
                        dev = devInfos.FirstOrDefault(x => x.DeviceId == ud.HidDeviceId);
                    }
                    ud.LoadHidDeviceInfo(hid);
                    ud.LoadDevDeviceInfo(dev);
                    var isVirtual = false;
                    if (hid != null)
                    {
                        DeviceInfo p = hid;
                        do
                        {
                            p = DeviceDetector.GetParentDevice(Guid.Empty, JocysCom.ClassLibrary.Win32.DIGCF.DIGCF_ALLCLASSES, p.DeviceId);
                            if (p != null && string.Compare(p.HardwareId, VirtualDriverInstaller.ViGEmBusHardwareId, true) == 0)
                            {
                                isVirtual = true;
                                break;
                            }
                        } while (p != null);
                    }
                    if (!isVirtual)
                    {
                        insertDevices.Add(ud);
                    }
                }
            }
            //if (insertDevices.Count > 0)
            //{
            //	CloudPanel.Add(CloudAction.Insert, insertDevices.ToArray(), true);
            //}
            for (int i = 0; i < updatedDevices.Length; i++)
            {
                var device = updatedDevices[i];
                var di     = SettingsManager.UserDevices.Items.First(x => x.InstanceGuid.Equals(device.InstanceGuid));
                updateDevices.Add(new KeyValuePair <UserDevice, DeviceInstance>(di, device));
            }
            if (Program.IsClosing)
            {
                return;
            }
            // Remove disconnected devices.
            for (int i = 0; i < deleteDevices.Length; i++)
            {
                deleteDevices[i].IsOnline = false;
            }
            for (int i = 0; i < insertDevices.Count; i++)
            {
                var ud = insertDevices[i];
                SettingsManager.UserDevices.Items.Add(ud);
            }
            for (int i = 0; i < updateDevices.Count; i++)
            {
                var kv = updateDevices[i];
                RefreshDevice(kv.Key, kv.Value);
            }
            // Enable Test instances.
            TestDeviceHelper.EnableTestInstances();
            RefreshDevicesCount++;
            var ev = DevicesUpdated;

            if (ev != null)
            {
                ev(this, new DInputEventArgs());
            }
            //	var game = CurrentGame;
            //	if (game != null)
            //	{
            //		// Auto-configure new devices.
            //		AutoConfigure(game);
            //	}
        }
        public void TestParseInvalidUa()
        {
            var dd = new DeviceDetector("12345");

            dd.Parse();
        }
        void UpdateDiDevices(DirectInput manager)
        {
            if (!UpdateDevicesPending)
            {
                return;
            }
            UpdateDevicesPending = false;
            // Make sure that interface handle is created, before starting device updates.
            UserDevice[] deleteDevices;
            // Add connected devices.
            var insertDevices = new List <UserDevice>();
            // List of connected devices (can be a very long operation).
            var devices = new List <DeviceInstance>();
            // Controllers.
            var controllerInstances = manager.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in controllerInstances)
            {
                devices.Add(item);
            }
            // Pointers.
            var pointerInstances = manager.GetDevices(DeviceClass.Pointer, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in pointerInstances)
            {
                devices.Add(item);
            }
            // Keyboards.
            var keyboardInstances = manager.GetDevices(DeviceClass.Keyboard, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in keyboardInstances)
            {
                devices.Add(item);
            }
            if (Program.IsClosing)
            {
                return;
            }
            // List of connected devices.
            var deviceInstanceGuid = devices.Select(x => x.InstanceGuid).ToList();
            // List of current devices.
            var uds = SettingsManager.UserDevices.ItemsToArraySyncronized();
            var currentInstanceGuids = uds.Select(x => x.InstanceGuid).ToArray();

            deleteDevices = uds.Where(x => !deviceInstanceGuid.Contains(x.InstanceGuid)).ToArray();
            var addedDevices   = devices.Where(x => !currentInstanceGuids.Contains(x.InstanceGuid)).ToArray();
            var updatedDevices = devices.Where(x => currentInstanceGuids.Contains(x.InstanceGuid)).ToArray();

            // Must find better way to find Device than by Vendor ID and Product ID.
            DeviceInfo[] devInfos = null;
            DeviceInfo[] intInfos = null;
            if (addedDevices.Length > 0 || updatedDevices.Length > 0)
            {
                devInfos = DeviceDetector.GetDevices();
                //var classes = devInfos.Select(x=>x.ClassDescription).Distinct().ToArray();
                intInfos = DeviceDetector.GetInterfaces();
                //var intclasses = intInfos.Select(x => x.ClassDescription).Distinct().ToArray();
            }
            //Joystick    = new Guid("6f1d2b70-d5a0-11cf-bfc7-444553540000");
            //SysMouse    = new Guid("6f1d2b60-d5a0-11cf-bfc7-444553540000");
            //SysKeyboard = new Guid("6f1d2b61-d5a0-11cf-bfc7-444553540000");
            for (int i = 0; i < addedDevices.Length; i++)
            {
                var        device = addedDevices[i];
                var        ud     = new UserDevice();
                DeviceInfo hid;
                RefreshDevice(manager, ud, device, devInfos, intInfos, out hid);
                var isVirtual = false;
                if (hid != null)
                {
                    DeviceInfo p = hid;
                    do
                    {
                        p = devInfos.FirstOrDefault(x => x.DeviceId == p.ParentDeviceId);
                        // If ViGEm hardware found then...
                        if (p != null && VirtualDriverInstaller.ViGEmBusHardwareIds.Any(x => string.Compare(p.HardwareIds, x, true) == 0))
                        {
                            isVirtual = true;
                            break;
                        }
                    } while (p != null);
                }
                if (!isVirtual)
                {
                    insertDevices.Add(ud);
                }
            }
            //if (insertDevices.Count > 0)
            //{
            //	CloudPanel.Add(CloudAction.Insert, insertDevices.ToArray(), true);
            //}
            for (int i = 0; i < updatedDevices.Length; i++)
            {
                var        device = updatedDevices[i];
                var        ud     = uds.First(x => x.InstanceGuid.Equals(device.InstanceGuid));
                DeviceInfo hid;
                // Will refresh device and fill more values with new x360ce app if available.
                RefreshDevice(manager, ud, device, devInfos, intInfos, out hid);
            }
            if (Program.IsClosing)
            {
                return;
            }
            // Remove disconnected devices.
            for (int i = 0; i < deleteDevices.Length; i++)
            {
                lock (SettingsManager.UserDevices.SyncRoot)
                    deleteDevices[i].IsOnline = false;
            }
            for (int i = 0; i < insertDevices.Count; i++)
            {
                var ud = insertDevices[i];
                lock (SettingsManager.UserDevices.SyncRoot)
                    SettingsManager.UserDevices.Items.Add(ud);
            }
            // Enable Test instances.
            TestDeviceHelper.EnableTestInstances();
            RefreshDevicesCount++;
            var ev = DevicesUpdated;

            if (ev != null)
            {
                ev(this, new DInputEventArgs());
            }
            //	var game = CurrentGame;
            //	if (game != null)
            //	{
            //		// Auto-configure new devices.
            //		AutoConfigure(game);
            //	}
        }
        // Login
        public async Task <LoginResponse> Login(LoginRequest model, string ipAddress, DeviceDetector deviceDetector)
        {
            model.Email = model.Email.ToLower();
            try
            {
                var user = await _context.Users.Include(u => u.Photos).FirstOrDefaultAsync(u => u.Email == model.Email && u.FacebookUID == null);

                if (user == null || !VerifyPasswordHash(model.Password, user.PasswordHash, user.PasswordSalt))
                {
                    throw new AppException("Email or password is incorrect");
                }
                if (user.Role != Role.Admin && model.Role == Role.Admin)
                {
                    throw new AppException("Not eligible");
                }
                if (!user.IsVerified)
                {
                    throw new AppException("Please verify your email before logging in");
                }
                if (user.Status == Status.Disabled || user.Status == Status.Deleted)
                {
                    throw new AppException($"Account {user.Status.ToString().ToLower()}");
                }
                var refreshToken = GenerateRefreshToken(ipAddress, deviceDetector);
                user.RefreshTokens.Add(refreshToken);
                _context.Update(user);
                await _context.SaveChangesAsync();

                var jwtToken = GenerateJwtToken(user);
                var response = _mapper.Map <LoginResponse>(user);
                response.JwtToken     = jwtToken;
                response.RefreshToken = refreshToken.Token;
                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #21
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());
        }
Beispiel #22
0
 public static bool IsTablet(this HttpContextBase httpContext)
 {
     return(DeviceDetector.IsTablet(httpContext));
 }
        // Login with facebook
        public async Task <LoginResponse> FacebookLogin(FacebookLoginRequest model, string ipAddress, DeviceDetector deviceDetector)
        {
            User user = null;

            var facebookUser = await _facebookService.GetUser(model);

            if (facebookUser.Existing)
            {
                user = await _context.Users.Include(u => u.Photos).FirstOrDefaultAsync(u => u.FacebookUID == model.FacebookUID);
            }
            else
            {
                var userToCreate = _mapper.Map <User>(facebookUser);
                userToCreate.Verified = DateTime.Now;
                userToCreate.Role     = Role.User;
                userToCreate.Status   = Status.Active;
                userToCreate.Created  = DateTime.Now;

                _context.Users.Add(userToCreate);

                if (await _context.SaveChangesAsync() > 0)
                {
                    user = await _context.Users.Include(u => u.Photos).FirstOrDefaultAsync(u => u.FacebookUID == facebookUser.FacebookUID);

                    if (facebookUser.Picture != null)
                    {
                        var photo = new Photo
                        {
                            Url       = facebookUser.Picture,
                            DateAdded = DateTime.Now
                        };
                        user.Photos.Add(photo);

                        if (await _context.SaveChangesAsync() <= 0)
                        {
                            throw new AppException("Registered with Facebook successfully, but failed to add photo");
                        }
                    }
                }
            }

            var refreshToken = GenerateRefreshToken(ipAddress, deviceDetector);

            user.RefreshTokens.Add(refreshToken);

            _context.Update(user);

            await _context.SaveChangesAsync();

            var jwtToken = GenerateJwtToken(user);

            var response = _mapper.Map <LoginResponse>(user);

            response.JwtToken     = jwtToken;
            response.RefreshToken = refreshToken.Token;

            return(response);
        }
        /// <summary>
        /// Refresh device.
        /// </summary>
        void RefreshDevice(DirectInput manager, UserDevice ud, DeviceInstance device, DeviceInfo[] allDevices, DeviceInfo[] allInterfaces, out DeviceInfo hid)
        {
            hid = null;
            if (Program.IsClosing)
            {
                return;
            }
            // If device added then...
            if (ud.Device == null)
            {
                try
                {
                    // Lock to avoid Exception: Collection was modified; enumeration operation may not execute.
                    lock (SettingsManager.UserDevices.SyncRoot)
                    {
                        // Getting state can fail.
                        var joystick = new Joystick(manager, device.InstanceGuid);
                        ud.Device          = joystick;
                        ud.IsExclusiveMode = null;
                        ud.LoadCapabilities(joystick.Capabilities);
                    }
                }
                catch (Exception) { }
            }
            // Lock to avoid Exception: Collection was modified; enumeration operation may not execute.
            lock (SettingsManager.UserDevices.SyncRoot)
            {
                ud.LoadInstance(device);
            }
            // If device is set as offline then make it online.
            if (!ud.IsOnline)
            {
                lock (SettingsManager.UserDevices.SyncRoot)
                    ud.IsOnline = true;
            }
            // Get device info for added devices.
            var dev = allDevices.FirstOrDefault(x => x.DeviceId == ud.HidDeviceId);

            // Lock to avoid Exception: Collection was modified; enumeration operation may not execute.
            lock (SettingsManager.UserDevices.SyncRoot)
            {
                ud.LoadDevDeviceInfo(dev);
                if (dev != null)
                {
                    ud.ConnectionClass = DeviceDetector.GetConnectionDevice(dev, allDevices)?.ClassGuid ?? Guid.Empty;
                }
            }
            // InterfacePath is available for HID devices.
            if (device.IsHumanInterfaceDevice && ud.Device != null)
            {
                var interfacePath = ud.Device.Properties.InterfacePath;
                // Get interface info for added devices.
                hid = allInterfaces.FirstOrDefault(x => x.DevicePath == interfacePath);
                // Lock to avoid Exception: Collection was modified; enumeration operation may not execute.
                lock (SettingsManager.UserDevices.SyncRoot)
                {
                    ud.LoadHidDeviceInfo(hid);
                    if (hid != null)
                    {
                        ud.ConnectionClass = DeviceDetector.GetConnectionDevice(hid, allDevices)?.ClassGuid ?? Guid.Empty;
                    }
                    // Workaround:
                    // Override Device values and description from the Interface,
                    // because it is more accurate and present.
                    // Note 1: Device fields below, probably, should not be used.
                    // Note 2: Available when device is online.
                    ud.DevManufacturer = ud.HidManufacturer;
                    ud.DevDescription  = ud.HidDescription;
                    ud.DevVendorId     = ud.HidVendorId;
                    ud.DevProductId    = ud.HidProductId;
                    ud.DevRevision     = ud.HidRevision;
                }
            }
        }
        // Login with google
        public async Task <LoginResponse> GoogleLogin(GoogleLoginRequest model, string ipAddress, DeviceDetector deviceDetector, string origin)
        {
            try
            {
                var payload = await ValidateAsync(model.GoogleToken, new ValidationSettings
                {
                    Audience = new[] { "95578192260-amn3dtj5avlfmk9su13ujrkqsnhr4btm.apps.googleusercontent.com" },
                    ExpirationTimeClockTolerance = new TimeSpan(0)
                });
            }
            catch
            {
                throw new AppException("Invalid token");
            }

            return(null);

            //var facebookUser = await _facebookService.GetUser(model, origin);

            //var user = await _context.Users.Include(u => u.Photos).SingleOrDefaultAsync(u => u.FacebookUID == facebookUser.FacebookUID);

            //// Create new user in db to store needed info
            //if (user == null)
            //{
            //    var userToCreate = _mapper.Map<User>(facebookUser);
            //    userToCreate.Created = DateTime.Now;
            //    userToCreate.Role = Role.User;
            //    userToCreate.Status = Status.Active;
            //    userToCreate.Verified = DateTime.Now;

            //    _context.Users.Add(userToCreate);

            //    // Add photo url after saving to db to have user id
            //    if (await _context.SaveChangesAsync() > 0)
            //    {
            //        var createdUser = await _context.Users.Include(u => u.Photos).SingleOrDefaultAsync(u => u.FacebookUID == facebookUser.FacebookUID);

            //        var photo = new Photo
            //        {
            //            Url = facebookUser.Picture,
            //            DateAdded = DateTime.Now,
            //            IsMain = true
            //        };

            //        createdUser.Photos.Add(photo);

            //        await _context.SaveChangesAsync();
            //    }

            //    user = await _context.Users.Include(u => u.Photos).SingleOrDefaultAsync(x => x.FacebookUID == facebookUser.FacebookUID);
            //}

            //var refreshToken = GenerateRefreshToken(ipAddress, deviceDetector);

            //var jwtToken = GenerateJwtToken(user);

            //var response = _mapper.Map<LoginResponse>(user);
            //response.JwtToken = jwtToken;
            //response.RefreshToken = refreshToken.Token;

            //return response;
        }
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (EXCLUDED_PAGES.Contains(context.Request.Path))
            {
                await next(context);

                return;
            }

            AuthenticatedUserExpanded?user;

            try
            {
                if (context.User?.Identity?.IsAuthenticated != true)
                {
                    user = _userService.ClaimsPrincipalToAuthenticatedUser(await SignInAnonymousUser(context));
                }
                else
                {
                    user = _userService.ClaimsPrincipalToAuthenticatedUser(context.User);
                }
                if (user is null)
                {
                    _logger.Warning("Failed to log in neither a proper user nor the anonymous idendity.");
                    await next(context);

                    return;
                }
            }
            catch (Exception ex)
            {
                _logger.Warning(ex, "Failed to parse claims");
                await next(context);

                return;
            }

            var(isAllowed, dbUser) = await GetDbUserOrAnonymousIfNotAllowed(user);

            if (!isAllowed)
            {
                await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                user = _userService.ClaimsPrincipalToAuthenticatedUser(await SignInAnonymousUser(context));
            }

            var permissionsTask = _userService.GetPermissions(user !.UserId);
            var tppTask         = GetTopicPostsPage(user.UserId);
            var foesTask        = _userService.GetFoes(user.UserId);
            await Task.WhenAll(permissionsTask, tppTask, foesTask);

            if (dbUser is null)
            {
                var anonymousClaimsPrincipal = await SignInAnonymousUser(context);

                user = _userService.ClaimsPrincipalToAuthenticatedUser(anonymousClaimsPrincipal);
            }

            var sessionTrackingTimeout = _config.GetValue <TimeSpan?>("UserActivityTrackingInterval") ?? TimeSpan.FromHours(1);

            if (dbUser is not null && !user !.IsAnonymous && (
                    await _cache.GetAsync <bool?>($"ReloadUser_{user.UsernameClean}") == true ||
                    DateTime.UtcNow.Subtract(dbUser.UserLastvisit.ToUtcTime()) > sessionTrackingTimeout))
            {
                var claimsPrincipal = await _userService.DbUserToClaimsPrincipal(dbUser);

                await Task.WhenAll(
                    SignIn(context, claimsPrincipal),
                    _context.GetDbConnection().ExecuteAsync(
                        "UPDATE phpbb_users SET user_lastvisit = @now WHERE user_id = @userId",
                        new { now = DateTime.UtcNow.ToUnixTimestamp(), user.UserId }
                        )
                    );

                user = _userService.ClaimsPrincipalToAuthenticatedUser(claimsPrincipal);
            }

            user !.AllPermissions  = await permissionsTask;
            user.TopicPostsPerPage = await tppTask;
            user.Foes = await foesTask;

            context.Items[nameof(AuthenticatedUserExpanded)] = user;

            if (user.IsAnonymous && context.Request.Headers.TryGetValue(HeaderNames.UserAgent, out var header) && (context.Session.GetInt32("SessionCounted") ?? 0) == 0)
            {
                try
                {
                    var userAgent = header.ToString();
                    var dd        = new DeviceDetector(userAgent);
                    dd.Parse();
                    var IsBot = dd.IsBot();
                    if (IsBot)
                    {
                        if (context.Connection.RemoteIpAddress is not null)
                        {
                            _sessionCounter.UpsertBot(context.Connection.RemoteIpAddress.ToString(), userAgent, sessionTrackingTimeout);
                        }
                    }
                    else
                    {
                        context.Session.SetInt32("SessionCounted", 1);
                        _sessionCounter.UpsertSession(context.Session.Id, sessionTrackingTimeout);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Warning(ex, "Failed to detect anonymous session type.");
                }
            }

            await next(context);
        }
        // Use refresh token to get a new jwt token (auto login)
        public async Task <LoginResponse> RefreshToken(string token, string ipAddress, DeviceDetector dd)
        {
            var newRefreshToken = GenerateRefreshToken(ipAddress, dd);

            var(refreshToken, user) = await GetRefreshToken(token);

            refreshToken.Token       = newRefreshToken.Token;
            refreshToken.Expires     = newRefreshToken.Expires;
            refreshToken.Created     = newRefreshToken.Created;
            refreshToken.CreatedByIp = newRefreshToken.CreatedByIp;
            refreshToken.Device      = newRefreshToken.Device;
            refreshToken.Application = newRefreshToken.Application;
            refreshToken.LastActive  = newRefreshToken.LastActive;

            _context.Update(user);

            await _context.SaveChangesAsync();

            var jwtToken = GenerateJwtToken(user);

            var response = _mapper.Map <LoginResponse>(user);

            response.JwtToken     = jwtToken;
            response.RefreshToken = newRefreshToken.Token;

            //var response = new LoginResponse
            //{
            //    JwtToken = jwtToken,
            //    RefreshToken = newRefreshToken.Token
            //};

            return(response);
        }