예제 #1
0
        /// <summary>
        /// User Agent 를 변경합니다.
        /// </summary>
        /// <param name="userAgent"></param>
        /// <returns></returns>
        public static bool ChangeUserAgent(string userAgent, ref string errMessage)
        {
            UserAgentInfo agent = SplitByUserAgent(userAgent);

            bool result = true;

            try
            {
                RegistryKey userAgentkey = Registry.LocalMachine.CreateSubKey(regKeyRoot);
                userAgentkey.SetValue("", agent.Agent);
                userAgentkey.SetValue("Compatible", agent.Compatible);
                userAgentkey.SetValue("Version", agent.Version);
                userAgentkey.SetValue("Platform", agent.Platform);
                try
                {
                    userAgentkey.DeleteSubKeyTree("Post Platform");
                }
                catch { }
            }
            catch (Exception ex)
            {
                WriteTextLog("ChangeUserAgent", ex.Message.ToString());
                errMessage = ex.Message.ToString();
                return(false);
            }

            return(result);
        }
예제 #2
0
        /// <summary>
        /// userAgent 를 변경하기 위하여 문자열을 변경합니다.
        /// </summary>
        /// <param name="userAgent"></param>
        /// <returns></returns>
        private static UserAgentInfo SplitByUserAgent(string userAgent)
        {
            UserAgentInfo agent = new UserAgentInfo();

            string[] arrUserAgent = userAgent.Split(';');

            if (arrUserAgent.Length > 0)
            {
                for (int i = 0; i < arrUserAgent.Length; i++)
                {
                    if (i == 0)
                    {
                        string[] arrHeader = arrUserAgent[0].Split('(');
                        agent.Agent      = arrHeader[0].Trim();
                        agent.Compatible = arrHeader[1].Trim();
                    }
                    else
                    {
                        if (i == 1)
                        {
                            agent.Version = arrUserAgent[i].ToString();
                        }
                        else
                        {
                            agent.Platform += "; " + arrUserAgent[i].ToString();
                        }
                    }
                }

                agent.Platform = agent.Platform.Substring(1).Trim() + " //";
            }

            return(agent);
        }
        public JsonResult UserAgent()
        {
            var userAgent = new UserAgentInfo();

            userAgent.UseUserAgent(Request.Headers["User-Agent"]);

            return(new JsonResult(userAgent));
        }
예제 #4
0
        public ContentResult UA()
        {
            UserAgentInfo ua = new UserAgentInfo(this.HttpContext);

            // string uaa = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko";
            // UserAgentInfo ua = new UserAgentInfo(uaa);

            return(Content(ua.Family, "text/plain"));
        }
        public static IList <object> CreatePersonalizerContext(this Controller controller, UserContext context, HttpRequest request)
        {
            var result = new List <object>
            {
                new { context.Device, context.TripType, context.TravelerHistory }
            };

            if (request != null)
            {
                var userAgent = new UserAgentInfo();
                userAgent.UseUserAgent(request.Headers["User-Agent"]);
                result.Add(userAgent);
            }

            return(result);
        }
예제 #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors(Constants.CORS_POLICY);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, Constants.STATIC_FILES_FOLDER_Name)),
            });
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/openapi.json", "Cloud SDK Api");
                c.InjectJavascript("/Swg/func.js");
                c.InjectJavascript("/Swg/toast/toastify.js");
                c.InjectStylesheet("/Swg/toast/toastify.css");
            });
            app.UseRouting();
            app.UseAuthorization();
            app.Use((context, next) =>
            {
                ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
                {
                    builder.AddConsole();
                });
                ILogger logger = loggerFactory.CreateLogger <Startup>();
                UserAgentInfo userAgentInfo = new UserAgentInfo(context.Request.Headers[Constants.UserAgent.USER_AGENT]);
                logger.LogInformation($"UserAgent:: [{userAgentInfo?.ClientInfo?.String}]");
                ICloudSdkConfiguration versionConfig = app.ApplicationServices.GetService <ICloudSdkConfiguration>();
                context.Response.Headers[Constants.Header.ACCESS_CONTROL_EXPOSE_HEADERS] = Constants.STAR;
                context.Response.Headers[Constants.Header.ACCESS_CONTROL_ALLOW_HEADERS]  = Constants.STAR;
                context.Response.Headers[Constants.Header.ACCESS_CONTROL_ALLOW_ORIGIN]   = Constants.STAR;
                context.Response.Headers[Constants.Header.VIA] = Environment.MachineName;
                context.Response.Headers[Constants.Header.SDK_ENGINE_VERSION] = versionConfig.SDKEngineVersion;
                context.Response.Headers[Constants.Header.SDK_API_VERSION]    = versionConfig.SDKApiVersion;
                return(next.Invoke());
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        private IList <object> CreateContext(UserContext context, HttpRequest request)
        {
            var result = new List <object>()
            {
                new { context.TimeOfDay, context.WeekDay },
                new { context.Weather }
            };

            if (request != null)
            {
                var userAgent = new UserAgentInfo();
                userAgent.UseUserAgent(request.Headers["User-Agent"]);
                result.Add(userAgent);
            }

            return(result);
        }
    /// <summary>
    /// Adds user agent to contact. Called when the "Add user agent to contact" button is pressed.
    /// Expects the CreateContact method to be run first.
    /// </summary>
    private bool AddUserAgent()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        InfoDataSet<ContactInfo> contacts = ContactInfoProvider.GetContacts(where, null, 1, null);

        if (!DataHelper.DataSourceIsEmpty(contacts))
        {
            // Get the contact from dataset
            ContactInfo contact = contacts.First<ContactInfo>();

            // Create new agent info
            UserAgentInfo agentInfo = new UserAgentInfo()
                                          {
                                              UserAgentActiveContactID = contact.ContactID,
                                              UserAgentOriginalContactID = contact.ContactID,
                                              UserAgentString = "My User Agent"
                                          };

            // Save the agent info
            UserAgentInfoProvider.SetUserAgentInfo(agentInfo);

            return true;
        }

        return false;
    }
예제 #9
0
        public async Task <object> GetUpdates([FromRoute(Name = "branch")] string updateBranch,
                                              [FromQuery(Name = "version")] string urlVersion,
                                              [FromQuery(Name = "os")] OperatingSystem operatingSystem,
                                              [FromQuery(Name = "runtime")] Runtime runtime,
                                              [FromQuery(Name = "runtimeVer")] string urlRuntimeVersion,
                                              [FromQuery(Name = "arch")] Architecture arch,
                                              [FromQuery(Name = "active")] bool activeInstall = true)
        {
            Response.Headers[HeaderNames.CacheControl] = GetCacheControlHeader(DateTime.UtcNow);

            // Check given version
            if (!Version.TryParse(urlVersion, out var version))
            {
                return(new
                {
                    ErrorMessage = "Invalid version number specified."
                });
            }

            var userAgentInfo = new UserAgentInfo(Request.Headers["User-Agent"].ToString());

            // Dont' send metrics for dev/debug instances
            if (version.Major < 10)
            {
                var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;

                Metrics.Write("userstats",
                              new Dictionary <string, object>
                {
                    { "source", remoteIpAddress }
                },
                              new Dictionary <string, string>
                {
                    { "program", _project },
                    { "requestApp", userAgentInfo.App ?? "Unknown" },
                    { "branch", updateBranch },
                    { "version", urlVersion },
                    { "os", operatingSystem.ToString() },
                    { "osName", userAgentInfo.Name ?? "Unknown" },
                    { "osVersion", userAgentInfo.OsVersion ?? "Unknown" },
                    { "runtime", runtime.ToString() },
                    { "runtimeVersion", urlRuntimeVersion },
                    { "arch", arch.ToString() },
                    { "activeinstall", activeInstall.ToString() }
                });
            }

            var files = await _updateFileService.Find(updateBranch, operatingSystem, runtime, arch, false, 1, urlVersion, urlRuntimeVersion);

            var updateFile = files.FirstOrDefault();

            if (updateFile == null)
            {
                return(new UpdatePackageContainer
                {
                    Available = false
                });
            }

            var update = updateFile.Update.Value;

            // Compare given version and update version
            var updateVersion = new Version(update.Version);

            if (updateVersion.CompareTo(version) <= 0)
            {
                return(new UpdatePackageContainer
                {
                    Available = false
                });
            }

            // Get the update changes
            UpdateChanges updateChanges = null;

            if (update.New.Count != 0 || update.Fixed.Count != 0)
            {
                updateChanges = new UpdateChanges
                {
                    New   = update.New,
                    Fixed = update.Fixed
                };
            }

            return(new UpdatePackageContainer
            {
                Available = true,
                UpdatePackage = new UpdatePackage
                {
                    Version = update.Version,
                    ReleaseDate = update.ReleaseDate,
                    Filename = updateFile.Filename,
                    Url = updateFile.Url,
                    Changes = updateChanges,
                    Hash = updateFile.Hash,
                    Branch = update.Branch.ToString().ToLower(),
                    Runtime = updateFile.Runtime.ToString().ToLower()
                }
            });
        }
예제 #10
0
        public async Task <IActionResult> GetSliderHtml([FromForm] string galleryTitle, [FromForm] string limits, [FromForm] string ratio)
        {
            _Logger.LogDebug("User1: " + HttpContext.User?.Identity?.Name
                             + Environment.NewLine + "User2: " + User.Identity.Name
                             );


            PublicLimits              limitsParsed = PublicLimits.Parse(limits);
            List <PublicModel>        meta         = _ContentManager.GetMetadata();
            IEnumerable <PublicModel> byLimits     = meta.Where(x => x.LimitValue == limitsParsed.LimitValue && x.Kind == limitsParsed.Kind);
            IEnumerable <PublicTopic> byTitle      = byLimits.SelectMany(x => x.Topics).Where(x => x.Title == galleryTitle);
            PublicTopic foundGallery = byTitle.FirstOrDefault();

            if (foundGallery == null)
            {
                throw new ArgumentException($"Gallery [{galleryTitle}] with specified limits ({limitsParsed}) not found");
            }

            decimal ratioParsed;

            if (!decimal.TryParse(ratio, out ratioParsed))
            {
                ratioParsed = 0;
            }

            if (ratioParsed < 1)
            {
                ratioParsed = 1;
            }


            // Shuffle gallery based on remote ip
            var galleryCopy = new PublicTopic()
            {
                Title = foundGallery.Title,
                Blobs = new List <PublicBlob>(foundGallery.Blobs)
            };
            var idUser = User?.Identity?.Name;

            if (string.IsNullOrEmpty(idUser))
            {
                idUser = HttpContext.Connection.RemoteIpAddress.ToString();
            }
            var seedByIp = HashExtentions.GetSHA1AsSeed(idUser);

            galleryCopy.Blobs.Shuffle(seedByIp);

            var userAgent = HttpContext.Request.Headers["User-Agent"];
            var uaInfo    = new UserAgentInfo(userAgent);

            var userPhotosByTopic = await _PhotosRepository.GetUserPhotosByTopic(galleryCopy.Title, idUser);

            var photoTotals = await _PhotosRepository.GetPhotoTotalsByTopic(galleryCopy.Title);

            List <JsPhotoModel> jsPhotos =
                galleryCopy.Blobs.Select(x => new JsPhotoModel()
            {
                Id     = x.IdContent,
                Url    = x.Id,
                Height = x.Height,
                Width  = x.Width
            }).ToList();

            foreach (var jsPhoto in jsPhotos)
            {
                userPhotosByTopic.TryGetValue(jsPhoto.Id, out var myFlags);
                photoTotals.TryGetValue(jsPhoto.Id, out var totals);
                if (myFlags != null)
                {
                    jsPhoto.MyDislikes = myFlags.Dislikes;
                    jsPhoto.MyLikes    = myFlags.Likes;
                    jsPhoto.MyShares   = myFlags.Shares;
                    jsPhoto.MyStars    = myFlags.Stars;
                }

                if (totals != null)
                {
                    jsPhoto.TotalDislikes = totals.Dislikes;
                    jsPhoto.TotalLikes    = totals.Likes;
                    jsPhoto.TotalShares   = totals.Shares;
                    jsPhoto.TotalStars    = totals.Stars;
                }
            }

            var angularModel = new
            {
                Gallery  = galleryCopy.Title,
                Ratio    = ratioParsed,
                Limits   = limitsParsed,
                IsMobile = uaInfo.IsMobile,
                Photos   = jsPhotos,
            };

            return(PartialView("GalleryPartial", new PartialGalleryModel()
            {
                Limits = limitsParsed,
                Topic = galleryCopy,
                Ratio = ratioParsed,
                IsMobile = uaInfo.IsMobile,
                AngularModel = angularModel.ToNewtonJSon(TheAppContext.IsDebug)
            }));
        }
예제 #11
0
        public async Task <IActionResult> GetSmartSliderHtml([FromForm] string galleryTitle, [FromForm] string windowHeight, [FromForm] string devicePixelRatio)
        {
            var enUs = new CultureInfo("en-US");

            decimal argHeight = 0;

            decimal.TryParse(windowHeight, NumberStyles.AllowDecimalPoint, enUs, out argHeight);

            decimal argRatio = 0;

            decimal.TryParse(devicePixelRatio, NumberStyles.AllowDecimalPoint, enUs, out argRatio);


            PublicLimits targetLimit = null;
            decimal      targetRatio = 1;

            targetLimit = new PublicLimits(LimitKind.Height, 512);
            targetRatio = 1.0m;

            var userAgent = HttpContext.Request.Headers["User-Agent"];
            var uaInfo    = new UserAgentInfo(userAgent);

            var reveredLimits = new List <PublicLimits>(TheAppContext.Limits);

            reveredLimits.Reverse();

            _Logger.LogInformation("Sorted Limits: " + string.Join(" ", reveredLimits));

            targetRatio = argRatio;
            var          pixels      = argHeight * argRatio;
            PublicLimits foundLimits = reveredLimits.FirstOrDefault(x => x.Kind == LimitKind.Height && x.LimitValue <= pixels);
            var          found0      = foundLimits;

            if (foundLimits == null)
            {
                if (!uaInfo.IsMobile)
                {
                    foundLimits = new PublicLimits(LimitKind.Height, 672);
                }
                else
                {
                    foundLimits = new PublicLimits(LimitKind.Height, 288);
                }
            }

            _Logger.LogInformation(string.Format(
                                       @"         Agent: {0}{1}Family+Version: {2}{1}   Height(arg): {3}{1}    Ratio(arg): {4}{1}        found0: {5}{1}      SELECTED: {6} / {7}{1}     Remote IP: {8}",
                                       userAgent,
                                       Environment.NewLine,
                                       uaInfo + ", " + (uaInfo.IsMobile ? "Mobile" : "PC"),
                                       argHeight,
                                       argRatio,
                                       found0 + " / " + targetRatio,
                                       foundLimits, targetRatio,
                                       HttpContext.Connection.RemoteIpAddress
                                       ));

            return(await GetSliderHtml(
                       galleryTitle,
                       foundLimits.Serialize(),
                       targetRatio.ToString("f3", enUs)
                       ));
        }
 public void Init()
 {
     instance = new UserAgentInfo();
 }