+fn get_user(env: *lmdb.Env, user_id: UserId) !?User {
+ const txn = try env.txn();
+ defer txn.abort();
+
+ const users = try Db.users(&txn);
+ return users.get(user_id);
+}
+
+// }}}
+
+// html {{{
+fn html_form(res: *http.Response, comptime fmt_action: []const u8, args_action: anytype, inputs: anytype) !void {
+ try res.write("<form style=\"display: inline-block!important;\" action=\"", .{});
+ try res.write(fmt_action, args_action);
+ try res.write("\" method=\"post\">", .{});
+
+ inline for (inputs) |input| {
+ switch (@typeInfo(@TypeOf(input))) {
+ .Struct => {
+ try res.write("<input ", .{});
+ try res.write(input[0], input[1]);
+ try res.write(" />", .{});
+ },
+ else => {
+ try res.write("<input ", .{});
+ try res.write(input, .{});
+ try res.write(" />", .{});
+ },
+ }
+ }
+
+ try res.write("</form>", .{});
+}
+// }}}
+
+// write {{{
+fn write_header(res: *http.Response, logged_in: ?Login) !void {
+ if (logged_in) |login| {
+ try res.write(
+ \\<a href="/user/{s}">Home</a><br />
+ , .{login.user.username.constSlice()});
+ try html_form(res, "/logout", .{}, .{
+ \\type="submit" value="Logout"
+ });
+ try html_form(res, "/quit", .{}, .{
+ \\type="submit" value="Quit"
+ });
+ try res.write("<br />", .{});
+ try html_form(res, "/post", .{}, .{
+ \\type="text" name="text"
+ ,
+ \\type="submit" value="Post"
+ });
+ } else {
+ try res.write(
+ \\<a href="/">Home</a><br />
+ \\<a href="/register">Register</a>
+ \\<a href="/login">Login</a><br />
+ , .{});
+ try html_form(res, "/quit", .{}, .{
+ \\type="submit" value="Quit"
+ });
+ }
+}
+fn write_posts(res: *http.Response, txn: *const lmdb.Txn, user: User, login: ?Login) !void {
+ const posts = try Db.posts(txn);
+ var it = try user.posts.it(txn);
+ while (it.next()) |post_id| {
+ const p = posts.get(post_id) orelse break;
+ try res.write(
+ \\<div>
+ \\<p>{s}</p>
+ , .{p.text.constSlice()});
+ if (login != null and try p.upvotes.has(txn, login.?.user_id)) {
+ try html_form(res, "/unupvote/{}", .{@intFromEnum(post_id)}, .{
+ .{ "type=\"submit\" value=\"⬆ {}\"", .{p.upvotes.len} },
+ });
+ } else {
+ try html_form(res, "/upvote/{}", .{@intFromEnum(post_id)}, .{
+ .{ "type=\"submit\" value=\"⬆ {}\"", .{p.upvotes.len} },
+ });
+ }
+ if (login != null and try p.downvotes.has(txn, login.?.user_id)) {
+ try html_form(res, "/undownvote/{}", .{@intFromEnum(post_id)}, .{
+ .{ "type=\"submit\" value=\"⬇ {}\"", .{p.downvotes.len} },
+ });
+ } else {
+ try html_form(res, "/downvote/{}", .{@intFromEnum(post_id)}, .{
+ .{ "type=\"submit\" value=\"⬇ {}\"", .{p.downvotes.len} },
+ });
+ }
+ try res.write(
+ \\<span>💭 {}</span>
+ \\</div>
+ , .{p.comments.len});
+ }
+}