~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
319 lines · 14.8 KB Raw History
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("<li class=\"empty\">no residents yet.</li>");
    } 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}&amp;resident={s}", .{ range_query, try percentEncode(allocator, resident.handle) });
            try accounts.writer.print(
                \\<li class="resident{s}">
                \\  <a class="pick" href="{s}"{s}>
                \\    {s}
                \\    <span class="who">
                \\      <span class="handle">{s}</span>
                \\      <span class="did">{s}</span>
                \\    </span>
                \\    <span class="meta"><span>{s}</span><span>{f} records</span></span>
                \\  </a>
                \\  <a class="profile" href="https://bsky.app/profile/{s}" data-profile-handle={f} data-profile-did={f} rel="me" aria-label="open {s}'s profile"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></svg></a>
                \\</li>
            , .{
                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("<li class=\"empty\">no records yet.</li>");
    } 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(
                \\<li class="collection"{s}>
                \\  <a href="https://ufos.microcosm.blue/collection/?nsid={s}"><code>{s}</code></a>
                \\  <span>{f}</span>
                \\  <i></i>
                \\</li>
            , .{ 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("<div class=\"collections-head\"><h2 class=\"section-title\" id=\"records-title\">collections</h2>");
    if (count > 1) {
        try w.writeAll("<label class=\"filter\" hidden><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"11\" cy=\"11\" r=\"7\"/><path d=\"m20 20-3.5-3.5\"/></svg><input type=\"search\" placeholder=\"filter\" aria-label=\"filter collections\" autocomplete=\"off\" autocapitalize=\"none\" spellcheck=\"false\" data-filter></label>");
    }
    try w.print("</div><ul class=\"collections{s}\" data-collections>{s}</ul>", .{ if (show_all or !more) " all" else "", items });
    try w.writeAll("<p class=\"collections-foot\" data-collections-foot>");
    if (more and !show_all) {
        try w.print("<a href=\"/?{s}{s}&amp;collections=all\" data-show-all>show all {d} collections</a>", .{ range_query, scope_query, count });
    }
    try w.writeAll("</p>");
    return out.toOwnedSlice();
}

fn renderScope(allocator: std.mem.Allocator, resident: store.Resident, range_query: []const u8) ![]const u8 {
    return std.fmt.allocPrint(allocator,
        \\<p class="scope">{s}<span>showing <b>@{s}</b></span><a href="/?{s}" aria-label="show every resident"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7L7 17"/></svg></a></p>
    , .{ 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,
            \\<section class="pulse" aria-label="repo signal">
            \\  <div><div class="pulse-kicker">repo signal</div><div class="pulse-row"><span class="pulse-path">waiting for first write.</span></div></div>
            \\</section>
        );
    }

    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,
        \\<section class="pulse" aria-label="repo signal">
        \\  <div>
        \\    <div class="pulse-kicker">latest indexed record</div>
        \\    <a class="pulse-link" href="https://pdsls.dev/at/{s}/{s}/{s}" title="open record in PDSls">
        \\      <span><code>{s}</code>/{s}</span>
        \\      <em>seq {d}</em>
        \\    </a>
        \\    <div class="pulse-cid">{s}</div>
        \\  </div>
        \\</section>
    , .{ 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, "<span class=\"avatar\" aria-hidden=\"true\">{c}</span>", .{initialFor(resident.handle)});
    };
    const did = try escapeHtml(allocator, resident.did);
    const cid = try escapeHtml(allocator, avatar_cid);
    return std.fmt.allocPrint(
        allocator,
        "<span class=\"avatar\"><img src=\"/xrpc/com.atproto.sync.getBlob?did={s}&cid={s}\" alt=\"\"></span>",
        .{ 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("&amp;"),
        '<' => try out.writer.writeAll("&lt;"),
        '>' => try out.writer.writeAll("&gt;"),
        '"' => try out.writer.writeAll("&quot;"),
        '\'' => try out.writer.writeAll("&#39;"),
        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;
}