推送模块

This commit is contained in:
2026-04-18 15:48:31 +08:00
parent e3f26ba1f7
commit 7d0f11fe43
19 changed files with 548 additions and 5 deletions

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace app\admin\controller\test;
use app\common\controller\Backend;
use app\common\library\admin\PushChannelConfigHelper;
use support\Response;
use Webman\Http\Request as WebmanRequest;
/**
* 推送测试public-game-period对局公共频道
*/
class PushGamePeriod extends Backend
{
protected ?object $model = null;
public function pushConfig(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
return $this->success('', [
'url' => PushChannelConfigHelper::wsBaseUrl(),
'app_key' => PushChannelConfigHelper::appKey(),
'channel' => 'public-game-period',
]);
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace app\admin\controller\test;
use app\common\controller\Backend;
use app\common\library\admin\PushChannelConfigHelper;
use support\Response;
use Webman\Http\Request as WebmanRequest;
/**
* 推送测试public-operation-notice公告广播频道
*/
class PushOperationNotice extends Backend
{
protected ?object $model = null;
public function pushConfig(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
return $this->success('', [
'url' => PushChannelConfigHelper::wsBaseUrl(),
'app_key' => PushChannelConfigHelper::appKey(),
'channel' => 'public-operation-notice',
]);
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace app\admin\controller\test;
use app\common\controller\Backend;
use app\common\library\admin\PushChannelConfigHelper;
use support\Response;
use Webman\Http\Request as WebmanRequest;
/**
* 推送测试private-user-{uuid}(用户私有频道)
*/
class PushPrivateUser extends Backend
{
protected ?object $model = null;
public function pushConfig(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
$uuid = trim((string) ($request->get('uuid') ?? $request->post('uuid') ?? ''));
if ($uuid === '') {
return $this->error(__('Parameter %s can not be empty', ['uuid']));
}
if (strlen($uuid) > 64 || !preg_match('/^[0-9a-zA-Z_-]+$/', $uuid)) {
return $this->error(__('Parameter error'));
}
return $this->success('', [
'url' => PushChannelConfigHelper::wsBaseUrl(),
'app_key' => PushChannelConfigHelper::appKey(),
'channel' => 'private-user-' . $uuid,
]);
}
}

View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace app\common\library\admin;
/**
* 后台推送测试页:读取 webman/push 配置(与 game/Live::pushConfig 口径一致)
*/
final class PushChannelConfigHelper
{
public static function wsBaseUrl(): string
{
$ws = (string) config('plugin.webman.push.app.websocket');
$ws = str_replace('websocket://', 'ws://', $ws);
return str_replace('0.0.0.0', '127.0.0.1', $ws);
}
public static function appKey(): string
{
return (string) config('plugin.webman.push.app.app_key');
}
}

View File

@@ -13,6 +13,12 @@ final class GameLiveService
private const BASE_ODDS = 33;
private const CHANNEL = 'game-live';
private const EVENT = 'bet-updated';
/** 与《36字花-移动端接口设计草案》7.1 对齐:公共对局频道 */
private const CHANNEL_PUBLIC_GAME_PERIOD = 'public-game-period';
private const EVT_PERIOD_TICK = 'period.tick';
private const EVT_PERIOD_LOCKED = 'period.locked';
private const EVT_PERIOD_OPENED = 'period.opened';
private const KEY_PERIOD_SECONDS = 'period_seconds';
private const KEY_BET_SECONDS = 'bet_seconds';
private const KEY_PICK_MAX_NUMBER_COUNT = 'pick_max_number_count';
@@ -203,6 +209,8 @@ final class GameLiveService
return ['ok' => false, 'msg' => $e->getMessage()];
}
self::publishPublicPeriodOpened((string) $record['period_no'], $finalNumber, $now);
self::publishSnapshot(null);
return [
'ok' => true,
@@ -227,6 +235,7 @@ final class GameLiveService
'update_time' => time(),
]);
$record['status'] = 1;
self::publishPublicPeriodLocked($record);
}
if ($elapsed < $periodSeconds) {
return;
@@ -238,16 +247,121 @@ final class GameLiveService
{
try {
$payload = self::buildSnapshot($recordId);
$api = new Api(
str_replace('0.0.0.0', '127.0.0.1', (string) config('plugin.webman.push.app.api')),
(string) config('plugin.webman.push.app.app_key'),
(string) config('plugin.webman.push.app.app_secret')
);
$api = self::createPushApi();
$api->trigger(self::CHANNEL, self::EVENT, $payload);
self::publishPublicPeriodTick($payload, $api);
} catch (Throwable) {
}
}
private static function createPushApi(): Api
{
return new Api(
str_replace('0.0.0.0', '127.0.0.1', (string) config('plugin.webman.push.app.api')),
(string) config('plugin.webman.push.app.app_key'),
(string) config('plugin.webman.push.app.app_secret')
);
}
/**
* 移动端公共频道:每秒心跳,含期号、倒计时、阶段(对齐 lobbyInit/periodCurrent 语义)
*/
private static function publishPublicPeriodTick(array $snapshot, Api $api): void
{
$record = $snapshot['record'] ?? null;
$serverTime = (int) ($snapshot['server_time'] ?? time());
$remaining = (int) ($snapshot['remaining_seconds'] ?? 0);
$betCloseIn = (int) ($snapshot['bet_remaining_seconds'] ?? 0);
$periodNo = '';
$dbStatus = 0;
$resultNumber = null;
if (is_array($record)) {
$periodNo = (string) ($record['period_no'] ?? '');
$dbStatus = (int) ($record['status'] ?? 0);
$rn = $record['result_number'] ?? null;
$resultNumber = is_numeric((string) $rn) ? (int) $rn : null;
}
if ($record === null || $periodNo === '') {
$status = 'idle';
} else {
$status = self::mapPublicPeriodStatus($dbStatus, $betCloseIn);
}
$payload = [
'server_time' => $serverTime,
'period_no' => $periodNo,
'status' => $status,
'countdown' => $remaining,
'bet_close_in'=> $betCloseIn,
];
if ($periodNo !== '' && $record !== null) {
$start = (int) ($record['period_start_at'] ?? 0);
$betSeconds = (int) ($snapshot['bet_seconds'] ?? 20);
$periodSeconds = (int) ($snapshot['period_seconds'] ?? 30);
if ($start > 0) {
$payload['lock_at'] = $start + $betSeconds;
$payload['open_at'] = $start + $periodSeconds;
}
}
if ($resultNumber !== null) {
$payload['result_number'] = $resultNumber;
}
$api->trigger(self::CHANNEL_PUBLIC_GAME_PERIOD, self::EVT_PERIOD_TICK, $payload);
}
/**
* @param array<string, mixed> $record game_record 行
*/
private static function publishPublicPeriodLocked(array $record): void
{
try {
$start = (int) ($record['period_start_at'] ?? 0);
$betSeconds = self::getConfigInt(self::KEY_BET_SECONDS, 20);
$periodNo = (string) ($record['period_no'] ?? '');
$payload = [
'period_no' => $periodNo,
'lock_at' => $start > 0 ? $start + $betSeconds : time(),
];
$api = self::createPushApi();
$api->trigger(self::CHANNEL_PUBLIC_GAME_PERIOD, self::EVT_PERIOD_LOCKED, $payload);
} catch (Throwable) {
}
}
private static function publishPublicPeriodOpened(string $periodNo, int $resultNumber, int $openTime): void
{
try {
$payload = [
'period_no' => $periodNo,
'result_number' => $resultNumber,
'open_time' => $openTime,
];
$api = self::createPushApi();
$api->trigger(self::CHANNEL_PUBLIC_GAME_PERIOD, self::EVT_PERIOD_OPENED, $payload);
} catch (Throwable) {
}
}
/**
* 与文档 3.1/4.1 中 status 字符串对齐betting / locked / settling / finished
*/
private static function mapPublicPeriodStatus(int $dbStatus, int $betCloseIn): string
{
if ($dbStatus === 0) {
return $betCloseIn > 0 ? 'betting' : 'locked';
}
if ($dbStatus === 1) {
return 'locked';
}
if ($dbStatus === 4) {
return 'finished';
}
if ($dbStatus === 2 || $dbStatus === 3) {
return 'settling';
}
return 'finished';
}
private static function resolveRecord(?int $recordId): ?array
{
if ($recordId !== null && $recordId > 0) {

View File

@@ -9,4 +9,8 @@ export default {
'/': ['./frontend/${lang}/index.ts'],
[adminBaseRoutePath + '/moduleStore']: ['./backend/${lang}/module.ts'],
[adminBaseRoutePath + '/crud/crud']: ['./backend/${lang}/crud/log.ts', './backend/${lang}/crud/state.ts'],
/** 推送测试三页:共享 test.push.* 文案(见 PushChannelTestPage.vue */
[adminBaseRoutePath + '/test/pushGamePeriod']: ['./backend/${lang}/test/push.ts'],
[adminBaseRoutePath + '/test/pushOperationNotice']: ['./backend/${lang}/test/push.ts'],
[adminBaseRoutePath + '/test/pushPrivateUser']: ['./backend/${lang}/test/push.ts'],
}

View File

@@ -0,0 +1,12 @@
export default {
connected: 'Push connected (subscribed)',
disconnected: 'Disconnected or idle',
user_uuid: 'User uuid',
user_uuid_placeholder: '10-char public id as in mobile profile',
btn_connect: 'Connect & subscribe',
btn_disconnect: 'Disconnect',
btn_clear: 'Clear log',
channel_label: 'Channel',
log_title: 'Event log',
log_empty: 'No messages yet. Ensure the push worker is running and the server publishes to this channel.',
}

View File

@@ -0,0 +1,3 @@
export default {
tip: 'Subscribe to public-game-period (global period channel) for period.tick / period.locked / period.opened. The server must publish to this channel.',
}

View File

@@ -0,0 +1,3 @@
export default {
tip: 'Subscribe to public-operation-notice for broadcast notices such as notice.popout. The server must publish to this channel.',
}

View File

@@ -0,0 +1,3 @@
export default {
tip: 'Subscribe to private-user-{uuid}: enter the player uuid; auth uses /plugin/webman/push/auth like the mobile client. For bet.accepted, wallet.changed, etc.',
}

View File

@@ -0,0 +1,12 @@
export default {
connected: '推送服务已连接(已订阅频道)',
disconnected: '未连接或已断开',
user_uuid: '用户 uuid',
user_uuid_placeholder: '与移动端档案一致的 10 位对外标识',
btn_connect: '连接并订阅',
btn_disconnect: '断开',
btn_clear: '清空日志',
channel_label: '当前频道',
log_title: '事件日志',
log_empty: '暂无推送,请确认 push 进程已启动且服务端会向对应频道发消息。',
}

View File

@@ -0,0 +1,3 @@
export default {
tip: '订阅文档中的「全局对局频道」public-game-period用于验证 period.tick / period.locked / period.opened 等公共事件(需服务端向该频道推送)。',
}

View File

@@ -0,0 +1,3 @@
export default {
tip: '订阅文档中的「公告广播频道」public-operation-notice用于验证 notice.popout 等全站公告类推送(需服务端向该频道推送)。',
}

View File

@@ -0,0 +1,3 @@
export default {
tip: '订阅「用户私有频道」private-user-{uuid}:请输入玩家 uuid连接后将走 /plugin/webman/push/auth 鉴权(与移动端一致)。用于验证 bet.accepted、wallet.changed 等私有事件。',
}

View File

@@ -0,0 +1,79 @@
/**
* 后台推送频道测试:加载官方 push.js 并订阅频道、监听文档约定事件
*/
const DOC_EVENTS = [
'period.tick',
'period.locked',
'period.opened',
'bet.accepted',
'wallet.changed',
'notice.popout',
'withdraw.review_required',
]
export async function loadPushJs(): Promise<void> {
if ((window as any).Push) {
return
}
await new Promise<void>((resolve, reject) => {
const script = document.createElement('script')
script.src = '/plugin/webman/push/push.js'
script.onload = () => resolve()
script.onerror = () => reject(new Error('load push.js failed'))
document.head.appendChild(script)
})
}
export type PushTestLogLine = { t: number; event: string; payload: string }
export function startPushChannelListener(options: {
url: string
app_key: string
channel: string
/** 私有频道需走 /plugin/webman/push/auth */
usePrivateAuth: boolean
onLog: (line: PushTestLogLine) => void
onConnected: (ok: boolean) => void
}): { disconnect: () => void } {
const PushCtor = (window as any).Push
const cfg: anyObj = { url: options.url, app_key: options.app_key }
if (options.usePrivateAuth) {
cfg.auth = '/plugin/webman/push/auth'
}
const client = new PushCtor(cfg)
const ch = client.subscribe(options.channel)
const pushLog = (event: string, data: unknown) => {
let payload = ''
try {
payload = typeof data === 'string' ? data : JSON.stringify(data)
} catch {
payload = String(data)
}
options.onLog({ t: Date.now(), event, payload })
}
ch.on('pusher:subscription_succeeded', () => {
options.onConnected(true)
pushLog('pusher:subscription_succeeded', {})
})
for (const ev of DOC_EVENTS) {
ch.on(ev, (data: unknown) => {
options.onConnected(true)
pushLog(ev, data)
})
}
return {
disconnect: () => {
try {
client.disconnect()
} catch {
/* ignore */
}
options.onConnected(false)
},
}
}

View File

@@ -0,0 +1,142 @@
<template>
<div class="default-main">
<el-alert type="info" :title="tip" show-icon class="mb-12" />
<el-alert :type="connected ? 'success' : 'warning'" :title="connected ? t('test.push.connected') : t('test.push.disconnected')" show-icon class="mb-12" />
<el-card shadow="never" class="mb-12">
<el-form :inline="true" @submit.prevent>
<el-form-item v-if="useUuid" :label="t('test.push.user_uuid')">
<el-input v-model="userUuid" :placeholder="t('test.push.user_uuid_placeholder')" clearable style="width: 280px" />
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" @click="connect">{{ t('test.push.btn_connect') }}</el-button>
<el-button :disabled="!session" @click="disconnect">{{ t('test.push.btn_disconnect') }}</el-button>
<el-button @click="clearLogs">{{ t('test.push.btn_clear') }}</el-button>
</el-form-item>
</el-form>
<div class="text-muted mb-8">{{ t('test.push.channel_label') }}: {{ channelName || '-' }}</div>
</el-card>
<el-card shadow="never">
<template #header>{{ t('test.push.log_title') }}</template>
<el-scrollbar max-height="480">
<pre class="push-log">{{ logText }}</pre>
</el-scrollbar>
</el-card>
</div>
</template>
<script setup lang="ts">
import { computed, onUnmounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import createAxios from '/@/utils/axios'
import { loadPushJs, startPushChannelListener, type PushTestLogLine } from '/@/utils/backend/pushChannelTest'
const props = withDefaults(
defineProps<{
/** 如 /admin/test.PushGamePeriod/pushConfig */
configApi: string
useUuid?: boolean
tip: string
}>(),
{
useUuid: false,
}
)
const { t } = useI18n()
const loading = ref(false)
const connected = ref(false)
const channelName = ref('')
const userUuid = ref('')
const logs = ref<PushTestLogLine[]>([])
const session = ref<{ disconnect: () => void } | null>(null)
const logText = computed(() => {
if (!logs.value.length) return t('test.push.log_empty')
return logs.value
.map((row) => {
const time = new Date(row.t).toLocaleString()
return `[${time}] ${row.event}\n${row.payload}`
})
.join('\n\n')
})
function appendLog(line: PushTestLogLine) {
logs.value = [...logs.value, line].slice(-200)
}
function clearLogs() {
logs.value = []
}
async function connect() {
if (props.useUuid && !userUuid.value.trim()) {
return
}
loading.value = true
disconnect()
try {
await loadPushJs()
const params: anyObj = {}
if (props.useUuid) {
params.uuid = userUuid.value.trim()
}
const res = await createAxios({
url: props.configApi,
method: 'get',
params,
showCodeMessage: true,
})
if (res.code !== 1 || !res.data) {
connected.value = false
return
}
const { url, app_key, channel } = res.data
channelName.value = typeof channel === 'string' ? channel : ''
try {
const handle = startPushChannelListener({
url,
app_key,
channel: channelName.value,
usePrivateAuth: !!props.useUuid,
onLog: appendLog,
onConnected: (ok) => {
connected.value = ok
},
})
session.value = handle
} catch {
connected.value = false
}
} finally {
loading.value = false
}
}
function disconnect() {
if (session.value) {
session.value.disconnect()
session.value = null
}
connected.value = false
}
onUnmounted(() => {
disconnect()
})
</script>
<style scoped>
.push-log {
margin: 0;
font-size: 12px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-all;
}
.text-muted {
color: var(--el-text-color-secondary);
font-size: 13px;
}
</style>

View File

@@ -0,0 +1,10 @@
<template>
<PushChannelTestPage config-api="/admin/test.PushGamePeriod/pushConfig" :tip="t('test.pushGamePeriod.tip')" />
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import PushChannelTestPage from '../components/PushChannelTestPage.vue'
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,10 @@
<template>
<PushChannelTestPage config-api="/admin/test.PushOperationNotice/pushConfig" :tip="t('test.pushOperationNotice.tip')" />
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import PushChannelTestPage from '../components/PushChannelTestPage.vue'
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,14 @@
<template>
<PushChannelTestPage
config-api="/admin/test.PushPrivateUser/pushConfig"
use-uuid
:tip="t('test.pushPrivateUser.tip')"
/>
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import PushChannelTestPage from '../components/PushChannelTestPage.vue'
const { t } = useI18n()
</script>