-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
109 lines (94 loc) · 2.97 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PlauschiServer.Model;
using Tfres;
namespace PlauschiServer
{
class Program
{
private static object _lock = new object();
private static Dictionary<string, Event> _events = new Dictionary<string, Event>();
private static uint _maxUsersPerGroup;
private static uint _maxEvents;
static void Main(string[] args)
{
var server = Load();
server.AddEndpoint(HttpVerb.GET, "/new", NewGroupMember);
server.AddEndpoint(HttpVerb.GET, "/check", CheckGroup);
while (true)
Console.ReadLine();
}
private static Task CheckGroup(HttpContext ctx)
{
try
{
var get = ctx.Request.GetData();
var eventId = get["event"];
var groupId = Guid.Parse(get["group"]);
lock (_lock)
{
if (!_events.ContainsKey(eventId))
return ctx.Response.Send(HttpStatusCode.InternalServerError);
var myEvent = _events[eventId];
return myEvent.Guid != groupId ? ctx.Response.Send(new Event(0)
{
Count = 0,
Guid = groupId
}) : ctx.Response.Send(myEvent);
}
}
catch
{
return ctx.Response.Send(HttpStatusCode.InternalServerError);
}
}
private static Task NewGroupMember(HttpContext ctx)
{
try
{
var get = ctx.Request.GetData();
var eventId = get["event"];
var groupSize = uint.Parse(get["size"]);
if (groupSize > _maxUsersPerGroup)
return ctx.Response.Send(HttpStatusCode.InternalServerError);
lock (_lock)
{
if (!_events.ContainsKey(eventId))
{
if (_events.Count > _maxEvents)
return ctx.Response.Send(HttpStatusCode.InternalServerError);
_events.Add(eventId, new Event(groupSize));
}
var myEvent = _events[eventId];
myEvent.Count++;
_events[eventId] = myEvent.Count >= myEvent.Max ? new Event(groupSize) : myEvent;
return ctx.Response.Send(myEvent);
}
}
catch
{
return ctx.Response.Send(HttpStatusCode.InternalServerError);
}
}
private static Server Load()
{
var config = File.Exists("server.cnf")
? JsonConvert.DeserializeObject<ServerConfiguration>(File.ReadAllText("server.cnf", Encoding.UTF8))
: NewServerConfiguration();
_maxEvents = config.MaxEvents;
_maxUsersPerGroup = config.MaxUsersPerGroup;
return new Server(config.HostnameOrIp, config.Port, ctx => ctx.Response.Send(HttpStatusCode.InternalServerError));
}
private static ServerConfiguration NewServerConfiguration()
{
var res = new ServerConfiguration();
File.WriteAllText("server.cnf", JsonConvert.SerializeObject(res), Encoding.UTF8);
return res;
}
}
}