ENH - integrate camera and gallery updates

# Conflicts:
#	frontend/src/config/apps.ts
#	sky_phone/fxmanifest.lua
#	sky_phone/source/html/index.html
This commit is contained in:
smx.pusha
2026-08-06 15:07:55 +02:00
38 changed files with 3185 additions and 862 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
+17 -11
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'
@@ -26,6 +27,7 @@ import { useAccountStore } from '@/stores/account'
import { useMailStore } from '@/stores/mail'
import { useMediaStore } from '@/stores/media'
import { useMarketplaceStore } from '@/stores/marketplace'
import { useAppStoreStore } from '@/stores/app-store'
import { useNotesStore } from '@/stores/notes'
import { useWeatherStore } from '@/stores/weather'
import {
@@ -84,6 +86,7 @@ const calls = useCallsStore()
const mail = useMailStore()
const media = useMediaStore()
const marketplace = useMarketplaceStore()
const appStore = useAppStoreStore()
const notes = useNotesStore()
const weather = useWeatherStore()
const notifications = useNotificationsStore()
@@ -110,7 +113,6 @@ const phoneFrameImage = computed(
)
let clockTicker: ReturnType<typeof setInterval> | undefined
let unlockTimer: number | undefined
let cameraTimer: number | undefined
function getViewportScale(): number {
const heightScale = window.innerHeight / REFERENCE_VIEWPORT_HEIGHT
@@ -126,6 +128,7 @@ function hydratePhone(payload: PhoneOpenPayload): void {
clock.hydrate(payload.device?.data.alarms?.payload)
games.hydrate(payload.device?.data.games?.payload)
media.hydrate(payload.device?.data.media?.payload)
appStore.hydrate(payload.device?.data.apps?.payload)
void mail.bootstrap(payload.account?.email ?? '')
if (payload.account?.email) void marketplace.loadCounts()
else marketplace.setCounts({ active: 0, unread: 0 })
@@ -226,22 +229,21 @@ function updateViewportScale(): void {
viewportScale.value = getViewportScale()
}
function unlockPhone(destination?: 'camera'): void {
function unlockPhone(): void {
if (!isLocked.value) return
isUnlocking.value = true
isLocked.value = false
if (destination === 'camera') {
cameraTimer = window.setTimeout(() => {
void router.push('/apps/camera')
}, 260)
}
unlockTimer = window.setTimeout(() => {
isUnlocking.value = false
}, 720)
}
function unlockCamera(): void {
unlockPhone()
window.setTimeout(() => void router.push('/apps/camera'), 0)
}
onMounted(() => {
window.addEventListener('message', onMessage)
window.addEventListener('keydown', onKeydown)
@@ -349,7 +351,6 @@ watch(
() => phone.isOpen,
(isOpen) => {
if (unlockTimer !== undefined) window.clearTimeout(unlockTimer)
if (cameraTimer !== undefined) window.clearTimeout(cameraTimer)
if (!isOpen) {
weather.stop()
isLocked.value = false
@@ -368,7 +369,6 @@ onBeforeUnmount(() => {
weather.stop()
if (clockTicker) clearInterval(clockTicker)
if (unlockTimer !== undefined) window.clearTimeout(unlockTimer)
if (cameraTimer !== undefined) window.clearTimeout(cameraTimer)
window.removeEventListener('message', onMessage)
window.removeEventListener('keydown', onKeydown)
window.removeEventListener('resize', updateViewportScale)
@@ -377,6 +377,7 @@ onBeforeUnmount(() => {
</script>
<template>
<PhoneMediaCapture />
<SimPhonePicker
v-if="simPicker"
:choices="simPicker.choices"
@@ -394,6 +395,7 @@ onBeforeUnmount(() => {
class="phone-stage"
:class="{
'phone-stage--dev': isDevelopment,
'phone-stage--landscape': phone.cameraLandscape,
'phone-stage--peek': notifications.isPeeking,
}"
:style="phoneResolutionStyle"
@@ -439,7 +441,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"
+27 -494
View File
@@ -251,6 +251,10 @@ button {
height: 844px;
zoom: var(--phone-zoom, 1);
}
.phone-stage--landscape .phone-resolution-wrapper--primary {
width: 844px;
height: 390px;
}
.phone-device-row {
display: flex;
align-items: flex-end;
@@ -282,6 +286,11 @@ button {
box-shadow: none;
filter: drop-shadow(0 40px 100px #0009);
}
.phone-stage--landscape .phone-resolution-wrapper--primary .phone-device {
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(-90deg);
}
.phone-device__frame {
position: absolute;
z-index: 100;
@@ -497,6 +506,18 @@ button {
bottom: 25px;
left: 0;
}
.lock-screen__shortcuts {
display: flex;
justify-content: space-between;
padding: 0 48px;
}
.lock-screen__shortcut {
--color-primary: #8e8e93;
}
.lock-screen__shortcut svg {
width: 21px;
height: 21px;
}
.lock-screen__swipe {
width: 100%;
margin-top: 18px;
@@ -1105,7 +1126,12 @@ button {
.weather-app--rain .weather-app__backdrop,
.weather-app--thunder .weather-app__backdrop {
background:
repeating-linear-gradient(104deg, transparent 0 22px, #bcecff17 23px 25px, transparent 26px 49px),
repeating-linear-gradient(
104deg,
transparent 0 22px,
#bcecff17 23px 25px,
transparent 26px 49px
),
linear-gradient(165deg, #354b69 0%, #253952 46%, #101b2d 100%);
}
.weather-app--thunder .weather-app__backdrop {
@@ -1734,174 +1760,9 @@ button {
.clock-timer {
padding-bottom: 28px;
}
.camera-app {
padding: 45px 0 25px;
background: #080808;
}
.camera-viewfinder {
position: relative;
height: 510px;
overflow: hidden;
background:
radial-gradient(circle at 66% 25%, #ffc66c99, transparent 18%),
linear-gradient(145deg, #193641, #443354 55%, #0c1b20);
}
.camera-facing--front {
background:
radial-gradient(circle at 48% 32%, #ffb58f99, transparent 16%),
linear-gradient(145deg, #56394e, #172f48);
}
.camera-grid {
position: absolute;
inset: 0;
background:
linear-gradient(
transparent 33%,
#ffffff30 33.2%,
transparent 33.5%,
transparent 66%,
#ffffff30 66.2%,
transparent 66.5%
),
linear-gradient(
90deg,
transparent 33%,
#ffffff30 33.2%,
transparent 33.5%,
transparent 66%,
#ffffff30 66.2%,
transparent 66.5%
);
}
.camera-flash {
position: absolute;
z-index: 3;
inset: 0;
background: white;
opacity: 0;
transition: opacity 0.12s;
}
.camera-flash.active {
opacity: 1;
}
.camera-zoom {
position: absolute;
bottom: 14px;
left: 0;
right: 0;
display: flex;
justify-content: center;
gap: 7px;
}
.camera-zoom button {
width: 34px;
height: 34px;
border: 0;
border-radius: 50%;
background: #0009;
color: white;
font-size: 11px;
}
.camera-zoom button.active {
color: #ffcc00;
}
.camera-modes {
height: 35px;
display: flex;
align-items: center;
justify-content: center;
gap: 18px;
}
.camera-modes button {
border: 0;
background: none;
color: white;
text-transform: uppercase;
font-size: 10px;
}
.camera-modes button.active {
color: #ffcc00;
}
.camera-controls {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
text-align: center;
}
.camera-controls > button {
justify-self: center;
width: 43px;
height: 43px;
border: 0;
border-radius: 50%;
background: #29292b;
color: white;
}
.camera-controls .shutter {
width: 65px;
height: 65px;
border: 4px solid white;
background: #fff;
color: #111;
box-shadow: inset 0 0 0 3px #000;
}
.photos-app,
.store-app {
background: #000;
}
.photo-grid {
height: calc(100% - 115px);
overflow: auto;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 111px;
gap: 2px;
padding-bottom: 65px;
}
.photo-tile {
min-height: 100px;
}
.album-cards {
padding: 12px 17px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
}
.album-cards article {
display: flex;
flex-direction: column;
}
.album-cards .photo-tile {
height: 145px;
border-radius: 13px;
}
.album-cards small {
color: #888;
}
.album-cards .favorites {
background: linear-gradient(145deg, #ff4777, #7f42db);
}
.featured-photo {
padding: 12px 17px;
}
.featured-photo p {
text-transform: uppercase;
color: #aaa;
font-size: 12px;
font-weight: 700;
}
.featured-photo div {
height: 390px;
border-radius: 19px;
display: flex;
align-items: flex-end;
padding: 18px;
}
.featured-photo span {
font-size: 25px;
font-weight: 700;
text-shadow: 0 2px 8px #000;
}
.store-app {
overflow-y: auto;
}
@@ -1980,165 +1841,6 @@ button {
font-weight: 400;
}
.reference-camera {
display: grid;
grid-template-rows: 83px minmax(0, 1fr) 190px;
padding: 0 0 24px;
background: #020202;
}
.camera-topbar {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: end;
padding: 45px 15px 11px;
}
.camera-topbar > div {
display: flex;
gap: 17px;
}
.camera-topbar > svg {
justify-self: end;
}
.camera-topbar button {
border: 0;
background: transparent;
color: inherit;
}
.camera-topbar .camera-chevron {
width: 34px;
height: 26px;
display: grid;
place-items: center;
border-radius: 20px;
background: #262629;
}
.reference-viewfinder {
position: relative;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 66% 21%, #ffd88baa, transparent 15%),
radial-gradient(circle at 45% 52%, #6d8ca5 0 6%, transparent 7%),
linear-gradient(150deg, #173542, #5b3e5b 56%, #13191c);
}
.reference-viewfinder::after {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
115deg,
transparent 45%,
#ffffff0f 46%,
transparent 48%
);
}
.focus-corner {
position: absolute;
z-index: 2;
width: 24px;
height: 24px;
border-color: white;
}
.focus-corner--tl {
top: 1px;
left: 1px;
border-top: 1px solid;
border-left: 1px solid;
}
.focus-corner--tr {
top: 1px;
right: 1px;
border-top: 1px solid;
border-right: 1px solid;
}
.focus-corner--bl {
bottom: 1px;
left: 1px;
border-bottom: 1px solid;
border-left: 1px solid;
}
.focus-corner--br {
right: 1px;
bottom: 1px;
border-right: 1px solid;
border-bottom: 1px solid;
}
.reference-viewfinder .camera-zoom {
z-index: 3;
bottom: 13px;
}
.reference-viewfinder .camera-zoom button {
display: inline-flex;
align-items: center;
justify-content: center;
background: #0008;
font-weight: 700;
}
.reference-viewfinder .camera-zoom small {
margin-left: 1px;
font-size: 8px;
}
.reference-camera-footer {
display: grid;
grid-template-rows: 43px 1fr;
background: #020202;
}
.camera-mode-strip {
display: flex;
align-items: center;
gap: 21px;
padding: 0 148px;
overflow: hidden;
}
.camera-mode-strip button {
flex: none;
padding: 0;
border: 0;
background: transparent;
color: white;
font-size: 10px;
font-weight: 650;
text-transform: uppercase;
white-space: nowrap;
}
.camera-mode-strip button.active {
color: #ffd60a;
}
.camera-shutter-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
padding: 0 31px 12px;
}
.camera-thumbnail {
width: 44px;
height: 44px;
border-radius: 4px;
}
.reference-shutter {
justify-self: center;
width: 62px;
height: 62px;
display: grid;
place-items: center;
border: 3px solid white;
border-radius: 50%;
background: white;
color: #111;
box-shadow: inset 0 0 0 3px #020202;
}
.reference-flip {
justify-self: end;
width: 42px;
height: 42px;
display: grid;
place-items: center;
border: 0;
border-radius: 50%;
background: #1c1c1e;
color: white;
}
.reference-tabbar {
position: absolute;
z-index: 6;
@@ -2189,169 +1891,6 @@ button {
color: #000;
}
.reference-photos {
padding: 0 0 79px;
background: #020202;
}
.photos-library,
.photos-scroll {
height: 100%;
overflow-y: auto;
}
.photos-floating-header {
position: sticky;
z-index: 3;
top: 0;
height: 95px;
display: flex;
align-items: flex-end;
gap: 8px;
padding: 47px 17px 14px;
background: linear-gradient(#000 55%, transparent);
}
.photos-floating-header > div {
display: flex;
flex: 1;
flex-direction: column;
}
.photos-floating-header strong {
font-size: 17px;
}
.photos-floating-header span {
font-size: 12px;
font-weight: 600;
}
.photos-floating-header button {
height: 27px;
padding: 0 12px;
border: 0;
border-radius: 18px;
background: #ffffff1d;
color: white;
font-size: 11px;
font-weight: 650;
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.photos-floating-header button:last-child {
width: 28px;
padding: 0;
border-radius: 50%;
}
.reference-photo-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 2px;
}
.reference-photo-grid article {
aspect-ratio: 1;
}
.photos-count {
padding: 15px;
text-align: center;
font-size: 11px;
}
.photos-period {
position: sticky;
bottom: 5px;
width: max-content;
margin: 0 auto;
display: flex;
padding: 3px;
border-radius: 22px;
background: #303033aa;
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.photos-period button {
padding: 5px 12px;
border: 0;
border-radius: 18px;
background: transparent;
color: #ddd;
font-size: 10px;
font-weight: 650;
}
.photos-period button.active {
background: #ffffff25;
color: white;
}
.photos-scroll {
padding: 82px 16px 20px;
}
.photos-scroll > h1 {
margin: 0 0 28px;
font-size: 34px;
}
.photos-section-title {
margin-top: 22px;
padding-top: 13px;
display: flex;
align-items: end;
border-top: 1px solid #ffffff1b;
}
.photos-section-title h2 {
flex: 1;
margin: 0;
font-size: 22px;
}
.photos-section-title button {
border: 0;
background: transparent;
color: #0a84ff;
}
.memory-card {
position: relative;
height: 410px;
margin-top: 12px;
padding: 16px;
display: flex;
flex-direction: column;
border-radius: 17px;
box-shadow: inset 0 -160px 100px #0008;
}
.memory-card > svg {
margin-left: auto;
}
.memory-card > div {
margin-top: auto;
display: flex;
flex-direction: column;
}
.memory-card strong {
font-size: 26px;
}
.memory-card span {
font-size: 11px;
letter-spacing: 2px;
text-transform: uppercase;
}
.featured-row {
display: flex;
gap: 9px;
margin-top: 12px;
overflow-x: auto;
}
.featured-row article {
width: 88%;
flex: none;
display: flex;
flex-direction: column;
}
.featured-row article > div {
aspect-ratio: 1;
border-radius: 10px;
}
.featured-row article span {
color: #777;
font-size: 12px;
}
.reference-photos .photo-grid {
height: auto;
margin-top: 13px;
padding-bottom: 10px;
}
.reference-store {
padding: 0 0 79px;
background: #0e0e0e;
@@ -2505,12 +2044,6 @@ button {
*::-webkit-scrollbar {
display: none;
}
.camera-mode-strip {
padding: 0;
}
.camera-mode-strip button:first-child {
margin-left: -205px;
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
+3
View File
@@ -36,6 +36,8 @@ const notificationBadgeColors = {
}
function launch(event: MouseEvent): void {
if (!props.app.route) return
const button = event.currentTarget as HTMLElement
const screen = button.closest('.phone-screen')
const icon = button.querySelector<HTMLElement>('.app-icon')
@@ -68,6 +70,7 @@ function launch(event: MouseEvent): void {
:class="{ 'app-icon-button--compact': compact }"
type="button"
:aria-label="phone.t(app.labelKey)"
:aria-disabled="!app.route"
@click="launch"
>
<span class="app-icon-anchor" aria-hidden="true">
+40 -43
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { kLink, kNavbar } from 'konsta/vue'
import { kFab } from 'konsta/vue'
import {
BatteryMedium,
Camera,
@@ -13,7 +13,8 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { usePhoneStore } from '@/stores/phone'
const emit = defineEmits<{
unlock: [destination?: 'camera']
camera: []
unlock: []
}>()
const phone = usePhoneStore()
@@ -21,12 +22,11 @@ const now = ref(new Date())
const dragOffset = ref(0)
const dragging = ref(false)
const flashlightActive = ref(false)
const lockNavbarColors = { bgIos: 'bg-transparent' }
const neutralGlassClass =
'!bg-white/10 !shadow-none ring-1 ring-inset ring-white/15 backdrop-saturate-150'
const activeFlashlightGlassClass =
'!bg-white !shadow-none ring-1 ring-inset ring-white/60 backdrop-saturate-150'
const whiteNavbarLinkColors = { navbarTextIos: 'text-white' }
const shortcutColors = {
bgIos: 'bg-ios-light-glass dark:bg-ios-dark-glass',
activeBgIos: 'active:bg-white/90 dark:active:bg-white/20',
textIos: 'text-black dark:text-white',
}
let pointerStart = 0
let pointerStartedAt = 0
let clockTicker: number | undefined
@@ -52,12 +52,15 @@ const time = computed(() =>
const dragStyle = computed(() => ({
'--lock-drag': `${dragOffset.value}px`,
}))
const flashlightGlassClass = computed(() =>
flashlightActive.value ? activeFlashlightGlassClass : neutralGlassClass,
const flashlightShortcutColors = computed(() =>
flashlightActive.value
? {
...shortcutColors,
bgIos: 'bg-white',
textIos: 'text-purple-500',
}
: shortcutColors,
)
const flashlightLinkColors = computed(() => ({
navbarTextIos: flashlightActive.value ? 'text-purple-500' : 'text-white',
}))
function onPointerDown(event: PointerEvent): void {
if ((event.target as HTMLElement).closest('button')) return
@@ -146,38 +149,32 @@ onBeforeUnmount(() => {
</div>
<div class="lock-screen__footer">
<k-navbar
transparent
:colors="lockNavbarColors"
inner-class="!px-12"
:left-class="flashlightGlassClass"
:right-class="neutralGlassClass"
>
<template #left>
<k-link
component="button"
icon-only
:colors="flashlightLinkColors"
:link-props="{ type: 'button' }"
:aria-label="phone.t('LockScreen.flashlight')"
@click="flashlightActive = !flashlightActive"
>
<nav class="lock-screen__shortcuts">
<k-fab
component="button"
type="button"
class="lock-screen__shortcut"
:colors="flashlightShortcutColors"
:aria-label="phone.t('LockScreen.flashlight')"
@click="flashlightActive = !flashlightActive"
>
<template #icon>
<Flashlight :stroke-width="1.4" aria-hidden="true" />
</k-link>
</template>
<template #right>
<k-link
component="button"
icon-only
:colors="whiteNavbarLinkColors"
:link-props="{ type: 'button' }"
:aria-label="phone.t('LockScreen.camera')"
@click="emit('unlock', 'camera')"
>
</template>
</k-fab>
<k-fab
component="button"
type="button"
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" />
</k-link>
</template>
</k-navbar>
</template>
</k-fab>
</nav>
<button class="lock-screen__swipe" type="button" @click="emit('unlock')">
<span class="lock-screen__swipe-chevron" aria-hidden="true"></span>
@@ -0,0 +1,360 @@
<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 maxCaptureEdge = 720
const portraitAspect = 3 / 4
const landscapeAspect = 16 / 9
let bitrateBps = 1_500_000
let landscape = false
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 captureDimensions(): { height: number; width: number } {
return landscape
? {
height: Math.round(maxCaptureEdge / landscapeAspect),
width: maxCaptureEdge,
}
: {
height: maxCaptureEdge,
width: Math.round(maxCaptureEdge * portraitAspect),
}
}
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 dimensions = captureDimensions()
gameView = createGameView(canvasRef.value)
gameView.resize(
dimensions.width,
dimensions.height,
window.innerWidth,
window.innerHeight,
)
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 { height, width } = captureDimensions()
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const view = createGameView(canvas, { preserveDrawingBuffer: true })
try {
view.resize(width, height, window.innerWidth, window.innerHeight)
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 === 'camera:orientation') {
landscape = message.data?.landscape === true
if (gameView && !gameView.isLost()) {
const dimensions = captureDimensions()
gameView.resize(
dimensions.width,
dimensions.height,
window.innerWidth,
window.innerHeight,
)
}
} 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>
+15 -4
View File
@@ -1,13 +1,15 @@
import { describe, expect, it } from 'vitest'
import { PHONE_APPS } from './apps'
import { isPhoneAppId, PHONE_APPS } from './apps'
describe('app registry', () => {
it('has unique ids and routes with the reference dock order', () => {
expect(new Set(PHONE_APPS.map((app) => app.id)).size).toBe(
PHONE_APPS.length,
)
expect(PHONE_APPS.every((app) => app.route === `/apps/${app.id}`)).toBe(
true,
)
expect(
PHONE_APPS.every(
(app) => app.route === null || app.route === `/apps/${app.id}`,
),
).toBe(true)
expect(PHONE_APPS.every((app) => app.iconImage.endsWith('.webp'))).toBe(
true,
)
@@ -74,6 +76,15 @@ describe('app registry', () => {
labelKey: 'Apps.citymarkt.name',
route: '/apps/citymarkt',
})
expect(PHONE_APPS.find((app) => app.id === 'camera')).toMatchObject({
route: '/apps/camera',
})
expect(PHONE_APPS.find((app) => app.id === 'photos')).toMatchObject({
route: '/apps/photos',
})
expect(isPhoneAppId('camera')).toBe(true)
expect(isPhoneAppId('photos')).toBe(true)
expect(isPhoneAppId('clock')).toBe(true)
expect(
PHONE_APPS.filter((app) => app.dockOrder !== null)
.sort((a, b) => (a.dockOrder ?? 0) - (b.dockOrder ?? 0))
+15 -4
View File
@@ -42,7 +42,11 @@ import neonDropIcon from '@/assets/img/app-icons/neon-drop.webp'
import weatherIcon from '@/assets/img/app-icons/weather.webp'
import citymarktIcon from '@/assets/img/app-icons/citymarkt.webp'
import localPagesIcon from '@/assets/img/app-icons/local-pages.webp'
import type { PhoneAppDefinition, PhoneAppId } from '@/types/apps'
import type {
LaunchablePhoneAppDefinition,
LaunchablePhoneAppId,
PhoneAppDefinition,
} from '@/types/apps'
export const PHONE_APPS: PhoneAppDefinition[] = [
{
@@ -164,7 +168,7 @@ export const PHONE_APPS: PhoneAppDefinition[] = [
},
{
component: markRaw(
defineAsyncComponent(() => import('@/views/apps/PhotosApp.vue')),
defineAsyncComponent(() => import('@/views/apps/GalleryApp.vue')),
),
dockOrder: null,
gridOrder: 7,
@@ -316,6 +320,13 @@ export function getPhoneApp(
return PHONE_APPS.find((app) => app.id === appId)
}
export function isPhoneAppId(value: string): value is PhoneAppId {
return PHONE_APP_IDS.includes(value as PhoneAppId)
export function isPhoneAppId(value: string): value is LaunchablePhoneAppId {
const app = getPhoneApp(value)
return !!app && isLaunchablePhoneApp(app)
}
export function isLaunchablePhoneApp(
app: PhoneAppDefinition,
): app is LaunchablePhoneAppDefinition {
return app.component !== null && app.route !== null
}
+28
View File
@@ -0,0 +1,28 @@
import { defineStore } from 'pinia'
import { usePhoneStore } from '@/stores/phone'
export const useAppStoreStore = defineStore('app-store', {
state: () => ({
claimedApps: [] as string[],
}),
actions: {
claimApp(id: string): void {
if (!this.claimedApps.includes(id)) {
this.claimedApps.push(id)
this.persist()
}
},
hydrate(payload: unknown): void {
const data = payload as { claimedApps?: unknown } | null
this.claimedApps = Array.isArray(data?.claimedApps)
? data.claimedApps.filter((id): id is string => typeof id === 'string')
: []
},
persist(): void {
usePhoneStore().saveDeviceNamespace('apps', {
claimedApps: this.claimedApps,
})
},
},
})
+2 -2
View File
@@ -2,7 +2,7 @@ import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { usePhoneStore } from '@/stores/phone'
import type { PhoneAppId } from '@/types/apps'
import type { LaunchablePhoneAppId } from '@/types/apps'
import type { PhonePreferencesV1 } from '@/utils/preferences'
import { playPhoneTone, type PhoneToneId } from '@/utils/tones'
@@ -13,7 +13,7 @@ export type PhoneNotificationDevice = {
}
export type PhoneNotificationInput = {
appId: PhoneAppId
appId: LaunchablePhoneAppId
critical?: boolean
device?: PhoneNotificationDevice
persistent?: boolean
+72 -45
View File
@@ -1,7 +1,7 @@
import { defineStore } from 'pinia'
import type { AppLaunchOrigin, PhoneAppId } from '@/types/apps'
import type { AppLaunchOrigin, LaunchablePhoneAppId } from '@/types/apps'
import type { DeviceBootstrap, PhoneDevice } from '@/types/device'
import { clampPage } from '@/utils/pages'
import { nuiCall } from '@/utils/nui'
@@ -488,18 +488,38 @@ const defaultLocales: LocaleTree = {
},
camera: {
name: 'Camera',
shutter: 'Take photo',
flash: 'Flash',
flip: 'Flip camera',
flash: 'Toggle flash',
controls: 'Camera controls',
modes: {
timelapse: 'Timelapse',
slowMo: 'Slow-Mo',
cinematic: 'Cinematic',
video: 'Video',
photo: 'Photo',
portrait: 'Portrait',
pano: 'Pano',
landscape: 'Switch to landscape',
portrait: 'Switch to portrait',
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: {
@@ -659,38 +679,40 @@ const defaultLocales: LocaleTree = {
deleteNote: 'Delete note',
},
photos: {
name: 'Photos',
searchPlaceholder: 'Photos, people, places...',
recents: 'Recents',
favorites: 'Favorites',
items: 'items',
memories: 'Memories',
featured: 'City colors',
dateRange: '19 Apr7 May 2024',
place: 'Los Santos & more',
select: 'Select',
count: '3,042 Photos, 125 Videos',
years: 'Years',
months: 'Months',
days: 'Days',
allPhotos: 'All Photos',
seeAll: 'See All',
onThisDay: 'On This Day',
trip: 'MAR 2024 TRIP',
featuredPhotos: 'Featured Photos',
featuredDate: '30 Mar 2024',
tabs: {
library: 'Library',
forYou: 'For You',
albums: 'Albums',
search: 'Search',
},
samples: {
sunset: 'Sunset drive',
ocean: 'Ocean air',
city: 'City lights',
desert: 'Desert road',
capture: 'Camera capture',
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: {
@@ -869,6 +891,7 @@ function getByPath(source: LocaleTree, path: string): unknown {
export const usePhoneStore = defineStore('phone', {
state: () => ({
cameraLandscape: false,
currentPage: 1,
device: null as PhoneDevice | null,
deviceRevisions: {} as Record<string, number>,
@@ -888,6 +911,7 @@ export const usePhoneStore = defineStore('phone', {
},
actions: {
close(): void {
this.cameraLandscape = false
this.isOpen = false
},
open(payload: PhoneOpenPayload = {}): void {
@@ -929,11 +953,14 @@ export const usePhoneStore = defineStore('phone', {
setCurrentPage(page: number): void {
this.currentPage = clampPage(page)
},
setCameraLandscape(landscape: boolean): void {
this.cameraLandscape = landscape
},
setLaunchOrigin(origin: AppLaunchOrigin | null): void {
this.launchOrigin = origin
},
setAppNotification(
appId: PhoneAppId,
appId: LaunchablePhoneAppId,
key: keyof AppNotificationPreferences,
value: boolean,
): void {
+10 -2
View File
@@ -22,6 +22,8 @@ export type PhoneAppId =
| 'citymarkt'
| 'local-pages'
export type LaunchablePhoneAppId = PhoneAppId
export type AppLaunchOrigin = {
borderRadius: number
scaleX: number
@@ -31,7 +33,7 @@ export type AppLaunchOrigin = {
}
export type PhoneAppDefinition = {
component: Component
component: Component | null
dockOrder: number | null
gridOrder: number
icon: Component
@@ -39,5 +41,11 @@ export type PhoneAppDefinition = {
iconImage: string
id: PhoneAppId
labelKey: string
route: `/apps/${PhoneAppId}`
route: `/apps/${LaunchablePhoneAppId}` | null
}
export type LaunchablePhoneAppDefinition = PhoneAppDefinition & {
component: Component
id: LaunchablePhoneAppId
route: `/apps/${LaunchablePhoneAppId}`
}
+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
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { coverTextureCoordinates } from '@/utils/gameView'
describe('coverTextureCoordinates', () => {
it('center-crops a widescreen game view for 3:4 portrait output', () => {
expect(Array.from(coverTextureCoordinates(1920, 1080, 540, 720))).toEqual([
expect.closeTo(0.29, 2),
0,
expect.closeTo(0.71, 2),
0,
expect.closeTo(0.29, 2),
1,
expect.closeTo(0.71, 2),
1,
])
})
it('keeps the full game view for 16:9 landscape output', () => {
expect(Array.from(coverTextureCoordinates(1920, 1080, 720, 405))).toEqual([
0, 0, 1, 0, 0, 1, 1, 1,
])
})
it('keeps the full texture when both aspect ratios match', () => {
expect(Array.from(coverTextureCoordinates(1600, 900, 800, 450))).toEqual([
0, 0, 1, 0, 0, 1, 1, 1,
])
})
})
+204
View File
@@ -0,0 +1,204 @@
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,
sourceWidth?: number,
sourceHeight?: number,
): void
}
export interface GameViewOptions {
preserveDrawingBuffer?: boolean
}
export function coverTextureCoordinates(
sourceWidth: number,
sourceHeight: number,
targetWidth: number,
targetHeight: number,
): Float32Array {
const sourceAspect = sourceWidth / sourceHeight
const targetAspect = targetWidth / targetHeight
let left = 0
let right = 1
let top = 0
let bottom = 1
if (sourceAspect > targetAspect) {
const visibleWidth = targetAspect / sourceAspect
left = (1 - visibleWidth) / 2
right = 1 - left
} else if (sourceAspect < targetAspect) {
const visibleHeight = sourceAspect / targetAspect
top = (1 - visibleHeight) / 2
bottom = 1 - top
}
return new Float32Array([left, top, right, top, left, bottom, right, bottom])
}
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)
// CitizenFX watches this exact wrap-mode sequence and replaces the seeded pixel with the live
// game backbuffer. These calls are intentionally not redundant.
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,
sourceWidth = window.innerWidth,
sourceHeight = window.innerHeight,
) {
if (disposed || lost) return
canvas.width = width
canvas.height = height
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer)
gl.bufferData(
gl.ARRAY_BUFFER,
coverTextureCoordinates(sourceWidth, sourceHeight, width, height),
gl.DYNAMIC_DRAW,
)
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 -3
View File
@@ -16,7 +16,7 @@ describe('preferences', () => {
notificationVolume: 45,
notificationDurationSeconds: 14,
notifications: {
camera: { enabled: false, sounds: false },
clock: { enabled: false, sounds: false },
},
phoneScale: 110,
wallpaper: 'ember',
@@ -26,11 +26,10 @@ describe('preferences', () => {
expect(value.settings.appearanceMode).toBe('light')
expect(value.settings.notificationVolume).toBe(45)
expect(value.settings.notificationDurationSeconds).toBe(14)
expect(value.settings.notifications.camera).toEqual({
expect(value.settings.notifications.clock).toEqual({
enabled: false,
sounds: false,
})
expect(value.settings.notifications.clock.enabled).toBe(true)
expect(value.settings.notifications.mail).toEqual({
enabled: true,
sounds: true,
+6 -6
View File
@@ -1,4 +1,4 @@
import type { PhoneAppId } from '@/types/apps'
import type { LaunchablePhoneAppId } from '@/types/apps'
export const APPEARANCE_MODE_IDS = ['automatic', 'light', 'dark'] as const
export const PHONE_FRAME_IDS = [
@@ -33,7 +33,7 @@ export type PhonePreferencesV1 = {
notificationSound: NotificationSoundId
notificationDurationSeconds: number
notificationVolume: number
notifications: Record<PhoneAppId, AppNotificationPreferences>
notifications: Record<LaunchablePhoneAppId, AppNotificationPreferences>
phoneScale: number
ringtone: RingtoneId
ringtoneVolume: number
@@ -44,7 +44,7 @@ export type PhonePreferencesV1 = {
}
const DEFAULT_APP_NOTIFICATIONS: Record<
PhoneAppId,
LaunchablePhoneAppId,
AppNotificationPreferences
> = {
phone: { enabled: true, sounds: true },
@@ -114,16 +114,16 @@ function readChoice<T extends string>(
function readNotifications(
value: unknown,
): Record<PhoneAppId, AppNotificationPreferences> {
): Record<LaunchablePhoneAppId, AppNotificationPreferences> {
const source =
value && typeof value === 'object'
? (value as Partial<
Record<PhoneAppId, Partial<AppNotificationPreferences>>
Record<LaunchablePhoneAppId, Partial<AppNotificationPreferences>>
>)
: {}
const notifications = structuredClone(DEFAULT_APP_NOTIFICATIONS)
for (const appId of Object.keys(notifications) as PhoneAppId[]) {
for (const appId of Object.keys(notifications) as LaunchablePhoneAppId[]) {
notifications[appId] = {
enabled: readBoolean(
source[appId]?.enabled,
+1 -1
View File
@@ -21,7 +21,7 @@ const launchStyle = computed(() => {
</script>
<template>
<div v-if="app" class="app-window" :style="launchStyle">
<div v-if="app?.component" class="app-window" :style="launchStyle">
<Suspense>
<component :is="app.component" />
<template #fallback>
+4 -4
View File
@@ -9,11 +9,11 @@ import {
} from 'lucide-vue-next'
import { computed, ref } from 'vue'
import { useMediaStore } from '@/stores/media'
import { useAppStoreStore } from '@/stores/app-store'
import { usePhoneStore } from '@/stores/phone'
const phone = usePhoneStore()
const media = useMediaStore()
const appStore = useAppStoreStore()
const tab = ref<'today' | 'apps' | 'games' | 'arcade' | 'search'>('today')
const query = ref('')
const tabs = [
@@ -126,10 +126,10 @@ const date = new Intl.DateTimeFormat(phone.lang, {
<strong>{{ item.title }}</strong
><small>{{ phone.t(item.subtitle) }}</small>
</div>
<button type="button" @click="media.claimApp(item.id)">
<button type="button" @click="appStore.claimApp(item.id)">
{{
phone.t(
media.claimedApps.includes(item.id)
appStore.claimedApps.includes(item.id)
? 'Apps.appStore.open'
: 'Apps.appStore.get',
)
+704 -89
View File
@@ -1,126 +1,741 @@
<script setup lang="ts">
import {
Aperture,
Camera,
ChevronUp,
RotateCcw,
kFab,
kNavbar,
kPage,
kSegmented,
kSegmentedButton,
kToast,
} from 'konsta/vue'
import {
Images,
RefreshCw,
RotateCcwSquare,
Video,
Zap,
ZapOff,
} from 'lucide-vue-next'
import { ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useMediaStore } from '@/stores/media'
import { usePhoneStore } from '@/stores/phone'
import type { MediaType, PhoneMedia, UploadResult } from '@/types/media'
import { createGameView, type GameView } from '@/utils/gameView'
import { formatRecordingDuration, mediaErrorKey } from '@/utils/media'
import { nuiCall } from '@/utils/nui'
const media = useMediaStore()
type CaptureItem = {
error?: string
id: string
mediaType: MediaType
status: 'uploading' | 'success' | 'error'
}
const isDevelopment = import.meta.env.DEV
const phone = usePhoneStore()
const flash = ref(false)
const router = useRouter()
const mode = ref<MediaType>('photo')
const flashEnabled = ref(false)
const modes = [
'timelapse',
'slowMo',
'cinematic',
'video',
'photo',
'portrait',
'pano',
] as const
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 gameCanvas = ref<HTMLCanvasElement | 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
let gameView: GameView | null = null
let renderFrameId: number | undefined
let resizeObserver: ResizeObserver | null = null
const pendingCount = computed(
() =>
captures.value.filter((capture) => capture.status === 'uploading').length,
)
const controlColors = {
bgIos: 'bg-ios-light-glass/75 dark:bg-ios-dark-glass/75',
activeBgIos: 'active:bg-white/90 dark:active:bg-white/20',
textIos: 'text-black/80 dark:text-white/80',
}
const modeColors = {
strongHighlightBgIos: 'bg-[#e5e5ea] dark:bg-[#2c2c2e]',
}
const modeNavbarColors = {
bgIos: 'bg-transparent',
}
const flashColors = computed(() => ({
...controlColors,
textIos: flashEnabled.value
? 'text-yellow-500 dark:text-yellow-300'
: controlColors.textIos,
}))
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 {
flash.value = true
media.capture()
window.setTimeout(() => (flash.value = false), 120)
if (mode.value === 'video') {
if (recording.value) {
stopRecording()
} else {
startRecording()
}
return
}
void requestPhoto()
}
function setMode(nextMode: MediaType): void {
if (recording.value || savingVideo.value) return
mode.value = nextMode
}
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 toggleOrientation(): void {
if (recording.value || savingVideo.value) return
phone.setCameraLandscape(!phone.cameraLandscape)
window.postMessage(
{
data: { landscape: phone.cameraLandscape },
type: 'camera:orientation',
},
'*',
)
}
function resizeGameView(): void {
if (!gameCanvas.value || !gameView) return
const bounds = gameCanvas.value.getBoundingClientRect()
const renderScale = Math.min(window.devicePixelRatio, 2)
gameView.resize(
Math.max(1, Math.round(bounds.width * renderScale)),
Math.max(1, Math.round(bounds.height * renderScale)),
window.innerWidth,
window.innerHeight,
)
}
function startGameView(): void {
if (isDevelopment || !gameCanvas.value) return
gameView = createGameView(gameCanvas.value)
resizeObserver = new ResizeObserver(resizeGameView)
resizeObserver.observe(gameCanvas.value)
resizeGameView()
const render = () => {
if (!gameView || gameView.isLost()) {
renderFrameId = undefined
return
}
gameView.render()
renderFrameId = window.requestAnimationFrame(render)
}
renderFrameId = window.requestAnimationFrame(render)
}
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(() => {
phone.setCameraLandscape(false)
window.postMessage(
{ data: { landscape: false }, type: 'camera:orientation' },
'*',
)
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()
startGameView()
})
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)
if (renderFrameId !== undefined) window.cancelAnimationFrame(renderFrameId)
resizeObserver?.disconnect()
gameView?.dispose()
phone.setCameraLandscape(false)
window.postMessage(
{ data: { landscape: false }, type: 'camera:orientation' },
'*',
)
window.postMessage({ type: 'camera:recordCancel' }, '*')
void nuiCall('camera:setFlash', { enabled: false })
void nuiCall('camera:setActive', { active: false })
})
</script>
<template>
<main class="native-app reference-camera">
<header class="camera-topbar">
<div>
<button
type="button"
:aria-label="phone.t('Apps.camera.flash')"
@click="flashEnabled = !flashEnabled"
>
<Zap v-if="flashEnabled" :size="22" />
<ZapOff v-else :size="22" />
</button>
<Aperture :size="22" />
<k-page
class="camera-page"
:class="{ 'camera-page--landscape': phone.cameraLandscape }"
:aria-label="phone.t('Apps.camera.name')"
>
<div class="camera-viewport">
<canvas
v-if="!isDevelopment"
ref="gameCanvas"
class="camera-game-view"
aria-hidden="true"
></canvas>
<div v-else class="camera-dev-view" aria-hidden="true">
<span class="camera-dev-sun"></span>
<span class="camera-dev-horizon"></span>
</div>
<button
class="camera-chevron"
<div class="camera-shade"></div>
<div class="camera-flash" :class="{ active: shutterActive }"></div>
</div>
<header class="camera-topbar">
<k-fab
component="button"
type="button"
:aria-label="phone.t('Apps.camera.controls')"
class="camera-control"
:colors="flashColors"
:aria-label="phone.t('Apps.camera.flash')"
@click="toggleFlash"
>
<ChevronUp :size="20" />
</button>
<Aperture :size="22" />
<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"
:disabled="recording || savingVideo"
:aria-label="
phone.t(
phone.cameraLandscape
? 'Apps.camera.portrait'
: 'Apps.camera.landscape',
)
"
@click="toggleOrientation"
>
<template #icon><RotateCcwSquare :size="19" /></template>
</k-fab>
</header>
<section
class="reference-viewfinder"
:class="`camera-facing--${media.cameraFacing}`"
>
<div class="camera-flash" :class="{ active: flash }" />
<i
v-for="corner in ['tl', 'tr', 'bl', 'br']"
:key="corner"
:class="`focus-corner focus-corner--${corner}`"
/>
<div class="camera-zoom">
<button
v-for="zoom in [0.5, 1]"
:key="zoom"
:class="{ active: media.cameraZoom === zoom }"
type="button"
@click="media.cameraZoom = zoom"
>
{{ zoom }}<small v-if="zoom === 1">x</small>
</button>
</div>
</section>
<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="reference-camera-footer">
<nav class="camera-mode-strip">
<footer class="camera-controls">
<div class="camera-capture-row">
<button
v-for="mode in modes"
:key="mode"
:class="{ active: media.cameraMode === mode }"
class="camera-latest"
type="button"
@click="
mode === 'photo' || mode === 'portrait' || mode === 'video'
? (media.cameraMode = mode)
: undefined
"
:aria-label="phone.t('Apps.camera.openGallery')"
@click="router.push('/apps/photos')"
>
{{ phone.t(`Apps.camera.modes.${mode}`) }}
<img
v-if="latestMedia?.mediaType === 'photo'"
:src="latestMedia.url"
alt=""
/>
<Video v-else-if="latestMedia" :size="22" />
<Images v-else :size="22" />
</button>
</nav>
<div class="camera-shutter-row">
<div
class="camera-thumbnail"
:style="{ background: media.photos[0]?.gradient }"
/>
<button
class="reference-shutter"
class="camera-shutter"
:class="{ recording, video: mode === 'video' }"
type="button"
:aria-label="phone.t('Apps.camera.shutter')"
:disabled="savingVideo"
:aria-label="
phone.t(
mode === 'photo'
? 'Apps.camera.takePhoto'
: recording
? 'Apps.camera.stopRecording'
: 'Apps.camera.startRecording',
)
"
@click="capture"
>
<Camera :size="23" />
<span></span>
</button>
<button
class="reference-flip"
<k-fab
component="button"
type="button"
class="camera-control camera-selfie"
:colors="controlColors"
:aria-label="phone.t('Apps.camera.flip')"
@click="
media.cameraFacing =
media.cameraFacing === 'rear' ? 'front' : 'rear'
"
@click="toggleFacing"
>
<RotateCcw :size="22" />
</button>
<template #icon><RefreshCw :size="20" /></template>
</k-fab>
</div>
<k-navbar
component="nav"
class="camera-mode-navbar"
inner-class="hidden"
:colors="modeNavbarColors"
:aria-label="phone.t('Apps.camera.name')"
>
<template #subnavbar>
<k-segmented strong rounded :colors="modeColors">
<k-segmented-button
large
:active="mode === 'photo'"
:disabled="recording || savingVideo"
:class="mode === 'photo' ? 'text-primary' : 'text-[#8e8e93]'"
:aria-pressed="mode === 'photo'"
@click="setMode('photo')"
>
{{ phone.t('Apps.camera.photo') }}
</k-segmented-button>
<k-segmented-button
large
:active="mode === 'video'"
:disabled="recording || savingVideo"
:class="mode === 'video' ? 'text-primary' : 'text-[#8e8e93]'"
:aria-pressed="mode === 'video'"
@click="setMode('video')"
>
{{ phone.t('Apps.camera.video') }}
</k-segmented-button>
</k-segmented>
</template>
</k-navbar>
</footer>
</main>
<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-viewport {
position: absolute;
top: 50%;
left: 0;
width: 100%;
aspect-ratio: 3 / 4;
overflow: hidden;
transform: translateY(-50%);
}
.camera-page--landscape .camera-viewport {
top: 50%;
left: 50%;
width: calc(100% * 16 / 9);
height: auto;
aspect-ratio: 16 / 9;
transform: translate(-50%, -50%) rotate(90deg);
}
.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%);
}
.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 {
--color-primary: rgb(99 99 102 / 75%);
}
.camera-control svg {
width: 21px;
height: 21px;
transition: transform 0.25s ease;
}
.camera-latest svg {
transition: transform 0.25s ease;
}
.camera-page--landscape .camera-control svg,
.camera-page--landscape .camera-latest svg {
transform: rotate(90deg);
}
.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: 0;
left: 0;
display: flex;
flex-direction: column;
gap: 0;
padding: 0;
}
.camera-capture-row {
display: grid;
grid-template-columns: 54px 1fr 54px;
align-items: center;
padding: 0 24px 4px;
}
.camera-latest {
width: 44px;
height: 44px;
overflow: hidden;
border: 0;
border-radius: 50%;
background: #111b;
color: #fff;
display: grid;
place-items: center;
}
.camera-selfie {
justify-self: end;
}
.camera-latest img {
width: 100%;
height: 100%;
object-fit: cover;
}
.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;
}
.camera-mode-navbar {
position: relative;
top: auto;
padding-bottom: 18px;
padding-top: 0;
}
</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>
-135
View File
@@ -1,135 +0,0 @@
<script setup lang="ts">
import { Heart, Images, Library, Search } from 'lucide-vue-next'
import { computed, ref } from 'vue'
import { useMediaStore } from '@/stores/media'
import { usePhoneStore } from '@/stores/phone'
const media = useMediaStore()
const phone = usePhoneStore()
const tab = ref<'library' | 'forYou' | 'albums' | 'search'>('library')
const query = ref('')
const tabs = [
{ id: 'library', icon: Library },
{ id: 'forYou', icon: Heart },
{ id: 'albums', icon: Images },
{ id: 'search', icon: Search },
] as const
const gallery = computed(() =>
Array.from(
{ length: 54 },
(_, index) => media.photos[index % media.photos.length],
),
)
const filtered = computed(() =>
media.photos.filter((photo) =>
phone.t(photo.titleKey).toLowerCase().includes(query.value.toLowerCase()),
),
)
</script>
<template>
<main class="native-app reference-photos">
<section v-if="tab === 'library'" class="photos-library">
<header class="photos-floating-header">
<div>
<strong>{{ phone.t('Apps.photos.dateRange') }}</strong
><span>{{ phone.t('Apps.photos.place') }}</span>
</div>
<button type="button">{{ phone.t('Apps.photos.select') }}</button
><button type="button"></button>
</header>
<div class="reference-photo-grid">
<article
v-for="(photo, index) in gallery"
:key="`${photo.id}-${index}`"
:style="{ background: photo.gradient }"
/>
</div>
<p class="photos-count">{{ phone.t('Apps.photos.count') }}</p>
<div class="photos-period">
<button>{{ phone.t('Apps.photos.years') }}</button
><button>{{ phone.t('Apps.photos.months') }}</button
><button>{{ phone.t('Apps.photos.days') }}</button
><button class="active">{{ phone.t('Apps.photos.allPhotos') }}</button>
</div>
</section>
<section v-else-if="tab === 'forYou'" class="photos-scroll">
<h1>{{ phone.t('Apps.photos.tabs.forYou') }}</h1>
<div class="photos-section-title">
<h2>{{ phone.t('Apps.photos.memories') }}</h2>
<button>{{ phone.t('Apps.photos.seeAll') }}</button>
</div>
<article
class="memory-card"
:style="{ background: media.photos[1]?.gradient }"
>
<Heart :size="25" />
<div>
<strong>{{ phone.t('Apps.photos.onThisDay') }}</strong
><span>{{ phone.t('Apps.photos.trip') }}</span>
</div>
</article>
<div class="photos-section-title">
<h2>{{ phone.t('Apps.photos.featuredPhotos') }}</h2>
</div>
<div class="featured-row">
<article v-for="photo in media.photos.slice(0, 2)" :key="photo.id">
<div :style="{ background: photo.gradient }" />
<strong>{{ phone.t(photo.titleKey) }}</strong
><span>{{ phone.t('Apps.photos.featuredDate') }}</span>
</article>
</div>
</section>
<section v-else-if="tab === 'albums'" class="photos-scroll">
<h1>{{ phone.t('Apps.photos.tabs.albums') }}</h1>
<div class="album-cards">
<article>
<div
class="photo-tile"
:style="{ background: media.photos[0]?.gradient }"
/>
<strong>{{ phone.t('Apps.photos.recents') }}</strong
><small
>{{ media.photos.length }} {{ phone.t('Apps.photos.items') }}</small
>
</article>
<article>
<div class="photo-tile favorites" />
<strong>{{ phone.t('Apps.photos.favorites') }}</strong
><small>2 {{ phone.t('Apps.photos.items') }}</small>
</article>
</div>
</section>
<section v-else class="photos-scroll">
<h1>{{ phone.t('Apps.photos.tabs.search') }}</h1>
<div class="app-search">
<Search :size="17" /><input
v-model="query"
:placeholder="phone.t('Apps.photos.searchPlaceholder')"
/>
</div>
<div class="photo-grid">
<article
v-for="photo in filtered"
:key="photo.id"
class="photo-tile"
:style="{ background: photo.gradient }"
/>
</div>
</section>
<nav class="reference-tabbar">
<button
v-for="item in tabs"
:key="item.id"
:class="{ active: tab === item.id }"
type="button"
@click="tab = item.id"
>
<component :is="item.icon" :size="22" /><span>{{
phone.t(`Apps.photos.tabs.${item.id}`)
}}</span>
</button>
</nav>
</main>
</template>
+13 -7
View File
@@ -43,11 +43,14 @@ import {
} from 'vue'
import { PHONE_FRAME_COLORS } from '@/config/appearance'
import { PHONE_APPS } from '@/config/apps'
import { isLaunchablePhoneApp, PHONE_APPS } from '@/config/apps'
import { IFRUIT_AUTH_INPUT_COLORS } from '@/config/ifruit'
import { usePhoneStore } from '@/stores/phone'
import { useAccountStore } from '@/stores/account'
import type { PhoneAppDefinition, PhoneAppId } from '@/types/apps'
import type {
LaunchablePhoneAppDefinition,
LaunchablePhoneAppId,
} from '@/types/apps'
import { nuiCall } from '@/utils/nui'
import { formatPhoneNumber } from '@/utils/phone'
import {
@@ -88,7 +91,7 @@ const phone = usePhoneStore()
const account = useAccountStore()
const query = ref('')
const activeView = ref<SettingsView>('root')
const selectedNotificationAppId = ref<PhoneAppId>('calculator')
const selectedNotificationAppId = ref<LaunchablePhoneAppId>('calculator')
const settingsPage = ref<ComponentPublicInstance | null>(null)
const framePickerButton = ref<ComponentPublicInstance | null>(null)
const framePickerOpened = ref(false)
@@ -177,12 +180,15 @@ const visiblePreferenceRows = computed(() =>
preferenceRows.filter((row) => matchesSearch(row.key)),
)
const notificationApps = computed(() =>
[...PHONE_APPS].sort((left, right) => left.gridOrder - right.gridOrder),
PHONE_APPS.filter(isLaunchablePhoneApp).sort(
(left, right) => left.gridOrder - right.gridOrder,
),
)
const selectedNotificationApp = computed(
() =>
PHONE_APPS.find((app) => app.id === selectedNotificationAppId.value) ??
PHONE_APPS[0],
notificationApps.value.find(
(app) => app.id === selectedNotificationAppId.value,
) ?? notificationApps.value[0],
)
const activeTitle = computed(() => {
if (activeView.value === 'account') {
@@ -215,7 +221,7 @@ function openView(view: SubmenuView): void {
scrollPageToTop()
}
function openNotificationApp(app: PhoneAppDefinition): void {
function openNotificationApp(app: LaunchablePhoneAppDefinition): void {
selectedNotificationAppId.value = app.id
activeView.value = 'notification-detail'
scrollPageToTop()
+53
View File
@@ -135,6 +135,20 @@ let mockNotes = [
},
]
const deviceData = {}
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 marketplaceInquiries = [
{
id: '4903b923-409a-437e-971f-b7a2b10e9e31',
@@ -337,6 +351,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 = {
@@ -377,6 +429,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
+32 -9
View File
@@ -151,8 +151,21 @@ Locales["en"] = {
unmute = "Turn on game sounds",
},
camera = {
name = "Camera", shutter = "Take photo", flip = "Flip camera", flash = "Toggle flash", controls = "Camera controls",
modes = { timelapse = "Timelapse", slowMo = "Slow-Mo", cinematic = "Cinematic", video = "Video", photo = "Photo", portrait = "Portrait", pano = "Pano" },
name = "Camera", flash = "Flash", flip = "Flip camera", landscape = "Switch to landscape",
portrait = "Switch to portrait", 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",
@@ -312,13 +325,23 @@ Locales["en"] = {
deleteNote = "Delete note",
},
photos = {
name = "Photos", searchPlaceholder = "Photos, people, places...", recents = "Recents",
favorites = "Favorites", items = "items", memories = "Memories", featured = "City colors",
dateRange = "19 Apr7 May 2024", place = "Los Santos & more", select = "Select", count = "3,042 Photos, 125 Videos",
years = "Years", months = "Months", days = "Days", allPhotos = "All Photos", seeAll = "See All",
onThisDay = "On This Day", trip = "MAR 2024 TRIP", featuredPhotos = "Featured Photos", featuredDate = "30 Mar 2024",
tabs = { library = "Library", forYou = "For You", albums = "Albums", search = "Search" },
samples = { sunset = "Sunset drive", ocean = "Ocean air", city = "City lights", desert = "Desert road", capture = "Camera capture" },
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",
+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',
@@ -45,6 +47,7 @@ server_scripts {
'source/server/mail.lua',
'source/server/marketplace.lua',
'source/server/pages.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
@@ -65,6 +65,8 @@ local server_callbacks = {
"calls:answer",
"calls:decline",
"calls:hangup",
"gallery:list",
"media:config",
}
local function get_locale()
@@ -102,6 +104,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-AOWIBJTS.js"></script>
<link rel="stylesheet" crossorigin href="./assets/sky-index-DMAIEjGF.css">
<script type="module" crossorigin src="./assets/sky-index-CNPLwlcz.js"></script>
<link rel="stylesheet" crossorigin href="./assets/sky-index-DnowIFpD.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 -1
View File
@@ -12,7 +12,6 @@ local allowed_device_namespaces = {
notifications = true,
wallpaper = true,
alarms = true,
media = true,
apps = true,
games = true,
}
@@ -358,6 +357,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
@@ -754,6 +761,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` = ?",
@@ -763,6 +771,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 },
@@ -778,6 +790,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,