import { image as e, video as t } from "bare-media"
import a from "b4a"
import {
CHAT_MESSAGE_PREVIEW as i,
CHAT_LINK_PREVIEW as n,
CHAT_MESSAGE_MAX_FRAMES as r,
PROFILE_AVATAR as o,
ROOM_AVATAR as d,
CHAT_MESSAGE_PREVIEW_DEFAULT_SIZES as s,
CHAT_MESSAGE_PREVIEW_SIZE as c,
} from "../shared/constants"
export async function createChatImagePreview({ path: t, sizes: a }) {
return m(await e(t).decode().orientate(), a)
}
export async function createChatVideoPreview({ path: a, sizes: i }) {
let n = await t(a).extractFrames({ frameIndex: 1 })
const { rotation: r, flipH: o, flipV: d } = await t(a).metadata()
return (
(r || o || d) && (n = await e(n).orientate({ transform: { rotate: r, flipH: o, flipV: d } })),
m(n, i)
)
}
export async function createChatLinkPreview({ path: t, buffer: a }) {
return h(t ? await e(t).decode() : await e.decode(a), n)
}
export async function createProfileAvatar({ path: e, crop: t }) {
return u(e, t, o)
}
export async function createRoomAvatar({ path: e, crop: t }) {
return u(e, t, d)
}
export async function decodeImage({ httpLink: t }) {
const a = await e(t).decode().orientate(),
{ width: i, height: n, data: r } = a
return { metadata: { dimensions: { width: i, height: n } }, data: r }
}
async function m(t, a) {
const n = a || s,
o = e.slice(t, { end: r }),
[d, m, u] = await Promise.all([
n.includes(c.SMALL) ? h(o, i.small) : void 0,
n.includes(c.MEDIUM) ? h(o, i.medium) : void 0,
n.includes(c.LARGE) ? h(t, i.large) : void 0,
])
return {
metadata: { dimensions: { width: t.width, height: t.height } },
small: d,
medium: m,
large: u,
}
}
async function h(t, i) {
const n = await e.resize(t, i.resize),
r = await e.encode(n, i.encode),
o = i.base64 ? { base64: a.toString(r, "base64") } : { buffer: r }
return {
metadata: { mimetype: i.encode.mimetype, dimensions: { width: n.width, height: n.height } },
...o,
}
}
async function u(t, a, i) {
const n = await e(t).decode().slice({ start: 0, end: 1 }).orientate(),
{ width: r, height: o } = n,
d = Math.min(r, o),
s = a || {
left: r > o ? Math.floor((r - o) / 2) : 0,
top: o > r ? Math.floor((o - r) / 2) : 0,
width: d,
height: d,
},
c = await e.crop(n, s),
[m, h] = await Promise.all([l(c, i.small), l(c, i.medium)])
return { small: m, medium: h }
}
async function l(t, i) {
const n = await e.resize(t, i.resize),
r = await e.encode(n, i.encode)
return {
metadata: { mimetype: i.encode.mimetype, dimensions: { width: n.width, height: n.height } },
base64: a.toString(r, "base64"),
}
}