aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2025-11-17 09:57:09 +0100
committerNathan Reiner <nathan@nathanreiner.xyz>2025-11-17 09:57:09 +0100
commite95cf5c7b6a08eb560763d5167fbddc1c2117bcc (patch)
tree2f7815c9f39328fcaced2113de727f63e4837fa3
parent0016aaa197697ec5ff38dfb3f63ac8b6f74b48e0 (diff)
add file uploading and multi-threading
-rw-r--r--build.zig110
-rw-r--r--flake.nix1
-rw-r--r--src/main.zig43
-rw-r--r--src/root.zig6
-rw-r--r--src/routes/api/image/list.zig30
-rw-r--r--src/routes/api/image/load.zig14
-rw-r--r--src/routes/api/image/root.zig2
-rw-r--r--src/routes/api/image/upload.zig4
-rw-r--r--src/routes/api/session/is-valid.zig5
-rw-r--r--src/routes/handler-info.zig34
-rw-r--r--src/server.zig71
-rw-r--r--src/storage/image-manager/image.zig73
-rw-r--r--src/storage/image-manager/root.zig66
-rw-r--r--src/storage/image.zig39
-rw-r--r--src/storage/root.zig8
-rw-r--r--src/storage/session-manager/root.zig21
-rw-r--r--src/storage/user.zig9
-rw-r--r--static/api/images.js35
-rw-r--r--static/index.js48
-rw-r--r--static/pages/image-viewer/index.js4
-rw-r--r--static/widgets/upload-bar/index.css41
-rw-r--r--static/widgets/upload-bar/index.js42
22 files changed, 477 insertions, 229 deletions
diff --git a/build.zig b/build.zig
index 53ede62..366613a 100644
--- a/build.zig
+++ b/build.zig
@@ -1,156 +1,60 @@
const std = @import("std");
-// Although this function looks imperative, it does not perform the build
-// directly and instead it mutates the build graph (`b`) that will be then
-// executed by an external runner. The functions in `std.Build` implement a DSL
-// for defining build steps and express dependencies between them, allowing the
-// build runner to parallelize the build automatically (and the cache system to
-// know when a step doesn't need to be re-run).
pub fn build(b: *std.Build) void {
- // Standard target options allow the person running `zig build` to choose
- // what target to build for. Here we do not override the defaults, which
- // means any target is allowed, and the default is native. Other options
- // for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
- // Standard optimization options allow the person running `zig build` to select
- // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
- // set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
- // It's also possible to define more custom flags to toggle optional features
- // of this build script using `b.option()`. All defined flags (including
- // target and optimize options) will be listed when running `zig build --help`
- // in this directory.
- // This creates a module, which represents a collection of source files alongside
- // some compilation options, such as optimization mode and linked system libraries.
- // Zig modules are the preferred way of making Zig code available to consumers.
- // addModule defines a module that we intend to make available for importing
- // to our consumers. We must give it a name because a Zig package can expose
- // multiple modules and consumers will need to be able to specify which
- // module they want to access.
+ const opts = b.addOptions();
+
+ const disable_auth = b.option(bool, "disable-auth", "disable-authentication") orelse false;
+ opts.addOption(bool, "disable_auth", disable_auth);
+
const mod = b.addModule("memora", .{
- // The root source file is the "entry point" of this module. Users of
- // this module will only be able to access public declarations contained
- // in this file, which means that if you have declarations that you
- // intend to expose to consumers that were defined in other files part
- // of this module, you will have to make sure to re-export them from
- // the root file.
.root_source_file = b.path("src/root.zig"),
- // Later on we'll use this module as the root module of a test executable
- // which requires us to specify a target.
.target = target,
});
- // Here we define an executable. An executable needs to have a root module
- // which needs to expose a `main` function. While we could add a main function
- // to the module defined above, it's sometimes preferable to split business
- // logic and the CLI into two separate modules.
- //
- // If your goal is to create a Zig library for others to use, consider if
- // it might benefit from also exposing a CLI tool. A parser library for a
- // data serialization format could also bundle a CLI syntax checker, for example.
- //
- // If instead your goal is to create an executable, consider if users might
- // be interested in also being able to embed the core functionality of your
- // program in their own executable in order to avoid the overhead involved in
- // subprocessing your CLI tool.
- //
- // If neither case applies to you, feel free to delete the declaration you
- // don't need and to put everything under a single module.
+ mod.addOptions("config", opts);
+
const exe = b.addExecutable(.{
.name = "memora",
.root_module = b.createModule(.{
- // b.createModule defines a new module just like b.addModule but,
- // unlike b.addModule, it does not expose the module to consumers of
- // this package, which is why in this case we don't have to give it a name.
.root_source_file = b.path("src/main.zig"),
- // Target and optimization levels must be explicitly wired in when
- // defining an executable or library (in the root module), and you
- // can also hardcode a specific target for an executable or library
- // definition if desireable (e.g. firmware for embedded devices).
.target = target,
.optimize = optimize,
- // List of modules available for import in source files part of the
- // root module.
.imports = &.{
- // Here "memora" is the name you will use in your source code to
- // import this module (e.g. `@import("memora")`). The name is
- // repeated because you are allowed to rename your imports, which
- // can be extremely useful in case of collisions (which can happen
- // importing modules from different packages).
.{ .name = "memora", .module = mod },
},
}),
});
- // This declares intent for the executable to be installed into the
- // install prefix when running `zig build` (i.e. when executing the default
- // step). By default the install prefix is `zig-out/` but can be overridden
- // by passing `--prefix` or `-p`.
b.installArtifact(exe);
- // This creates a top level step. Top level steps have a name and can be
- // invoked by name when running `zig build` (e.g. `zig build run`).
- // This will evaluate the `run` step rather than the default step.
- // For a top level step to actually do something, it must depend on other
- // steps (e.g. a Run step, as we will see in a moment).
const run_step = b.step("run", "Run the app");
- // This creates a RunArtifact step in the build graph. A RunArtifact step
- // invokes an executable compiled by Zig. Steps will only be executed by the
- // runner if invoked directly by the user (in the case of top level steps)
- // or if another step depends on it, so it's up to you to define when and
- // how this Run step will be executed. In our case we want to run it when
- // the user runs `zig build run`, so we create a dependency link.
const run_cmd = b.addRunArtifact(exe);
run_step.dependOn(&run_cmd.step);
- // By making the run step depend on the default step, it will be run from the
- // installation directory rather than directly from within the cache directory.
run_cmd.step.dependOn(b.getInstallStep());
- // This allows the user to pass arguments to the application in the build
- // command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
- // Creates an executable that will run `test` blocks from the provided module.
- // Here `mod` needs to define a target, which is why earlier we made sure to
- // set the releative field.
const mod_tests = b.addTest(.{
.root_module = mod,
});
- // A run step that will run the test executable.
const run_mod_tests = b.addRunArtifact(mod_tests);
- // Creates an executable that will run `test` blocks from the executable's
- // root module. Note that test executables only test one module at a time,
- // hence why we have to create two separate ones.
const exe_tests = b.addTest(.{
.root_module = exe.root_module,
});
- // A run step that will run the second test executable.
const run_exe_tests = b.addRunArtifact(exe_tests);
- // A top level step for running all tests. dependOn can be called multiple
- // times and since the two run steps do not depend on one another, this will
- // make the two of them run in parallel.
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_mod_tests.step);
test_step.dependOn(&run_exe_tests.step);
- // Just like flags, top level steps are also listed in the `--help` menu.
- //
- // The Zig build system is entirely implemented in userland, which means
- // that it cannot hook into private compiler APIs. All compilation work
- // orchestrated by the build system will result in other Zig compiler
- // subcommands being invoked with the right flags defined. You can observe
- // these invocations when one fails (or you pass a flag to increase
- // verbosity) to validate assumptions and diagnose problems.
- //
- // Lastly, the Zig build system is relatively simple and self-contained,
- // and reading its source code will allow you to master it.
}
diff --git a/flake.nix b/flake.nix
index b0a941a..cb542ea 100644
--- a/flake.nix
+++ b/flake.nix
@@ -13,6 +13,7 @@
devShells.x86_64-linux.default = pkgs.mkShell {
packages = [
pkgs.zig
+ pkgs.libexif
];
};
};
diff --git a/src/main.zig b/src/main.zig
index 6b6838c..4ea4954 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -5,15 +5,9 @@ pub const std_options = std.Options {
.logFn = memora.log.handler,
};
-const log = std.log.scoped(.main);
-
-var net_server: std.net.Server = undefined;
-var storage: memora.Storage = undefined;
-
fn signal_handler(signo: i32) callconv(.c) void {
if (signo == std.os.linux.SIG.INT) {
- log.info("shutdown", .{});
- net_server.deinit();
+ server.deinit();
std.process.exit(0);
}
}
@@ -28,42 +22,15 @@ fn register_sigaction() void {
_ = std.os.linux.sigaction(std.os.linux.SIG.INT, &sa, null);
}
+var server = memora.Server{};
+
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == .ok);
const allocator = gpa.allocator();
- storage = try .init(allocator);
-
const address = try std.net.Address.parseIpAndPort("0.0.0.0:8080");
- net_server = try address.listen(.{ .reuse_address = true });
- defer net_server.deinit();
-
+ try server.init(address, allocator);
register_sigaction();
-
- log.info("listening on {f}", .{address});
-
- while (true) {
- const connection = net_server.accept() catch |err| {
- log.err("error: {}", .{err});
- continue;
- };
- defer connection.stream.close();
-
- var read_buf: [1024 * 8]u8 = undefined;
- var write_buf: [1024 * 8]u8 = undefined;
- var reader = connection.stream.reader(&read_buf);
- var writer = connection.stream.writer(&write_buf);
- var http_server = std.http.Server.init(reader.interface(), &writer.interface);
-
- var request = http_server.receiveHead() catch continue;
- log.info("{s} {s}", .{std.enums.tagName(std.http.Method, request.head.method) orelse "<unknown>", request.head.target});
-
- const handler_info = memora.routes.get(request.head.target);
- try handler_info.handle(
- &request,
- &storage,
- allocator
- );
- }
+ server.run(allocator);
}
diff --git a/src/root.zig b/src/root.zig
index 301664e..c5ea36e 100644
--- a/src/root.zig
+++ b/src/root.zig
@@ -1,6 +1,8 @@
-//! By convention, root.zig is the root source file when making a library.
const std = @import("std");
+
pub const log = @import("log.zig");
+
pub const routes = @import("routes/root.zig");
-pub const Storage = @import("storage/root.zig");
+pub const Server = @import("server.zig");
+pub const Storage = @import("storage/root.zig");
diff --git a/src/routes/api/image/list.zig b/src/routes/api/image/list.zig
new file mode 100644
index 0000000..ee7a648
--- /dev/null
+++ b/src/routes/api/image/list.zig
@@ -0,0 +1,30 @@
+const std = @import("std");
+const Context = @import("../../context.zig");
+const Storage = @import("../../../storage/root.zig");
+
+pub const access = .users;
+
+const ImageInfo = struct {
+ id: []const u8,
+};
+
+const Result = struct {
+ images: []ImageInfo,
+};
+
+pub fn get(ctx: *Context) !Result {
+ var images: std.ArrayList(ImageInfo) = .empty;
+
+ const images_list = ctx.storage.images.list();
+ defer images_list.deinit();
+
+ for (images_list.images) |*image| {
+ try images.append(ctx.allocator, .{
+ .id = image.id
+ });
+ }
+
+ return .{
+ .images = try images.toOwnedSlice(ctx.allocator),
+ };
+}
diff --git a/src/routes/api/image/load.zig b/src/routes/api/image/load.zig
new file mode 100644
index 0000000..1bafb11
--- /dev/null
+++ b/src/routes/api/image/load.zig
@@ -0,0 +1,14 @@
+const std = @import("std");
+const Context = @import("../../context.zig");
+const Storage = @import("../../../storage/root.zig");
+
+pub const access = .users;
+
+pub fn get(ctx: *Context) ![]const u8 {
+ const id = ctx.request.head.target["/api/image/load/".len..];
+ var image = Storage.Image { .id = id };
+ var file = try image.file(ctx.storage);
+ defer file.close();
+
+ return try file.readToEndAlloc(ctx.allocator, std.math.maxInt(usize));
+}
diff --git a/src/routes/api/image/root.zig b/src/routes/api/image/root.zig
index 0ad1960..dafa090 100644
--- a/src/routes/api/image/root.zig
+++ b/src/routes/api/image/root.zig
@@ -1,3 +1,5 @@
const HandlerInfo = @import("../../handler-info.zig");
pub const upload: HandlerInfo = .from_type(@import("upload.zig"));
+pub const list: HandlerInfo = .from_type(@import("list.zig"));
+pub const load: HandlerInfo = .from_type(@import("load.zig"));
diff --git a/src/routes/api/image/upload.zig b/src/routes/api/image/upload.zig
index 7cd5cf1..3aa2ea6 100644
--- a/src/routes/api/image/upload.zig
+++ b/src/routes/api/image/upload.zig
@@ -4,12 +4,12 @@ const Storage = @import("../../../storage/root.zig");
const log = std.log.scoped(.image_upload);
-pub const access = .everyone;
+pub const access = .users;
pub fn post(ctx: *Context) !void {
if (ctx.request.head.content_length) |length| {
var buffer: [1024]u8 = undefined;
const reader = try ctx.request.readerExpectContinue(&buffer);
- try Storage.Image.new(ctx.storage, reader, length);
+ try ctx.storage.images.add(ctx.storage, reader, length);
}
}
diff --git a/src/routes/api/session/is-valid.zig b/src/routes/api/session/is-valid.zig
index 0c26040..4ea4f1a 100644
--- a/src/routes/api/session/is-valid.zig
+++ b/src/routes/api/session/is-valid.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const config = @import("config");
const Context = @import("../../context.zig");
pub const access = .everyone;
@@ -8,6 +9,10 @@ const Result = struct {
};
pub fn get(ctx: *Context) !Result {
+ if (comptime config.disable_auth) {
+ return .{ .is_valid = true };
+ }
+
return .{
.is_valid = ctx.storage.sessions.get(ctx.storage, ctx.fingerprint) != null
};
diff --git a/src/routes/handler-info.zig b/src/routes/handler-info.zig
index 7b744d2..94d0491 100644
--- a/src/routes/handler-info.zig
+++ b/src/routes/handler-info.zig
@@ -2,6 +2,8 @@ const std = @import("std");
const Context = @import("context.zig");
const Storage = @import("../storage/root.zig");
+const config = @import("config");
+
const Access = @import("access.zig").Access;
const log = std.log.scoped(.handler_info);
@@ -71,22 +73,24 @@ pub fn handle(
.fingerprint = get_fingerprint(cookie),
};
- const allowed = switch (self.access) {
- .everyone => true,
- .users => storage.sessions.get(storage, context.fingerprint) != null,
- .admins => admin: {
- if (storage.sessions.get(storage, context.fingerprint)) |session| {
- break :admin session.info.is_admin;
- }
- break :admin false;
- },
- };
+ if (!comptime config.disable_auth) {
+ const allowed = switch (self.access) {
+ .everyone => true,
+ .users => storage.sessions.get(storage, context.fingerprint) != null,
+ .admins => admin: {
+ if (storage.sessions.get(storage, context.fingerprint)) |session| {
+ break :admin session.info.is_admin;
+ }
+ break :admin false;
+ },
+ };
- if (!allowed) {
- return request.respond(
- "{ \"error\": \"Forbidden\" }",
- .{ .status = .forbidden }
- );
+ if (!allowed) {
+ return request.respond(
+ "{ \"error\": \"Forbidden\" }",
+ .{ .status = .forbidden }
+ );
+ }
}
const response = handler(&context) catch |err| {
diff --git a/src/server.zig b/src/server.zig
new file mode 100644
index 0000000..184af92
--- /dev/null
+++ b/src/server.zig
@@ -0,0 +1,71 @@
+const std = @import("std");
+const log = std.log.scoped(.server);
+
+const routes = @import("routes/root.zig");
+const Storage = @import("storage/root.zig");
+const config = @import("config");
+
+const Self = @This();
+
+storage: Storage = undefined,
+net_server: std.net.Server = undefined,
+pool: std.Thread.Pool = undefined,
+
+pub fn init(
+ self: *Self,
+ address: std.net.Address,
+ allocator: std.mem.Allocator,
+) !void {
+ self.storage = try .init(allocator);
+ self.net_server = try address.listen(.{ .reuse_address = true });
+ try self.pool.init(.{ .allocator = allocator });
+ log.info("listing on {f}", .{address});
+
+ if (comptime config.disable_auth) {
+ log.warn("authentication is disabled", .{});
+ }
+}
+
+pub fn run(self: *Self, allocator: std.mem.Allocator) void {
+ while (true) {
+ const connection = self.net_server.accept() catch |err| {
+ log.err("error: {}", .{err});
+ continue;
+ };
+
+ self.pool.spawn(handle_connection, .{self, allocator, connection}) catch |err| {
+ std.log.err("failed to spawn thread: {}", .{err});
+ };
+ }
+}
+
+fn handle_connection(
+ self: *Self,
+ allocator: std.mem.Allocator,
+ connection: std.net.Server.Connection,
+) void {
+ defer connection.stream.close();
+
+ var read_buf: [1024 * 8]u8 = undefined;
+ var write_buf: [1024 * 8]u8 = undefined;
+ var reader = connection.stream.reader(&read_buf);
+ var writer = connection.stream.writer(&write_buf);
+ var http_server = std.http.Server.init(reader.interface(), &writer.interface);
+
+ var request = http_server.receiveHead() catch return;
+ log.info("{s} {s}", .{
+ std.enums.tagName(std.http.Method, request.head.method) orelse "<unknown>",
+ request.head.target,
+ });
+
+ const handler_info = routes.get(request.head.target);
+ handler_info.handle(&request, &self.storage, allocator) catch |err| {
+ std.log.err("{}", .{err});
+ };
+}
+
+pub fn deinit(self: *Self) void {
+ log.info("shutdown", .{});
+ self.net_server.deinit();
+ self.storage.deinit();
+}
diff --git a/src/storage/image-manager/image.zig b/src/storage/image-manager/image.zig
new file mode 100644
index 0000000..91a094e
--- /dev/null
+++ b/src/storage/image-manager/image.zig
@@ -0,0 +1,73 @@
+const std = @import("std");
+const Storage = @import("../root.zig");
+
+const id_size = 32;
+
+const log = std.log.scoped(.image);
+
+fn new_id() [id_size]u8 {
+ var buffer: [id_size]u8 = undefined;
+ var raw_buffer: [id_size / 2]u8 = undefined;
+ std.crypto.random.bytes(&raw_buffer);
+
+ var writer = std.Io.Writer.fixed(buffer[0..]);
+ writer.print("{x}", .{raw_buffer}) catch unreachable;
+
+ return buffer[0..].*;
+}
+
+const Self = @This();
+
+id: []const u8,
+
+pub fn new(
+ storage: *Storage,
+ reader: *std.Io.Reader,
+ size: usize,
+) !Self {
+ var dir = try storage.dir.openDir("image", .{});
+ defer dir.close();
+
+ var file_name: [id_size+4]u8 = undefined;
+ const self: Self = .{ .id = &new_id() };
+ @memcpy(file_name[0..id_size], self.id);
+ @memcpy(file_name[id_size..], ".jpg");
+
+ var image_file = try dir.createFile(&file_name, .{});
+ defer image_file.close();
+
+ var buffer: [1024]u8 = undefined;
+ var file_writer = image_file.writer(&buffer);
+
+ try reader.streamExact(&file_writer.interface, size);
+
+ try file_writer.interface.flush();
+
+ log.info("uploaded {s} [{} bytes]", .{self.id, size});
+
+ return self;
+}
+
+pub fn init(allocator: std.mem.Allocator, id: []const u8) !Self {
+ return .{
+ .id = try allocator.dupe(u8, id),
+ };
+}
+
+pub fn file(self: *Self, storage: *Storage) !std.fs.File {
+ var dir = storage.dir.openDir("image", .{}) catch blk: {
+ try storage.dir.makeDir("image");
+ break :blk try storage.dir.openDir("image", .{});
+ };
+ defer dir.close();
+
+ var file_name: [id_size+4]u8 = undefined;
+ @memcpy(file_name[0..id_size], self.id);
+ @memcpy(file_name[id_size..], ".jpg");
+
+ return dir.openFile(&file_name, .{});
+}
+
+pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
+ allocator.free(self.id);
+}
diff --git a/src/storage/image-manager/root.zig b/src/storage/image-manager/root.zig
new file mode 100644
index 0000000..7742df2
--- /dev/null
+++ b/src/storage/image-manager/root.zig
@@ -0,0 +1,66 @@
+const std = @import("std");
+
+const Storage = @import("../root.zig");
+pub const Image = @import("image.zig");
+
+const Self = @This();
+
+pub const empty: Self = .{};
+
+items: std.ArrayList(Image) = .empty,
+rw_lock: std.Thread.RwLock = .{},
+
+pub const LockedImages = struct {
+ images: []Image,
+ rw_lock: *std.Thread.RwLock,
+
+ pub fn deinit(self: *const @This()) void {
+ self.rw_lock.unlockShared();
+ }
+};
+
+pub fn init(
+ self: *Self,
+ storage: *Storage,
+) !void {
+ var dir = storage.dir.openDir("image", .{ .iterate = true }) catch blk: {
+ try storage.dir.makeDir("image");
+ break :blk try storage.dir.openDir("image", .{ .iterate = true });
+ };
+ defer dir.close();
+
+ var iterator = dir.iterate();
+
+ errdefer self.items.deinit(storage.allocator);
+
+ while (try iterator.next()) |entry| {
+ if (entry.kind == .file and std.mem.endsWith(u8, entry.name, ".jpg")) {
+ try self.items.append(
+ storage.allocator,
+ try .init(storage.allocator, entry.name[0..entry.name.len - 4])
+ );
+ }
+ }
+}
+
+pub fn add(
+ self: *Self,
+ storage: *Storage,
+ reader: *std.Io.Reader,
+ size: usize,
+) !void {
+ self.rw_lock.lock();
+ defer self.rw_lock.unlock();
+
+ try self.items.append(
+ storage.allocator,
+ try Image.new(storage, reader, size),
+ );
+}
+
+pub fn list(self: *Self) LockedImages {
+ return .{
+ .images = self.items.items,
+ .rw_lock = &self.rw_lock,
+ };
+}
diff --git a/src/storage/image.zig b/src/storage/image.zig
deleted file mode 100644
index 73bca84..0000000
--- a/src/storage/image.zig
+++ /dev/null
@@ -1,39 +0,0 @@
-const std = @import("std");
-const Storage = @import("root.zig");
-
-const id_size = 32;
-
-fn new_id() [id_size]u8 {
- var buffer: [id_size]u8 = undefined;
- var raw_buffer: [id_size / 2]u8 = undefined;
- std.crypto.random.bytes(&raw_buffer);
-
- var writer = std.Io.Writer.fixed(buffer[0..]);
- writer.print("{x}", .{raw_buffer}) catch unreachable;
-
- return buffer[0..].*;
-}
-
-pub fn new(
- storage: *Storage,
- reader: *std.Io.Reader,
- size: usize,
-) !void {
- var dir = storage.dir.openDir("image", .{}) catch blk: {
- try storage.dir.makeDir("image");
- break :blk try storage.dir.openDir("image", .{});
- };
- defer dir.close();
-
- var file_name: [id_size+4]u8 = undefined;
- @memcpy(file_name[0..id_size], &new_id());
- @memcpy(file_name[id_size..], ".jpg");
-
- var file = try dir.createFile(&file_name, .{});
- defer file.close();
-
- var buffer: [1024]u8 = undefined;
- var file_writer = file.writer(&buffer);
-
- try reader.streamExact(&file_writer.interface, size);
-}
diff --git a/src/storage/root.zig b/src/storage/root.zig
index c121ca9..381dc45 100644
--- a/src/storage/root.zig
+++ b/src/storage/root.zig
@@ -3,7 +3,10 @@ const config = @import("../config.zig");
const prompt = @import("../prompt.zig");
pub const User = @import("user.zig");
-pub const Image = @import("image.zig");
+
+pub const ImageManager = @import("image-manager/root.zig");
+pub const Image = ImageManager.Image;
+
pub const SessionManager = @import("session-manager/root.zig");
pub const Session = SessionManager.Session;
@@ -11,6 +14,7 @@ const Self = @This();
dir: std.fs.Dir,
sessions: SessionManager = .empty,
+images: ImageManager = .empty,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) !Self {
@@ -56,6 +60,8 @@ pub fn init(allocator: std.mem.Allocator) !Self {
else => return err,
};
+ try self.images.init(&self);
+
return self;
}
diff --git a/src/storage/session-manager/root.zig b/src/storage/session-manager/root.zig
index 7f44bf0..d0e1441 100644
--- a/src/storage/session-manager/root.zig
+++ b/src/storage/session-manager/root.zig
@@ -11,8 +11,12 @@ pub const empty: Self = .{
};
cache: std.StringHashMapUnmanaged(Session),
+rw_lock: std.Thread.RwLock = .{},
pub fn add(self: *Self, storage: *Storage, info: Storage.User.Info) !*Session {
+ self.rw_lock.lock();
+ defer self.rw_lock.unlock();
+
const session = try Session.init(storage.allocator, info);
errdefer session.deinit(storage.allocator);
try self.cache.put(storage.allocator, session.fingerprint, session);
@@ -20,7 +24,12 @@ pub fn add(self: *Self, storage: *Storage, info: Storage.User.Info) !*Session {
}
pub fn renew(self: *Self, storage: *Storage, fingerprint: []const u8) !*Session {
+ self.rw_lock.lockShared();
if (self.cache.get(fingerprint)) |s| {
+ self.rw_lock.unlockShared();
+ self.rw_lock.lock();
+ defer self.rw_lock.unlock();
+
var session = s;
try session.reset();
@@ -29,24 +38,34 @@ pub fn renew(self: *Self, storage: *Storage, fingerprint: []const u8) !*Session
_ = self.cache.remove(fingerprint);
return self.cache.getPtr(session.fingerprint) orelse unreachable;
+ } else {
+ self.rw_lock.unlockShared();
}
return error.SessionNotFound;
}
pub fn remove(self: *Self, storage: *Storage, fingerprint: []const u8) void {
+ self.rw_lock.lockShared();
if (self.cache.getPtr(fingerprint)) |session| {
+ self.rw_lock.unlockShared();
+ self.rw_lock.lock();
+ defer self.rw_lock.unlock();
+
session.deinit(storage.allocator);
_ = self.cache.remove(fingerprint);
+ } else {
+ self.rw_lock.unlockShared();
}
}
pub fn get(self: *Self, storage: *Storage, fingerprint: []const u8) ?*Session {
+ self.rw_lock.lockShared();
+ defer self.rw_lock.unlockShared();
if (self.cache.getPtr(fingerprint)) |session| {
const now = std.time.Instant.now() catch return null;
const since = now.since(session.age);
if (since > config.session_expires_after) {
- std.debug.print("here\n", .{});
session.deinit(storage.allocator);
_ = self.cache.remove(fingerprint);
return null;
diff --git a/src/storage/user.zig b/src/storage/user.zig
index 4170fd1..d5260fe 100644
--- a/src/storage/user.zig
+++ b/src/storage/user.zig
@@ -58,7 +58,7 @@ pub fn open(
var dir = try user_dir.openDir(name, .{});
errdefer dir.close();
- const file = try dir.openFile("info.json", .{});
+ const file = try dir.openFile("info.json", .{ .lock = .shared });
defer file.close();
const content = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
@@ -91,7 +91,7 @@ pub fn new(
var dir = try user_dir.openDir(name, .{});
errdefer dir.close();
- var file = try dir.createFile("info.json", .{});
+ var file = try dir.createFile("info.json", .{ .lock = .exclusive });
file.close();
const hash_buf = try allocator.alloc(u8, 256);
@@ -124,7 +124,10 @@ pub fn new(
}
pub fn sync(self: *Self) !void {
- const file = try self.dir.openFile("info.json", .{ .mode = .write_only });
+ const file = try self.dir.openFile("info.json", .{
+ .mode = .write_only,
+ .lock = .exclusive,
+ });
defer file.close();
var buffer: [1024]u8 = undefined;
diff --git a/static/api/images.js b/static/api/images.js
index 4a41a3c..4bdac1f 100644
--- a/static/api/images.js
+++ b/static/api/images.js
@@ -1,31 +1,29 @@
import * as sfw from 'sfw';
const { Input } = sfw.element.native;
+import * as rest from './rest.js';
class FileUploader {
- constructor(url) {
+ constructor(url, files) {
this.onprogress = () => {}
this.ondone = () => {}
this.url = url;
this.sessions = [];
+ this.files = files;
}
- send(...files) {
+ send() {
let count = 0;
- this.sessions = this.sessions.concat(files.map(
- file => new Promise((resolve) => {
+ this.sessions = this.sessions.concat(this.files.map(
+ (file) => new Promise((resolve) => {
const xhr = new XMLHttpRequest();
- xhr.upload.addEventListener("progress", (event) => {
- if (event.lengthComputable) {
- this.onprogress(file, event.loaded, event.total)
- }
- });
-
- xhr.addEventListener("loadend", () => {
+ xhr.addEventListener("loadend", (event) => {
count += 1;
+ this.onprogress(count, this.files.length)
+
resolve(xhr.readyState === 4 && xhr.status === 200);
- if (count == files.length) {
+ if (count == this.files.length) {
this.ondone();
}
});
@@ -46,11 +44,12 @@ export async function upload_to_timeline() {
})
input.click();
- const uploader = new FileUploader('/api/image/upload');
- input.onchange = async () => {
- uploader.send(...input.files);
- }
+ return new Promise((resolve) => {
+ input.onchange = () => {
+ resolve(new FileUploader('/api/image/upload', [...input.files]));
+ }
+ })
}
export async function upload_to_profile() {
@@ -61,3 +60,7 @@ export async function upload_to_profile() {
})
input.click();
}
+
+export function list() {
+ return rest.get('/api/image/list').then(r => r.images);
+}
diff --git a/static/index.js b/static/index.js
index 90b5ffd..2fcca88 100644
--- a/static/index.js
+++ b/static/index.js
@@ -11,14 +11,25 @@ import Search from './widgets/search/index.js';
import MonthSelect from './widgets/month-select/index.js';
import SettingsView from './pages/settings/index.js';
import ShuffleView from './pages/shuffle/index.js';
+import UploadBar from './widgets/upload-bar/index.js';
sfw.theme.add_css(await sfw.css(import.meta.url, './index.css'));
const image_viewer = ImageViewer.new();
+const reload = () => {
+ image_viewer.clear();
+ api.images.list().then(images => {
+ for (const image of images) {
+ image_viewer.add(`/api/image/load/${image.id}`);
+ }
+ });
+}
+
const login = LoginView.new({
onlogin: async (user, password) => {
if (await api.auth.login(user, password)) {
+ reload();
login.hide();
} else {
login.comment = 'Incorrect username or password.';
@@ -38,10 +49,13 @@ const search = Search.new({
onsubmit: (content) => console.log(content),
onhide: () => main.show(),
});
+
const month_select = MonthSelect.new({
months: m`2019-08`.to(m`2025-11`),
});
+const upload_bar = UploadBar.new();
+
const settings = SettingsView.new({
onlogout: () => {
login.show();
@@ -49,8 +63,7 @@ const settings = SettingsView.new({
},
});
-const shuffle = ShuffleView.new({
-});
+const shuffle = ShuffleView.new({ });
const main = MainView.new({
active_view: image_viewer,
@@ -66,7 +79,23 @@ const main = MainView.new({
main.active_view = image_viewer;
month_select.show();
},
- onupload: () => api.images.upload_to_timeline(),
+ onupload: async () => {
+ const uploader = await api.images.upload_to_timeline();
+
+ upload_bar.progress = 0;
+ upload_bar.show();
+
+ uploader.onprogress = (count, total) => {
+ upload_bar.progress = count / total;
+ }
+
+ uploader.ondone = () => {
+ upload_bar.hide();
+ reload();
+ }
+
+ uploader.send();
+ },
onshuffle: () => {
main.active_kind = MainView.Kind.home;
main.active_view = shuffle;
@@ -86,12 +115,13 @@ document.body.append(
main,
search,
month_select,
+ upload_bar,
);
-login.hide();
-//if (await api.session.is_valid()) {
-// login.hide();
-//} else {
-// login.focus();
-//}
+if (await api.session.is_valid()) {
+ login.hide();
+ reload();
+} else {
+ login.focus();
+}
diff --git a/static/pages/image-viewer/index.js b/static/pages/image-viewer/index.js
index 76d720f..f65c12b 100644
--- a/static/pages/image-viewer/index.js
+++ b/static/pages/image-viewer/index.js
@@ -17,4 +17,8 @@ export default class ImageViewer extends sfw.element.Container {
add(url) {
this.#container.append(Img.new({ src: url }));
}
+
+ clear() {
+ this.#container.innerHTML = '';
+ }
}
diff --git a/static/widgets/upload-bar/index.css b/static/widgets/upload-bar/index.css
new file mode 100644
index 0000000..8ec1697
--- /dev/null
+++ b/static/widgets/upload-bar/index.css
@@ -0,0 +1,41 @@
+
+#container {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: calc(100% - 10px);
+ height: 100px;
+ background: #efefef99;
+ backdrop-filter: blur(10px);
+ border-radius: var(--border-radius);
+ max-width: 500px;
+ padding: 10px 20px;
+ display: grid;
+}
+
+#files {
+ background: #efefef;
+ padding: 10px;
+ border-radius: 20px;
+ margin: auto;
+ width: min-content;
+ white-space: nowrap;
+}
+
+#inner-progress {
+ width: 100%;
+ height: 5px;
+ border-radius: 5px;
+ background: #efefef;
+ overflow: hidden;
+ margin: auto;
+}
+
+
+#progress {
+ background: var(--primary);
+ height: 100%;
+ border-radius: 5px;
+ transition: width 0.2s ease;
+}
diff --git a/static/widgets/upload-bar/index.js b/static/widgets/upload-bar/index.js
new file mode 100644
index 0000000..a9e0220
--- /dev/null
+++ b/static/widgets/upload-bar/index.js
@@ -0,0 +1,42 @@
+import * as sfw from 'sfw';
+const { Div } = sfw.element.native;
+
+const css = await sfw.css(import.meta.url, './index.css')
+
+export default class UploadBar extends sfw.element.Container {
+ #files_progress
+ #inner_progress
+ #container
+
+ constructor() {
+ super({ css });
+
+ this.body.append(
+ this.#container = Div.new({
+ id: 'container',
+ style: { display: 'none' },
+ children: [
+ this.#files_progress = Div.new({ id: 'files', innerText: 'Uploading...' }),
+ Div.new({
+ id: 'inner-progress',
+ children: [
+ this.#inner_progress = Div.new({ id: 'progress' }),
+ ]
+ })
+ ]
+ })
+ );
+ }
+
+ set progress(progress) {
+ this.#inner_progress.style.width = `${progress * 100}%`
+ }
+
+ hide() {
+ this.#container.style.display = 'none';
+ }
+
+ show() {
+ this.#container.style.display = '';
+ }
+}