static void SimulateRandomUserPreferences() { for (int i = 0; i < 1000; i++) { Random random = new Random(DateTime.Now.Millisecond); IList <RankableAction> actions = GetActions(); PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint); IList <object> currentContext = new List <object>() { new { professiom = random.Next(1, 5) }, new { preference = random.Next(1, 3) } }; IList <string> excludeActions = new List <string> { "http://codestories.gr/index.php/2018/10/21/297/" }; // Generate an ID to associate with the request. string eventId = Guid.NewGuid().ToString(); var request = new RankRequest(actions, currentContext, excludeActions, eventId); RankResponse response = client.Rank(request); client.Reward(response.EventId, new RewardRequest(random.Next(0, 2))); } }
public float SimulateEvent() { IList <RankableAction> actions = GetActions(); int userId = 1; UserSimulator sim = new UserSimulator(userId, rand); var currentContext = GetSimulatedContext(userId); string eventId = Guid.NewGuid().ToString(); var request = new RankRequest(actions, currentContext, null, eventId); RankResponse response = client.Rank(request); //RankResponse response = new RankResponse(); float reward = 0f; string simulationResponse = sim.ReturnSimulatedAction(currentContext); Console.WriteLine("For Context {2}: Personalizer suggested {0}, simulation chose {1}", response.RewardActionId, simulationResponse, sim.GetKey((FoodContext)currentContext[0])); if (response.RewardActionId == simulationResponse) { reward = 1f; } // Send the reward for the action based on user response. client.Reward(response.EventId, new RewardRequest(reward)); return(reward); }
private Tuple <string, string> callPersonalizationService(HttpRequestFeatures httpRequestFeatures) { // Generate an ID to associate with the request. string eventId = Guid.NewGuid().ToString(); // Get the actions list to choose from personalization with their features. IList <RankableAction> actions = GetActions(); // Get context information from the user. string timeOfDayFeature = GetUsersTimeOfDay(); string tasteFeature = GetUsersTastePreference(); // Create current context from user specified data. IList <object> currentContext = new List <object>() { new { time = timeOfDayFeature }, new { taste = tasteFeature }, new { httpRequestFeatures } }; // Exclude an action for personalization ranking. This action will be held at its current position. IList <string> excludeActions = new List <string> { "juice" }; // Rank the actions var request = new RankRequest(actions, currentContext, excludeActions, eventId); RankResponse response = client.Rank(request); string rankjson = JsonConvert.SerializeObject(request, Formatting.Indented); string rewardjson = JsonConvert.SerializeObject(response, Formatting.Indented); return(Tuple.Create(rankjson, rewardjson)); }
public async Task <IActionResult> Index() { var actions = GetActions(); var timeOfDayFeature = GetTimeOfDay(); var userOsFeature = GetUserOs(Request.Headers["User-Agent"]); var currentContext = new List <object> { new { time = timeOfDayFeature }, new { userOs = userOsFeature } }; var request = new RankRequest(actions, currentContext); var response = await _personalizerClient.RankAsync(request); return(View(new PersonalizerModel { PersonalizerEventId = response.EventId, PersonalizerEventStartTime = DateTime.UtcNow, Action = response.RewardActionId, TimeOfDay = timeOfDayFeature, UserOs = userOsFeature, Ranking = response.Ranking })); }
public void Handle(RankRequest message) { byte[] omsg = { 0x1a, 0x01 }; FLMsgType.AddUInt32(ref omsg, _charAccount.Rank); FLMsgType.AddUInt32(ref omsg, 0xffffffff); //dunno Context.Sender.Tell(omsg); }
public async Task RankNullParameters() { using (MockContext.Start(this.GetType())) { HttpMockServer.Initialize(this.GetType(), "RankNullParameters"); IPersonalizerClient client = GetClient(HttpMockServer.CreateInstance()); IList <RankableAction> actions = new List <RankableAction>(); actions.Add(new RankableAction { Id = "Person", Features = new List <object>() { new { videoType = "documentary", videoLength = 35, director = "CarlSagan" }, new { mostWatchedByAge = "30-35" } } }); var request = new RankRequest(actions); // Action RankResponse response = await client.RankAsync(request); // Assert Assert.Equal(actions.Count, response.Ranking.Count); for (int i = 0; i < response.Ranking.Count; i++) { Assert.Equal(actions[i].Id, response.Ranking[i].Id); } } }
/// <summary> /// A Personalizer rank request. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='rankRequest'> /// A Personalizer request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <RankResponse> RankAsync(this IEvents operations, RankRequest rankRequest, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RankWithHttpMessagesAsync(rankRequest, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public RankResponse GetRecommendations(IList <object> context, bool useTextAnalytics = false) { var eventId = Guid.NewGuid().ToString(); var actions = _actionsRepository.GetActions(useTextAnalytics); var request = new RankRequest(actions, context, null, eventId); RankResponse response = _personalizerClient.Rank(request); return(response); }
public RankResult Friend([FromBody] RankRequest rankRequest) { RankResult result = new RankResult(); List <RankUser> list = rankDao.FriendRank(rankRequest.FriendList); result.Data = list; return(result); }
//当前基金排行 post https://www.doctorxiong.club/api/v1/fund/rank async Task <String> growthRankAsync(String sortby) { String tradeDate = lastTradeDateWithData(); int rankStrategyId = 1; String rankSource = "doctorxiong"; var cachedContent = await _dbService.QueryRankRawCacheAsync(tradeDate, rankStrategyId, rankSource); if (cachedContent != null) { Console.WriteLine($"got date from cache: tradeDate:{tradeDate} from:{rankSource} with StrategyId:{rankStrategyId}"); return(cachedContent.RankRawContent); } //https://stackoverflow.com/questions/4015324/how-to-make-an-http-post-web-request RankRequest request = new RankRequest { sortBy = sortby }; String postContentStr = JsonSerializer.Serialize(request); var postContent = new StringContent(postContentStr, Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://api.doctorxiong.club/v1/fund/rank", postContent); var content = await response.Content.ReadAsStringAsync(); //TODO 增加返回数据的验证的方法 bool isValidContent = true; if (!isValidContent) { Console.WriteLine($"got invalid content when query with tradeDate:{tradeDate} from:{rankSource} with StrategyId:{rankStrategyId}, content:{content}"); return(null); } //重要设计点: 有可能其他线程/进程在查询期间把数据添加进去了,这时候我应该可以继续运行业务逻辑而不进行更新了 //Answer:很简单,这里的添加是允许失败的(不管是因为uniq失败,还是网络问题)。 //- bad design:只要增加一个函数叫TryAddRankRawCacheAsync就行了,失败就打印一个Warning(并明确说一般不是问题,可以检查uniq之类的) //- better design: 只要忽略task的执行错误就行了,不过要记录执行失败情况,作为后续可能的trouble shooting材料 //- 另外:另一个解决思路:MySql数据库有个insertORupdate特性,发现uniq问题之后变为update语句。不过对于本应用的当前这个cache插入来说,SqlServer有没有这个feature都无伤大雅。上面的解决思路就足够了。 //add to cache in case we use it later Console.WriteLine($"add date to cache: tradeDate:{tradeDate} from:{rankSource} with StrategyId:{rankStrategyId}"); Task taskAddRecord = _dbService.AddRankRawCacheAsync(tradeDate, rankStrategyId, rankSource, content); //我们只关心失败情况,成功的就让他过去吧 //tech:这里也没有使用await,因为也不想获取结果了,没有必要通过await做什么线程切换了 _ = taskAddRecord.ContinueWith(task => { return("bad, fault with :" + taskAddRecord.Exception.InnerException); }, TaskContinuationOptions.OnlyOnFaulted); return(content); }
public JsonResult Recommendation([FromBody] UserContext context) { var currentContext = CreateContext(context, context.UseUserAgent ? Request : null); var eventId = Guid.NewGuid().ToString(); var actions = _actionsRepository.GetActions(context.UseTextAnalytics); var request = new RankRequest(actions, currentContext, null, eventId); RankResponse response = _client.Rank(request); return(new JsonResult(response)); }
public RankResponse Rank(RankRequest request) { return(PolicyService.ExecuteRetryAndCapture400Errors( "PersonalizerService.Rank", ApiKeys.PersonalizerRetryInSeconds, () => { var result = Repository.Rank(request); return result; }, null)); }
public async Task RankServerFeatures() { using (MockContext.Start(this.GetType().FullName)) { HttpMockServer.Initialize(this.GetType().FullName, "RankServerFeatures"); IPersonalizerClient client = GetClient(HttpMockServer.CreateInstance()); IList <object> contextFeatures = new List <object>() { new { Features = new { day = "tuesday", time = "night", weather = "rainy" } }, new { Features = new { userId = "1234", payingUser = true, favoriteGenre = "documentary", hoursOnSite = 0.12, lastwatchedType = "movie" } } }; IList <RankableAction> actions = new List <RankableAction>(); actions.Add(new RankableAction { Id = "Person1", Features = new List <object>() { new { videoType = "documentary", videoLength = 35, director = "CarlSagan" }, new { mostWatchedByAge = "30-35" } } }); actions.Add(new RankableAction { Id = "Person2", Features = new List <object>() { new { videoType = "documentary", videoLength = 35, director = "CarlSagan" }, new { mostWatchedByAge = "40-45" } } }); IList <string> excludeActions = new List <string> { "Person1" }; string eventId = "123456789"; var request = new RankRequest(actions, contextFeatures, excludeActions, eventId); // Action RankResponse response = await client.RankAsync(request); // Assert Assert.Equal(eventId, response.EventId); Assert.Equal(actions.Count, response.Ranking.Count); for (int i = 0; i < response.Ranking.Count; i++) { Assert.Equal(actions[i].Id, response.Ranking[i].Id); } } }
public static void b(ulong userId, string requestedTeamId, string ostInfo, bool initialRequest, string signed, Action <bool> rankRequestedCallback = null) #endif { //Build score object RankRequest s = new RankRequest(userId.ToString(), requestedTeamId, ostInfo, initialRequest, signed); JSONObject o = new JSONObject(); o.Add("pb", new JSONString(s.ToBase64())); SharedCoroutineStarter.instance.StartCoroutine(PostCoroutine(o.ToString(), $"{discordCommunityApi}/requestrank/", rankRequestedCallback)); }
public RankResult Friend([FromBody] RankRequest rankRequest) { RankResult result = new RankResult(); List <RankUser> list = rankDao.FriendRank(rankRequest.UserID, rankRequest.FriendList); result.Data = list; result.ResultCode = 1; result.Message = "Success"; return(result); }
public void testSerialization() { //{"fundType":[],"sort":"lastWeekGrowth","fundCompany":[],"createTimeLimit":0,"fundScale":0,"asc":0,"pageIndex":1,"pageSize":10} RankRequest request = new RankRequest { sortBy = "lastWeekGrowth" }; var jsonString = JsonSerializer.Serialize(request); var expectedString = "{\"fundType\":null,\"sort\":\"lastWeekGrowth\",\"fundCompany\":null,\"createTimeLimit\":0,\"fundScale\":0,\"asc\":0,\"pageIndex\":1,\"pageSize\":10}"; Assert.AreEqual(expectedString, jsonString); }
public IActionResult PostRank([FromBody] RankCategories rankCategories) { RankRequest request = CreateRankRequest(rankCategories); RankResponse response; try { response = personalizerClient?.Rank(request); return(Ok(response)); } catch (Exception e) { return(BadRequest(e.Message)); } }
public void Train(TrainingCase[] cases) { if (cases != null) { foreach (TrainingCase testCase in cases) { Console.WriteLine($"{testCase.Name}:"); string lessonId = Guid.NewGuid().ToString(); var request = new RankRequest(Actions, testCase.Features, testCase.Exclude, lessonId, false); RankResponse response = Client.Rank(request); double reward = 0.0; if (response.RewardActionId.Equals(testCase.Expected)) { reward = 1.0; } Client.Reward(response.EventId, new RewardRequest(reward)); } } }
public void RankTest() { var request = new RankRequest { contextFeatures = new List <object> { new { time = "Morning" } }, actions = new List <RankableAction> { new RankableAction { id = "NewsArticle", features = new List <object> { new { type = "News" } } }, new RankableAction { id = "SportsArticle", features = new List <object> { new { type = "Sports" } } }, new RankableAction { id = "EntertainmentArticle", features = new List <object> { new { type = "Entertainment" } } } }, excludedActions = new List <string> { "SportsArticle" }, eventId = "75269AD0-BFEE-4598-8196-C57383D38E10", deferActivation = false }; var result = _sut.Rank(request); Assert.Greater(result.ranking.Count(), 0); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { try { string requestBody = String.Empty; using (StreamReader sReader = new StreamReader(req.Body)) { requestBody = await sReader.ReadToEndAsync(); } var recommendationRequest = JsonConvert.DeserializeObject <RecommendationRequest>(requestBody); var personalizerEndpoint = Environment.GetEnvironmentVariable("AzurePersonalizerEndpoint", EnvironmentVariableTarget.Process); var personalizerKey = Environment.GetEnvironmentVariable("AzurePersonalizerKey", EnvironmentVariableTarget.Process); if (!string.IsNullOrWhiteSpace(personalizerEndpoint) || !string.IsNullOrWhiteSpace(personalizerKey)) { var personalizerClient = new PersonalizerClient( new ApiKeyServiceClientCredentials(personalizerKey)) { Endpoint = personalizerEndpoint }; var actions = GetRankableActions(recommendationRequest.Catalogitems); var contextFeatures = GetContextFeatures(recommendationRequest.UserName); var excludeActions = new List <string>(); var request = new RankRequest(actions, contextFeatures, excludeActions, Guid.NewGuid().ToString()); var response = await personalizerClient.RankAsync(request); var recommendationReponse = new RecommendationResponse { eventId = response.EventId, PrefferedItemId = Convert.ToInt32(response.RewardActionId) }; return(new OkObjectResult(recommendationReponse)); } return(new BadRequestObjectResult("No endpoint or key configured")); } catch (Exception ex) { Console.WriteLine(ex); return(new BadRequestObjectResult(ex)); } }
public async Task <IActionResult> GetSearchMethodForRank(RankRequest request, string Name) { var result = new RankResponse(); var rank = await _context.Ranks.Take(request.Quantity).Where(c => c.Name.StartsWith(Name) || c.Name.Contains(Name) || c.Name.EndsWith(Name)).Select(p => new Ranks { RankId = p.Id, Name = p.Name }).ToListAsync(); if (rank.Count == 0) { result.Code = -100; result.Message = "Can't get products with given parameters."; return(Ok(result)); } result.Code = 100; result.Message = "Success"; result.Ranks = rank; return(Ok(result)); }
public async Task <IActionResult> GetRank(RankRequest request) { var result = new RankResponse(); var rank = await _context.Ranks.Skip(request.Skip).Take(request.Quantity).Select(p => new Ranks { RankId = p.Id, Name = p.Name }).ToListAsync(); if (rank.Count == 0) { result.Code = -100; result.Message = "Can't get products with given parameters."; return(Ok(result)); } result.Code = 100; result.Message = "Success"; result.Ranks = rank; return(Ok(result)); }
private static void RunTasteTest(PersonalizerService personalizer) { IList <RankableAction> actions = new List <RankableAction> { new RankableAction { Id = "pasta", Features = new List <object>() { new { taste = "salty", spiceLevel = "medium" }, new { nutritionLevel = 5, cuisine = "italian" } } }, new RankableAction { Id = "salad", Features = new List <object>() { new { taste = "salty", spiceLevel = "low" }, new { nutritionLevel = 8 } } } }; string id = Guid.NewGuid().ToString(); IList <object> currentContext = new List <object>() { new { time = "morning" }, new { taste = "salty" } }; IList <string> exclude = new List <string> { "pasta" }; var request = new RankRequest(actions, currentContext, exclude, id); RankResponse resp = personalizer.Client.Rank(request); Assert.AreEqual("salad", resp.RewardActionId); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "recommendation")] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); var client = InitializePersonalizerClient(); var currentContext = GetContextFeatures(req); var actions = await GetActions(); string eventId = Guid.NewGuid().ToString(); IList <string> excludeActions = new List <string>(); var request = new RankRequest(actions, currentContext, excludeActions, eventId); RankResponse response = client.Rank(request); var recommendationDetail = new RecommendationDetail(); recommendationDetail.EventId = response.EventId; recommendationDetail.RewardActionId = response.RewardActionId; return(new OkObjectResult(recommendationDetail)); }
public string getBestNewsArticleID() { // Create context to personalize for, from user data or contextual information IList <object> currentContext = new List <object>() { new { time = "EarlyEvening" }, new { weather = "Rainy" }, new { userFavoriteTopic = "SpaceExploration" }, new { userProfile = "PayingUser" } //Add your own features in your own schema }; // Provide a list of possible actions -articles- to choose from var actionsB = new RankableAction[] { new RankableAction("news_article_1", new List <object> { new { topic = "politics", breakingNews = true, controversy = false } }), new RankableAction("news_article_2", new List <object> { new { topic = "technology", breakingNews = false, publishedWithin = "week" } }) }; var request = new RankRequest(actions, currentContext, null, eventId); // Call Personalizer and get the action that should be shown RankResponse response = personalizer.Rank(request); //Use the result given by Personalizer return(response.RewardActionId); }
/// <summary> /// A Personalizer rank request. /// </summary> /// <param name='rankRequest'> /// A Personalizer request. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <RankResponse> > RankWithHttpMessagesAsync(RankRequest rankRequest, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.Endpoint == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint"); } if (rankRequest == null) { throw new ValidationException(ValidationRules.CannotBeNull, "rankRequest"); } if (rankRequest != null) { rankRequest.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("rankRequest", rankRequest); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Rank", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "rank"; _url = _url.Replace("{Endpoint}", Client.Endpoint); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (rankRequest != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(rankRequest, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <RankResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <RankResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// A Personalizer rank request. /// </summary> /// <param name='client'> /// The PersonalizerClient for this extension method. /// </param> /// <param name='rankRequest'> /// A Personalizer request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static Task <RankResponse> RankAsync(this IPersonalizerClient client, RankRequest rankRequest, CancellationToken cancellationToken = default(CancellationToken)) { return(client.Events.RankAsync(rankRequest, cancellationToken)); }
/// <summary> /// A Personalizer rank request. /// <param name='client'> /// The PersonalizerClient for this extension method. /// The operations group for this extension method. /// </param> /// <param name='rankRequest'> /// A Personalizer request. /// </param> public static RankResponse Rank(this IPersonalizerClient client, RankRequest rankRequest) { return(client.Events.Rank(rankRequest)); }
static void Main(string[] args) { int iteration = 1; bool runLoop = true; // Get the actions list to choose from personalizer with their features. IList <RankableAction> actions = GetActions(); // Initialize Personalizer client. PersonalizerClient client = InitializePersonalizerClient(ServiceEndpoint); do { Console.WriteLine("\nIteration: " + iteration++); // Get context information from the user. string timeOfDayFeature = GetUsersTimeOfDay(); string tasteFeature = GetUsersTastePreference(); // Create current context from user specified data. IList <object> currentContext = new List <object>() { new { time = timeOfDayFeature }, new { taste = tasteFeature } }; // Exclude an action for personalizer ranking. This action will be held at its current position. IList <string> excludeActions = new List <string> { "juice" }; // Generate an ID to associate with the request. string eventId = Guid.NewGuid().ToString(); // Rank the actions var request = new RankRequest(actions, currentContext, excludeActions, eventId); RankResponse response = client.Rank(request); Console.WriteLine("\nPersonalizer service thinks you would like to have: " + response.RewardActionId + ". Is this correct? (y/n)"); float reward = 0.0f; string answer = GetKey(); if (answer == "Y") { reward = 1; Console.WriteLine("\nGreat! Enjoy your food."); } else if (answer == "N") { reward = 0; Console.WriteLine("\nYou didn't like the recommended food choice."); } else { Console.WriteLine("\nEntered choice is invalid. Service assumes that you didn't like the recommended food choice."); } Console.WriteLine("\nPersonalizer service ranked the actions with the probabilities as below:"); foreach (var rankedResponse in response.Ranking) { Console.WriteLine(rankedResponse.Id + " " + rankedResponse.Probability); } // Send the reward for the action based on user response. client.Reward(response.EventId, new RewardRequest(reward)); Console.WriteLine("\nPress q to break, any other key to continue:"); runLoop = !(GetKey() == "Q"); } while (runLoop); }
public static void StartHttpServer() { var route_config = new List <Route>() { new Route { Name = "Score Receiver", UrlRegex = @"^/submit/$", Method = "POST", Callable = (HttpRequest request) => { try { //Get JSON object from request content JSONNode node = JSON.Parse(WebUtility.UrlDecode(request.Content)); //Get Score object from JSON Score s = Score.FromString(node["pb"]); if (RSA.SignScore(Convert.ToUInt64(s.UserId), s.SongHash, s.Difficulty, s.Characteristic, s.FullCombo, s.Score_, s.PlayerOptions, s.GameOptions) == s.Signed && Song.Exists(s.SongHash, (LevelDifficulty)s.Difficulty, s.Characteristic, true) && !new Song(s.SongHash, (LevelDifficulty)s.Difficulty, s.Characteristic).Old&& Player.Exists(s.UserId) && Player.IsRegistered(s.UserId)) { Logger.Info($"RECEIVED VALID SCORE: {s.Score_} FOR {new Player(s.UserId).DiscordName} {s.SongHash} {s.Difficulty} {s.Characteristic}"); } else { Logger.Error($"RECEIVED INVALID SCORE {s.Score_} FROM {new Player(s.UserId).DiscordName} FOR {s.UserId} {s.SongHash} {s.Difficulty} {s.Characteristic}"); return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } #if BEATKHANA PostToBeatKhana(s.UserId, s.SongHash, s.Score_.ToString(), new EventServer.BeatSaver.Song(s.SongHash).GetMaxScore(s.Characteristic, (LevelDifficulty)s.Difficulty).ToString()); #endif Database.Score oldScore = null; if (Database.Score.Exists(s.SongHash, s.UserId, (LevelDifficulty)s.Difficulty, s.Characteristic)) { oldScore = new Database.Score(s.SongHash, s.UserId, (LevelDifficulty)s.Difficulty, s.Characteristic); } if (oldScore == null ^ (oldScore != null && oldScore.GetScore() < s.Score_)) { Player player = new Player(s.UserId); long oldScoreNumber = oldScore == null ? 0 : oldScore.GetScore(); oldScore?.SetOld(); //Player stats if (oldScoreNumber > 0) { player.IncrementPersonalBestsBeaten(); } else { player.IncrementSongsPlayed(); } player.IncrementSongsPlayed(); player.TotalScore += s.Score_ - oldScoreNumber; //Increment total score only by the amount the score has increased Database.Score newScore = new Database.Score(s.SongHash, s.UserId, (LevelDifficulty)s.Difficulty, s.Characteristic); newScore.SetScore(s.Score_, s.FullCombo); //Only send message if player is registered if (Player.Exists(s.UserId)) { CommunityBot.SendToScoreChannel($"User \"{player.DiscordMention}\" has scored {s.Score_} on {new Song(s.SongHash, (LevelDifficulty)s.Difficulty, s.Characteristic).SongName} ({(LevelDifficulty)s.Difficulty}) ({s.Characteristic})!"); } } return(new HttpResponse() { ReasonPhrase = "OK", StatusCode = "200" }); } catch (Exception e) { Logger.Error($"{e}"); } return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } }, new Route { Name = "Rank Receiver", UrlRegex = @"^/requestrank/$", Method = "POST", Callable = (HttpRequest request) => { try { //Get JSON object from request content JSONNode node = JSON.Parse(WebUtility.UrlDecode(request.Content)); //Get Score object from JSON RankRequest r = RankRequest.FromString(node["pb"]); if (RSA.SignRankRequest(Convert.ToUInt64(r.UserId), r.RequestedTeamId, r.InitialAssignment) == r.Signed && Player.Exists(r.UserId) && Player.IsRegistered(r.UserId) && Team.Exists(r.RequestedTeamId)) { Logger.Info($"RECEIVED VALID RANK REQUEST: {r.RequestedTeamId} FOR {r.UserId} {r.RequestedTeamId} {r.InitialAssignment}"); var player = new Player(r.UserId); var team = new Team(r.RequestedTeamId); //The rank up system will ignore requets where the player doesn't have the required tokens, //or is requesting a rank higher than the one above their current rank (if it's not an inital rank assignment) if (r.InitialAssignment && player.Team == "-1") { CommunityBot.ChangeTeam(player, team); } else if (player.Team != "gold") { var oldTeam = new Team(player.Team); var nextTeam = new Team(oldTeam.NextPromotion); if (player.Tokens >= nextTeam.RequiredTokens) { CommunityBot.ChangeTeam(player, nextTeam); } } else if (player.Team == "gold" && player.Tokens >= new Team("blue").RequiredTokens) //Player is submitting for Blue { new Vote(player.UserId, r.OstScoreInfo); } else { return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } return(new HttpResponse() { ReasonPhrase = "OK", StatusCode = "200" }); } else { Logger.Warning($"RECEIVED INVALID RANK REQUEST {r.RequestedTeamId} FROM {r.UserId}"); } } catch (Exception e) { Logger.Error($"{e}"); } return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } }, new Route { Name = "Song Getter", UrlRegex = @"^/songs/", Method = "GET", Callable = (HttpRequest request) => { string[] requestData = request.Path.Substring(1).Split('/'); string userId = requestData[1]; userId = Regex.Replace(userId, "[^a-zA-Z0-9- ]", ""); //If the userid is null, we'll give them e+ everything. It's likely the leaderboard site if (!string.IsNullOrEmpty(userId) && (!Player.Exists(userId) || !Player.IsRegistered(userId))) { return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } JSONNode json = new JSONObject(); List <SongConstruct> songs = GetActiveSongs(); songs.ForEach(x => { //If the request doesn't include a player id, we can't be sure which difficulty the player is supposed to play, so we'll just leave //the difficulty set to Auto because it's probably the website asking if (x.Difficulty == LevelDifficulty.Auto && !string.IsNullOrEmpty(userId)) { if (OstHelper.IsOst(x.SongHash)) { x.Difficulty = new Player(userId).GetPreferredDifficulty(OstHelper.IsOst(x.SongHash)); } else { var preferredDifficulty = new Player(userId).GetPreferredDifficulty(OstHelper.IsOst(x.SongHash)); x.Difficulty = new BeatSaver.Song(x.SongHash).GetClosestDifficultyPreferLower(preferredDifficulty); } } var item = new JSONObject(); item["songName"] = x.Name; item["songHash"] = x.SongHash; item["difficulty"] = (int)x.Difficulty; item["gameOptions"] = (int)x.GameOptions; item["playerOptions"] = (int)x.PlayerOptions; item["characteristic"] = x.Characteristic; json.Add(x.SongHash + (int)x.Difficulty, item); }); return(new HttpResponse() { ContentAsUTF8 = json.ToString(), ReasonPhrase = "OK", StatusCode = "200" }); } }, new Route { Name = "Team Getter", UrlRegex = @"^/teams/", Method = "GET", Callable = (HttpRequest request) => { string source = request.Path.Substring(request.Path.LastIndexOf("/") + 1); if (!string.IsNullOrEmpty(source)) { Logger.Success("Team Request from Duo's Site"); } JSONNode json = new JSONObject(); List <Team> teams = GetAllTeams(); foreach (var team in teams) { var item = new JSONObject(); item["captainId"] = team.Captain; item["teamName"] = team.TeamName; item["color"] = team.Color; item["requiredTokens"] = team.RequiredTokens; item["nextPromotion"] = team.NextPromotion; json.Add(team.TeamId, item); } return(new HttpResponse() { ContentAsUTF8 = json.ToString(), ReasonPhrase = "OK", StatusCode = "200" }); } }, new Route { Name = "Player Stats Getter", UrlRegex = @"^/playerstats/", Method = "GET", Callable = (HttpRequest request) => { string userId = request.Path.Substring(request.Path.LastIndexOf("/") + 1); userId = Regex.Replace(userId, "[^a-zA-Z0-9]", ""); if (!(userId.Length == 17 || userId.Length == 16 || userId.Length == 15)) //17 = vive, 16 = oculus, 15 = sfkwww { Logger.Error($"Invalid id size: {userId.Length}"); return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } JSONNode json = new JSONObject(); if (Player.Exists(userId) && Player.IsRegistered(userId)) { #if QUALIFIER var isRegistered = true; if (userId != "76561198063268251") { var registrationCheck = IsPlayerRegisteredInBSWC(userId); registrationCheck.Wait(); isRegistered = registrationCheck.Result; } #else var isRegistered = true; #endif if ((Config.ServerFlags.HasFlag(ServerFlags.Teams) && new Player(userId).Team == "-1") || !isRegistered) { json["message"] = "Please be sure you're assigned to a team before playing"; } else { Player player = new Player(userId); json["version"] = VersionCode; json["team"] = player.Team; json["tokens"] = player.Tokens; json["serverSettings"] = (int)Config.ServerFlags; } } else if (Player.Exists(userId) && !Player.IsRegistered(userId)) { json["message"] = "You have been banned from this event."; } else { json["message"] = "Please register with the bot before playing. Check #plugin-information for more info. Sorry for the inconvenience."; } return(new HttpResponse() { ContentAsUTF8 = json.ToString(), ReasonPhrase = "OK", StatusCode = "200" }); } }, new Route { Name = "Song Leaderboard Getter", UrlRegex = @"^/leaderboards/", Method = "GET", Callable = (HttpRequest request) => { string[] requestData = request.Path.Substring(1).Split('/'); string songHash = requestData[1]; JSONNode json = new JSONObject(); #if HIDDENNOTES return(new HttpResponse() { ContentAsUTF8 = json.ToString(), ReasonPhrase = "OK", StatusCode = "200" }); #endif if (songHash == "all") { int take = 10; string teamId = "-1"; if (requestData.Length > 2) { take = Convert.ToInt32(requestData[2]); } if (requestData.Length > 3) { teamId = requestData[3]; } List <SongConstruct> songs = GetAllScores(teamId); songs.ToList().ForEach(x => { JSONNode songNode = new JSONObject(); songNode["levelId"] = x.SongHash; songNode["songName"] = x.Name; songNode["difficulty"] = (int)x.Difficulty; songNode["characteristic"] = x.Characteristic; songNode["scores"] = new JSONObject(); int place = 1; x.Scores.Take(take).ToList().ForEach(y => { JSONNode scoreNode = new JSONObject(); scoreNode["score"] = y.Score; scoreNode["player"] = new Player(y.UserId).DiscordName; scoreNode["place"] = place; scoreNode["fullCombo"] = y.FullCombo ? "true" : "false"; scoreNode["userId"] = y.UserId; scoreNode["team"] = y.TeamId; songNode["scores"].Add(Convert.ToString(place++), scoreNode); }); json.Add(x.SongHash + ":" + (int)x.Difficulty, songNode); }); } else { int take = 10; int difficulty = Convert.ToInt32(requestData[2]); string characteristic = requestData[3]; string teamId = requestData[4]; if (requestData.Length > 5) { take = Convert.ToInt32(requestData[5]); } songHash = Regex.Replace(songHash, "[^a-zA-Z0-9- ]", ""); teamId = Regex.Replace(teamId, "[^a-zA-Z0-9- ]", ""); SongConstruct songConstruct = new SongConstruct() { SongHash = songHash, Difficulty = (LevelDifficulty)difficulty, Characteristic = characteristic }; if (!Song.Exists(songHash, (LevelDifficulty)difficulty, characteristic, true)) { Logger.Error($"Song doesn't exist for leaderboards: {songHash}"); return(new HttpResponse() { ReasonPhrase = "Bad Request", StatusCode = "400" }); } List <ScoreConstruct> scores = GetScoresForSong(songConstruct, teamId); int place = 1; scores.Take(take).ToList().ForEach(x => { JSONNode node = new JSONObject(); node["score"] = x.Score; node["player"] = new Player(x.UserId).DiscordName; node["place"] = place; node["fullCombo"] = x.FullCombo ? "true" : "false"; node["userId"] = x.UserId; node["team"] = x.TeamId; json.Add(Convert.ToString(place++), node); }); } return(new HttpResponse() { ContentAsUTF8 = json.ToString(), ReasonPhrase = "OK", StatusCode = "200" }); } } }; Logger.Info($"HTTP Server listening on {Dns.GetHostName()}"); #if (TEAMSABER) int port = 3707; #elif (DISCORDCOMMUNITY) int port = 3703; #elif (TRUEACCURACY) int port = 3711; #elif (ASIAVR) int port = 3709; #elif (QUALIFIER) int port = 3713; #elif (BTH) int port = 3715; #elif (FENCINGQUALIFIER) int port = 3717; #elif (BEATKHANA) int port = 3719; #elif (HIDDENNOTES) int port = 3721; #elif BETA int port = 3704; //My vhost is set up to direct to 3708 when the /api-beta/ route is followed #endif HttpServer httpServer = new HttpServer(port, route_config); httpServer.Listen(); }