60 lines
1.4 KiB
Lua
60 lines
1.4 KiB
Lua
local util = {}
|
|
local magick = require("magick")
|
|
local db = require("lapis.db")
|
|
|
|
local Avatars = require("models").Avatars
|
|
local Users = require("models").Users
|
|
|
|
function util.get_user_avatar_url(req, user)
|
|
if not user.avatar_id then
|
|
return "/avatars/default.webp"
|
|
end
|
|
return Avatars:find(user.avatar_id).file_path
|
|
end
|
|
|
|
function util.validate_and_create_image(input_image, filename)
|
|
local img = magick.load_image_from_blob(input_image)
|
|
|
|
if not img then
|
|
return false
|
|
end
|
|
|
|
img:strip()
|
|
img:set_gravity("CenterGravity")
|
|
|
|
local width, height = img:get_width(), img:get_height()
|
|
local min_dim = math.min(width, height)
|
|
if min_dim > 256 then
|
|
local ratio = 256.0 / min_dim
|
|
local new_w, new_h = width * ratio, height * ratio
|
|
img:resize(new_w, new_h)
|
|
end
|
|
|
|
width, height = img:get_width(), img:get_height()
|
|
local crop_size = math.min(width, height)
|
|
local x_offset = (width - crop_size) / 2
|
|
local y_offset = (height - crop_size) / 2
|
|
img:crop(crop_size, crop_size, x_offset, y_offset)
|
|
|
|
img:set_format("webp")
|
|
img:set_quality(85)
|
|
|
|
img:write(filename)
|
|
img:destroy()
|
|
return true
|
|
end
|
|
|
|
function util.get_logged_in_user(req)
|
|
if req.session.session_key == nil then
|
|
return nil
|
|
end
|
|
|
|
local session = db.select('* FROM "sessions" WHERE "key" = ? AND "expires_at" > "?" LIMIT 1', req.session.session_key, os.time())
|
|
if #session > 0 then
|
|
return Users:find({id = session[1].user_id})
|
|
end
|
|
|
|
return nil
|
|
end
|
|
|
|
return util |