15m44w 工单附件换思路: issue API不支持附件, 改走git推图仓

- gh_api.php 新增 ghImgRepoPush/ghGitAvailable/ghImgRepoPushViaGit/ghImgRepoPushViaContents
  读 img.json repo.imgrepo(模式/用户名/仓库地址/key登录密码/分支), 运行时先 ghGitAvailable
  有git走 commit+push(PAT拼认证URL), 没git走 Contents API 兜底, raw链接 raw.githubusercontent.com
  仓内路径 {玩家名}/{工单号}_{YYYYMMDD}_{清洗标题}/{原文件名}; 删掉 ghReadGitCredential(改读img.json token)
- lsky.php loadImgJson 解析 imgrepo 段 + imgrepo_mode/owner/full/branch/token
- api/ticket.php uploadTicketFiles 分流: imgrepo_mode=gh 存临时文件返回 @ghimgrepo: 占位,
  图床模式走图床拿真URL; ticketCreate 推仓后回写 images 拿 raw URL
- api/gh_git_probe.php 新增诊断端点(检测git/imgrepo配置/raw域名可达性)
- img.json 仓库版 imgrepo 段全占位符(真PAT在 .workbuddy 不推git)
This commit is contained in:
ypsdf1
2026-11-25 17:30:25 +08:00
parent 8543f8e573
commit 534bb36b99
5 changed files with 394 additions and 6 deletions
+154
View File
@@ -443,6 +443,160 @@ function ghHandleWebhook($payload, $event) {
return false;
}
/**
* ★ 15m44w: 把工单附件图推到 GitHub 图片仓(imgrepo = issueimg),拿 raw 链接。
* 用户定调:GitHub 模式本就是为省服务器内存,附件不走图床 API,改成 git 推图仓。
* - 运行时先检测 git 环境:有 git → 走 git commit+push(账号/key 用【img.json 的 PAT】拼认证 URL);
* 无 git → 走 GitHub Contents API(token 也从 img.json 读)。
* - 文件路径:{玩家名}/{工单号}_{YYYYMMDD}_{工单标题}/{原文件名}(每玩家一个文件夹)
* - raw 链接:raw.githubusercontent.com/{owner}/{repo}/{branch}/{path}
* 失败返回 ['ok'=>false,'msg'=>..],调用方回退 @gh: 占位。
*/
/** 服务端是否装了 git(git --version 能跑) */
function ghGitAvailable() {
static $cached = null;
if ($cached !== null) return $cached;
$cached = false;
if (function_exists('exec')) {
$o = []; $ret = 0;
@exec('git --version 2>NUL', $o, $ret); // Windows: 2>NUL 吞错误
if ($ret !== 0) @exec('git --version 2>/dev/null', $o, $ret); // Linux
$cached = ($ret === 0 && !empty($o));
}
return $cached;
}
function ghImgRepoPush($player, $ticketId, $title, $tmpPath, $origName) {
$cfg = ghGetCfg();
$full = isset($cfg['imgrepo_full']) ? $cfg['imgrepo_full'] : '';
$owner = isset($cfg['imgrepo_owner']) ? $cfg['imgrepo_owner'] : '';
$branch = (isset($cfg['imgrepo_branch']) && $cfg['imgrepo_branch'] !== '') ? $cfg['imgrepo_branch'] : 'main';
$token = isset($cfg['imgrepo_token']) ? $cfg['imgrepo_token'] : ''; // ★ 15m44w:账号/key 走 img.json(真值在 .workbuddy,不进 git)
if ($full === '' || strpos($full, '/') === false) {
return ['ok' => false, 'url' => '', 'path' => '', 'msg' => 'imgrepo 仓库地址未配置(img.json repo.imgrepo.仓库地址)'];
}
if ($owner === '') $owner = explode('/', $full)[0];
// 仓内相对路径:{玩家名}/{工单号}_{YYYYMMDD}_{清洗标题}/{原文件名}
$safeTitle = preg_replace('/[^A-Za-z0-9_\x{4E00}-\x{9FFF}]/u', '_', mb_substr($title, 0, 30));
if ($safeTitle === '') $safeTitle = 'untitled';
$safePlayer = preg_replace('/[^A-Za-z0-9_]/', '_', $player);
$relPath = $safePlayer . '/' . ((int)$ticketId) . '_' . date('Ymd') . '_' . $safeTitle . '/' . $origName;
$rawUrl = 'https://raw.githubusercontent.com/' . $full . '/' . $branch . '/' . $relPath;
// ===== 分支1:有 git 环境 → git commit + push(账号/key 用 img.json 的 PAT 拼认证 URL)=====
if (ghGitAvailable()) {
$commitMsg = 'ticket#' . $ticketId . ': ' . mb_substr($title, 0, 40);
$r = ghImgRepoPushViaGit($full, $owner, $branch, $relPath, $tmpPath, $token, $commitMsg);
if (!empty($r['ok'])) {
ghLog('imgrepo push(via git) ok ticket=' . $ticketId . ' path=' . $relPath);
return ['ok' => true, 'url' => $rawUrl, 'path' => $relPath, 'msg' => 'ok'];
}
// git 失败 → 记日志,落 Contents API 兜底(git 可能没配全局 credential)
ghLog('imgrepo git push failed ticket=' . $ticketId . ': ' . $r['msg'] . ' → fallback Contents API');
}
// ===== 分支2:无 git(或 git 失败)→ GitHub Contents API(token 来自 img.json)=====
if ($token === '') {
return ['ok' => false, 'url' => '', 'path' => '', 'msg' => 'img.json repo.imgrepo 的 key/登录密码 未配置(git 与 Contents API 都需要 PAT)'];
}
$r2 = ghImgRepoPushViaContents($full, $branch, $relPath, $tmpPath, $token, 'ticket#' . $ticketId . ': ' . mb_substr($title, 0, 40));
if (!empty($r2['ok'])) {
ghLog('imgrepo push(via Contents API) ok ticket=' . $ticketId . ' path=' . $relPath);
return ['ok' => true, 'url' => $rawUrl, 'path' => $relPath, 'msg' => 'ok'];
}
ghLog('imgrepo contents api failed ticket=' . $ticketId . ': ' . $r2['msg']);
return ['ok' => false, 'url' => '', 'path' => '', 'msg' => $r2['msg']];
}
/** git 方式推图(★ 15m44w:账号/key 走 img.json 的 PAT,拼进认证 URL,不依赖服务端全局 git 缓存) */
function ghImgRepoPushViaGit($full, $owner, $branch, $relPath, $tmpPath, $token, $commitMsg) {
$workRoot = __DIR__ . '/db/gh_imgrepo_work';
if (!is_dir($workRoot)) @mkdir($workRoot, 0755, true);
$repoDir = $workRoot . '/' . preg_replace('/[^A-Za-z0-9_.-]/', '_', $full);
$gitBin = 'git';
// 跑 git 命令(Windows/Linux 通用,env 注入 GIT_TERMINAL_PROMPT=0 禁交互 + 走全局 credential)
$runGit = function($args, $cwd, $timeout = 60) use ($gitBin) {
$cmd = $gitBin . ' ' . implode(' ', array_map(function($a) {
if (preg_match('/[^\x20-\x7E]/', $a) || strpos($a, ' ') !== false) return '"' . str_replace('"', '\\"', $a) . '"';
return $a;
}, $args));
$env = array_merge($_SERVER, ['GIT_TERMINAL_PROMPT' => '0']);
if ($token !== '') {
// ★ 用 img.json 的 PAT 做认证(禁交互 + 不污染全局 credential)
$env['GIT_CONFIG_COUNT'] = '1';
$env['GIT_CONFIG_KEY_0'] = 'http.https://github.com/.extraheader';
$env['GIT_CONFIG_VALUE_0'] = 'Authorization: Basic ' . base64_encode($owner . ':' . $token);
}
$desc = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$proc = proc_open($cmd, $desc, $pipes, $cwd, $env);
if (!is_resource($proc)) return ['ok' => false, 'msg' => 'proc_open 失败'];
fclose($pipes[0]);
$out = stream_get_contents($pipes[1]); fclose($pipes[1]);
$err = stream_get_contents($pipes[2]); fclose($pipes[2]);
$st = proc_close($proc);
return ['ok' => ($st === 0), 'msg' => trim((string)$err . (string)$out)];
};
$cloneUrl = ($token !== '')
? ('https://' . $owner . ':' . $token . '@github.com/' . $full . '.git') // ★ PAT 拼认证 URL(img.json token)
: ('https://github.com/' . $full . '.git');
try {
// 1) 本地仓(首次 clone,已有则 fetch)
if (is_dir($repoDir . '/.git')) {
$runGit(['fetch', '--all'], $repoDir, 60);
$runGit(['checkout', '-B', $branch, 'origin/' . $branch], $repoDir, 30);
} else {
@mkdir(dirname($repoDir), 0755, true);
$r = $runGit(['clone', '--depth', '1', '--branch', $branch, '--single-branch', $cloneUrl, $repoDir], $workRoot, 120);
if (!$r['ok']) return ['ok' => false, 'msg' => 'clone 失败: ' . mb_substr($r['msg'], 0, 160)];
$runGit(['config', 'user.name', 'caoyuan-ticket-bot'], $repoDir, 10);
$runGit(['config', 'user.email', 'bot@caoyuan.local'], $repoDir, 10);
}
// 2) 写文件到仓内
$target = $repoDir . '/' . $relPath;
@mkdir(dirname($target), 0755, true);
if (!@copy($tmpPath, $target)) return ['ok' => false, 'msg' => '写仓内文件失败'];
// 3) add + commit + push(认证走 img.json PAT:clone URL 已带 owner:token,push 复用 origin)
$runGit(['add', '--', $relPath], $repoDir, 30);
$runGit(['commit', '-m', $commitMsg, '--allow-empty'], $repoDir, 30);
$rp = $runGit(['push', 'origin', 'HEAD:refs/heads/' . $branch], $repoDir, 90);
if (!$rp['ok']) {
@unlink($target);
return ['ok' => false, 'msg' => 'push 失败: ' . mb_substr($rp['msg'], 0, 200)];
}
return ['ok' => true, 'msg' => 'ok'];
} catch (\Throwable $e) {
return ['ok' => false, 'msg' => 'git 异常: ' . $e->getMessage()];
}
}
/** GitHub Contents API 方式推图(免 git 二进制;token 当 Authorization: Bearer) */
function ghImgRepoPushViaContents($full, $branch, $relPath, $tmpPath, $token, $commitMsg) {
if (!is_file($tmpPath)) return ['ok' => false, 'msg' => '临时文件不存在'];
$content = @file_get_contents($tmpPath);
if ($content === false) return ['ok' => false, 'msg' => '读临时文件失败'];
$encoded = base64_encode($content);
// 路径 URL 编码(每段单独编码,保留 /)
$encPath = implode('/', array_map('rawurlencode', explode('/', $relPath)));
$apiPath = '/repos/' . $full . '/contents/' . $encPath;
// 同名文件已存在?GET 拿 sha(Contents API 更新需带 sha)
$chk = ghApiRequest('GET', $apiPath, null, $token);
$payload = [
'message' => $commitMsg,
'content' => $encoded,
'branch' => $branch,
];
if (!empty($chk['ok']) && is_array($chk['data']) && isset($chk['data']['sha'])) {
$payload['sha'] = $chk['data']['sha'];
}
$r = ghApiRequest('PUT', $apiPath, $payload, $token);
if (!$r['ok']) return ['ok' => false, 'msg' => $r['msg']];
return ['ok' => true, 'msg' => 'ok'];
}
/** 写诊断日志(1 天自动清理) */
function ghLog($msg) {
try {