static Reply SubmissionTest(Request request) { Document document = new Document("Submission"); string body = ""; foreach (var entry in request.Content) body += Markup.Paragraph(string.Format("{0}: {1}", entry.Key, entry.Value)); Reply reply = new Reply(document.Render(body)); return reply; }
static Reply MarkupTest(Request request) { Document document = new Document("<Test>"); string body = Markup.Paragraph(Markup.Bold("Success!")); body += Markup.Paragraph(string.Format("The path of this handler is: {0}", Markup.Bold(request.RequestHandler.GetPath()))); string form = Markup.Text("input1") + Markup.Text("input2") + Markup.Submit("Submit"); body += Markup.Form(SubmissionHandler.GetPath(), form); Reply reply = new Reply(document.Render(body)); return reply; }
Reply ApiSummonerProfile(Request request) { var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; int accountId = (int)request.Arguments[1]; Worker worker = GetWorkerByAbbreviation(regionAbbreviation); SummonerProfileResult output; Summoner summoner = StatisticsService.GetSummoner(worker.Region, accountId); if (summoner != null) output = new SummonerProfileResult(summoner); else output = new SummonerProfileResult(OperationResult.NotFound); return GetJSONReply(output); }
Reply ApiSearch(Request request) { PrivilegeCheck(request); var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; string summonerName = (string)request.Arguments[1]; Worker worker = GetWorkerByAbbreviation(regionAbbreviation); Summoner summoner = null; OperationResult result = worker.FindSummoner(summonerName, ref summoner); SummonerSearchResult output; if (result == OperationResult.Success) output = new SummonerSearchResult(summoner.AccountId); else output = new SummonerSearchResult(result); return GetJSONReply(output); }
Reply ApiSetAutomaticUpdates(Request request) { PrivilegeCheck(request); var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; int accountId = (int)request.Arguments[1]; bool updateAutomatically = (int)request.Arguments[2] != 0; Worker worker = GetWorkerByAbbreviation(regionAbbreviation); SummonerAutomaticUpdatesResult output; Summoner summoner = StatisticsService.GetSummoner(worker.Region, accountId); if (summoner != null) { OperationResult result = SetSummonerAutomaticUpdates(summoner, updateAutomatically); output = new SummonerAutomaticUpdatesResult(result); } else output = new SummonerAutomaticUpdatesResult(OperationResult.NotFound); return GetJSONReply(output); }
Reply AutomaticUpdates(Request request) { var arguments = request.Arguments; string regionName = (string)arguments[0]; int accountId = (int)arguments[1]; RegionHandler regionHandler = GetRegionHandler(regionName); using (NpgsqlConnection database = DatabaseProvider.GetConnection()) { SQLCommand command = GetCommand("update summoner set update_automatically = true where region = cast(:region as region_type) and account_id = :account_id", database); command.SetEnum("region", regionHandler.GetRegionEnum()); command.Set("account_id", accountId); int rowsAffected = command.Execute(); bool success = rowsAffected > 0; AutomaticUpdatesResult result = new AutomaticUpdatesResult(success); string body = Serialiser.Serialize(result); Reply reply = new Reply(ReplyCode.Ok, ContentType.JSON, body); return reply; } }
Reply ApiSummonerGames(Request request) { var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; int accountId = (int)request.Arguments[1]; Worker worker = GetWorkerByAbbreviation(regionAbbreviation); SummonerGamesResult output; Summoner summoner = StatisticsService.GetSummoner(worker.Region, accountId); if (summoner != null) { using (var connection = GetConnection()) { List<ExtendedPlayer> games = GetSummonerGames(summoner, connection); output = new SummonerGamesResult(games); } } else output = new SummonerGamesResult(OperationResult.NotFound); return GetJSONReply(output); }
Reply ApiGetGameTeam(Request request) { PrivilegeCheck(request); var arguments = request.Arguments; var regionAbbreviation = (string)arguments[0]; var gameId = (int) arguments[1]; SummonerGameTeamResult output; using (var connection = GetConnection()) { var listParticipants = GetGameTeam(connection, gameId); output = listParticipants != null ? new SummonerGameTeamResult(listParticipants) : new SummonerGameTeamResult(OperationResult.NotFound); } return GetJSONReply(output); }
Reply ApiGetComments(Request request) { PrivilegeCheck(request); var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; int summonerId = (int)request.Arguments[1]; //Worker worker = GetWorkerByAbbreviation(regionAbbreviation); var comments = GetComments(summonerId); SummonerGetCommentsResult output; if (comments != null) output = new SummonerGetCommentsResult(comments); else output = new SummonerGetCommentsResult(OperationResult.Success); return GetJSONReply(output); }
Reply Index(Request request) { string title = "Index"; string body = GetSearchForm("Enter the name of the summoner you want to look up:"); return Template(title, body, false); }
Reply ViewSummonerGames(Request request) { var arguments = request.Arguments; string regionName = (string)arguments[0]; int accountId = (int)arguments[1]; using (NpgsqlConnection database = DatabaseProvider.GetConnection()) { Summoner summoner = LoadSummoner(regionName, accountId, database); List<GameTeamPlayer> games = LoadSummonerGames(summoner, database); string title = string.Format("Games of {0}", summoner.SummonerName); string table = GetSummonerGamesTable(summoner, games); Document document = GetDocument(title); Reply reply = new Reply(document.Render(table)); return reply; } }
Reply ViewSummoner(Request request) { var arguments = request.Arguments; string regionName = (string)arguments[0]; int accountId = (int)arguments[1]; using (NpgsqlConnection database = DatabaseProvider.GetConnection()) { Summoner summoner = LoadSummoner(regionName, accountId, database); LoadSummonerRating(summoner, database); LoadSummonerRankedStatistics(summoner, database); LoadAggregatedChampionStatistics(summoner, database); string title = summoner.SummonerName; string script = GetScript("Statistics.js"); string overview = GetSummonerOverview(regionName, summoner); string rating = GetRatingTable(summoner); string rankedStatistics = GetRankedStatistics(summoner); string aggregatedStatistics = GetAggregatedChampionStatistics(summoner); string body = script + overview + rating + rankedStatistics + aggregatedStatistics; return Template(title, body); } }
Reply Search(Request request) { var arguments = request.Content; string summonerName; if (!arguments.TryGetValue(SummonerField, out summonerName)) throw new HandlerException("No summoner specified"); string regionName; if (!arguments.TryGetValue(RegionField, out regionName)) throw new HandlerException("No region specified"); RegionHandler regionHandler = GetRegionHandler(regionName); using (NpgsqlConnection database = DatabaseProvider.GetConnection()) { SQLCommand select = GetCommand("select account_id from summoner where lower(summoner_name) = lower(:summoner_name) and region = cast(:region as region_type)", database); select.Set("summoner_name", summonerName); select.SetEnum("region", regionHandler.GetRegionEnum()); using (NpgsqlDataReader reader = select.ExecuteReader()) { if (reader.Read()) { int accountId = (int)reader[0]; return Reply.Referral(ViewSummonerHandler.GetPath(regionName, accountId.ToString())); } else { LookupJob job = regionHandler.PerformSummonerLookup(summonerName); switch (job.Result) { case JobQueryResult.Success: return Reply.Referral(ViewSummonerHandler.GetPath(regionName, job.AccountId.ToString())); case JobQueryResult.NotFound: return Template("Search", GetSearchForm("Unable to find summoner.", summonerName, regionName), false); case JobQueryResult.Timeout: return Template("Search", GetSearchForm("A timeout has occurred.", summonerName, regionName), false); default: throw new HandlerException("Unknown job result"); } } } } }
void Observe(Request request) { WriteLine("[{0}] {1}", request.ClientAddress, request.Path); }
public Reply CatchAll(Request request) { //Display the index for any path other than the API ones //This way all routing is performed by JavaScript return Index(request); }
string GetPrivilegeString(Request request) { List<string> privileges = GetPrivileges(request); var arguments = from x in privileges select GetJavaScriptString(x); return string.Format("[{0}]", string.Join(", ", arguments)); }
bool IsPrivileged(Request request) { PrivilegeClass privilegeClass = GetRequestClass(request); return privilegeClass != null && privilegeClass.EnabledAPIFunctions.Contains(request.RequestHandler.Name); }
Reply LoadAccountData(Request request) { var arguments = request.Arguments; string regionName = (string)arguments[0]; int accountId = (int)arguments[1]; RegionHandler regionHandler = GetRegionHandler(regionName); AccountIdJob job = regionHandler.PerformManualSummonerUpdate(accountId); SummonerUpdateResult result = new SummonerUpdateResult(job); string body = Serialiser.Serialize(result); Reply reply = new Reply(ReplyCode.Ok, ContentType.JSON, body); return reply; }
static string ChunkedTest(Request request) { Thread.Sleep(2000); return Markup.InlineScript("alert('Success');"); }
static Reply ExceptionTest(Request request) { throw new Exception("This is a test"); }
Reply Index(Request request) { List<string> regionStrings = new List<string>(); foreach (var profile in StatisticsService.GetActiveProfiles()) { //Avoid race conditions since the profile is modified by other threads //Just in case lock (profile) { regionStrings.Add(string.Format("[{0}, {1}, {2}]", GetJavaScriptString(profile.Abbreviation), GetJavaScriptString(profile.Description), profile.Identifier)); } } string regions = string.Format("[{0}]", string.Join(", ", regionStrings)); string privileged = IsPrivileged(request.ClientAddress) ? "true" : "false"; string content = IndexContents; content = content.Replace("$REGIONS", regions); content = content.Replace("$PRIVILEGED", privileged); content = content.Replace("$REVISION", Assembly.GetEntryAssembly().GetName().Version.Revision.ToString()); return new Reply(content); }
Reply ApiUpdateSummoner(Request request) { PrivilegeCheck(request); var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; int accountId = (int)request.Arguments[1]; Worker worker = GetWorkerByAbbreviation(regionAbbreviation); OperationResult result = worker.UpdateSummonerByAccountId(accountId); SummonerUpdateResult output = new SummonerUpdateResult(result); return GetJSONReply(output); }
List<string> GetPrivileges(Request request) { PrivilegeClass privilegeClass = GetRequestClass(request); if (privilegeClass == null) return new List<string>(); else return privilegeClass.EnabledAPIFunctions; }
public byte[] GetChunkedData(Request request, out bool WasLastChunk) { string chunkBody = ChunkedHandlerDelegate(request); if (chunkBody == null) { WasLastChunk = true; return Encoding.GetBytes("0\r\n"); } else { WasLastChunk = false; const string tail = "\r\n"; byte[] chunkBodyBytes = Encoding.GetBytes(chunkBody + tail); int chunkBodySize = chunkBodyBytes.Length - tail.Length; string chunkHeader = string.Format("{0:X}\r\n", chunkBodySize); byte[] chunkHeaderBytes = Encoding.GetBytes(chunkHeader); return MergeHeaderAndBody(chunkHeaderBytes, chunkBodyBytes); } }
PrivilegeClass GetRequestClass(Request request) { foreach (var privilegeClass in ProgramConfiguration.Privileges) { if (privilegeClass.MatchAllAddresses || privilegeClass.Addresses.Contains(request.ClientAddress)) return privilegeClass; } return null; }
//Returns null if the handler does not match public Reply RouteRequest(Request request, List<string> remainingPath) { if (remainingPath.Count == 0) { if (IsDefaultHandler) { //Execute handler return ProcessRequest(request); } else return null; } if (IsDefaultHandler) { //Default handlers can only match empty remaining paths return null; } else { string currentName = remainingPath[0]; remainingPath = remainingPath.GetRange(1, remainingPath.Count - 1); if (currentName == Name) { //We have a match for the request if (IsContainer) { //We have a hit for the container but the container does not handle the request itself //The remaining path needs to be passed on to the children so don't do anything at this point and just continue with the children } else { //The request must be handled by this object List<string> argumentStrings = remainingPath; if (argumentStrings.Count != ArgumentTypes.Length) throw new HandlerException("Invalid argument count"); List<object> arguments = new List<object>(); for (int i = 0; i < ArgumentTypes.Length; i++) { ArgumentType type = ArgumentTypes[i]; string argumentString = argumentStrings[i]; object argument; switch (type) { case ArgumentType.String: argument = argumentString; break; case ArgumentType.Integer: try { argument = Convert.ToInt32(argumentString); } catch (FormatException) { throw new HandlerException("Invalid integer specified"); } break; default: throw new Exception("Unknown argument type encountered"); } arguments.Add(argument); } request.Arguments = arguments; //Execute handler return ProcessRequest(request); } } else { //The handler does not match the request return null; } } //Check children foreach (var child in Children) { Reply reply = child.RouteRequest(request, remainingPath); if (reply != null) { //A child of the handler found a match for the request return reply; } } //None of the children matched return null; }
void PrivilegeCheck(Request request) { if(!IsPrivileged(request)) throw new HandlerException("You do not have the permission to use this service"); }
Reply ProcessRequest(Request request) { request.RequestHandler = this; if (IsChunkedHandler) return new Reply(ChunkedReplyCode, ChunkedContentType, ChunkedHandlerDelegate); else return HandlerDelegate(request); }
//Interfaces public void ObserveRequest(Request request) { WriteLine("[HTTP {0}] {1}", request.ClientAddress, request.Path); }
Reply ApiWriteComment(Request request) { PrivilegeCheck(request); var arguments = request.Arguments; string regionAbbreviation = (string)request.Arguments[0]; int summonerId = (int)request.Arguments[1]; string commenterName = (string)request.Arguments[2]; string comment = (string)request.Arguments[3]; Worker worker = GetWorkerByAbbreviation(regionAbbreviation); OperationResult result = worker.WriteComment(summonerId, commenterName, comment); var output = new SummonerWriteCommentResult(result); return GetJSONReply(output); }