ADD - camera and gallery apps

This commit is contained in:
Eichenholz
2026-08-06 12:07:35 +02:00
parent becd3f3cf7
commit ab09f61b1c
28 changed files with 2830 additions and 18 deletions
+8
View File
@@ -12,9 +12,17 @@ An iFruit account is optional. Unlinked devices retain local settings, alarms, m
- Two unique, non-stackable inventory items named `sky_phone_sim_registered` and `sky_phone_sim_anonymous`. Their metadata is initialized automatically on first use, so shops and crafting recipes add plain items without supplying a number.
- `oxmysql` with MySQL/MariaDB.
- `pma-voice` when `Config.Calls.VoiceProvider` is set to `"pma"`.
- A FiveManage V3 Media API token for Camera photo/video uploads and Gallery deletion. Set the
server-only `Config.Media.FiveManage.ApiKey` in `sky_phone/config/media.lua`; the token is never
sent to NUI because clients receive temporary presigned upload URLs instead.
Database migrations run automatically. Existing `sky_phone_mail_accounts` installations are renamed to `sky_phone_accounts` while preserving account IDs and mail foreign keys. iFruit passwords are intentional in-character credentials and remain plaintext `VARCHAR(64)` values; registration screens warn players never to reuse a real password.
Camera and Gallery media is stored in `sky_phone_media`. Signed-out captures belong to the current
IMEI; linking an iFruit account moves those rows into the account gallery so every linked phone sees
them. Signing out hides cloud media without deleting it. Factory reset removes device-local media
and attempts to delete its remote FiveManage files, while account-owned media remains in the cloud.
For a fresh manual database installation, import `sky_phone/sql/install.sql`. It contains the complete current table, key, index, collation, and foreign-key schema. Runtime migrations remain authoritative for upgrading an existing installation and must stay enabled.
Framework, inventory, callback, notification, and database integrations live under `sky_phone/source/bridge`. The resource has no dependency on any other Sky resource.
+1
View File
@@ -14,6 +14,7 @@
"test": "vitest run"
},
"dependencies": {
"fix-webm-duration": "^1.0.6",
"konsta": "~5.2.0",
"lucide-vue-next": "^0.525.0",
"pinia": "^3.0.3",
+8
View File
@@ -8,6 +8,9 @@ importers:
.:
dependencies:
fix-webm-duration:
specifier: ^1.0.6
version: 1.0.6
konsta:
specifier: ~5.2.0
version: 5.2.0
@@ -1152,6 +1155,9 @@ packages:
resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}
engines: {node: '>=10'}
fix-webm-duration@1.0.6:
resolution: {integrity: sha512-zVAqi4gE+8ywxJuAyV/rlJVX6CMtvyapEbQx6jyoeX9TMjdqAlt/FdG5d7rXSSkDVzTvS0H7CtwzHcH/vh4FPA==}
flat-cache@4.0.1:
resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==}
engines: {node: '>=16'}
@@ -3002,6 +3008,8 @@ snapshots:
locate-path: 6.0.0
path-exists: 4.0.0
fix-webm-duration@1.0.6: {}
flat-cache@4.0.1:
dependencies:
flatted: 3.4.4
+12 -1
View File
@@ -11,6 +11,7 @@ import {
import { useRoute, useRouter } from 'vue-router'
import PhoneHomeIndicator from '@/components/PhoneHomeIndicator.vue'
import PhoneMediaCapture from '@/components/PhoneMediaCapture.vue'
import PhoneLockScreen from '@/components/PhoneLockScreen.vue'
import PhoneNotifications from '@/components/PhoneNotifications.vue'
import NotificationPhonePreview from '@/components/NotificationPhonePreview.vue'
@@ -194,6 +195,11 @@ function unlockPhone(): void {
}, 720)
}
function unlockCamera(): void {
unlockPhone()
window.setTimeout(() => void router.push('/apps/camera'), 0)
}
onMounted(() => {
window.addEventListener('message', onMessage)
window.addEventListener('keydown', onKeydown)
@@ -305,6 +311,7 @@ onBeforeUnmount(() => {
</script>
<template>
<PhoneMediaCapture />
<SimPhonePicker
v-if="simPicker"
:choices="simPicker.choices"
@@ -367,7 +374,11 @@ onBeforeUnmount(() => {
</RouterView>
<PhoneHomeIndicator v-if="!isLocked" />
<Transition name="lock-screen">
<PhoneLockScreen v-if="isLocked" @unlock="unlockPhone" />
<PhoneLockScreen
v-if="isLocked"
@camera="unlockCamera"
@unlock="unlockPhone"
/>
</Transition>
<PhoneNotifications
:notification="notifications.current"
@@ -13,6 +13,7 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { usePhoneStore } from '@/stores/phone'
const emit = defineEmits<{
camera: []
unlock: []
}>()
@@ -167,6 +168,7 @@ onBeforeUnmount(() => {
class="lock-screen__shortcut"
:colors="shortcutColors"
:aria-label="phone.t('LockScreen.camera')"
@click="emit('camera')"
>
<template #icon>
<Camera :stroke-width="1.4" aria-hidden="true" />
@@ -0,0 +1,333 @@
<script setup lang="ts">
import fixWebmDuration from 'fix-webm-duration'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import type { UploadReady } from '@/types/media'
import { createGameView, type GameView } from '@/utils/gameView'
import { nuiCall } from '@/utils/nui'
type RecordingChunk = { blob: Blob; durationMs: number }
type PendingVideo = { blob: Blob; fileName: string }
const canvasRef = ref<HTMLCanvasElement | null>(null)
const pendingVideos = new Map<string, PendingVideo>()
const captureFps = 30
const maxCaptureHeight = 720
let bitrateBps = 1_500_000
let gameView: GameView | null = null
let renderFrameId: number | undefined
let lastRenderAt = 0
let recorder: MediaRecorder | null = null
let stream: MediaStream | null = null
let chunks: RecordingChunk[] = []
let lastChunkAt = 0
let lastChunkTimecode: number | null = null
let flushTimer: number | undefined
function postRecordState(active: boolean, saving = false): void {
window.postMessage(
{ data: { active, saving }, type: 'camera:recordState' },
'*',
)
}
function ensureGameView(): GameView {
if (!canvasRef.value) throw new Error('capture_failed')
if (gameView && !gameView.isLost()) return gameView
gameView?.dispose()
const scale = Math.min(1, maxCaptureHeight / window.innerHeight)
gameView = createGameView(canvasRef.value)
gameView.resize(
Math.round(window.innerWidth * scale),
Math.round(window.innerHeight * scale),
)
return gameView
}
function startRenderLoop(): void {
const view = ensureGameView()
if (renderFrameId !== undefined) return
const render = (now: number) => {
if (!gameView || gameView.isLost()) {
renderFrameId = undefined
return
}
renderFrameId = window.requestAnimationFrame(render)
if (now - lastRenderAt < 1000 / captureFps) return
lastRenderAt = now
view.render()
}
lastRenderAt = 0
renderFrameId = window.requestAnimationFrame(render)
}
function stopRenderLoop(): void {
if (renderFrameId !== undefined) {
window.cancelAnimationFrame(renderFrameId)
renderFrameId = undefined
}
}
function resetRecording(): void {
chunks = []
lastChunkAt = 0
lastChunkTimecode = null
}
function stopTracks(): void {
stream?.getTracks().forEach((track) => track.stop())
stream = null
}
function cleanupRecording(): void {
if (recorder && recorder.state !== 'inactive') recorder.stop()
recorder = null
stopTracks()
if (flushTimer !== undefined) window.clearInterval(flushTimer)
flushTimer = undefined
stopRenderLoop()
resetRecording()
postRecordState(false)
}
function startRecording(data: Record<string, unknown>): void {
if (recorder) return
if (typeof MediaRecorder === 'undefined') {
window.postMessage(
{
data: { error: 'unsupported', success: false },
type: 'camera:recordError',
},
'*',
)
return
}
const configuredBitrate = Number(data.bitrateKbps)
if (Number.isFinite(configuredBitrate) && configuredBitrate > 0) {
bitrateBps = Math.round(configuredBitrate * 1000)
}
startRenderLoop()
resetRecording()
stream = canvasRef.value?.captureStream(captureFps) ?? null
if (!stream) {
cleanupRecording()
return
}
recorder = new MediaRecorder(stream, {
mimeType: 'video/webm',
videoBitsPerSecond: bitrateBps,
})
recorder.ondataavailable = (event) => {
if (!event.data.size) return
const now = Date.now()
let durationMs = Math.max(0, now - lastChunkAt)
if (typeof event.timecode === 'number') {
durationMs =
lastChunkTimecode === null
? 0
: Math.max(0, event.timecode - lastChunkTimecode)
lastChunkTimecode = event.timecode
}
lastChunkAt = now
chunks.push({ blob: event.data, durationMs })
}
recorder.start()
flushTimer = window.setInterval(() => {
if (recorder?.state === 'recording') recorder.requestData()
}, 1000)
postRecordState(true)
}
async function stopRecording(data: Record<string, unknown>): Promise<void> {
const correlationId = String(data.correlationId ?? '')
if (!recorder || recorder.state === 'inactive' || !correlationId) return
postRecordState(false, true)
recorder.requestData()
await new Promise((resolve) => window.setTimeout(resolve, 120))
recorder.stop()
await new Promise((resolve) => window.setTimeout(resolve, 120))
if (flushTimer !== undefined) window.clearInterval(flushTimer)
flushTimer = undefined
stopTracks()
recorder = null
stopRenderLoop()
const durationMs = chunks.reduce((sum, entry) => sum + entry.durationMs, 0)
let blob = new Blob(
chunks.map((entry) => entry.blob),
{ type: 'video/webm' },
)
blob = await (
fixWebmDuration as unknown as (
source: Blob,
duration: number,
options: { logger: boolean },
) => Promise<Blob>
)(blob, durationMs, { logger: false })
resetRecording()
pendingVideos.set(correlationId, {
blob,
fileName: `camera-${correlationId}.webm`,
})
await nuiCall('media:requestUpload', {
correlationId,
mediaType: 'video',
})
}
async function renderFrames(view: GameView, count: number): Promise<void> {
for (let index = 0; index < count; index += 1) {
await new Promise<void>((resolve) => {
window.requestAnimationFrame(() => {
view.render()
resolve()
})
})
}
}
async function capturePhotoBlob(ready: UploadReady): Promise<Blob> {
const width = window.innerWidth
const height = window.innerHeight
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const view = createGameView(canvas, { preserveDrawingBuffer: true })
try {
view.resize(width, height)
await renderFrames(view, 3)
const output = document.createElement('canvas')
output.width = width
output.height = height
const context = output.getContext('2d')
if (!context) throw new Error('capture_failed')
context.drawImage(canvas, 0, 0)
const encoding = ready.photo?.Encoding ?? 'jpg'
const mimeType =
encoding === 'png'
? 'image/png'
: encoding === 'webp'
? 'image/webp'
: 'image/jpeg'
return await new Promise<Blob>((resolve, reject) => {
output.toBlob(
(blob) => (blob ? resolve(blob) : reject(new Error('capture_failed'))),
mimeType,
ready.photo?.Quality ?? 0.95,
)
})
} finally {
view.dispose()
}
}
async function failUpload(requestId: string, error: string): Promise<void> {
await nuiCall('media:failUpload', { error, requestId })
}
async function uploadReady(ready: UploadReady): Promise<void> {
let blob: Blob
let fileName: string
try {
if (ready.mediaType === 'video') {
const pending = pendingVideos.get(ready.correlationId)
if (!pending) throw new Error('capture_failed')
pendingVideos.delete(ready.correlationId)
blob = pending.blob
fileName = pending.fileName
} else {
blob = await capturePhotoBlob(ready)
fileName = `camera-${ready.correlationId}.${ready.photo?.Encoding ?? 'jpg'}`
}
} catch {
await failUpload(ready.requestId, 'capture_failed')
return
}
const form = new FormData()
form.append('file', blob, fileName)
form.append(
'metadata',
JSON.stringify({ captureToken: ready.captureToken, source: 'sky_phone' }),
)
const controller = new AbortController()
const timeout = window.setTimeout(
() => controller.abort(),
ready.uploadTimeoutMs ?? 25000,
)
try {
const response = await fetch(ready.presignedUrl, {
body: form,
method: 'POST',
signal: controller.signal,
})
const text = await response.text()
const body = JSON.parse(text) as {
data?: { id?: string; url?: string }
id?: string
url?: string
}
const uploaded = body.data ?? body
if (!response.ok || !uploaded.id || !uploaded.url) {
throw new Error('upload_failed')
}
await nuiCall('media:completeUpload', {
remoteId: uploaded.id,
requestId: ready.requestId,
url: uploaded.url,
})
} catch (error) {
await failUpload(
ready.requestId,
error instanceof DOMException && error.name === 'AbortError'
? 'upload_timeout'
: 'upload_failed',
)
} finally {
window.clearTimeout(timeout)
}
}
function onMessage(event: MessageEvent): void {
const message = event.data as {
data?: Record<string, unknown>
type?: string
}
if (message.type === 'camera:recordStart') {
startRecording(message.data ?? {})
} else if (message.type === 'camera:recordStop') {
void stopRecording(message.data ?? {})
} else if (message.type === 'camera:recordCancel') {
cleanupRecording()
} else if (message.type === 'media:uploadReady') {
void uploadReady(message.data as UploadReady)
}
}
onMounted(() => window.addEventListener('message', onMessage))
onBeforeUnmount(() => {
window.removeEventListener('message', onMessage)
cleanupRecording()
pendingVideos.clear()
gameView?.dispose()
gameView = null
})
</script>
<template>
<canvas
ref="canvasRef"
class="phone-media-capture"
aria-hidden="true"
></canvas>
</template>
<style scoped>
.phone-media-capture {
position: fixed;
width: 0;
height: 0;
opacity: 0;
pointer-events: none;
}
</style>
+4 -6
View File
@@ -29,15 +29,13 @@ describe('app registry', () => {
route: '/apps/weather',
})
expect(PHONE_APPS.find((app) => app.id === 'camera')).toMatchObject({
component: null,
route: null,
route: '/apps/camera',
})
expect(PHONE_APPS.find((app) => app.id === 'photos')).toMatchObject({
component: null,
route: null,
route: '/apps/photos',
})
expect(isPhoneAppId('camera')).toBe(false)
expect(isPhoneAppId('photos')).toBe(false)
expect(isPhoneAppId('camera')).toBe(true)
expect(isPhoneAppId('photos')).toBe(true)
expect(isPhoneAppId('clock')).toBe(true)
expect(
PHONE_APPS.filter((app) => app.dockOrder !== null)
+8 -4
View File
@@ -97,7 +97,9 @@ export const PHONE_APPS: PhoneAppDefinition[] = [
route: '/apps/calculator',
},
{
component: null,
component: markRaw(
defineAsyncComponent(() => import('@/views/apps/CameraApp.vue')),
),
dockOrder: 2,
gridOrder: 2,
icon: markRaw(Camera),
@@ -105,7 +107,7 @@ export const PHONE_APPS: PhoneAppDefinition[] = [
iconImage: cameraIcon,
id: 'camera',
labelKey: 'Apps.camera.name',
route: null,
route: '/apps/camera',
},
{
component: markRaw(
@@ -134,7 +136,9 @@ export const PHONE_APPS: PhoneAppDefinition[] = [
route: '/apps/weather',
},
{
component: null,
component: markRaw(
defineAsyncComponent(() => import('@/views/apps/GalleryApp.vue')),
),
dockOrder: null,
gridOrder: 7,
icon: markRaw(Images),
@@ -142,7 +146,7 @@ export const PHONE_APPS: PhoneAppDefinition[] = [
iconImage: photosIcon,
id: 'photos',
labelKey: 'Apps.photos.name',
route: null,
route: '/apps/photos',
},
{
component: markRaw(
+71 -2
View File
@@ -182,7 +182,40 @@ const defaultLocales: LocaleTree = {
snow: 'Cold conditions with snow across the region.',
},
},
camera: { name: 'Camera' },
camera: {
name: 'Camera',
flash: 'Flash',
flip: 'Flip camera',
photo: 'Photo',
video: 'Video',
focusHelp: 'Space for movement',
returnHelp: 'Space to return',
uploading: '{count} uploading',
saving: 'Saving video...',
openGallery: 'Open Gallery',
takePhoto: 'Take photo',
startRecording: 'Start recording',
stopRecording: 'Stop recording',
saved: 'Saved to Gallery.',
errors: {
cancelled: 'Capture cancelled.',
capture_failed: 'Unable to capture the game view.',
invalid_media_type: 'The uploaded media type is invalid.',
invalid_upload: 'The upload could not be verified.',
invalid_upload_token: 'The upload session is no longer valid.',
missing_config: 'Camera uploads are not configured.',
not_found: 'The media item no longer exists.',
operation_in_progress:
'Another media operation is already in progress.',
owner_changed: 'The active phone account changed during upload.',
rate_limited: 'Too many media actions. Try again shortly.',
request_failed: 'The camera request failed.',
request_timeout: 'The media service timed out.',
unsupported: 'Video recording is not supported.',
upload_failed: 'The media upload failed.',
upload_timeout: 'The media upload timed out.',
},
},
clock: {
name: 'Clock',
lap: 'Lap',
@@ -339,7 +372,43 @@ const defaultLocales: LocaleTree = {
unpin: 'Unpin note',
deleteNote: 'Delete note',
},
photos: { name: 'Photos' },
photos: {
name: 'Gallery',
count: '{count} items',
loading: 'Loading Gallery...',
emptyTitle: 'No Photos or Videos',
emptyBody: 'Captures from Camera will appear here.',
photo: 'Photo',
video: 'Video',
photoAlt: 'Gallery photo',
videoAlt: 'Gallery video',
delete: 'Delete media',
deleteTitle: 'Delete Media?',
deleteBody: 'This photo or video will be permanently deleted.',
deleted: 'Media deleted.',
zoomIn: 'Zoom in',
zoomOut: 'Zoom out',
resetZoom: 'Reset zoom',
filters: { all: 'All', photos: 'Photos', videos: 'Videos' },
errors: {
cancelled: 'The media action was cancelled.',
capture_failed: 'Unable to capture the game view.',
invalid_media_type: 'The media type is invalid.',
invalid_upload: 'The upload could not be verified.',
invalid_upload_token: 'The upload session is no longer valid.',
missing_config: 'Gallery uploads are not configured.',
not_found: 'The media item no longer exists.',
operation_in_progress:
'Another media operation is already in progress.',
owner_changed: 'The active phone account changed.',
rate_limited: 'Too many media actions. Try again shortly.',
request_failed: 'The Gallery request failed.',
request_timeout: 'The media service timed out.',
unsupported: 'This media format is not supported.',
upload_failed: 'The media upload failed.',
upload_timeout: 'The media upload timed out.',
},
},
settings: {
name: 'Settings',
searchPlaceholder: 'Search',
+1 -1
View File
@@ -13,7 +13,7 @@ export type PhoneAppId =
| 'app-store'
| 'settings'
export type LaunchablePhoneAppId = Exclude<PhoneAppId, 'camera' | 'photos'>
export type LaunchablePhoneAppId = PhoneAppId
export type AppLaunchOrigin = {
borderRadius: number
+39
View File
@@ -0,0 +1,39 @@
export type MediaType = 'photo' | 'video'
export type GalleryFilter = 'all' | MediaType
export type PhoneMedia = {
createdAt: number
id: number
mediaType: MediaType
url: string
}
export type UploadReady = {
captureToken: string
correlationId: string
mediaType: MediaType
photo?: {
Encoding?: 'jpg' | 'png' | 'webp'
Quality?: number
}
presignedUrl: string
requestId: string
uploadTimeoutMs?: number
video?: {
BitrateKbps?: number
}
}
export type UploadResult = {
correlationId: string
error?: string
media?: PhoneMedia
success: boolean
}
export type DeleteResult = {
correlationId: string
error?: string
id?: number
success: boolean
}
+160
View File
@@ -0,0 +1,160 @@
const VERTEX_SHADER = `
attribute vec2 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texcoord = a_texcoord;
}
`
const FRAGMENT_SHADER = `
varying highp vec2 v_texcoord;
uniform sampler2D u_texture;
void main() {
gl_FragColor = texture2D(u_texture, v_texcoord);
}
`
export interface GameView {
readonly canvas: HTMLCanvasElement
dispose(): void
isLost(): boolean
render(): void
resize(width: number, height: number): void
}
export interface GameViewOptions {
preserveDrawingBuffer?: boolean
}
function compileShader(
gl: WebGLRenderingContext,
type: number,
source: string,
): WebGLShader {
const shader = gl.createShader(type)
if (!shader) throw new Error('game_view_shader_unavailable')
gl.shaderSource(shader, source)
gl.compileShader(shader)
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader) || 'game_view_shader_failed')
}
return shader
}
export function createGameView(
canvas: HTMLCanvasElement,
options: GameViewOptions = {},
): GameView {
const gl = canvas.getContext('webgl', {
alpha: false,
antialias: false,
depth: false,
desynchronized: true,
failIfMajorPerformanceCaveat: false,
preserveDrawingBuffer: options.preserveDrawingBuffer === true,
stencil: false,
}) as WebGLRenderingContext | null
if (!gl) throw new Error('game_view_unavailable')
let lost = false
let disposed = false
const onContextLost = (event: Event) => {
event.preventDefault()
lost = true
console.error('[Camera] Game-view WebGL context lost.')
}
canvas.addEventListener(
'webglcontextlost',
onContextLost as EventListener,
false,
)
const program = gl.createProgram()
if (!program) throw new Error('game_view_program_unavailable')
gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER))
gl.attachShader(
program,
compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER),
)
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(gl.getProgramInfoLog(program) || 'game_view_program_failed')
}
gl.useProgram(program)
const positionLocation = gl.getAttribLocation(program, 'a_position')
const texcoordLocation = gl.getAttribLocation(program, 'a_texcoord')
if (positionLocation < 0 || texcoordLocation < 0) {
throw new Error('game_view_attributes_unavailable')
}
const positionBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
gl.STATIC_DRAW,
)
gl.enableVertexAttribArray(positionLocation)
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)
const texcoordBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer)
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]),
gl.STATIC_DRAW,
)
gl.enableVertexAttribArray(texcoordLocation)
gl.vertexAttribPointer(texcoordLocation, 2, gl.FLOAT, false, 0, 0)
const texture = gl.createTexture()
gl.bindTexture(gl.TEXTURE_2D, texture)
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
1,
1,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
new Uint8Array([0, 0, 0, 255]),
)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
gl.uniform1i(gl.getUniformLocation(program, 'u_texture'), 0)
return {
canvas,
dispose() {
if (disposed) return
disposed = true
canvas.removeEventListener(
'webglcontextlost',
onContextLost as EventListener,
false,
)
gl.getExtension('WEBGL_lose_context')?.loseContext()
},
isLost: () => lost,
render() {
if (disposed || lost) return
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
gl.finish()
},
resize(width: number, height: number) {
if (disposed || lost) return
canvas.width = width
canvas.height = height
gl.viewport(0, 0, width, height)
},
}
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import {
filterMedia,
formatRecordingDuration,
mediaErrorKey,
mergeMedia,
} from './media'
const media = [
{ createdAt: 10, id: 1, mediaType: 'photo' as const, url: 'photo' },
{ createdAt: 20, id: 2, mediaType: 'video' as const, url: 'video' },
]
describe('media utilities', () => {
it('filters gallery media by explicit type', () => {
expect(filterMedia(media, 'all')).toHaveLength(2)
expect(filterMedia(media, 'photo').map((entry) => entry.id)).toEqual([1])
expect(filterMedia(media, 'video').map((entry) => entry.id)).toEqual([2])
})
it('merges pages without duplicates and keeps newest first', () => {
expect(
mergeMedia(media, [
{ createdAt: 30, id: 1, mediaType: 'photo', url: 'updated' },
{ createdAt: 25, id: 3, mediaType: 'photo', url: 'new' },
]).map((entry) => [entry.id, entry.url]),
).toEqual([
[1, 'updated'],
[3, 'new'],
[2, 'video'],
])
})
it('formats unlimited recording durations', () => {
expect(formatRecordingDuration(0)).toBe('00:00')
expect(formatRecordingDuration(3_725_000)).toBe('62:05')
})
it('maps unknown server failures to the localized default', () => {
expect(mediaErrorKey('upload_timeout')).toBe('upload_timeout')
expect(mediaErrorKey('private_provider_error')).toBe('request_failed')
})
})
+53
View File
@@ -0,0 +1,53 @@
import type { GalleryFilter, MediaType, PhoneMedia } from '@/types/media'
export function isMediaType(value: unknown): value is MediaType {
return value === 'photo' || value === 'video'
}
export function filterMedia(
media: PhoneMedia[],
filter: GalleryFilter,
): PhoneMedia[] {
return filter === 'all'
? media
: media.filter((entry) => entry.mediaType === filter)
}
export function mergeMedia(
current: PhoneMedia[],
incoming: PhoneMedia[],
): PhoneMedia[] {
const byId = new Map(current.map((entry) => [entry.id, entry]))
for (const entry of incoming) byId.set(entry.id, entry)
return [...byId.values()].sort(
(left, right) => right.createdAt - left.createdAt || right.id - left.id,
)
}
export function formatRecordingDuration(elapsedMs: number): string {
const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000))
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
}
export function mediaErrorKey(error?: string): string {
const known = new Set([
'cancelled',
'capture_failed',
'invalid_media_type',
'invalid_upload',
'invalid_upload_token',
'missing_config',
'not_found',
'operation_in_progress',
'owner_changed',
'rate_limited',
'request_failed',
'request_timeout',
'unsupported',
'upload_failed',
'upload_timeout',
])
return known.has(error ?? '') ? (error as string) : 'request_failed'
}
+2
View File
@@ -50,11 +50,13 @@ const DEFAULT_APP_NOTIFICATIONS: Record<
phone: { enabled: true, sounds: true },
'app-store': { enabled: true, sounds: true },
calculator: { enabled: true, sounds: true },
camera: { enabled: true, sounds: true },
clock: { enabled: true, sounds: true },
weather: { enabled: true, sounds: true },
mail: { enabled: true, sounds: true },
map: { enabled: true, sounds: true },
notes: { enabled: true, sounds: true },
photos: { enabled: true, sounds: true },
settings: { enabled: true, sounds: true },
}
+602
View File
@@ -0,0 +1,602 @@
<script setup lang="ts">
import { kFab, kPage, kSegmented, kSegmentedButton, kToast } from 'konsta/vue'
import {
Camera as CameraIcon,
Images,
RefreshCw,
Video,
Zap,
ZapOff,
} from 'lucide-vue-next'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { usePhoneStore } from '@/stores/phone'
import type { MediaType, PhoneMedia, UploadResult } from '@/types/media'
import { formatRecordingDuration, mediaErrorKey } from '@/utils/media'
import { nuiCall } from '@/utils/nui'
type CaptureItem = {
error?: string
id: string
mediaType: MediaType
status: 'uploading' | 'success' | 'error'
}
const isDevelopment = import.meta.env.DEV
const phone = usePhoneStore()
const router = useRouter()
const mode = ref<MediaType>('photo')
const flashEnabled = ref(false)
const frontCamera = ref(false)
const shutterActive = ref(false)
const focused = ref(true)
const recording = ref(false)
const savingVideo = ref(false)
const recordingStartedAt = ref(0)
const elapsed = ref('00:00')
const captures = ref<CaptureItem[]>([])
const latestMedia = ref<PhoneMedia | null>(null)
const toastOpened = ref(false)
const toastText = ref('')
const videoBitrateKbps = ref(1500)
let shutterTimer: number | undefined
let toastTimer: number | undefined
let recordingTimer: number | undefined
const pendingCount = computed(
() =>
captures.value.filter((capture) => capture.status === 'uploading').length,
)
const controlColors = {
bgIos: 'bg-black/40',
textIos: 'text-white',
}
const flashColors = computed(() => ({
...controlColors,
textIos: flashEnabled.value ? 'text-yellow-300' : 'text-white',
}))
function correlationId(): string {
return `${Date.now()}-${crypto.randomUUID()}`
}
function showToast(text: string): void {
if (toastTimer !== undefined) window.clearTimeout(toastTimer)
toastText.value = text
toastOpened.value = true
toastTimer = window.setTimeout(() => {
toastOpened.value = false
}, 3000)
}
function updateCapture(id: string, updates: Partial<CaptureItem>): void {
const index = captures.value.findIndex((capture) => capture.id === id)
if (index < 0) return
captures.value[index] = { ...captures.value[index], ...updates }
}
function queueCapture(id: string, mediaType: MediaType): void {
captures.value.unshift({ id, mediaType, status: 'uploading' })
captures.value = captures.value.slice(0, 6)
}
function devMedia(id: string, mediaType: MediaType): PhoneMedia {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="1600"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#19354f"/><stop offset="1" stop-color="#d78357"/></linearGradient></defs><rect width="900" height="1600" fill="url(#g)"/><circle cx="680" cy="380" r="210" fill="#ffffff22"/><path d="M0 1200 260 840l180 220 170-170 290 310v400H0z" fill="#102331aa"/></svg>`
return {
createdAt: Date.now(),
id: Number(Date.now()),
mediaType,
url: `data:image/svg+xml,${encodeURIComponent(svg)}#${id}`,
}
}
async function requestPhoto(): Promise<void> {
if (recording.value || savingVideo.value) return
const id = correlationId()
queueCapture(id, 'photo')
shutterActive.value = true
if (shutterTimer !== undefined) window.clearTimeout(shutterTimer)
shutterTimer = window.setTimeout(() => {
shutterActive.value = false
}, 280)
if (isDevelopment) {
window.setTimeout(() => {
window.dispatchEvent(
new MessageEvent('message', {
data: {
data: {
correlationId: id,
media: devMedia(id, 'photo'),
success: true,
},
type: 'media:uploadResult',
},
}),
)
}, 700)
return
}
await nuiCall('media:requestUpload', {
correlationId: id,
mediaType: 'photo',
})
}
function startRecording(): void {
if (savingVideo.value) return
window.postMessage(
{
data: { bitrateKbps: videoBitrateKbps.value },
type: 'camera:recordStart',
},
'*',
)
}
function stopRecording(): void {
if (!recording.value || savingVideo.value) return
const id = correlationId()
queueCapture(id, 'video')
if (isDevelopment) {
recording.value = false
savingVideo.value = true
window.setTimeout(() => {
window.dispatchEvent(
new MessageEvent('message', {
data: {
data: {
correlationId: id,
media: devMedia(id, 'video'),
success: true,
},
type: 'media:uploadResult',
},
}),
)
}, 900)
return
}
window.postMessage(
{ data: { correlationId: id }, type: 'camera:recordStop' },
'*',
)
}
function capture(): void {
if (mode.value === 'video') {
if (recording.value) {
stopRecording()
} else {
startRecording()
}
return
}
void requestPhoto()
}
async function toggleFlash(): Promise<void> {
flashEnabled.value = !flashEnabled.value
await nuiCall('camera:setFlash', { enabled: flashEnabled.value })
}
async function toggleFacing(): Promise<void> {
frontCamera.value = !frontCamera.value
await nuiCall('camera:setFacing', { front: frontCamera.value })
}
function updateRecordingTimer(): void {
elapsed.value = formatRecordingDuration(Date.now() - recordingStartedAt.value)
}
function onKeydown(event: KeyboardEvent): void {
if (event.code !== 'Space' || event.repeat || !focused.value) return
event.preventDefault()
focused.value = false
void nuiCall('camera:setFocus', { focused: false })
}
function onMessage(event: MessageEvent): void {
const message = event.data as {
data?: Record<string, unknown>
type?: string
}
if (message.type === 'camera:focus') {
focused.value = message.data?.focused === true
} else if (message.type === 'camera:recordState') {
const active = message.data?.active === true
savingVideo.value = message.data?.saving === true
recording.value = active
if (active) {
recordingStartedAt.value = Date.now()
updateRecordingTimer()
if (recordingTimer !== undefined) window.clearInterval(recordingTimer)
recordingTimer = window.setInterval(updateRecordingTimer, 250)
} else if (recordingTimer !== undefined) {
window.clearInterval(recordingTimer)
recordingTimer = undefined
}
} else if (message.type === 'camera:recordError') {
showToast(
phone.t(
`Apps.camera.errors.${mediaErrorKey(String(message.data?.error ?? ''))}`,
),
)
} else if (message.type === 'media:uploadResult') {
const result = message.data as UploadResult
if (!result?.correlationId) return
savingVideo.value = false
if (result.success && result.media) {
latestMedia.value = result.media
updateCapture(result.correlationId, { status: 'success' })
showToast(phone.t('Apps.camera.saved'))
window.setTimeout(() => {
captures.value = captures.value.filter(
(captureItem) => captureItem.id !== result.correlationId,
)
}, 2500)
} else {
const error = mediaErrorKey(result.error)
updateCapture(result.correlationId, { error, status: 'error' })
showToast(phone.t(`Apps.camera.errors.${error}`))
}
}
}
async function loadLatest(): Promise<void> {
const response = await nuiCall<PhoneMedia[]>('gallery:list', {
limit: 1,
offset: 0,
})
if (response.success && response.data?.[0])
latestMedia.value = response.data[0]
}
onMounted(() => {
window.addEventListener('keydown', onKeydown)
window.addEventListener('message', onMessage)
void nuiCall('camera:setActive', { active: true })
void nuiCall<{ videoBitrateKbps?: number }>('media:config').then(
(response) => {
if (response.success && response.data?.videoBitrateKbps) {
videoBitrateKbps.value = response.data.videoBitrateKbps
}
},
)
void loadLatest()
})
onBeforeUnmount(() => {
if (shutterTimer !== undefined) window.clearTimeout(shutterTimer)
if (toastTimer !== undefined) window.clearTimeout(toastTimer)
if (recordingTimer !== undefined) window.clearInterval(recordingTimer)
window.removeEventListener('keydown', onKeydown)
window.removeEventListener('message', onMessage)
window.postMessage({ type: 'camera:recordCancel' }, '*')
void nuiCall('camera:setFlash', { enabled: false })
void nuiCall('camera:setActive', { active: false })
})
</script>
<template>
<k-page class="camera-page" :aria-label="phone.t('Apps.camera.name')">
<object
v-if="!isDevelopment"
class="camera-game-view"
type="application/x-cfx-game-view"
aria-hidden="true"
></object>
<div v-else class="camera-dev-view" aria-hidden="true">
<span class="camera-dev-sun"></span>
<span class="camera-dev-horizon"></span>
</div>
<div class="camera-shade"></div>
<div class="camera-flash" :class="{ active: shutterActive }"></div>
<header class="camera-topbar">
<k-fab
component="button"
type="button"
class="camera-control"
:colors="flashColors"
:aria-label="phone.t('Apps.camera.flash')"
@click="toggleFlash"
>
<template #icon>
<Zap v-if="flashEnabled" :size="19" />
<ZapOff v-else :size="19" />
</template>
</k-fab>
<span v-if="pendingCount" class="camera-upload-pill">
{{ phone.t('Apps.camera.uploading', { count: String(pendingCount) }) }}
</span>
<span v-else class="camera-focus-pill">
{{
phone.t(focused ? 'Apps.camera.focusHelp' : 'Apps.camera.returnHelp')
}}
</span>
<k-fab
component="button"
type="button"
class="camera-control"
:colors="controlColors"
:aria-label="phone.t('Apps.camera.flip')"
@click="toggleFacing"
>
<template #icon><RefreshCw :size="19" /></template>
</k-fab>
</header>
<div v-if="recording || savingVideo" class="camera-record-status">
<span class="camera-record-dot"></span>
{{ savingVideo ? phone.t('Apps.camera.saving') : elapsed }}
</div>
<footer class="camera-controls">
<k-segmented class="camera-mode-picker">
<k-segmented-button
:active="mode === 'photo'"
:disabled="recording || savingVideo"
@click="mode = 'photo'"
>
{{ phone.t('Apps.camera.photo') }}
</k-segmented-button>
<k-segmented-button
:active="mode === 'video'"
:disabled="recording || savingVideo"
@click="mode = 'video'"
>
{{ phone.t('Apps.camera.video') }}
</k-segmented-button>
</k-segmented>
<div class="camera-capture-row">
<button
class="camera-latest"
type="button"
:aria-label="phone.t('Apps.camera.openGallery')"
@click="router.push('/apps/photos')"
>
<img
v-if="latestMedia?.mediaType === 'photo'"
:src="latestMedia.url"
alt=""
/>
<Video v-else-if="latestMedia" :size="22" />
<Images v-else :size="22" />
</button>
<button
class="camera-shutter"
:class="{ recording, video: mode === 'video' }"
type="button"
:disabled="savingVideo"
:aria-label="
phone.t(
mode === 'photo'
? 'Apps.camera.takePhoto'
: recording
? 'Apps.camera.stopRecording'
: 'Apps.camera.startRecording',
)
"
@click="capture"
>
<span></span>
</button>
<span class="camera-row-spacer" aria-hidden="true">
<CameraIcon :size="22" />
</span>
</div>
</footer>
<k-toast
:opened="toastOpened"
position="center"
@click="toastOpened = false"
>
{{ toastText }}
</k-toast>
</k-page>
</template>
<style scoped>
.camera-page {
position: relative;
overflow: hidden;
background: #000;
color: #fff;
}
.camera-game-view,
.camera-dev-view,
.camera-shade,
.camera-flash {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
.camera-game-view {
border: 0;
object-fit: cover;
}
.camera-dev-view {
overflow: hidden;
background: linear-gradient(#4a88ad 0 48%, #a88d68 49% 62%, #283528 63%);
}
.camera-dev-sun {
position: absolute;
top: 18%;
right: 16%;
width: 68px;
height: 68px;
border-radius: 50%;
background: #fff3b0;
box-shadow: 0 0 50px #ffd36a;
}
.camera-dev-horizon {
position: absolute;
left: -10%;
right: -10%;
bottom: 31%;
height: 24%;
background: #142b21;
clip-path: polygon(
0 100%,
0 64%,
18% 22%,
34% 61%,
54% 8%,
73% 58%,
88% 27%,
100% 74%,
100% 100%
);
}
.camera-shade {
pointer-events: none;
background: linear-gradient(#0008, transparent 22%, transparent 62%, #000d);
}
.camera-flash {
z-index: 8;
pointer-events: none;
background: #fff;
opacity: 0;
transition: opacity 0.25s ease;
}
.camera-flash.active {
opacity: 0.9;
transition-duration: 0.04s;
}
.camera-topbar {
position: absolute;
z-index: 4;
top: 52px;
left: 18px;
right: 18px;
display: grid;
grid-template-columns: 44px 1fr 44px;
align-items: center;
gap: 10px;
}
.camera-control {
width: 42px;
height: 42px;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.camera-focus-pill,
.camera-upload-pill {
min-width: 0;
padding: 7px 10px;
overflow: hidden;
border-radius: 999px;
background: #0006;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 11px;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.camera-upload-pill {
color: #ffd60a;
}
.camera-record-status {
position: absolute;
z-index: 4;
top: 108px;
left: 50%;
display: flex;
align-items: center;
gap: 7px;
padding: 6px 10px;
border-radius: 999px;
background: #0009;
transform: translateX(-50%);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.camera-record-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ff3b30;
}
.camera-controls {
position: absolute;
z-index: 4;
right: 0;
bottom: 35px;
left: 0;
display: flex;
flex-direction: column;
gap: 18px;
padding: 0 24px;
}
.camera-mode-picker {
align-self: center;
width: 188px;
padding: 2px;
border-radius: 10px;
background: #0007;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.camera-capture-row {
display: grid;
grid-template-columns: 54px 1fr 54px;
align-items: center;
}
.camera-latest,
.camera-row-spacer {
width: 50px;
height: 50px;
overflow: hidden;
border: 2px solid #ffffff99;
border-radius: 12px;
background: #111b;
color: #fff;
display: grid;
place-items: center;
}
.camera-latest img {
width: 100%;
height: 100%;
object-fit: cover;
}
.camera-row-spacer {
justify-self: end;
visibility: hidden;
}
.camera-shutter {
justify-self: center;
width: 76px;
height: 76px;
padding: 4px;
border: 3px solid #fff;
border-radius: 50%;
background: transparent;
}
.camera-shutter span {
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background: #fff;
transition: 0.18s ease;
}
.camera-shutter.video span {
background: #ff3b30;
}
.camera-shutter.recording span {
width: 48%;
height: 48%;
margin: 26%;
border-radius: 6px;
}
.camera-shutter:disabled {
opacity: 0.5;
}
</style>
+557
View File
@@ -0,0 +1,557 @@
<script setup lang="ts">
import {
kBlock,
kDialog,
kDialogButton,
kLink,
kNavbar,
kNavbarBackLink,
kPage,
kPreloader,
kSegmented,
kSegmentedButton,
kToast,
} from 'konsta/vue'
import { Play, RotateCcw, Trash2, ZoomIn, ZoomOut } from 'lucide-vue-next'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { usePhoneStore } from '@/stores/phone'
import type { DeleteResult, GalleryFilter, PhoneMedia } from '@/types/media'
import { mediaErrorKey, mergeMedia } from '@/utils/media'
import { nuiCall } from '@/utils/nui'
const isDevelopment = import.meta.env.DEV
const developmentGalleryState = isDevelopment
? new URLSearchParams(window.location.search).get('galleryMock')
: null
const pageSize = 36
const phone = usePhoneStore()
const media = ref<PhoneMedia[]>([])
const filter = ref<GalleryFilter>('all')
const loading = ref(true)
const fetching = ref(false)
const hasMore = ref(true)
const loadError = ref('')
const selected = ref<PhoneMedia | null>(null)
const deleteDialogOpened = ref(false)
const deleting = ref(false)
const toastOpened = ref(false)
const toastText = ref('')
const loadTrigger = ref<HTMLElement | null>(null)
const imageZoom = ref(1)
const imagePan = ref({ x: 0, y: 0 })
const dragging = ref(false)
const dragStart = ref({ panX: 0, panY: 0, x: 0, y: 0 })
let observer: IntersectionObserver | null = null
let toastTimer: number | undefined
let pendingDeleteCorrelation = ''
const countLabel = computed(() =>
phone.t('Apps.photos.count', { count: String(media.value.length) }),
)
const imageStyle = computed(() => ({
cursor:
imageZoom.value > 1 ? (dragging.value ? 'grabbing' : 'grab') : 'zoom-in',
transform: `translate3d(${imagePan.value.x}px, ${imagePan.value.y}px, 0) scale(${imageZoom.value})`,
}))
function buildMockPhoto(
id: number,
label: string,
first: string,
second: string,
): PhoneMedia {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="1200"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop stop-color="${first}"/><stop offset="1" stop-color="${second}"/></linearGradient></defs><rect width="900" height="1200" fill="url(#g)"/><circle cx="680" cy="290" r="180" fill="#ffffff20"/><path d="M0 930 230 650l190 190 120-130 360 300v190H0z" fill="#08131d66"/><text x="70" y="1080" fill="white" font-size="54" font-family="sans-serif">${label}</text></svg>`
return {
createdAt: Date.now() - id * 3_600_000,
id,
mediaType: 'photo',
url: `data:image/svg+xml,${encodeURIComponent(svg)}`,
}
}
function mockMedia(): PhoneMedia[] {
const photos = [
buildMockPhoto(1, 'Vespucci', '#23567b', '#e08d5c'),
buildMockPhoto(2, 'Downtown', '#442c69', '#c86a77'),
buildMockPhoto(3, 'Paleto Bay', '#1f6653', '#d1a85b'),
buildMockPhoto(4, 'Mirror Park', '#355c7d', '#6c5b7b'),
buildMockPhoto(5, 'Del Perro', '#b06ab3', '#4568dc'),
buildMockPhoto(6, 'Sandy Shores', '#7b4f35', '#d2a35f'),
buildMockPhoto(7, 'Rockford', '#203a43', '#2c5364'),
buildMockPhoto(8, 'Little Seoul', '#8e2de2', '#4a00e0'),
]
return [
photos[0],
{
createdAt: Date.now() - 1_800_000,
id: 100,
mediaType: 'video',
url: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
},
...photos.slice(1),
]
}
function showToast(text: string): void {
if (toastTimer !== undefined) window.clearTimeout(toastTimer)
toastText.value = text
toastOpened.value = true
toastTimer = window.setTimeout(() => {
toastOpened.value = false
}, 3000)
}
function formatDate(timestamp: number): string {
return new Intl.DateTimeFormat(phone.lang, {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(timestamp))
}
async function fetchMore(): Promise<void> {
if (fetching.value || !hasMore.value) return
fetching.value = true
const offset = media.value.length
const response = await nuiCall<PhoneMedia[]>('gallery:list', {
limit: pageSize,
mediaType: filter.value === 'all' ? undefined : filter.value,
mockState: developmentGalleryState ?? undefined,
offset,
})
if (response.success && Array.isArray(response.data)) {
media.value = mergeMedia(media.value, response.data)
hasMore.value = response.data.length === pageSize
} else if (
isDevelopment &&
developmentGalleryState !== 'error' &&
offset === 0
) {
const mock = mockMedia().filter(
(entry) => filter.value === 'all' || entry.mediaType === filter.value,
)
media.value = mock
hasMore.value = false
} else {
if (offset === 0) {
loadError.value = phone.t(
`Apps.photos.errors.${mediaErrorKey(response.error)}`,
)
}
hasMore.value = false
}
fetching.value = false
}
async function loadGallery(): Promise<void> {
media.value = []
hasMore.value = true
loadError.value = ''
loading.value = true
await fetchMore()
loading.value = false
await nextTick()
observeMore()
}
function observeMore(): void {
observer?.disconnect()
observer = null
if (!hasMore.value || !loadTrigger.value) return
observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) void fetchMore()
},
{ rootMargin: '180px' },
)
observer.observe(loadTrigger.value)
}
function openMedia(entry: PhoneMedia): void {
selected.value = entry
imageZoom.value = 1
imagePan.value = { x: 0, y: 0 }
}
function closeMedia(): void {
selected.value = null
deleteDialogOpened.value = false
stopDragging()
}
function setZoom(value: number): void {
imageZoom.value = Math.min(4, Math.max(1, value))
if (imageZoom.value === 1) imagePan.value = { x: 0, y: 0 }
}
function startDragging(event: PointerEvent): void {
if (imageZoom.value === 1) {
setZoom(2)
return
}
dragging.value = true
dragStart.value = {
panX: imagePan.value.x,
panY: imagePan.value.y,
x: event.clientX,
y: event.clientY,
}
window.addEventListener('pointermove', moveImage)
window.addEventListener('pointerup', stopDragging)
}
function moveImage(event: PointerEvent): void {
if (!dragging.value) return
imagePan.value = {
x: dragStart.value.panX + event.clientX - dragStart.value.x,
y: dragStart.value.panY + event.clientY - dragStart.value.y,
}
}
function stopDragging(): void {
dragging.value = false
window.removeEventListener('pointermove', moveImage)
window.removeEventListener('pointerup', stopDragging)
}
async function deleteSelected(): Promise<void> {
if (!selected.value || deleting.value) return
deleting.value = true
deleteDialogOpened.value = false
pendingDeleteCorrelation = `${Date.now()}-${crypto.randomUUID()}`
if (isDevelopment) {
window.setTimeout(() => {
window.dispatchEvent(
new MessageEvent('message', {
data: {
data: {
correlationId: pendingDeleteCorrelation,
id: selected.value?.id,
success: true,
},
type: 'media:deleteResult',
},
}),
)
}, 500)
return
}
await nuiCall('gallery:delete', {
correlationId: pendingDeleteCorrelation,
id: selected.value.id,
})
}
function onMessage(event: MessageEvent): void {
const message = event.data as { data?: DeleteResult; type?: string }
if (
message.type !== 'media:deleteResult' ||
message.data?.correlationId !== pendingDeleteCorrelation
) {
return
}
deleting.value = false
if (message.data.success && message.data.id) {
media.value = media.value.filter((entry) => entry.id !== message.data?.id)
closeMedia()
showToast(phone.t('Apps.photos.deleted'))
} else {
showToast(
phone.t(`Apps.photos.errors.${mediaErrorKey(message.data.error)}`),
)
}
}
watch(filter, () => void loadGallery())
watch(hasMore, () => void nextTick().then(observeMore))
onMounted(() => {
window.addEventListener('message', onMessage)
void loadGallery()
})
onBeforeUnmount(() => {
observer?.disconnect()
stopDragging()
if (toastTimer !== undefined) window.clearTimeout(toastTimer)
window.removeEventListener('message', onMessage)
})
</script>
<template>
<k-page
v-if="!selected"
class="gallery-page !pt-[44px] !pb-[25px]"
:aria-label="phone.t('Apps.photos.name')"
>
<k-navbar large transparent :title="phone.t('Apps.photos.name')">
<template #right>
<span class="gallery-count">{{ countLabel }}</span>
</template>
<template #subnavbar>
<k-segmented class="gallery-filter">
<k-segmented-button
:active="filter === 'all'"
@click="filter = 'all'"
>
{{ phone.t('Apps.photos.filters.all') }}
</k-segmented-button>
<k-segmented-button
:active="filter === 'photo'"
@click="filter = 'photo'"
>
{{ phone.t('Apps.photos.filters.photos') }}
</k-segmented-button>
<k-segmented-button
:active="filter === 'video'"
@click="filter = 'video'"
>
{{ phone.t('Apps.photos.filters.videos') }}
</k-segmented-button>
</k-segmented>
</template>
</k-navbar>
<div v-if="loading" class="gallery-state">
<k-preloader />
<span>{{ phone.t('Apps.photos.loading') }}</span>
</div>
<k-block v-else-if="loadError" strong inset class="gallery-error">
{{ loadError }}
</k-block>
<div v-else-if="!media.length" class="gallery-state gallery-empty">
<strong>{{ phone.t('Apps.photos.emptyTitle') }}</strong>
<span>{{ phone.t('Apps.photos.emptyBody') }}</span>
</div>
<div v-else class="gallery-grid">
<button
v-for="entry in media"
:key="entry.id"
class="gallery-tile"
type="button"
:aria-label="
phone.t(
entry.mediaType === 'video'
? 'Apps.photos.videoAlt'
: 'Apps.photos.photoAlt',
)
"
@click="openMedia(entry)"
>
<img
v-if="entry.mediaType === 'photo'"
:src="entry.url"
alt=""
loading="lazy"
/>
<video
v-else
:src="entry.url"
muted
playsinline
preload="metadata"
></video>
<span v-if="entry.mediaType === 'video'" class="gallery-video-badge">
<Play :size="16" fill="currentColor" />
</span>
</button>
<span
v-if="hasMore"
ref="loadTrigger"
class="gallery-load-trigger"
></span>
</div>
</k-page>
<k-page v-else class="gallery-detail !pt-[44px] !pb-[25px]">
<k-navbar
:title="
phone.t(
selected.mediaType === 'video'
? 'Apps.photos.video'
: 'Apps.photos.photo',
)
"
>
<template #left>
<k-navbar-back-link
component="button"
:text="phone.t('Common.back')"
@click="closeMedia"
/>
</template>
<template #right>
<k-link
component="button"
icon-only
class="text-red-500"
:aria-label="phone.t('Apps.photos.delete')"
:disabled="deleting"
@click="deleteDialogOpened = true"
>
<Trash2 :size="20" />
</k-link>
</template>
</k-navbar>
<div class="gallery-detail-stage">
<img
v-if="selected.mediaType === 'photo'"
:src="selected.url"
:alt="phone.t('Apps.photos.photoAlt')"
:style="imageStyle"
draggable="false"
@pointerdown="startDragging"
@dblclick="setZoom(imageZoom === 1 ? 2 : 1)"
/>
<video v-else :src="selected.url" controls autoplay playsinline></video>
</div>
<nav v-if="selected.mediaType === 'photo'" class="gallery-zoom-controls">
<k-link
component="button"
icon-only
:aria-label="phone.t('Apps.photos.zoomOut')"
:disabled="imageZoom === 1"
@click="setZoom(imageZoom - 0.5)"
><ZoomOut :size="20"
/></k-link>
<k-link
component="button"
icon-only
:aria-label="phone.t('Apps.photos.resetZoom')"
:disabled="imageZoom === 1"
@click="setZoom(1)"
><RotateCcw :size="19"
/></k-link>
<k-link
component="button"
icon-only
:aria-label="phone.t('Apps.photos.zoomIn')"
:disabled="imageZoom === 4"
@click="setZoom(imageZoom + 0.5)"
><ZoomIn :size="20"
/></k-link>
</nav>
<div class="gallery-detail-date">{{ formatDate(selected.createdAt) }}</div>
</k-page>
<k-dialog
:opened="deleteDialogOpened"
@backdropclick="deleteDialogOpened = false"
>
<template #title>{{ phone.t('Apps.photos.deleteTitle') }}</template>
<p>{{ phone.t('Apps.photos.deleteBody') }}</p>
<template #buttons>
<k-dialog-button @click="deleteDialogOpened = false">
{{ phone.t('Common.cancel') }}
</k-dialog-button>
<k-dialog-button strong class="text-red-500" @click="deleteSelected">
{{ phone.t('Common.delete') }}
</k-dialog-button>
</template>
</k-dialog>
<k-toast :opened="toastOpened" position="center" @click="toastOpened = false">
{{ toastText }}
</k-toast>
</template>
<style scoped>
.gallery-count {
color: #8e8e93;
font-size: 12px;
}
.gallery-filter {
width: calc(100% - 24px);
margin: 0 12px 8px;
}
.gallery-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2px;
padding: 8px 2px 30px;
}
.gallery-tile {
position: relative;
aspect-ratio: 1;
min-width: 0;
overflow: hidden;
border: 0;
background: #d1d1d6;
}
.gallery-tile img,
.gallery-tile video {
width: 100%;
height: 100%;
display: block;
object-fit: cover;
}
.gallery-video-badge {
position: absolute;
right: 7px;
bottom: 7px;
width: 28px;
height: 28px;
display: grid;
place-items: center;
border-radius: 50%;
background: #0009;
color: #fff;
}
.gallery-load-trigger {
height: 1px;
grid-column: 1 / -1;
}
.gallery-state {
min-height: 430px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 36px;
color: #8e8e93;
text-align: center;
}
.gallery-empty strong {
color: currentColor;
font-size: 20px;
}
.gallery-error {
color: #ff3b30;
}
.gallery-detail-stage {
height: calc(100cqh - 174px);
overflow: hidden;
background: #000;
display: grid;
place-items: center;
touch-action: none;
}
.gallery-detail-stage img,
.gallery-detail-stage video {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transform-origin: center;
user-select: none;
}
.gallery-detail-stage img {
transition: transform 0.12s ease-out;
}
.gallery-zoom-controls {
height: 48px;
display: flex;
align-items: center;
justify-content: center;
gap: 30px;
border-bottom: 1px solid #8e8e9333;
}
.gallery-detail-date {
padding: 12px 18px;
color: #8e8e93;
text-align: center;
font-size: 12px;
}
</style>
+53
View File
@@ -11,6 +11,20 @@ let authenticated = false
let draft = null
let linkedAccount = null
let mockNotes = []
let mockMedia = [
{
createdAt: Date.now() - 60_000,
id: 1,
mediaType: 'photo',
url: 'https://picsum.photos/seed/sky-phone-1/600/800',
},
{
createdAt: Date.now() - 120_000,
id: 2,
mediaType: 'video',
url: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
},
]
const deviceData = {}
const accountDevices = [
{
@@ -114,6 +128,44 @@ app.post('/api/:endpoint', (request, response) => {
})
return
}
if (endpoint === 'media:config') {
response.json({ success: true, data: { videoBitrateKbps: 1500 } })
return
}
if (endpoint === 'gallery:list') {
if (request.body.mockState === 'error') {
response.json({ success: false, error: 'service_unavailable' })
return
}
if (request.body.mockState === 'empty') {
response.json({ success: true, data: [] })
return
}
const filtered = request.body.mediaType
? mockMedia.filter((item) => item.mediaType === request.body.mediaType)
: mockMedia
const offset = Number(request.body.offset) || 0
const limit = Number(request.body.limit) || 36
response.json({
success: true,
data: filtered.slice(offset, offset + limit),
})
return
}
if (
endpoint === 'media:requestUpload' ||
endpoint === 'media:completeUpload' ||
endpoint === 'media:failUpload' ||
endpoint === 'media:cancelUpload'
) {
response.json({ success: true })
return
}
if (endpoint === 'gallery:delete') {
mockMedia = mockMedia.filter((item) => item.id !== Number(request.body.id))
response.json({ success: true })
return
}
if (endpoint === 'account:login' || endpoint === 'account:register') {
authenticated = true
linkedAccount = {
@@ -153,6 +205,7 @@ app.post('/api/:endpoint', (request, response) => {
authenticated = false
linkedAccount = null
mockNotes = []
mockMedia = []
for (const key of Object.keys(deviceData)) delete deviceData[key]
response.json({ success: true })
return
+35 -2
View File
@@ -61,7 +61,22 @@ Locales["en"] = {
},
},
calculator = { name = "Calculator" },
camera = { name = "Camera" },
camera = {
name = "Camera", flash = "Flash", flip = "Flip camera", photo = "Photo", video = "Video",
focusHelp = "Space for movement", returnHelp = "Space to return", uploading = "{count} uploading",
saving = "Saving video...", openGallery = "Open Gallery", takePhoto = "Take photo",
startRecording = "Start recording", stopRecording = "Stop recording", saved = "Saved to Gallery.",
errors = {
cancelled = "Capture cancelled.", capture_failed = "Unable to capture the game view.",
invalid_media_type = "The uploaded media type is invalid.", invalid_upload = "The upload could not be verified.",
invalid_upload_token = "The upload session is no longer valid.", missing_config = "Camera uploads are not configured.",
not_found = "The media item no longer exists.", owner_changed = "The active phone account changed during upload.",
operation_in_progress = "Another media operation is already in progress.",
rate_limited = "Too many media actions. Try again shortly.", request_failed = "The camera request failed.",
request_timeout = "The media service timed out.", unsupported = "Video recording is not supported.",
upload_failed = "The media upload failed.", upload_timeout = "The media upload timed out.",
},
},
clock = {
name = "Clock", lap = "Lap", minutes = "Minutes", add = "Add alarm", location = "Los Santos",
tabs = { world = "Clock", alarm = "Alarm", stopwatch = "Stopwatch", timer = "Timer" },
@@ -140,7 +155,25 @@ Locales["en"] = {
noResultsBody = "Try searching for a different word or phrase.", pin = "Pin note", unpin = "Unpin note",
deleteNote = "Delete note",
},
photos = { name = "Photos" },
photos = {
name = "Gallery", count = "{count} items", loading = "Loading Gallery...",
emptyTitle = "No Photos or Videos", emptyBody = "Captures from Camera will appear here.",
photo = "Photo", video = "Video", photoAlt = "Gallery photo", videoAlt = "Gallery video",
delete = "Delete media", deleteTitle = "Delete Media?",
deleteBody = "This photo or video will be permanently deleted.", deleted = "Media deleted.",
zoomIn = "Zoom in", zoomOut = "Zoom out", resetZoom = "Reset zoom",
filters = { all = "All", photos = "Photos", videos = "Videos" },
errors = {
cancelled = "The media action was cancelled.", capture_failed = "Unable to capture the game view.",
invalid_media_type = "The media type is invalid.", invalid_upload = "The upload could not be verified.",
invalid_upload_token = "The upload session is no longer valid.", missing_config = "Gallery uploads are not configured.",
not_found = "The media item no longer exists.", owner_changed = "The active phone account changed.",
operation_in_progress = "Another media operation is already in progress.",
rate_limited = "Too many media actions. Try again shortly.", request_failed = "The Gallery request failed.",
request_timeout = "The media service timed out.", unsupported = "This media format is not supported.",
upload_failed = "The media upload failed.", upload_timeout = "The media upload timed out.",
},
},
appStore = {
name = "App Store", eyebrow = "Discover", featured = "Featured", heroTitle = "Apps for every day",
heroBody = "Fresh ideas, built for your life in the city.", get = "GET", open = "OPEN",
+17
View File
@@ -0,0 +1,17 @@
Config.Media = {
FiveManage = {
ApiKey = "e4UZ9y39JfkxHoZMAgRUVK6KMQsNCKPJ", -- Dashboard -> Tokens -> create a token with Media access.
BaseUrl = "https://api.fivemanage.com/api/v3/file",
RequestTimeoutMs = 10000,
UploadTimeoutMs = 25000,
},
Photo = {
Encoding = "jpg",
Quality = 0.95,
},
Video = {
BitrateKbps = 1500,
},
UploadSessionTimeoutMs = 60000,
PageSize = 36,
}
+3
View File
@@ -24,12 +24,14 @@ client_scripts {
'config/locales/*.lua',
'source/bridge/client/framework.lua',
'source/bridge/client/callbacks.lua',
'source/client/camera.lua',
'source/client/main.lua',
}
server_scripts {
'@oxmysql/lib/MySQL.lua',
'config/config.lua',
'config/media.lua',
'source/bridge/server/database.lua',
'source/bridge/server/migrations.lua',
'source/bridge/server/callbacks.lua',
@@ -43,6 +45,7 @@ server_scripts {
'source/server/calls.lua',
'source/server/notes.lua',
'source/server/mail.lua',
'source/server/media.lua',
}
files {
+275
View File
@@ -0,0 +1,275 @@
local first_person_view_mode = 4
local third_person_view_mode = 1
local front_camera_view_mode = 0
local front_camera_fov = 25.0
local front_camera_distance = 0.75
local front_camera_height = 0.05
local front_camera_target_height = 0.03
local camera_state = {
active = false,
enforcing = false,
flash_enabled = false,
flash_thread = false,
focus_watcher = false,
front_camera = false,
front_camera_handle = nil,
nui_focused = true,
previous_ped_view = nil,
previous_radar_hidden = nil,
previous_vehicle_view = nil,
}
local function rotation_to_direction(rotation)
local z = math.rad(rotation.z)
local x = math.rad(rotation.x)
local horizontal = math.abs(math.cos(x))
return vector3(-math.sin(z) * horizontal, math.cos(z) * horizontal, math.sin(x))
end
local function draw_flash_light()
local camera_coords = GetGameplayCamCoord()
local direction = rotation_to_direction(GetGameplayCamRot(2))
local light_position = camera_coords + (direction * 0.8)
DrawLightWithRange(light_position.x, light_position.y, light_position.z, 255, 255, 255, 12.0, 8.0)
end
local function set_flash_enabled(enabled)
camera_state.flash_enabled = enabled
if not enabled or not camera_state.active or camera_state.flash_thread then
return
end
camera_state.flash_thread = true
CreateThread(function()
while camera_state.active and camera_state.flash_enabled do
draw_flash_light()
Wait(0)
end
camera_state.flash_thread = false
end)
end
local function apply_camera_view()
local ped = PlayerPedId()
local view_mode = camera_state.front_camera and front_camera_view_mode or first_person_view_mode
if IsPedInAnyVehicle(ped, false) then
SetFollowVehicleCamViewMode(view_mode)
return
end
SetFollowPedCamViewMode(view_mode)
end
local function front_camera_position(ped)
local head = GetPedBoneCoords(ped, 31086, 0.0, 0.0, 0.0)
local forward = GetEntityForwardVector(ped)
local forward_vector = vector3(forward.x, forward.y, forward.z)
local offset = forward_vector * front_camera_distance
local camera_position = head + offset + vector3(0.0, 0.0, front_camera_height)
local to_camera = camera_position - head
local dot = (to_camera.x * forward_vector.x) + (to_camera.y * forward_vector.y) + (to_camera.z * forward_vector.z)
if dot < 0.0 then
camera_position = head - offset + vector3(0.0, 0.0, front_camera_height)
end
return camera_position, head + vector3(0.0, 0.0, front_camera_target_height)
end
local function ensure_front_camera(ped)
if camera_state.front_camera_handle and DoesCamExist(camera_state.front_camera_handle) then
return
end
camera_state.front_camera_handle = CreateCam("DEFAULT_SCRIPTED_CAMERA", true)
SetCamFov(camera_state.front_camera_handle, front_camera_fov)
SetCamActive(camera_state.front_camera_handle, true)
RenderScriptCams(true, false, 0, true, true)
end
local function clear_front_camera()
if camera_state.front_camera_handle and DoesCamExist(camera_state.front_camera_handle) then
RenderScriptCams(false, false, 0, true, true)
DestroyCam(camera_state.front_camera_handle, false)
end
camera_state.front_camera_handle = nil
end
local function restore_camera_view()
if camera_state.previous_ped_view ~= nil then
SetFollowPedCamViewMode(camera_state.previous_ped_view)
end
if camera_state.previous_vehicle_view ~= nil then
SetFollowVehicleCamViewMode(camera_state.previous_vehicle_view)
end
if camera_state.previous_radar_hidden ~= nil then
DisplayRadar(not camera_state.previous_radar_hidden)
end
end
local function set_camera_focus(focused)
if camera_state.nui_focused == focused then
return
end
camera_state.nui_focused = focused
if focused then
SetNuiFocus(true, true)
SetNuiFocusKeepInput(false)
SendNUIMessage({ type = "camera:focus", data = { focused = true } })
return
end
SetNuiFocus(false, false)
SetNuiFocusKeepInput(true)
SendNUIMessage({ type = "camera:focus", data = { focused = false } })
if camera_state.focus_watcher then
return
end
camera_state.focus_watcher = true
CreateThread(function()
while camera_state.active and not camera_state.nui_focused do
if IsControlJustReleased(0, 22) then
set_camera_focus(true)
break
end
Wait(0)
end
camera_state.focus_watcher = false
end)
end
local function set_camera_active(active)
if camera_state.active == active then
return
end
camera_state.active = active
if active then
camera_state.front_camera = false
clear_front_camera()
camera_state.previous_ped_view = GetFollowPedCamViewMode()
camera_state.previous_vehicle_view = GetFollowVehicleCamViewMode()
camera_state.previous_radar_hidden = IsRadarHidden()
DisplayRadar(false)
set_camera_focus(true)
apply_camera_view()
if camera_state.enforcing then
return
end
camera_state.enforcing = true
CreateThread(function()
local next_apply = 0
while camera_state.active do
HideHudAndRadarThisFrame()
if camera_state.front_camera then
local ped = PlayerPedId()
ensure_front_camera(ped)
local camera_position, target = front_camera_position(ped)
SetCamCoord(
camera_state.front_camera_handle,
camera_position.x,
camera_position.y,
camera_position.z
)
PointCamAtCoord(camera_state.front_camera_handle, target.x, target.y, target.z)
end
local now = GetGameTimer()
if now >= next_apply then
apply_camera_view()
next_apply = now + 250
end
Wait(0)
end
camera_state.enforcing = false
end)
return
end
camera_state.flash_enabled = false
camera_state.front_camera = false
clear_front_camera()
restore_camera_view()
if not camera_state.nui_focused then
camera_state.nui_focused = true
SetNuiFocusKeepInput(false)
SetNuiFocus(true, true)
end
end
local function set_front_camera(active)
if camera_state.front_camera == active then
return
end
camera_state.front_camera = active
if not camera_state.active then
return
end
if active then
ensure_front_camera(PlayerPedId())
else
clear_front_camera()
end
apply_camera_view()
end
RegisterNUICallback("camera:setActive", function(data, cb)
set_camera_active(data and data.active == true)
cb({ success = true })
end)
RegisterNUICallback("camera:setFocus", function(data, cb)
if camera_state.active then
set_camera_focus(data and data.focused == true)
end
cb({ success = true })
end)
RegisterNUICallback("camera:setFlash", function(data, cb)
set_flash_enabled(data and data.enabled == true)
cb({ success = true })
end)
RegisterNUICallback("camera:setFacing", function(data, cb)
set_front_camera(data and data.front == true)
cb({ success = true })
end)
RegisterNUICallback("media:requestUpload", function(data, cb)
TriggerServerEvent("sky_phone:media:request-upload", data or {})
cb({ success = true })
end)
RegisterNUICallback("media:completeUpload", function(data, cb)
TriggerServerEvent("sky_phone:media:complete-upload", data or {})
cb({ success = true })
end)
RegisterNUICallback("media:cancelUpload", function(data, cb)
TriggerServerEvent("sky_phone:media:cancel-upload", data or {})
cb({ success = true })
end)
RegisterNUICallback("media:failUpload", function(data, cb)
TriggerServerEvent("sky_phone:media:fail-upload", data or {})
cb({ success = true })
end)
RegisterNUICallback("gallery:delete", function(data, cb)
TriggerServerEvent("sky_phone:media:delete", data or {})
cb({ success = true })
end)
RegisterNetEvent("sky_phone:media:upload-ready", function(data)
SendNUIMessage({ type = "media:uploadReady", data = data })
end)
RegisterNetEvent("sky_phone:media:upload-result", function(data)
SendNUIMessage({ type = "media:uploadResult", data = data })
end)
RegisterNetEvent("sky_phone:media:delete-result", function(data)
SendNUIMessage({ type = "media:deleteResult", data = data })
end)
AddEventHandler("sky_phone:nuiClosed", function()
set_camera_active(false)
end)
AddEventHandler("onResourceStop", function(resource_name)
if resource_name == GetCurrentResourceName() then
set_camera_active(false)
SetNuiFocusKeepInput(false)
end
end)
+3
View File
@@ -43,6 +43,8 @@ local server_callbacks = {
"calls:answer",
"calls:decline",
"calls:hangup",
"gallery:list",
"media:config",
}
local function get_locale()
@@ -80,6 +82,7 @@ local function close_phone()
end
is_open = false
TriggerEvent("sky_phone:nuiClosed")
SetNuiFocus(notification_focus or sim_picker_open, notification_focus or sim_picker_open)
SendNUIMessage({ type = "app:close" })
Bridge.Callbacks.Trigger("sky_phone:device:close", {})
+2 -2
View File
@@ -4,8 +4,8 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sky Phone</title>
<script type="module" crossorigin src="./assets/sky-index-C4p7E0-O.js"></script>
<link rel="stylesheet" crossorigin href="./assets/sky-index-CjoATJPG.css">
<script type="module" crossorigin src="./assets/sky-index-BZSEyvMU.js"></script>
<link rel="stylesheet" crossorigin href="./assets/sky-index-StMblc29.css">
</head>
<body>
<div id="app"></div>
+33
View File
@@ -246,6 +246,39 @@ local schema = {
},
tableOptions = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
},
{
name = "sky_phone_media",
columns = {
{ name = "id", type = "BIGINT UNSIGNED NOT NULL AUTO_INCREMENT" },
{ name = "account_id", type = "BIGINT UNSIGNED NULL" },
{
name = "device_imei",
type = "CHAR(15) NULL",
characterSet = "ascii",
collation = "ascii_bin",
},
{ name = "url", type = "TEXT NOT NULL" },
{ name = "remote_id", type = "VARCHAR(128) NOT NULL" },
{ name = "media_type", type = "ENUM('photo', 'video') NOT NULL" },
{ name = "created_at", type = "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP" },
},
primaryKey = "id",
indexes = {
{ name = "idx_sky_phone_media_account", columns = "(`account_id`, `created_at`, `id`)" },
{ name = "idx_sky_phone_media_device", columns = "(`device_imei`, `created_at`, `id`)" },
},
foreignKeys = {
{
column = "account_id",
references = "`sky_phone_accounts` (`id`) ON DELETE CASCADE",
},
{
column = "device_imei",
references = "`sky_phone_devices` (`imei`) ON DELETE CASCADE",
},
},
tableOptions = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
},
{
name = "sky_phone_contacts",
columns = {
+475
View File
@@ -0,0 +1,475 @@
Bridge.Database.AfterMigration("sky_phone", function()
SkyPhoneMedia = {}
local pending_uploads = {}
local pending_deletes = {}
local function media_config()
return Config.Media.FiveManage
end
local function api_configured()
local api_key = media_config().ApiKey
return type(api_key) == "string" and api_key ~= "" and api_key ~= "YOUR_API_TOKEN"
end
local function http_request(url, method, body, headers, timeout_ms)
local request = promise.new()
local settled = false
PerformHttpRequest(url, function(status, response_body, response_headers)
if settled then
return
end
settled = true
request:resolve({
body = response_body,
headers = response_headers,
status = status,
})
end, method, body or "", headers or {})
SetTimeout(timeout_ms, function()
if settled then
return
end
settled = true
request:resolve({ status = 0, body = "request_timeout" })
end)
return Citizen.Await(request)
end
local function decode_response(response)
if type(response) ~= "table" or type(response.status) ~= "number" then
return nil, "invalid_response"
end
if response.status == 0 then
return nil, "request_timeout"
end
if response.status < 200 or response.status >= 300 then
return nil, ("request_failed_%s"):format(response.status)
end
local success, decoded = pcall(json.decode, response.body or "")
if not success or type(decoded) ~= "table" then
return nil, "invalid_response"
end
return decoded.data or decoded
end
local function request_presigned_url()
if not api_configured() then
return nil, "missing_config"
end
local config = media_config()
local response = http_request(
tostring(config.BaseUrl):gsub("/+$", "") .. "/presigned-url",
"GET",
"",
{ ["Authorization"] = config.ApiKey },
tonumber(config.RequestTimeoutMs) or 10000
)
local data, response_error = decode_response(response)
if not data then
return nil, response_error
end
local presigned_url = data.presignedUrl or data.presigned_url
if type(presigned_url) ~= "string" or presigned_url == "" then
return nil, "missing_presigned_url"
end
return presigned_url
end
local function get_remote_file(remote_id)
if not api_configured() then
return nil, "missing_config"
end
local config = media_config()
local response = http_request(
("%s/%s"):format(tostring(config.BaseUrl):gsub("/+$", ""), remote_id),
"GET",
"",
{ ["Authorization"] = config.ApiKey },
tonumber(config.RequestTimeoutMs) or 10000
)
return decode_response(response)
end
local function delete_remote_file(remote_id)
if not api_configured() then
return false, "missing_config"
end
local config = media_config()
local response = http_request(
("%s/%s"):format(tostring(config.BaseUrl):gsub("/+$", ""), remote_id),
"DELETE",
"",
{ ["Authorization"] = config.ApiKey },
tonumber(config.RequestTimeoutMs) or 10000
)
if response.status < 200 or response.status >= 300 then
return false, response.status == 0 and "request_timeout" or ("delete_failed_%s"):format(response.status)
end
return true
end
local function session_owner(source)
local session, error_response = SkyPhone.RequireSession(source)
if not session then
return nil, error_response
end
local device = SkyPhone.LoadDevice(session.imei)
if not device then
return nil, { success = false, error = "device_not_found" }
end
return {
account_id = device.account_id and tonumber(device.account_id) or nil,
imei = session.imei,
}
end
local function owner_condition(owner)
if owner.account_id then
return "`account_id` = ?", { owner.account_id }
end
return "`account_id` IS NULL AND `device_imei` = ?", { owner.imei }
end
local function owners_match(left, right)
return left.imei == right.imei and left.account_id == right.account_id
end
local function upload_result(source, correlation_id, success, error_code, media)
TriggerClientEvent("sky_phone:media:upload-result", source, {
correlationId = correlation_id,
success = success,
error = error_code,
media = media,
})
end
local function delete_result(source, correlation_id, success, error_code, media_id)
TriggerClientEvent("sky_phone:media:delete-result", source, {
correlationId = correlation_id,
success = success,
error = error_code,
id = media_id,
})
end
local function parse_metadata(value)
if type(value) == "table" then
return value
end
if type(value) ~= "string" then
return nil
end
local success, decoded = pcall(json.decode, value)
return success and type(decoded) == "table" and decoded or nil
end
local function valid_remote_id(value)
return type(value) == "string" and #value >= 4 and #value <= 128 and value:match("^[%w_%-]+$") ~= nil
end
local function verify_remote_upload(state, remote_id, uploaded_url)
if not valid_remote_id(remote_id) or type(uploaded_url) ~= "string" or #uploaded_url > 2048
or not uploaded_url:match("^https://")
then
return nil, "invalid_upload"
end
local remote, remote_error = get_remote_file(remote_id)
if not remote then
return nil, remote_error
end
if remote.id ~= remote_id then
return nil, "invalid_upload"
end
if remote.url ~= uploaded_url and remote.originalUrl ~= uploaded_url then
return nil, "invalid_upload"
end
local remote_type = tostring(remote.type or remote.mimeType or ""):lower()
if state.media_type == "photo" and remote_type ~= "" and not remote_type:find("image", 1, true) then
return nil, "invalid_media_type"
end
if state.media_type == "video" and remote_type ~= "" and not remote_type:find("video", 1, true) then
return nil, "invalid_media_type"
end
local metadata = parse_metadata(remote.metadata)
if not metadata or metadata.captureToken ~= state.capture_token then
return nil, "invalid_upload_token"
end
return {
remote_id = remote_id,
url = remote.url or uploaded_url,
}
end
local function expire_upload(request_id)
local state = pending_uploads[request_id]
if not state or state.completing then
return
end
pending_uploads[request_id] = nil
upload_result(state.source, state.correlation_id, false, "upload_timeout")
end
Bridge.Callbacks.Register("sky_phone:gallery:list", function(source, data)
local owner, error_response = session_owner(source)
if not owner then
return error_response
end
data = data or {}
local limit = math.max(1, math.min(math.floor(tonumber(data.limit) or Config.Media.PageSize), 100))
local offset = math.max(0, math.floor(tonumber(data.offset) or 0))
local media_type = data.mediaType
if media_type ~= "photo" and media_type ~= "video" then
media_type = nil
end
local condition, params = owner_condition(owner)
if media_type then
condition = condition .. " AND `media_type` = ?"
params[#params + 1] = media_type
end
params[#params + 1] = limit
params[#params + 1] = offset
local rows = Bridge.Database.Query(([[
SELECT `id`, `url`, `media_type` AS `mediaType`,
UNIX_TIMESTAMP(`created_at`) * 1000 AS `createdAt`
FROM `sky_phone_media`
WHERE %s
ORDER BY `created_at` DESC, `id` DESC
LIMIT ? OFFSET ?
]]):format(condition), params)
for _, row in ipairs(rows) do
row.id = tonumber(row.id)
row.createdAt = tonumber(row.createdAt) or 0
end
return { success = true, data = rows }
end)
Bridge.Callbacks.Register("sky_phone:media:config", function(source)
local owner, error_response = session_owner(source)
if not owner then
return error_response
end
return {
success = true,
data = {
videoBitrateKbps = tonumber(Config.Media.Video.BitrateKbps) or 1500,
},
}
end)
RegisterNetEvent("sky_phone:media:request-upload", function(data)
local src = source
data = data or {}
local correlation_id = data.correlationId
local media_type = data.mediaType
if type(correlation_id) ~= "string" or #correlation_id > 80
or (media_type ~= "photo" and media_type ~= "video")
then
upload_result(src, correlation_id, false, "invalid_request")
return
end
if not SkyPhone.AllowOperation(src, "media_write", 20, 60) then
upload_result(src, correlation_id, false, "rate_limited")
return
end
local owner, error_response = session_owner(src)
if not owner then
upload_result(src, correlation_id, false, error_response.error)
return
end
local presigned_url, presigned_error = request_presigned_url()
if not presigned_url then
upload_result(src, correlation_id, false, presigned_error)
return
end
local ids = Bridge.Database.Query("SELECT UUID() AS `request_id`, UUID() AS `capture_token`", {})
local request_id = ids[1] and ids[1].request_id
local capture_token = ids[1] and ids[1].capture_token
if type(request_id) ~= "string" or type(capture_token) ~= "string" then
upload_result(src, correlation_id, false, "request_failed")
return
end
pending_uploads[request_id] = {
capture_token = capture_token,
correlation_id = correlation_id,
media_type = media_type,
owner = owner,
source = src,
}
SetTimeout(tonumber(Config.Media.UploadSessionTimeoutMs) or 60000, function()
expire_upload(request_id)
end)
TriggerClientEvent("sky_phone:media:upload-ready", src, {
captureToken = capture_token,
correlationId = correlation_id,
mediaType = media_type,
photo = Config.Media.Photo,
presignedUrl = presigned_url,
requestId = request_id,
uploadTimeoutMs = media_config().UploadTimeoutMs,
video = Config.Media.Video,
})
end)
RegisterNetEvent("sky_phone:media:complete-upload", function(data)
local src = source
data = data or {}
local request_id = data.requestId
local state = type(request_id) == "string" and pending_uploads[request_id] or nil
if not state or state.source ~= src or state.completing then
return
end
state.completing = true
local owner, error_response = session_owner(src)
if not owner or not owners_match(owner, state.owner) then
pending_uploads[request_id] = nil
upload_result(src, state.correlation_id, false, error_response and error_response.error or "owner_changed")
return
end
local verified, verify_error = verify_remote_upload(state, data.remoteId, data.url)
if not verified then
pending_uploads[request_id] = nil
upload_result(src, state.correlation_id, false, verify_error)
return
end
local result
if owner.account_id then
result = Bridge.Database.Query([[
INSERT INTO `sky_phone_media` (`account_id`, `device_imei`, `url`, `remote_id`, `media_type`)
VALUES (?, NULL, ?, ?, ?)
]], { owner.account_id, verified.url, verified.remote_id, state.media_type })
else
result = Bridge.Database.Query([[
INSERT INTO `sky_phone_media` (`account_id`, `device_imei`, `url`, `remote_id`, `media_type`)
VALUES (NULL, ?, ?, ?, ?)
]], { owner.imei, verified.url, verified.remote_id, state.media_type })
end
pending_uploads[request_id] = nil
local media_id = type(result) == "number" and result or (type(result) == "table" and tonumber(result.insertId))
if not media_id then
delete_remote_file(verified.remote_id)
upload_result(src, state.correlation_id, false, "request_failed")
return
end
upload_result(src, state.correlation_id, true, nil, {
id = media_id,
url = verified.url,
mediaType = state.media_type,
createdAt = os.time() * 1000,
})
end)
RegisterNetEvent("sky_phone:media:cancel-upload", function(data)
local src = source
local request_id = data and data.requestId
local state = type(request_id) == "string" and pending_uploads[request_id] or nil
if state and state.source == src and not state.completing then
pending_uploads[request_id] = nil
upload_result(src, state.correlation_id, false, "cancelled")
end
end)
RegisterNetEvent("sky_phone:media:fail-upload", function(data)
local src = source
local request_id = data and data.requestId
local state = type(request_id) == "string" and pending_uploads[request_id] or nil
if not state or state.source ~= src or state.completing then
return
end
local allowed_errors = {
capture_failed = true,
unsupported = true,
upload_failed = true,
upload_timeout = true,
}
pending_uploads[request_id] = nil
local error_code = allowed_errors[data.error] and data.error or "upload_failed"
upload_result(src, state.correlation_id, false, error_code)
end)
RegisterNetEvent("sky_phone:media:delete", function(data)
local src = source
data = data or {}
local correlation_id = data.correlationId
local media_id = tonumber(data.id)
if type(correlation_id) ~= "string" or #correlation_id > 80 or not media_id then
delete_result(src, correlation_id, false, "invalid_request", media_id)
return
end
if not SkyPhone.AllowOperation(src, "media_delete", 30, 60) then
delete_result(src, correlation_id, false, "rate_limited", media_id)
return
end
local owner, error_response = session_owner(src)
if not owner then
delete_result(src, correlation_id, false, error_response.error, media_id)
return
end
local condition, params = owner_condition(owner)
local query_params = { media_id }
for _, value in ipairs(params) do
query_params[#query_params + 1] = value
end
local rows = Bridge.Database.Query(([[
SELECT `id`, `remote_id` FROM `sky_phone_media`
WHERE `id` = ? AND %s LIMIT 1
]]):format(condition), query_params)
local row = rows[1]
if not row then
delete_result(src, correlation_id, false, "not_found", media_id)
return
end
if pending_deletes[media_id] then
delete_result(src, correlation_id, false, "operation_in_progress", media_id)
return
end
pending_deletes[media_id] = src
local deleted, delete_error = delete_remote_file(row.remote_id)
if not deleted then
pending_deletes[media_id] = nil
delete_result(src, correlation_id, false, delete_error, media_id)
return
end
Bridge.Database.Query(("DELETE FROM `sky_phone_media` WHERE `id` = ? AND %s"):format(condition), query_params)
pending_deletes[media_id] = nil
delete_result(src, correlation_id, true, nil, media_id)
end)
function SkyPhoneMedia.GetDeviceRemoteIds(imei)
local rows = Bridge.Database.Query([[
SELECT `id`, `remote_id` FROM `sky_phone_media`
WHERE `account_id` IS NULL AND `device_imei` = ?
]], { imei })
return rows
end
function SkyPhoneMedia.CleanupRemoteFiles(rows)
CreateThread(function()
for _, row in ipairs(rows) do
local deleted, delete_error = delete_remote_file(row.remote_id)
if not deleted then
Bridge.Debug(
"warn",
"[sky_phone] Could not delete remote media %s during factory reset: %s.",
tostring(row.id),
tostring(delete_error)
)
end
end
end)
end
AddEventHandler("playerDropped", function()
local src = source
for request_id, state in pairs(pending_uploads) do
if state.source == src then
pending_uploads[request_id] = nil
end
end
end)
if not api_configured() then
print("^3[sky_phone] Camera and Gallery uploads are disabled until Config.Media.FiveManage.ApiKey is set in config/media.lua.^7")
end
end)
+14
View File
@@ -356,6 +356,14 @@ local function link_account(source, account)
]],
params = { account.id, session.imei },
},
{
query = [[
UPDATE `sky_phone_media`
SET `account_id` = ?, `device_imei` = NULL
WHERE `device_imei` = ? AND `account_id` IS NULL
]],
params = { account.id, session.imei },
},
}) then
return { success = false, error = "request_failed" }
end
@@ -752,6 +760,7 @@ Bridge.Callbacks.Register("sky_phone:device:factory-reset", function(source)
if not session then
return error_response
end
local media_remote_ids = SkyPhoneMedia.GetDeviceRemoteIds(session.imei)
if not Bridge.Database.Transaction({
{
query = "DELETE FROM `sky_phone_device_data` WHERE `device_imei` = ?",
@@ -761,6 +770,10 @@ Bridge.Callbacks.Register("sky_phone:device:factory-reset", function(source)
query = "DELETE FROM `sky_phone_notes` WHERE `device_imei` = ? AND `account_id` IS NULL",
params = { session.imei },
},
{
query = "DELETE FROM `sky_phone_media` WHERE `device_imei` = ? AND `account_id` IS NULL",
params = { session.imei },
},
{
query = "DELETE FROM `sky_phone_contacts` WHERE `device_imei` = ? AND `account_id` IS NULL",
params = { session.imei },
@@ -776,6 +789,7 @@ Bridge.Callbacks.Register("sky_phone:device:factory-reset", function(source)
}) then
return { success = false, error = "request_failed" }
end
SkyPhoneMedia.CleanupRemoteFiles(media_remote_ids)
refresh_source(source)
return { success = true }
end)
+15
View File
@@ -109,6 +109,21 @@ CREATE TABLE IF NOT EXISTS `sky_phone_notes` (
FOREIGN KEY (`device_imei`) REFERENCES `sky_phone_devices` (`imei`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `sky_phone_media` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`account_id` BIGINT UNSIGNED NULL,
`device_imei` CHAR(15) CHARACTER SET ascii COLLATE ascii_bin NULL,
`url` TEXT NOT NULL,
`remote_id` VARCHAR(128) NOT NULL,
`media_type` ENUM('photo', 'video') NOT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_sky_phone_media_account` (`account_id`, `created_at`, `id`),
KEY `idx_sky_phone_media_device` (`device_imei`, `created_at`, `id`),
FOREIGN KEY (`account_id`) REFERENCES `sky_phone_accounts` (`id`) ON DELETE CASCADE,
FOREIGN KEY (`device_imei`) REFERENCES `sky_phone_devices` (`imei`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `sky_phone_contacts` (
`id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`contact_id` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL,