-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
332 lines (298 loc) · 9.34 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
using Microsoft.OpenApi.Models;
using Coravel;
using Coravel.Scheduling.Schedule;
using Api.Contexts;
using Serilog;
using Api.Handlers;
using Api.Processors;
using Api.Tasks;
using Nure.NET.Types;
using Discord.Webhook;
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
var allowAny = "_any";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: allowAny,
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Host.UseSerilog();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddScheduler();
builder.Services.AddTransient<UpdateTask>();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File(
$"Logs/{DateTime.Now.Day}_{DateTime.Now.Month}_{DateTime.Now.Year}-{DateTime.Now.TimeOfDay}.txt",
rollingInterval: RollingInterval.Infinite)
.CreateLogger();
Log.Information("Application started!");
try
{
var client = new DiscordWebhookClient(Environment.GetEnvironmentVariable("DISCORD_WEBHOOK_URL"));
await client.SendMessageAsync("Application started!");
}
catch (Exception e)
{
Log.Error(e, "Error while sending message to discord");
}
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1.0.1",
Title = "Mindenit API",
Description = "The NURE schedule API",
License = new OpenApiLicense
{
Name = "License",
Url = new Uri("https://www.gnu.org/licenses/gpl-3.0.uk.html")
}
});
// Приховування шляхів, що містять певний шаблон, наприклад "/update"
options.DocInclusionPredicate((_, api) => !api.RelativePath.Contains("update"));
});
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("MyRateLimiter", limiterOptions =>
{
limiterOptions.PermitLimit = 5; // Максимум 5 запитів
limiterOptions.Window = TimeSpan.FromSeconds(15); // Протягом 10 секунд
limiterOptions.QueueLimit = 5; // Дозволити ще 2 запити у черзі, якщо ліміт перевищено
limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; // Обробка запитів з черги в порядку їх надходження
});
});
using (var context = new Context())
{
if(!context.Groups.Any())
{
Log.Information("No groups found, updating...");
GroupsHandler.Update();
}
if (!context.Teachers.Any())
{
Log.Information("No teachers found, updating...");
TeachersHandler.Update();
}
if (!context.Auditories.Any())
{
Log.Information("No auditories found, updating...");
AuditoriesHandler.Update();
}
}
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
var provider = app.Services;
provider.UseScheduler(scheduler =>
{
scheduler.Schedule<UpdateTask>()
.Cron("0 */7 * * *")
.PreventOverlapping("UpdateTask");
});
app.MapGet("/lists/groups", async (HttpContext x) => { return Results.Content(GroupsHandler.GetJson(), "application/json"); })
.WithOpenApi(generatedOperation =>
{
generatedOperation.Description = "List all groups";
generatedOperation.Summary = "List all groups";
return generatedOperation;
})
.Produces<IList<Group>>();
app.MapGet("/lists/teachers", async (HttpContext x) => { return Results.Content(TeachersHandler.GetJson(), "application/json"); })
.WithOpenApi(generatedOperation =>
{
generatedOperation.Description = "List all teachers";
generatedOperation.Summary = "List all teachers";
return generatedOperation;
})
.Produces<IList<Teacher>>();
app.MapGet("/lists/auditories", async (HttpContext x) => { return Results.Content(AuditoriesHandler.GetJson(), "application/json"); })
.WithOpenApi(generatedOperation =>
{
generatedOperation.Description = "List all auditories";
generatedOperation.Summary = "List all auditories";
return generatedOperation;
})
.Produces<IList<Auditory>>();
app.MapGet("schedule/groups/{id}", async (HttpContext x, long id) =>
{
var group_id = id;
var start = x.Request.Query.ContainsKey("start") ? long.Parse(x.Request.Query["start"]) : 0;
var end = x.Request.Query.ContainsKey("end") ? long.Parse(x.Request.Query["end"]) : 0;
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if(start > end)
{
return Results.BadRequest("Start time must be less than end time");
}
if(GroupsHandler.IsExist(group_id))
{
return Results.Content(GroupProcessor.GetJson(group_id, start, end), "application/json");
}
else
{
return Results.NotFound($"Group with id {group_id} not found");
}
})
.WithOpenApi(generatedOperation =>
{
generatedOperation.Description = "Get group schedule";
generatedOperation.Summary = "Get group schedule";
generatedOperation.Parameters.Add(new OpenApiParameter
{
Name = "start",
In = ParameterLocation.Query,
Required = false,
Description = "Start time, in unix timestamp",
Schema = new OpenApiSchema
{
Type = "integer"
}
});
generatedOperation.Parameters.Add(new OpenApiParameter
{
Name = "end",
In = ParameterLocation.Query,
Required = false,
Description = "End time, in unix timestamp",
Schema = new OpenApiSchema
{
Type = "integer"
}
});
return generatedOperation;
})
.Produces<IList<Event>>();
app.MapGet("schedule/teachers/{id}", async (HttpContext x, long id) =>
{
var teacher_id = id;
var start = x.Request.Query.ContainsKey("start") ? long.Parse(x.Request.Query["start"]) : 0;
var end = x.Request.Query.ContainsKey("end") ? long.Parse(x.Request.Query["end"]) : 0;
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if(start > end)
{
return Results.BadRequest("Start time must be less than end time");
}
if (TeachersHandler.IsExist(teacher_id))
{
return Results.Content(TeacherProcessor.GetJson(teacher_id, start, end), "application/json");
}
else
{
return Results.NotFound($"Teacher with id {teacher_id} not found");
}
})
.WithOpenApi(generatedOperation =>
{
generatedOperation.Description = "Get teacher schedule";
generatedOperation.Summary = "Get teacher schedule";
generatedOperation.Parameters.Add(new OpenApiParameter
{
Name = "start",
In = ParameterLocation.Query,
Required = false,
Description = "Start time, in unix timestamp",
Schema = new OpenApiSchema
{
Type = "integer"
}
});
generatedOperation.Parameters.Add(new OpenApiParameter
{
Name = "end",
In = ParameterLocation.Query,
Required = false,
Description = "End time, in unix timestamp",
Schema = new OpenApiSchema
{
Type = "integer"
}
});
return generatedOperation;
})
.Produces<IList<Event>>();
app.MapGet("schedule/auditories/{id}", async (HttpContext x, long id) =>
{
var auditory_id = id;
var start = x.Request.Query.ContainsKey("start") ? long.Parse(x.Request.Query["start"]) : 0;
var end = x.Request.Query.ContainsKey("end") ? long.Parse(x.Request.Query["end"]) : 0;
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if(start > end)
{
return Results.BadRequest("Start time must be less than end time");
}
if (AuditoriesHandler.IsExist(auditory_id))
{
return Results.Content(AuditoryProcessor.GetJson(auditory_id, start, end), "application/json");
}
else
{
return Results.NotFound($"Auditory with id {auditory_id} not found");
}
})
.WithOpenApi(generatedOperation =>
{
generatedOperation.Description = "Get auditory schedule";
generatedOperation.Summary = "Get auditory schedule";
generatedOperation.Parameters.Add(new OpenApiParameter
{
Name = "start",
In = ParameterLocation.Query,
Required = false,
Description = "Start time, in unix timestamp",
Schema = new OpenApiSchema
{
Type = "integer"
}
});
generatedOperation.Parameters.Add(new OpenApiParameter
{
Name = "end",
In = ParameterLocation.Query,
Required = false,
Description = "End time, in unix timestamp",
Schema = new OpenApiSchema
{
Type = "integer"
}
});
return generatedOperation;
})
.Produces<IList<Event>>();
// hidden endpoint from swagger for updating task
app.MapGet("/update", async (HttpContext x) =>
{
var task = provider.GetRequiredService<UpdateTask>();
var client = new DiscordWebhookClient(Environment.GetEnvironmentVariable("DISCORD_WEBHOOK_URL"));
await client.SendMessageAsync("Forced updating information...");
task.Invoke();
return Results.Ok();
});
app.UseCors(allowAny);
app.UseSwagger(options =>
{
options.SerializeAsV2 = true;
});
// change swagger endpoint to /
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Mindenit API");
c.RoutePrefix = "";
});
app.Run();