const std = @import("std"); const assets = @import("assets.zig"); const config = @import("../../core/config.zig"); const entropy = @import("entropy.zig"); pub const preview = @import("preview.zig"); const http_api = @import("../api.zig"); const icons = @import("../../internal/web/icons.zig"); const skin = @import("../../internal/web/skin.zig"); const store = @import("../../storage/store.zig"); const http = std.http; pub fn serve(request: *http_api.Request) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var range_buf: [8]u8 = undefined; var resident_buf: [256]u8 = undefined; var collections_buf: [8]u8 = undefined; const target = request.url.raw; const page = try render(allocator, .{ .range = store.ActivityRange.parse(http_api.queryParam(target, "range", &range_buf) orelse "") orelse .all, .resident = http_api.queryParam(target, "resident", &resident_buf), .all_collections = std.mem.eql(u8, http_api.queryParam(target, "collections", &collections_buf) orelse "", "all"), .now_us = store.nowMicros(), }); const body = try icons.decorate(allocator, page.html); const headers = [_]http.Header{ .{ .name = "content-type", .value = "text/html; charset=utf-8" }, .{ .name = "cache-control", .value = "no-store" }, .{ .name = "access-control-allow-origin", .value = "*" }, .{ .name = "access-control-allow-private-network", .value = "true" }, .{ .name = "connection", .value = "close" }, } ++ try http_api.htmlSecurityHeadersWithStyle(allocator, .{ .scripts = &([_][]const u8{ assets.script, icons.script } ++ skin.policy_scripts), .styles = &([_][]const u8{ assets.css, icons.style } ++ skin.home_policy_styles), }, page.style); try http_api.respond(request, .ok, body, &headers); } pub fn serveFavicon(request: *http_api.Request) !void { const headers = [_]http.Header{ .{ .name = "content-type", .value = "image/svg+xml; charset=utf-8" }, .{ .name = "cache-control", .value = "public, max-age=86400" }, .{ .name = "access-control-allow-origin", .value = "*" }, .{ .name = "connection", .value = "close" }, }; try http_api.respond(request, .ok, skin.favicon() orelse assets.favicon, &headers); } pub fn serveFont(request: *http_api.Request) !void { const bytes = skin.font().bytes() orelse { const missing = [_]http.Header{.{ .name = "connection", .value = "close" }}; return http_api.respond(request, .not_found, "", &missing); }; const headers = [_]http.Header{ .{ .name = "content-type", .value = "font/woff2" }, .{ .name = "cache-control", .value = "public, max-age=86400" }, .{ .name = "access-control-allow-origin", .value = "*" }, .{ .name = "connection", .value = "close" }, }; try http_api.respond(request, .ok, bytes, &headers); } pub fn renderOgImage(allocator: std.mem.Allocator) ![]u8 { return preview.renderLook(allocator, displayHost(config.publicUrl()), if (skin.current() == .glass) .glass else .paper); } pub fn serveOgImage(request: *http_api.Request, png: []const u8) !void { const headers = [_]http.Header{ .{ .name = "content-type", .value = "image/png" }, .{ .name = "cache-control", .value = "public, max-age=86400" }, .{ .name = "access-control-allow-origin", .value = "*" }, .{ .name = "connection", .value = "close" }, }; try http_api.respond(request, .ok, png, &headers); } const Page = struct { html: []const u8, /// Per-request visual values, which the policy allows by hash. style: []const u8, }; pub const View = struct { range: store.ActivityRange = .all, /// A resident's handle or DID; the page shows only their writes. resident: ?[]const u8 = null, /// Show every collection rather than the top few (the no-script path). all_collections: bool = false, now_us: u64, }; /// Collections listed before "show all". const top_collections = 10; pub fn render(allocator: std.mem.Allocator, view: View) !Page { const residents = try store.listResidents(allocator, 24); var scoped: ?store.Resident = null; if (view.resident) |wanted| for (residents) |resident| { if (std.mem.eql(u8, resident.handle, wanted) or std.mem.eql(u8, resident.did, wanted)) scoped = resident; }; const scope_query = if (scoped) |resident| try std.fmt.allocPrint(allocator, "&resident={s}", .{try percentEncode(allocator, resident.handle)}) else ""; const range_query = try std.fmt.allocPrint(allocator, "range={s}", .{view.range.label()}); var accounts: std.Io.Writer.Allocating = .init(allocator); defer accounts.deinit(); if (residents.len == 0) { try accounts.writer.writeAll("
  • no residents yet.
  • "); } else { for (residents) |resident| { const handle = try escapeHtml(allocator, resident.handle); const did = try escapeHtml(allocator, resident.did); const avatar = try renderAvatar(allocator, resident); const picked = if (scoped) |s| std.mem.eql(u8, s.did, resident.did) else false; const status = if (picked) "showing" else if (resident.active) "active" else "paused"; // Picking the resident already shown goes back to everyone. const scope_href = if (picked) try std.fmt.allocPrint(allocator, "/?{s}", .{range_query}) else try std.fmt.allocPrint(allocator, "/?{s}&resident={s}", .{ range_query, try percentEncode(allocator, resident.handle) }); try accounts.writer.print( \\
  • \\ \\ {s} \\ \\ {s} \\ {s} \\ \\ {s}{f} records \\ \\ \\
  • , .{ if (picked) " picked" else "", scope_href, if (picked) " aria-current=\"true\"" else "", avatar, handle, did, status, entropy.grouped(resident.record_count), handle, std.json.fmt(resident.handle, .{}), std.json.fmt(resident.did, .{}), handle, }); } } const scope_did = if (scoped) |resident| resident.did else null; const collections = try store.listCollectionSummaries(allocator, scope_did, 1000); const activity = try store.listRecordActivity(allocator, view.range, scope_did, view.now_us); const signal = try entropy.fromState(allocator, residents, collections, activity, view.range, scope_query); var collection_items: std.Io.Writer.Allocating = .init(allocator); defer collection_items.deinit(); var style: std.Io.Writer.Allocating = .init(allocator); defer style.deinit(); try style.writer.writeAll(signal.style); // The host fills one line: monospace glyphs are about 0.61em wide, so the // heading never overflows a phone and stays at its cap on wide screens. const title_ems = @as(f64, @floatFromInt(@max(displayHost(config.publicUrl()).len, 1))) * 0.61; try style.writer.print("h1{{font-size:min(74px,calc(100cqi / {d:.2}))}}", .{title_ems}); if (collections.len == 0) { try collection_items.writer.writeAll("
  • no records yet.
  • "); } else { const max_count = collections[0].count; for (collections, 1..) |summary, position| { const collection = try escapeHtml(allocator, summary.collection); const width = if (max_count == 0) 0 else @max(@as(u64, 1), summary.count * 100 / max_count); try collection_items.writer.print( \\
  • \\ {s} \\ {f} \\ \\
  • , .{ if (position > top_collections) " data-rest" else "", collection, collection, entropy.grouped(summary.count) }); try style.writer.print(".collection:nth-child({d}) i{{width:{d}%}}", .{ position, width }); } } const collections_html = try renderCollections(allocator, collections.len, view.all_collections, range_query, scope_query, collection_items.written()); const scope_html = if (scoped) |resident| try renderScope(allocator, resident, range_query) else ""; const recent_records = try store.listLandingRecentRecords(allocator, 8); const pulse = try renderPulse(allocator, recent_records); const public_url = config.publicUrl(); const public_host = try escapeHtml(allocator, displayHost(public_url)); const public_url_html = try escapeHtml(allocator, public_url); const preview_image = try escapeHtml(allocator, try std.fmt.allocPrint(allocator, "{s}/og-image?v=3", .{public_url})); const html = try std.fmt.allocPrint(allocator, @embedFile("../../internal/web/home.html"), .{ public_url_html, public_host, public_url_html, preview_image, public_host, preview_image, assets.css, skin.homeStyle(), style.written(), public_host, scope_html, signal.html, pulse, accounts.written(), collections_html, assets.script, skin.script(), }); return .{ .html = html, .style = try style.toOwnedSlice() }; } fn renderCollections( allocator: std.mem.Allocator, count: usize, show_all: bool, range_query: []const u8, scope_query: []const u8, items: []const u8, ) ![]const u8 { const more = count > top_collections; var out: std.Io.Writer.Allocating = .init(allocator); const w = &out.writer; try w.writeAll("

    collections

    "); if (count > 1) { try w.writeAll(""); } try w.print("
    ", .{ if (show_all or !more) " all" else "", items }); try w.writeAll("

    "); if (more and !show_all) { try w.print("show all {d} collections", .{ range_query, scope_query, count }); } try w.writeAll("

    "); return out.toOwnedSlice(); } fn renderScope(allocator: std.mem.Allocator, resident: store.Resident, range_query: []const u8) ![]const u8 { return std.fmt.allocPrint(allocator, \\

    {s}showing @{s}

    , .{ try renderAvatar(allocator, resident), try escapeHtml(allocator, resident.handle), range_query }); } fn percentEncode(allocator: std.mem.Allocator, text: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(allocator); for (text) |c| { if (std.ascii.isAlphanumeric(c) or c == '.' or c == '-' or c == '_' or c == ':') try out.writer.writeByte(c) else try out.writer.print("%{X:0>2}", .{c}); } return out.toOwnedSlice(); } fn renderPulse(allocator: std.mem.Allocator, records: []const store.RecentRecord) ![]const u8 { if (records.len == 0) { return allocator.dupe(u8, \\
    \\
    repo signal
    waiting for first write.
    \\
    ); } const newest = records[0]; const collection = try escapeHtml(allocator, newest.collection); const rkey = try escapeHtml(allocator, newest.rkey); const cid = try escapeHtml(allocator, newest.cid); const did = try escapeHtml(allocator, newest.did); return std.fmt.allocPrint(allocator, \\
    \\
    \\
    latest indexed record
    \\ \\ {s}/{s} \\ seq {d} \\ \\
    {s}
    \\
    \\
    , .{ did, collection, rkey, collection, rkey, newest.seq, cid }); } fn renderAvatar(allocator: std.mem.Allocator, resident: store.Resident) ![]const u8 { const avatar_cid = try store.profileAvatarCid(allocator, resident.did) orelse { return std.fmt.allocPrint(allocator, "{c}", .{initialFor(resident.handle)}); }; const did = try escapeHtml(allocator, resident.did); const cid = try escapeHtml(allocator, avatar_cid); return std.fmt.allocPrint( allocator, "\"\"", .{ did, cid }, ); } fn initialFor(handle: []const u8) u8 { for (handle) |c| if (std.ascii.isAlphanumeric(c)) return std.ascii.toLower(c); return 'z'; } fn escapeHtml(allocator: std.mem.Allocator, text: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(allocator); defer out.deinit(); for (text) |c| switch (c) { '&' => try out.writer.writeAll("&"), '<' => try out.writer.writeAll("<"), '>' => try out.writer.writeAll(">"), '"' => try out.writer.writeAll("""), '\'' => try out.writer.writeAll("'"), else => try out.writer.writeByte(c), }; return out.toOwnedSlice(); } fn displayHost(public_url: []const u8) []const u8 { var value = public_url; if (std.mem.startsWith(u8, value, "https://")) value = value["https://".len..]; if (std.mem.startsWith(u8, value, "http://")) value = value["http://".len..]; if (std.mem.indexOfScalar(u8, value, '/')) |idx| value = value[0..idx]; return value; }