diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-05-20 10:16:50 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-05-20 10:16:50 +0200 |
| commit | 44445734ba4a0f05564f808c2fd34a7f23c6fafb (patch) | |
| tree | 3bd22add718620cbf931286f55137bcc666100be /src/storage | |
| parent | 95ae9f15e1db335a7f8358d811ea37e2c89dd10f (diff) | |
Let's do a rewrite!
Created project structure and changed `build.zig` and added licence.
Diffstat (limited to 'src/storage')
| -rw-r--r-- | src/storage/image-manager/exif.zig | 57 | ||||
| -rw-r--r-- | src/storage/image-manager/image.zig | 110 | ||||
| -rw-r--r-- | src/storage/image-manager/root.zig | 138 | ||||
| -rw-r--r-- | src/storage/media-manager/root.zig | 0 | ||||
| -rw-r--r-- | src/storage/root.zig | 79 | ||||
| -rw-r--r-- | src/storage/session-manager/root.zig | 78 | ||||
| -rw-r--r-- | src/storage/session-manager/session.zig | 34 | ||||
| -rw-r--r-- | src/storage/user.zig | 234 |
8 files changed, 0 insertions, 730 deletions
diff --git a/src/storage/image-manager/exif.zig b/src/storage/image-manager/exif.zig deleted file mode 100644 index 88e9b48..0000000 --- a/src/storage/image-manager/exif.zig +++ /dev/null @@ -1,57 +0,0 @@ -const std = @import("std"); -const exif = @cImport(@cInclude("libexif/exif-data.h")); -const cstd = @cImport(@cInclude("time.h")); - -const tags = [_]c_uint { - exif.EXIF_TAG_DATE_TIME, - exif.EXIF_TAG_DATE_TIME_ORIGINAL, - exif.EXIF_TAG_DATE_TIME_DIGITIZED, -}; - -pub fn get_date_time(path: [*:0]const u8) ?i64 { - const exif_data = exif.exif_data_new_from_file(path); - defer exif.exif_data_unref(exif_data); - - if (exif_data == 0) { - return null; - } - - var entry: ?[*c]exif.struct__ExifEntry = null; - for (0..exif.EXIF_IFD_COUNT) |index| { - for (tags) |tag| { - entry = exif.exif_content_get_entry((exif_data.*).ifd[index], tag); - - if (entry) |_| { break; } - } - - if (entry) |_| { break; } - } - - if (entry == 0) { - return null; - } - - if (entry) |e| { - const c_data = (e.*).data; - return parse_date(c_data); - } - - return null; -} - -extern fn strptime( - s: [*c]const u8, - format: [*c]const u8, - tm: *cstd.tm, -) ?*const u8; - -extern fn mktime(tm: *cstd.tm) i64; - -fn parse_date(date: [*:0]const u8) ?i64 { - var tm: cstd.tm = std.mem.zeroes(cstd.tm); - if (strptime(date, "%Y:%m:%d %H:%M:%S", &tm)) |_| { - return mktime(&tm); - } - - return null; -} diff --git a/src/storage/image-manager/image.zig b/src/storage/image-manager/image.zig deleted file mode 100644 index bdac5c7..0000000 --- a/src/storage/image-manager/image.zig +++ /dev/null @@ -1,110 +0,0 @@ -const std = @import("std"); -const Storage = @import("../root.zig"); - -const exif = @import("exif.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, -timestamp: ?i64, - -pub fn new( - storage: *Storage, - reader: *std.Io.Reader, - size: usize, -) !Self { - var dir = try storage.dir.openDir("image", .{}); - defer dir.close(); - - var self: Self = undefined; - - self.id = try storage.allocator.dupe(u8, &new_id()); - - var file_name: [id_size + 4]u8 = undefined; - @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 }); - - self.timestamp = try load_timestamp(storage, self.id); - - return self; -} - -pub fn delete(self: *Self, storage: *Storage) !void { - var dir = 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"); - - try dir.deleteFile(&file_name); -} - -pub fn init(storage: *Storage, id: []const u8) !Self { - return .{ - .id = try storage.allocator.dupe(u8, id), - .timestamp = try load_timestamp(storage, 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); -} - -fn load_timestamp(storage: *Storage, id: []const u8) !?i64 { - 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], id); - @memcpy(file_name[id_size..], ".jpg"); - - var path_buffer: [std.fs.max_path_bytes:0]u8 = std.mem.zeroes([std.fs.max_path_bytes:0]u8); - const path = try dir.realpath(&file_name, &path_buffer); - - return exif.get_date_time(@ptrCast(path)); -} diff --git a/src/storage/image-manager/root.zig b/src/storage/image-manager/root.zig deleted file mode 100644 index efc216f..0000000 --- a/src/storage/image-manager/root.zig +++ /dev/null @@ -1,138 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Storage = memora.Storage; -pub const Image = @import("image.zig"); - -const Self = @This(); - -pub const empty: Self = .{}; - -const Timestamp = struct { - index: usize, - node: std.DoublyLinkedList.Node, - - pub fn next(self: *Timestamp) ?*Timestamp { - return @fieldParentPtr("node", self.node.next orelse return null); - } - - pub fn prev(self: *Timestamp) ?*Timestamp { - return @fieldParentPtr("node", self.node.prev orelse return null); - } -}; - -items: std.ArrayList(Image) = .empty, -rw_lock: std.Thread.RwLock = .{}, -timestamp_order: std.DoublyLinkedList = .{}, - -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.add( - storage.allocator, - try .init(storage, entry.name[0..entry.name.len - 4]) - ); - } - } -} - -pub fn add(self: *Self, allocator: std.mem.Allocator, image: Image) !void { - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - try self.items.append( - allocator, - image, - ); - - var current = self.timestamp_order.first; - - while (current) |c| { - const index = @as(*Timestamp, @fieldParentPtr("node", c)).index; - if (image.timestamp orelse 0 > self.items.items[index].timestamp orelse 0) { - const timestamp = try allocator.create(Timestamp); - timestamp.index = self.items.items.len - 1; - self.timestamp_order.insertBefore(c, ×tamp.node); - return; - } - - current = c.next; - } - - const timestamp = try allocator.create(Timestamp); - timestamp.index = self.items.items.len - 1; - self.timestamp_order.append(×tamp.node); - return; -} - -pub fn save( - self: *Self, - storage: *Storage, - reader: *std.Io.Reader, - size: usize, -) !void { - return self.add(storage.allocator, try Image.new(storage, reader, size)); -} - -pub fn list(self: *Self) memora.locked.Shared([]Image) { - self.rw_lock.lockShared(); - return .{ - .value = self.items.items, - .rw_lock = &self.rw_lock, - }; -} - -pub fn first_by_timestamp(self: *Self) memora.locked.Shared(?*Timestamp) { - self.rw_lock.lockShared(); - return .{ - .value = if (self.timestamp_order.first) |first| @fieldParentPtr("node", first) - else null, - .rw_lock = &self.rw_lock, - }; -} - -pub fn delete(self: *Self, storage: *Storage, id: []const u8) !void { - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - const index = index: { - for (self.items.items, 0..) |image, index| { - if (std.mem.eql(u8, image.id, id)) { - break :index index; - } - } - break :index null; - }; - - if (index) |idx| { - try self.items.items[idx].delete(storage); - const old_index = self.items.items.len - 1; - _ = self.items.swapRemove(idx); - - var current: ?*Timestamp = if (self.timestamp_order.first) |c| @fieldParentPtr("node", c) else null; - - while (current) |c| { - if (c.index == idx) { - self.timestamp_order.remove(&c.node); - storage.allocator.destroy(c); - } else if (c.index == old_index) { - c.index = idx; - } - - current = c.next(); - } - } -} diff --git a/src/storage/media-manager/root.zig b/src/storage/media-manager/root.zig deleted file mode 100644 index e69de29..0000000 --- a/src/storage/media-manager/root.zig +++ /dev/null diff --git a/src/storage/root.zig b/src/storage/root.zig deleted file mode 100644 index f11798b..0000000 --- a/src/storage/root.zig +++ /dev/null @@ -1,79 +0,0 @@ -const std = @import("std"); -const prompt = @import("../prompt.zig"); -const Config = @import("../config.zig"); - -pub const User = @import("user.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; - -const Self = @This(); - -dir: std.fs.Dir, -sessions: SessionManager = .empty, -images: ImageManager = .empty, -config: Config, -allocator: std.mem.Allocator, - -pub fn init( - allocator: std.mem.Allocator, -) !Self { - var config = try Config.load(allocator); - errdefer config.deinit(); - - const dir = std.fs.cwd().openDir(config.storage_path, .{}) catch blk: { - try std.fs.cwd().makeDir(config.storage_path); - break :blk try std.fs.cwd().openDir(config.storage_path, .{}); - }; - - var self = Self { - .config = config, - .dir = dir, - .allocator = allocator, - }; - - dir.access("user", .{}) catch |err| switch (err) { - error.FileNotFound => { - const name = try prompt.read("Username", allocator); - defer allocator.free(name); - - const full_name = try prompt.read("Full Name", allocator); - defer allocator.free(full_name); - - const birthday = try prompt.read("Birthday", allocator); - defer allocator.free(birthday); - - const password = try prompt.read("Password", allocator); - defer allocator.free(password); - - try self.dir.makeDir("user"); - - var user: User = try .new( - &self, - name, - full_name, - birthday, - password, - true, - allocator, - ); - defer user.deinit(); - - try user.sync(); - }, - else => return err, - }; - - try self.images.init(&self); - - return self; -} - -pub fn deinit(self: *Self) void { - self.dir.close(); - self.config.deinit(); - self.* = undefined; -} diff --git a/src/storage/session-manager/root.zig b/src/storage/session-manager/root.zig deleted file mode 100644 index db95629..0000000 --- a/src/storage/session-manager/root.zig +++ /dev/null @@ -1,78 +0,0 @@ -const std = @import("std"); -const config = @import("../../config.zig"); -const Storage = @import("../root.zig"); - -pub const Session = @import("session.zig"); - -const Self = @This(); - -pub const empty: Self = .{ - .cache = .empty, -}; - -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); - return self.cache.getPtr(session.fingerprint) orelse unreachable; -} - -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(); - - try self.cache.put(storage.allocator, session.fingerprint, 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.contains(fingerprint)) { - self.rw_lock.unlockShared(); - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - const kv = self.cache.fetchRemove(fingerprint) orelse return; - kv.value.deinit(storage.allocator); - } 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 > storage.config.session_expires_after) { - session.deinit(storage.allocator); - _ = self.cache.remove(fingerprint); - return null; - } - - return session; - } - - return null; -} diff --git a/src/storage/session-manager/session.zig b/src/storage/session-manager/session.zig deleted file mode 100644 index 943334b..0000000 --- a/src/storage/session-manager/session.zig +++ /dev/null @@ -1,34 +0,0 @@ -const std = @import("std"); -const User = @import("../user.zig"); - -const Self = @This(); - -const fingerprint_size = 512; - -age: std.time.Instant, -info: User.Info, -fingerprint: []u8, - -pub fn init(allocator: std.mem.Allocator, info: User.Info) !Self { - var self: Self = undefined; - self.info = try info.clone(allocator); - self.fingerprint = try allocator.alloc(u8, fingerprint_size); - try self.reset(); - - return self; -} - -pub fn reset(self: *Self) !void { - var raw_buffer: [fingerprint_size / 2]u8 = undefined; - std.crypto.random.bytes(&raw_buffer); - - var writer = std.Io.Writer.fixed(self.fingerprint); - writer.print("{x}", .{raw_buffer}) catch unreachable; - - self.age = try std.time.Instant.now(); -} - -pub fn deinit(self: *const Self, allocator: std.mem.Allocator) void { - self.info.deinit(allocator); - allocator.free(self.fingerprint); -} diff --git a/src/storage/user.zig b/src/storage/user.zig deleted file mode 100644 index c2cc82a..0000000 --- a/src/storage/user.zig +++ /dev/null @@ -1,234 +0,0 @@ -const std = @import("std"); -const Storage = @import("root.zig"); - -const log = std.log.scoped(.user); - -const Self = @This(); - -pub const Info = struct { - name: []const u8, - full_name: []const u8, - birthday: []const u8, - hash: []const u8, - is_admin: bool, - - pub fn clone(self: *const @This(), allocator: std.mem.Allocator) !@This() { - var clone_self: @This() = undefined; - var i: usize = 0; - - inline for (std.meta.fields(@This())) |field_info| { - if (field_info.type == []const u8) { - @field(clone_self, field_info.name) = try allocator.dupe( - u8, - @field(self, field_info.name), - ); - errdefer allocator.free(@field(clone_self, field_info.name)); - } else { - @field(clone_self, field_info.name) = @field(self, field_info.name); - } - i += 1; - } - - return clone_self; - } - - pub fn deinit(self: *const @This(), allocator: std.mem.Allocator) void { - inline for (std.meta.fields(@This())) |field_info| { - if (field_info.type == []const u8) { - allocator.free(@field(self, field_info.name)); - } - } - } -}; - -dir: std.fs.Dir, -info: Info, -arena: std.heap.ArenaAllocator, - -pub fn open( - storage: *Storage, - name: []const u8, -) !Self { - var arena: std.heap.ArenaAllocator = .init(storage.allocator); - errdefer arena.deinit(); - const allocator = arena.allocator(); - - var user_dir = try storage.dir.openDir("user", .{}); - defer user_dir.close(); - - var dir = try user_dir.openDir(name, .{}); - errdefer dir.close(); - - const file = try dir.openFile("info.json", .{ .lock = .shared }); - defer file.close(); - const content = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); - - const info = try std.json.parseFromSliceLeaky(Info, allocator, content, .{}); - - return .{ - .dir = dir, - .arena = arena, - .info = info, - }; -} - -pub fn new( - storage: *Storage, - name: []const u8, - full_name: []const u8, - birthday: []const u8, - password: []const u8, - is_admin: bool, - inner_allocator: std.mem.Allocator -) !Self { - var arena: std.heap.ArenaAllocator = .init(inner_allocator); - const allocator = arena.allocator(); - errdefer arena.deinit(); - - var user_dir = try storage.dir.openDir("user", .{}); - defer user_dir.close(); - - try user_dir.makeDir(name); - var dir = try user_dir.openDir(name, .{}); - errdefer dir.close(); - - var file = try dir.createFile("info.json", .{ .lock = .exclusive }); - file.close(); - - const hash_buf = try allocator.alloc(u8, 256); - const hash = try std.crypto.pwhash.bcrypt.strHash( - password, - .{ - .params = .{ - .rounds_log = 3, - .silently_truncate_password = false, - }, - .encoding = .phc, - }, - hash_buf - ); - - const info: Info = .{ - .name = name, - .full_name = full_name, - .birthday = birthday, - .hash = hash, - .is_admin = is_admin, - }; - - - return .{ - .dir = dir, - .arena = arena, - .info = info, - }; -} - -pub fn set_password(self: *Self, password: []const u8) !void { - const allocator = self.arena.allocator(); - const hash_buf = try allocator.alloc(u8, 256); - const hash = try std.crypto.pwhash.bcrypt.strHash( - password, - .{ - .params = .{ - .rounds_log = 3, - .silently_truncate_password = false, - }, - .encoding = .phc, - }, - hash_buf - ); - - self.info.hash = hash; -} - -pub fn sync(self: *Self) !void { - const file = try self.dir.createFile("info.json", .{ - .lock = .exclusive, - }); - defer file.close(); - - var buffer: [1024]u8 = undefined; - var writer = file.writer(&buffer); - - var stringify = std.json.Stringify { - .writer = &writer.interface, - .options = .{ .whitespace = .indent_2 } - }; - - try stringify.write(self.info); - try writer.interface.flush(); -} - -pub fn check_password(self: *Self, password: []const u8) bool { - std.crypto.pwhash.bcrypt.strVerify(self.info.hash, password, .{ - .silently_truncate_password = false, - }) catch return false; - return true; -} - -pub fn deinit(self: *Self) void { - self.dir.close(); - self.arena.deinit(); - self.* = undefined; -} - -pub fn exists(storage: *Storage, name: []const u8) bool { - var user = storage.dir.openDir("user", .{}) catch return false; - defer user.close(); - - user.access(name, .{}) catch return false; - return true; -} - -pub fn image(storage: *Storage, name: []const u8) ?std.fs.File { - var user = storage.dir.openDir("user", .{}) catch return null; - defer user.close(); - - var profile = user.openDir(name, .{}) catch return null; - defer profile.close(); - return profile.openFile("image.jpg", .{ .lock = .shared }) catch null; -} - -pub fn set_image( - storage: *Storage, - name: []const u8, - reader: *std.Io.Reader, - size: usize, -) !void { - var user = try storage.dir.openDir("user", .{}); - defer user.close(); - - var profile = try user.openDir(name, .{}); - defer profile.close(); - - var image_file = try profile.createFile("image.jpg", .{ .lock = .exclusive }); - defer image_file.close(); - - var buffer: [1024]u8 = undefined; - var file_writer = image_file.writer(&buffer); - - log.info("uploaded to profile {s} [{} bytes]", .{ name, size }); - - try reader.streamExact(&file_writer.interface, size); - - try file_writer.interface.flush(); -} - -pub fn list( - storage: *Storage, - allocator: std.mem.Allocator, -) ![][]const u8 { - var user = try storage.dir.openDir("user", .{ .iterate = true }); - defer user.close(); - - var ids: std.ArrayList([]const u8) = .empty; - - var iterator = user.iterate(); - - while (try iterator.next()) |entry| { - try ids.append(allocator, try allocator.dupe(u8, entry.name)); - } - - return ids.toOwnedSlice(allocator); -} |