From 9e66ef441b29d6ca8f8c57ddda9705e263c83a48 Mon Sep 17 00:00:00 2001 From: jaina heartles Date: Tue, 6 Dec 2022 02:53:41 -0800 Subject: [PATCH] File dereference endpoint --- src/api/lib.zig | 15 +++++++++++++++ src/main/controllers/web.zig | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/api/lib.zig b/src/api/lib.zig index 3fb10e8..58602ba 100644 --- a/src/api/lib.zig +++ b/src/api/lib.zig @@ -159,6 +159,11 @@ pub const DriveGetResult = union(services.drive.Kind) { }, }; +pub const FileResult = struct { + meta: services.files.FileUpload, + data: []const u8, +}; + pub fn isAdminSetup(db: sql.Db) !bool { _ = services.communities.adminCommunityId(db) catch |err| switch (err) { error.NotFound => return false, @@ -616,5 +621,15 @@ fn ApiConn(comptime DbConn: type) type { std.log.debug("{}", .{entry.id}); try services.files.update(self.db, entry.file_id orelse return error.NotAFile, meta, self.allocator); } + + pub fn fileDereference(self: *Self, id: Uuid) !FileResult { + const meta = try services.files.get(self.db, id, self.allocator); + errdefer util.deepFree(self.allocator, meta); + + return FileResult{ + .meta = meta, + .data = try services.files.deref(self.allocator, id), + }; + } }; } diff --git a/src/main/controllers/web.zig b/src/main/controllers/web.zig index 430e405..0d0efe8 100644 --- a/src/main/controllers/web.zig +++ b/src/main/controllers/web.zig @@ -1,4 +1,5 @@ const std = @import("std"); +const util = @import("util"); const controllers = @import("../controllers.zig"); pub const routes = .{ @@ -7,6 +8,7 @@ pub const routes = .{ controllers.apiEndpoint(login), controllers.apiEndpoint(global_timeline), controllers.apiEndpoint(cluster.overview), + controllers.apiEndpoint(media), }; const index = struct { @@ -87,3 +89,24 @@ const cluster = struct { } }; }; + +const media = struct { + pub const path = "/media/:id"; + pub const method = .GET; + + pub const Args = struct { + id: util.Uuid, + }; + + pub fn handler(req: anytype, res: anytype, srv: anytype) !void { + const result = try srv.fileDereference(req.args.id); + defer util.deepFree(srv.allocator, result); + + try res.headers.put("Content-Type", result.meta.content_type orelse "application/octet-stream"); + var stream = try res.open(.ok); + defer stream.close(); + + try stream.writer().writeAll(result.data); + try stream.finish(); + } +};