calendar-webapp/source/app.d

102 lines
2.3 KiB
D
Raw Normal View History

2017-08-02 01:56:36 +02:00
import std.datetime.date;
import std.typecons : Nullable;
2017-08-02 01:56:36 +02:00
2017-08-05 17:31:35 +02:00
import vibe.vibe;
2017-08-02 01:56:36 +02:00
2017-08-05 17:31:35 +02:00
class CalendarWebapp
{
private:
immutable fileName = Path("events.json");
2017-08-02 01:56:36 +02:00
enum EventType
{
Holiday,
Birthday,
FSI_Event,
General_University_Event,
Any
}
struct Entry
{
@name("date") Date begin;
@name("end_date") Nullable!Date end;
Event event;
}
2017-08-05 17:31:35 +02:00
struct Event
{
@(vibe.data.serialization.name("eid")) string id;
string name;
@(vibe.data.serialization.name("desc")) string[] description;
@(vibe.data.serialization.name("etype")) EventType type;
bool shout;
2017-08-05 17:31:35 +02:00
}
2017-08-02 01:56:36 +02:00
Entry[] getEventsFromFile(in Path fileName)
2017-08-05 17:31:35 +02:00
{
Entry[] entries;
2017-08-05 17:31:35 +02:00
try
{
auto entriesString = readFileUTF8(fileName);
try
{
deserializeJson(entries, entriesString.parseJsonString);
}
catch (std.json.JSONException)
{
}
2017-08-05 17:31:35 +02:00
}
catch(Exception)
{}
return entries;
2017-08-05 17:31:35 +02:00
}
2017-08-02 01:56:36 +02:00
2017-08-05 17:31:35 +02:00
public:
2017-08-02 01:56:36 +02:00
2017-08-05 17:31:35 +02:00
@method(HTTPMethod.POST) @path("/event/create")
void createEvent(Date begin, Nullable!Date end, string description,
string name, EventType type, bool shout)
2017-08-05 17:31:35 +02:00
{
import std.array : split, replace;
2017-08-02 01:56:36 +02:00
if (!end.isNull)
enforce(end - begin >= 1.days);
2017-08-02 01:56:36 +02:00
auto entry = Entry(begin, end, Event("", name,
description.replace("\r", "").split('\n'), type, shout));
2017-08-02 01:56:36 +02:00
auto entries = getEventsFromFile(fileName);
entries ~= entry;
writeFileUTF8(fileName, serializeToPrettyJson(entries));
render!("showevents.dt", entries);
2017-08-05 17:31:35 +02:00
}
2017-08-02 01:56:36 +02:00
2017-08-05 17:31:35 +02:00
@method(HTTPMethod.GET) @path("create")
void newEvent()
{
render!("create.dt");
}
2017-08-02 01:56:36 +02:00
2017-08-05 17:31:35 +02:00
void index()
2017-08-02 01:56:36 +02:00
{
auto entries = getEventsFromFile(fileName);
render!("showevents.dt", entries);
2017-08-02 01:56:36 +02:00
}
2017-08-05 17:31:35 +02:00
2017-08-02 01:56:36 +02:00
}
2017-08-05 17:31:35 +02:00
shared static this()
2017-08-02 01:56:36 +02:00
{
2017-08-05 17:31:35 +02:00
auto router = new URLRouter;
router.registerWebInterface(new CalendarWebapp);
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, router);
logInfo("Please open http://127.0.0.1:8080/ in your browser.");
2017-08-02 01:56:36 +02:00
}