Özel uygulamalar
Başlangıç
Tek küçük bir resource'ta eksiksiz bir özel uygulama: liste girişi, sayfa, iki server aksiyonu, tema ve sinyal, bir bildirim ve Lua'dan gelen bir mesaj.
#Ne yapıyoruz
Bu, fx-pocketbook/sdk/examples/fx-pocketbook-example içinde gelen örnektir: bir yolcu kartı. Uygulama:
- kendini listeye ekler ve iki server aksiyonu kaydeder,
- defterin mürekkep renklerini ve sinyal çubuklarını alır,
- oyuncunun kendi kartını (ad, meslek, rütbe, hattın çalışıp çalışmadığı) server'dan okur,
- oyuncuya bir bildirim gönderir,
- Lua'dan gönderilen bir mesajı alır,
- sayfa kapanınca temizlik yapar.
Veritabanına hiçbir şey yazmaz, para ya da item taşımaz.
Denemek için klasörü fx-pocketbook'un yanına kopyala, Config.CustomApps.Enabled = true bırak ve ensure fx-pocketbook'tan sonra ensure fx-pocketbook-example ekle. Config.CustomApps.RequireInstall = true iken uygulamayı önce App Store'dan kur. Uygulama listede Yolcu Kartı olarak görünür; /pocketcard komutu da açar.
#fxmanifest.lua
luafx_version 'cerulean'
game 'rdr3'
rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.'
author 'Fixitfy'
description 'Optional Pocketbook SDK example: personal traveller card'
version '1.0.0'
dependency 'fx-pocketbook'
shared_script 'config.lua'
client_script 'client.lua'
server_script 'server.lua'
files {
'ui/index.html', 'ui/app.js', 'ui/style.css', 'ui/pocketbook.js',
'ui/assets/*.svg', 'ui/assets/*.png', 'ui/assets/*.ttf'
}
-- No ui_page: Pocketbook owns the embedded frame and focus.
#config.lua
luaPocketExample = {
Core = 'fx-pocketbook', AppId = 'traveller_card', Title = 'Yolcu Kartı',
JobLabels = { unemployed = 'Serbest', police = 'Kanun görevlisi', doctor = 'Doktor' },
NotificationCooldown = 10
}
Defter klasörünün adı farklıysa Core ve dependency değerlerini birlikte değiştir.
#client.lua
Uygulama bu resource başlarken ve fx-pocketbook:ready event'inde yeniden kaydedilir; böylece defter yeniden başladıktan sonra geri gelir.
lualocal registered = false
local function register()
if registered or GetResourceState(PocketExample.Core) ~= 'started' then return end
local ok, result = pcall(function()
return exports[PocketExample.Core]:AddCustomApp({
identifier = PocketExample.AppId,
name = PocketExample.Title,
ui = 'ui/index.html',
icon = 'ui/assets/account-box-outline.svg',
})
end)
registered = ok and result == true
end
AddEventHandler('onClientResourceStart', function(resource)
if resource == GetCurrentResourceName() then SetTimeout(0, register) end
end)
AddEventHandler('fx-pocketbook:ready', register)
AddEventHandler('onClientResourceStop', function(resource)
if resource == PocketExample.Core then registered = false end
end)
RegisterCommand('pocketcard', function()
register()
if registered then exports[PocketExample.Core]:OpenApp(PocketExample.AppId) end
end, false)
-- A message from this resource to its own page, while it is open.
RegisterCommand('pocketcardmessage', function()
if registered then
exports[PocketExample.Core]:SendCustomAppMessage(PocketExample.AppId, { kind = 'hint', text = 'Yolunuz açık olsun. Kartınızı dilediğinizde yenileyebilirsiniz.' })
end
end, false)
#server.lua
Her aksiyon oyuncuyu ValidateApplicationPlayer ile yeniden kontrol eder. Kart, payload'dan değil, çekirdeğin verdiği character tablosundan kurulur.
lualocal registered = false
local notices = {}
local function allowed(src, char)
local ok, result, reason = pcall(function()
return exports[PocketExample.Core]:ValidateApplicationPlayer(PocketExample.AppId, src, char.id)
end)
if not ok then return false, 'Kartınıza şu an ulaşılamıyor. Yeniden deneyin.' end
return result, reason
end
local actions = {}
function actions.getCard(src, char)
local ok, reason = allowed(src, char)
if not ok then return { ok = false, error = reason or 'Kartınıza erişilemiyor.' } end
return { ok = true, card = {
name = char.name,
job = PocketExample.JobLabels[char.job] or char.job or 'Belirtilmemiş',
grade = char.grade or 0,
canSend = exports[PocketExample.Core]:CanUseOnline(src, 'send'),
canReceive = exports[PocketExample.Core]:CanUseOnline(src, 'receive'),
}, audit = { recordId = char.id, operation = 'readOwnCard' } }
end
function actions.remind(src, char)
local ok, reason = allowed(src, char)
if not ok then return { ok = false, error = reason or 'Bildirim gönderilemiyor.' } end
local previous, now = notices[src], os.time()
if previous and previous.character == char.id and now - previous.at < PocketExample.NotificationCooldown then
return { ok = false, error = 'Yeni bir hatırlatma için birkaç saniye bekleyin.' }
end
local sent = exports[PocketExample.Core]:Notify(src, { title = PocketExample.Title, message = 'Yolcu kartınız hazır. İyi yolculuklar.', offline = true })
if not sent then return { ok = false, error = 'Bildirim iletilemedi. Kartınızı yenileyin.' } end
notices[src] = { character = char.id, at = now }
return { ok = true, audit = { recordId = char.id, operation = 'selfReminder' } }
end
local function register()
if registered or GetResourceState(PocketExample.Core) ~= 'started' then return end
local ok, result = pcall(function()
return exports[PocketExample.Core]:RegisterApplication(PocketExample.AppId, actions)
end)
registered = ok and result == true
end
AddEventHandler('onResourceStart', function(resource)
if resource == GetCurrentResourceName() or resource == PocketExample.Core then SetTimeout(0, register) end
end)
AddEventHandler('onResourceStop', function(resource)
if resource == PocketExample.Core then registered = false end
end)
AddEventHandler('playerDropped', function() notices[source] = nil end)
#ui/index.html
pocketbook.js, fx-pocketbook/sdk/pocketbook.js dosyasından kopyalanan dosyadır. app.js'ten önce yüklenir.
html<!doctype html>
<html lang="tr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Yolcu Kartı</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<div class="scroll">
<h1 id="name">Kartınız açılıyor…</h1>
<dl id="card" hidden>
<div><dt>Meslek</dt><dd id="job"></dd></div>
<div><dt>Rütbe</dt><dd id="grade"></dd></div>
<div><dt>Telgraf gönderme</dt><dd id="send"></dd></div>
<div><dt>Telgraf alma</dt><dd id="receive"></dd></div>
</dl>
<p id="signal" aria-live="polite"></p>
<p id="hint" hidden></p>
</div>
<footer>
<p id="status" role="status" aria-live="polite">Pocketbook bağlantısı bekleniyor…</p>
<button id="refresh" class="ink" disabled>Kartımı yenile</button>
<button id="remind" class="secondary" disabled>Hatırlatma gönder</button>
<button id="home" class="secondary" disabled>Ana sayfaya dön</button>
</footer>
</main>
<script src="pocketbook.js"></script>
<script src="app.js"></script>
</body>
</html>
#ui/app.js
js(() => {
'use strict';
const $ = (id) => document.getElementById(id);
const controller = new AbortController();
let alive = true, ready = false, busy = false, loaded = false, sequence = 0;
const status = (text, error = false) => { $('status').textContent = text; $('status').dataset.error = String(error); };
function controls() {
for (const id of ['refresh', 'remind']) $(id).disabled = !ready || busy || (id === 'remind' && !loaded);
$('home').disabled = !ready;
}
async function request(action) {
if (!ready || busy) return;
busy = true; controls();
const token = ++sequence;
status(action === 'getCard' ? 'Kartınız yenileniyor…' : 'Hatırlatma gönderiliyor…');
try {
const r = await Pocketbook.request(action, {});
if (!alive || token !== sequence) return;
if (!r?.ok) {
status(r?.error || 'Bağlantı kurulamadı. Yeniden deneyin.', true);
if (action === 'getCard' && !loaded) $('name').textContent = 'Kartınız yüklenemedi';
return;
}
if (action === 'getCard') {
const card = r.card; loaded = true;
$('card').hidden = false;
$('name').textContent = card.name;
$('job').textContent = card.job;
$('grade').textContent = String(card.grade);
$('send').textContent = card.canSend ? 'Kullanılabilir' : 'Sinyal yetersiz';
$('receive').textContent = card.canReceive ? 'Kullanılabilir' : 'Sinyal yetersiz';
status('Kartınız güncel.');
} else status('Hatırlatma bildirime iletildi.');
} catch {
if (alive) status('Bağlantı kurulamadı. Yeniden deneyin.', true);
} finally {
if (alive) { busy = false; controls(); }
}
}
// Theme colours and signal; the first context also means "ready".
const stopContext = Pocketbook.onContext((context) => {
for (const key of ['ink', 'muted', 'accent']) {
if (context.colors?.[key]) document.documentElement.style.setProperty('--' + key, context.colors[key]);
}
$('signal').textContent = `Hat sinyali: ${Math.max(0, Math.min(5, Number(context.signal) || 0))} / 5`;
if (!ready) { ready = true; controls(); request('getCard'); }
});
// Messages from SendCustomAppMessage.
const stopMessage = Pocketbook.onMessage((data) => {
if (data?.kind === 'hint' && typeof data.text === 'string') {
$('hint').textContent = data.text.slice(0, 300);
$('hint').hidden = false;
}
});
$('refresh').addEventListener('click', () => request('getCard'), { signal: controller.signal });
$('remind').addEventListener('click', () => request('remind'), { signal: controller.signal });
$('home').addEventListener('click', () => Pocketbook.home(), { signal: controller.signal });
// The frame is destroyed when the player leaves the app.
window.addEventListener('pagehide', () => {
alive = false; sequence++; controller.abort(); stopContext(); stopMessage();
}, { once: true });
})();
#ui/style.css
Sayfa defterin kâğıdının üzerine çizilir; bu yüzden arka planı şeffaf bırak ve mürekkep renklerini context'ten al. Kısa bir başlangıç:
css:root { --ink: #3b3224; --muted: #66573d; --accent: #795a2e; }
html, body { height: 100%; margin: 0; background: transparent; color: var(--ink); font-family: serif; }
dl > div { display: flex; justify-content: space-between; border-bottom: 1px solid var(--muted); }
button { display: block; width: 100%; font: inherit; color: var(--ink); }
#Log'lar
Çekirdek traveller_card.getCard ve traveller_card.remind aksiyonlarını server'ın log ayarlarıyla kaydeder. Bunları ayrı bir webhook'a göndermek için çekirdeğin config_server.lua dosyasına PocketServerConfig.Apps.traveller_card.Logs ekle.