, reporting: list}, * seeds_initialized: bool, * sync_rebuilt: bool, * support_path: string, * weifile_path: ?string, * daily_path: string, * support_template?: string, * } */ public function generate( string $channelId, string $supportTemplate = self::DEFAULT_SUPPORT_TEMPLATE, ?string $deploymentSeed = null, ?string $reportingSeed = null, string $builderType = self::BUILDER_OLD, ): array { $builderType = $this->normalizeBuilderType($builderType); if ($builderType === self::BUILDER_NEW) { return $this->generateNew($channelId); } [$deploymentSeed, $reportingSeed] = $this->normalizeOptionalSeeds( $deploymentSeed, $reportingSeed, ); return $this->generateOld( $this->normalizeChannelId($channelId), $supportTemplate, $deploymentSeed, $reportingSeed, ); } public function deleteWebTree( string $channelId, string $builderType = self::BUILDER_OLD, ): void { $builderType = $this->normalizeBuilderType($builderType); if ($builderType === self::BUILDER_NEW) { $code = Channel::normalizeNewChannelId($channelId); if ($code === null) { return; } $zip = $this->newChannelZipPath($code); if (is_file($zip) && ! unlink($zip)) { throw new RuntimeException('删除渠道安装包失败: '.$zip); } return; } try { $channelId = $this->normalizeChannelId($channelId); } catch (RuntimeException) { return; } $cmd = [ $this->pythonBinary($builderType), $this->builderScript('delete_channel_web.py', $builderType), '--artifact-root', $this->artifactRoot(), '--channel-id', $channelId, ]; $this->runBuilder($cmd, '删除渠道资源失败', $this->builderCwd($builderType)); } /** * @return array{ * channel_id: string, * builder_type: string, * seeds: array{deployment_seed: string, reporting_seed: string, channel_c?: string}, * domains: array{deployment: list, reporting: list}, * seeds_initialized: bool, * sync_rebuilt: bool, * support_path: string, * weifile_path: ?string, * daily_path: string, * support_template?: string, * } */ private function generateOld( string $channelId, string $supportTemplate, ?string $deploymentSeed, ?string $reportingSeed, ): array { $supportTemplate = $this->normalizeSupportTemplate($supportTemplate); $cmd = [ $this->pythonBinary(self::BUILDER_OLD), $this->builderScript('new_project.py', self::BUILDER_OLD), '--artifact-root', $this->artifactRoot(), '--state-root', $this->stateRoot(self::BUILDER_OLD), '--channel-id', $channelId, '--support-template', $supportTemplate, '--force', ]; if ($deploymentSeed !== null && $reportingSeed !== null) { $cmd[] = '--deployment-seed'; $cmd[] = $deploymentSeed; $cmd[] = '--reporting-seed'; $cmd[] = $reportingSeed; } $result = $this->runBuilder($cmd, '生成渠道资源失败', $this->builderCwd(self::BUILDER_OLD)); $supportPath = (string) ($result['support_path'] ?? '/web/'.$channelId.'/support.html'); return [ 'channel_id' => (string) ($result['channel_id'] ?? $channelId), 'builder_type' => self::BUILDER_OLD, 'seeds' => [ 'deployment_seed' => (string) data_get($result, 'seeds.deployment_seed', ''), 'reporting_seed' => (string) data_get($result, 'seeds.reporting_seed', ''), ], 'domains' => [ 'deployment' => array_values((array) data_get($result, 'domains.deployment', [])), 'reporting' => array_values((array) data_get($result, 'domains.reporting', [])), ], 'seeds_initialized' => (bool) ($result['seeds_initialized'] ?? false), 'sync_rebuilt' => (bool) ($result['sync_rebuilt'] ?? false), 'support_path' => $supportPath, 'weifile_path' => null, 'daily_path' => (string) ($result['daily_path'] ?? '/sync/daily.html'), 'support_template' => (string) ($result['support_template'] ?? $supportTemplate), ]; } /** * Rebuild shared /details and staged weifile from `c`. * Only used by `php artisan xxbb:build`, not when creating a channel. * * @return array */ public function buildSharedArtifacts(?string $channelC = null, bool $randomC = false): array { if ($randomC && $channelC !== null && $channelC !== '') { throw new RuntimeException('不能同时指定 channel-c 和 random-c'); } $cmd = [ $this->pythonBinary(self::BUILDER_NEW), $this->builderScript('build.py', self::BUILDER_NEW), '--artifact-root', $this->artifactRoot(), '--state-root', $this->stateRoot(self::BUILDER_NEW), '--apply', '--force', ]; if ($randomC) { $cmd[] = '--random-c'; } else { $c = $this->normalizeSharedChannelC($channelC); if ($c !== null) { $cmd[] = '--channel-c'; $cmd[] = $c; } } return $this->runBuilder($cmd, '构建共享产物失败', $this->builderCwd(self::BUILDER_NEW)); } private function generateNew(string $channelId): array { $channelId = Channel::normalizeNewChannelId($channelId); if ($channelId === null) { throw new RuntimeException('新版渠道 ID 必须是 8 位字母或数字(例如 FAFA9988)'); } $weifileSrc = $this->stagedWeifileDir(); if (! is_file($weifileSrc.DIRECTORY_SEPARATOR.'index.js')) { throw new RuntimeException('请先运行构建脚本: php artisan xxbb:build'); } $zipPath = $this->newChannelZipPath($channelId); $this->ensureDirectory(dirname($zipPath), '新版渠道产物目录'); $cmd = [ $this->pythonBinary(self::BUILDER_NEW), $this->builderScript('pack_channel.py', self::BUILDER_NEW), '--channel-code', $channelId, '--state-root', $this->stateRoot(self::BUILDER_NEW), '--weifile-src', $weifileSrc, '--zip-out', $zipPath, ]; $result = $this->runBuilder($cmd, '打包渠道代码失败', $this->builderCwd(self::BUILDER_NEW)); $seeds = $this->loadNewLabSeeds(); $relativeZip = $this->newChannelZipRelative($channelId); return [ 'channel_id' => $channelId, 'builder_type' => self::BUILDER_NEW, 'seeds' => [ 'deployment_seed' => (string) data_get($result, 'seeds.deployment_seed', $seeds['deployment_seed']), 'reporting_seed' => (string) data_get($result, 'seeds.reporting_seed', $seeds['reporting_seed']), 'channel_c' => (string) data_get($result, 'seeds.channel_c', $seeds['channel_c']), ], 'domains' => [ 'deployment' => array_values((array) data_get($result, 'domains.deployment', $seeds['domains']['deployment'])), 'reporting' => array_values((array) data_get($result, 'domains.reporting', $seeds['domains']['reporting'])), ], 'seeds_initialized' => false, 'sync_rebuilt' => false, 'support_path' => '', 'weifile_path' => null, 'daily_path' => '/details/', 'zip_path' => '/'.$relativeZip, ]; } public function stagedWeifileDir(): string { return $this->stateRoot(self::BUILDER_NEW).DIRECTORY_SEPARATOR.'out'.DIRECTORY_SEPARATOR.'weifile'; } public function newChannelZipPath(string $channelId): string { return $this->artifactRoot().DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $this->newChannelZipRelative($channelId)); } public function newChannelZipRelative(string $channelId): string { $dir = trim((string) config('coruna.channel_builder_new.source_dir', 'channel-source-new'), '/'); $code = Channel::normalizeNewChannelId($channelId) ?? $channelId; return $dir.'/'.$code.'.zip'; } /** * @return array{deployment_seed: string, reporting_seed: string, channel_c: string, domains: array{deployment: list, reporting: list}} */ private function loadNewLabSeeds(): array { $empty = [ 'deployment_seed' => '', 'reporting_seed' => '', 'channel_c' => '', 'domains' => ['deployment' => [], 'reporting' => []], ]; $path = $this->stateRoot(self::BUILDER_NEW).DIRECTORY_SEPARATOR.'lab_seeds.json'; if (! is_file($path)) { return $empty; } $decoded = json_decode((string) file_get_contents($path), true); if (! is_array($decoded)) { return $empty; } return [ 'deployment_seed' => (string) ($decoded['deployment_seed'] ?? ''), 'reporting_seed' => (string) ($decoded['reporting_seed'] ?? ''), 'channel_c' => (string) ($decoded['channel_c'] ?? ''), 'domains' => [ 'deployment' => array_values((array) data_get($decoded, 'domains.deployment', [])), 'reporting' => array_values((array) data_get($decoded, 'domains.reporting', [])), ], ]; } private function normalizeSharedChannelC(?string $channelC): ?string { $c = strtolower(trim((string) ($channelC !== null && $channelC !== '' ? $channelC : config('coruna.xxbb.channel_c', '')))); if ($c === '') { return null; } if (! preg_match('/^[0-9a-f]{32}$/', $c)) { throw new RuntimeException('XXBB_CHANNEL_C 必须是 32 位 hex'); } if ($c === '202800cfb1ad3de68e11239dcc26c30b') { throw new RuntimeException('XXBB_CHANNEL_C 不能与 7z 密码槽相同'); } return $c; } /** * @param list $cmd * @return array */ private function runBuilder(array $cmd, string $errorPrefix, string $cwd): array { $timeout = (float) config('coruna.channel_builder.timeout', 600); $process = Process::timeout((int) max(1, $timeout)) ->path($cwd) ->run($cmd); if (! $process->successful()) { $detail = trim($process->errorOutput() ?: $process->output()); $detail = mb_substr($detail !== '' ? $detail : 'builder exited '.$process->exitCode(), 0, 800); Log::error('Channel builder failed', [ 'exit_code' => $process->exitCode(), 'detail' => $detail, 'cmd' => $cmd, ]); throw new RuntimeException("{$errorPrefix}: {$detail}"); } return $this->parseResultMarker($process->output(), $errorPrefix); } /** * @return array */ private function parseResultMarker(string $output, string $errorPrefix): array { $lines = preg_split("/\r\n|\n|\r/", $output) ?: []; for ($i = count($lines) - 1; $i >= 0; $i--) { $line = $lines[$i]; if (! str_starts_with($line, self::RESULT_MARKER)) { continue; } $json = substr($line, strlen(self::RESULT_MARKER)); $decoded = json_decode($json, true); if (! is_array($decoded)) { throw new RuntimeException("{$errorPrefix}: invalid builder JSON"); } return $decoded; } throw new RuntimeException("{$errorPrefix}: missing builder result marker"); } private function pythonBinary(string $builderType): string { $configKey = $builderType === self::BUILDER_NEW ? 'coruna.channel_builder_new.python' : 'coruna.channel_builder.python'; $configured = trim((string) config($configKey, '')); if ($configured !== '') { return $configured; } $venv = $this->builderCwd($builderType).'/.venv/bin/python'; if (is_file($venv)) { return $venv; } if ($builderType === self::BUILDER_NEW) { $fallback = base_path('channel-builder/.venv/bin/python'); if (is_file($fallback)) { return $fallback; } } return 'python3'; } private function builderScript(string $name, string $builderType): string { $path = $this->builderCwd($builderType).'/tools/'.$name; if (! is_file($path)) { throw new RuntimeException("渠道构建脚本不存在: {$path}"); } return $path; } private function builderCwd(string $builderType): string { return $builderType === self::BUILDER_NEW ? base_path('channel-builder-new') : base_path('channel-builder'); } private function artifactRoot(): string { $root = trim((string) config('coruna.channel_builder.artifact_root', '')); if ($root === '') { $root = public_path(); } return $this->ensureDirectory($root, '产物目录'); } private function stateRoot(string $builderType): string { $key = $builderType === self::BUILDER_NEW ? 'coruna.channel_builder_new.state_root' : 'coruna.channel_builder.state_root'; $root = trim((string) config($key, '')); if ($root === '') { $root = $builderType === self::BUILDER_NEW ? storage_path('app/channel-builder-new') : storage_path('app/channel-builder'); } return $this->ensureDirectory($root, '构建状态目录'); } private function ensureDirectory(string $root, string $label): string { if (! is_dir($root) && ! mkdir($root, 0775, true) && ! is_dir($root)) { throw new RuntimeException("无法创建{$label}: {$root}"); } return $root; } private function normalizeBuilderType(string $builderType): string { $builderType = strtolower(trim($builderType)); if ($builderType === '') { return self::BUILDER_OLD; } if (! in_array($builderType, [self::BUILDER_OLD, self::BUILDER_NEW], true)) { throw new RuntimeException('无效的渠道类型(支持: old, new)'); } return $builderType; } private function normalizeChannelId(string $channelId): string { $channelId = strtolower(trim($channelId)); if (! preg_match('/^[a-z0-9]{32}$/', $channelId)) { throw new RuntimeException('Invalid channel id'); } return $channelId; } private function normalizeSupportTemplate(string $supportTemplate): string { $supportTemplate = strtolower(trim($supportTemplate)); if ($supportTemplate === '') { return self::DEFAULT_SUPPORT_TEMPLATE; } if (! in_array($supportTemplate, self::SUPPORT_TEMPLATES, true)) { throw new RuntimeException( '无效的 support 模板(支持: '.implode(', ', self::SUPPORT_TEMPLATES).')' ); } return $supportTemplate; } /** * @return array{0: ?string, 1: ?string} */ private function normalizeOptionalSeeds( ?string $deploymentSeed, ?string $reportingSeed, ): array { $deploymentSeed = $deploymentSeed !== null ? trim($deploymentSeed) : null; $reportingSeed = $reportingSeed !== null ? trim($reportingSeed) : null; if (($deploymentSeed === null || $deploymentSeed === '') && ($reportingSeed === null || $reportingSeed === '')) { return [null, null]; } if ($deploymentSeed === null || $deploymentSeed === '' || $reportingSeed === null || $reportingSeed === '') { throw new RuntimeException('deployment_seed 与 reporting_seed 必须同时提供'); } foreach (['deployment_seed' => $deploymentSeed, 'reporting_seed' => $reportingSeed] as $name => $value) { if (! preg_match('/^[ -~]{1,32}$/', $value)) { throw new RuntimeException("无效的 {$name}(需 1–32 位 ASCII)"); } } if ($deploymentSeed !== $reportingSeed) { throw new RuntimeException('deployment_seed 与 reporting_seed 必须相同'); } return [$deploymentSeed, $reportingSeed]; } }