github/app/Services/TG/Hook/Mod/Git.php
2025-04-14 21:02:26 +08:00

111 lines
3.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Services\TG\Hook\Mod;
use App\Models\Article as ModelArticle;
class Git extends Base {
public function AddSshHostGithub()
{
// 定义要添加的主机
$host = 'github.com';
// 执行 ssh-keyscan 命令
$key = shell_exec("ssh-keyscan -t ed25519 $host");
// 检查是否成功获取到公钥
if ($key) {
// 获取 known_hosts 文件的路径
$knownHostsFile = '/root/.ssh/known_hosts';
// 检查 known_hosts 文件中是否已经存在该主机的公钥
if (strpos(file_get_contents($knownHostsFile), $host) === false) {
// 将公钥写入 known_hosts 文件
file_put_contents($knownHostsFile, $key, FILE_APPEND);
$sMsg = "公钥已成功添加到 $knownHostsFile\n";
} else {
$sMsg = "公钥已存在于 $knownHostsFile\n";
}
} else {
$sMsg = "无法获取 $host 的公钥\n";
}
$this->oTGHttp->sendToTG($sMsg);
$this->oHttp::response(200, 'ok');
}
public function Clone($aParam)
{
$iId = $aParam['aArg'][1];
// 查找文章
$aArticle = ModelArticle::find($iId);
if ($aArticle) {
// 复制文章
$newArticle = $aArticle->replicate();
// 如果需要,可以修改新文章的某些字段,例如标题或状态
// $newArticle->title = $newArticle->title . ' - Copy'; // 修改标题
// $newArticle->status = 'draft'; // 例如,将状态设置为草稿
// 保存新文章
$newArticle->save();
// 发送新文章的 ID 到 Telegram
$sMsg = "新文章已创建ID: " . $newArticle->id;
$this->oTGHttp->sendToTG($sMsg);
// 返回 HTTP 响应
$this->oHttp::response(200, 'ok');
} else {
throw new \Exception("没有这个id");
}
}
// /Git#PullR 3
public function PullR($aParam)
{
$iId = $aParam['aArg'][1];
$aArticle = ModelArticle::find($iId);
$sProjectPath = env("BASE_DIR")."github/".$aArticle->user_name."-".$aArticle->project_name;
// 进入指定目录
if (!chdir($sProjectPath)) {
echo "无法进入目录 {$sProjectPath}\n";
exit(1);
}
// 获取远程更新
$this->runCommand('git fetch origin');
// 硬重置到远程主分支
$this->runCommand('git reset --hard origin/main');
echo "操作完成:已重置到远程主分支。\n";
}
private function runCommand($command) {
$output = [];
$returnVar = 0;
exec($command, $output, $returnVar);
if ($returnVar !== 0) {
// 将输出数组转换为 JSON 格式
$jsonOutput = json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$errorMessage = "命令失败: $command\n" . $jsonOutput . "\n";
throw new \Exception($errorMessage);
}
}
}