acpgram 1.26.0 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -1
- package/README.ru.md +31 -0
- package/package.json +1 -1
- package/src/bot.mjs +14 -0
- package/src/db.mjs +31 -0
- package/src/engines.mjs +3 -2
- package/src/git.mjs +235 -0
- package/src/gitAccess.mjs +112 -0
- package/src/gitHosts.mjs +195 -0
- package/src/gitInspect.mjs +163 -0
- package/src/gitRepoUi.mjs +189 -0
- package/src/gitUi.mjs +444 -0
- package/src/i18n.mjs +106 -0
- package/src/projectsUi.mjs +9 -2
- package/src/state.mjs +2 -0
- package/src/turn.mjs +2 -1
- package/src/ui.mjs +2 -1
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Экраны /git «Изменения» и «Ветки»: что изменено в проекте (список файлов, изменения по файлу, неотправленные и
|
|
2
|
+
// ожидающие на сервере коммиты) и ветки (список, переключение, новая ветка). Смотреть может любой пользователь —
|
|
3
|
+
// без агента и без запросов к модели; переключать и создавать ветки — тот, кому разрешено менять файлы проекта.
|
|
4
|
+
// Вызывается из gitUi.mjs, который передаёт сюда общие помощники (h): проект, репозиторий, запуск git.
|
|
5
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { basename, join } from 'node:path';
|
|
7
|
+
import { log, say } from './ctx.mjs';
|
|
8
|
+
import { isSecretName, outboxDir, safeFileName } from './files.mjs';
|
|
9
|
+
import { canManageFiles } from './filesUi.mjs';
|
|
10
|
+
import { GitError, fetchRepo } from './git.mjs';
|
|
11
|
+
import { branchName, changedFiles, commitList, createBranch, fileDiff, listBranches, switchBranch } from './gitInspect.mjs';
|
|
12
|
+
import { errText, t } from './i18n.mjs';
|
|
13
|
+
import { endAgent, userPath } from './state.mjs';
|
|
14
|
+
import { escHtml, sendFile } from './telegram.mjs';
|
|
15
|
+
import { hCode, th } from './ui.mjs';
|
|
16
|
+
|
|
17
|
+
/** Действия кнопок, которые обрабатывает этот модуль (gt:<действие>:<аргумент>). */
|
|
18
|
+
export const REPO_ACTIONS = ['ch', 'cf', 'cm', 'br', 'bs', 'bn'];
|
|
19
|
+
|
|
20
|
+
const PAGE = 10;
|
|
21
|
+
/** Изменения файла длиннее этого приходят файлом: в сообщение Telegram они не помещаются. */
|
|
22
|
+
export const DIFF_INLINE_MAX = 3200;
|
|
23
|
+
const DIFF_FILE_MAX = 1024 * 1024;
|
|
24
|
+
const MARK = { new: '🆕', modified: '✏️', deleted: '🗑', renamed: '🔀', conflict: '⚠️' };
|
|
25
|
+
|
|
26
|
+
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError ? e.message : errText(e, lang) });
|
|
27
|
+
/** Длинный путь на кнопке показывается хвостом: имя файла важнее начала пути. */
|
|
28
|
+
const tail = (s, n) => ([...s].length > n ? `…${[...s].slice(-(n - 1)).join('')}` : s);
|
|
29
|
+
const counts = (f) => [f.added ? `+${f.added}` : '', f.deleted ? `−${f.deleted}` : ''].filter(Boolean).join(' ');
|
|
30
|
+
const pager = (prefix, page, pages) => {
|
|
31
|
+
const nav = [];
|
|
32
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `${prefix}:${page - 1}` });
|
|
33
|
+
nav.push({ text: `${page + 1}/${pages}`, callback_data: 'nav:n' });
|
|
34
|
+
if (page < pages - 1) nav.push({ text: '▶', callback_data: `${prefix}:${page + 1}` });
|
|
35
|
+
return nav;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Экран «Изменения»: несохранённые изменения рабочей папки кнопками по файлам и переходы к спискам коммитов. */
|
|
39
|
+
async function changesView(st, project, repo, opts, page, lang) {
|
|
40
|
+
const { files, total } = await changedFiles(project, opts);
|
|
41
|
+
st.gitChanges = files; // кнопки ссылаются на файл номером в этом списке
|
|
42
|
+
const pages = Math.max(1, Math.ceil(files.length / PAGE));
|
|
43
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
44
|
+
const sum = (key) => files.reduce((n, f) => n + (f[key] ?? 0), 0);
|
|
45
|
+
const head = th('git.ch.head', lang, { p: hCode(userPath(st.userId, project, lang)), branch: repo.state.branch ?? '—' });
|
|
46
|
+
const body = total ? th('git.ch.sum', lang, { n: total, a: sum('added'), d: sum('deleted') }) + (total > files.length ? `\n<i>${th('git.ch.cut', lang, { n: files.length })}</i>` : '') : th('git.ch.none', lang);
|
|
47
|
+
const rows = files.slice(page * PAGE, (page + 1) * PAGE).map((f, i) => [{ text: [...`${MARK[f.kind] ?? '✏️'} ${tail(f.path, 40)} ${counts(f)}`.trim()].slice(0, 60).join(''), callback_data: `gt:cf:${page * PAGE + i}` }]);
|
|
48
|
+
if (pages > 1) rows.push(pager('gt:ch', page, pages));
|
|
49
|
+
const s = repo.state;
|
|
50
|
+
const commits = [];
|
|
51
|
+
if (!s.upstream) commits.push({ text: t('git.ch.local', lang), callback_data: 'gt:cm:o' });
|
|
52
|
+
if (s.upstream && s.ahead) commits.push({ text: t('git.ch.out', lang, { n: s.ahead }), callback_data: 'gt:cm:o' });
|
|
53
|
+
if (s.upstream && s.behind) commits.push({ text: t('git.ch.in', lang, { n: s.behind }), callback_data: 'gt:cm:i' });
|
|
54
|
+
if (commits.length) rows.push(commits);
|
|
55
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
56
|
+
return { text: `${head}\n\n${body}`, markup: { inline_keyboard: rows } };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Экран «Ветки»: текущая отмечена, ветки только с сервера помечены облаком; нажатие переключает. */
|
|
60
|
+
async function branchesView(st, project, repo, opts, page, lang, { sync = false } = {}) {
|
|
61
|
+
// ветки сервера узнаём сверкой с ним — нужен подключённый аккаунт; не вышло — показываем то, что известно
|
|
62
|
+
if (sync && repo.account && !st.busy && !st.gitBusy) await fetchRepo(project, opts).catch((e) => log('git: сверка веток:', e.message, '| пользователь', st.userId));
|
|
63
|
+
const { current, branches } = await listBranches(project, opts);
|
|
64
|
+
st.gitBranches = branches;
|
|
65
|
+
const pages = Math.max(1, Math.ceil(branches.length / PAGE));
|
|
66
|
+
page = Math.min(Math.max(page, 0), pages - 1);
|
|
67
|
+
const rows = branches.slice(page * PAGE, (page + 1) * PAGE).map((b, i) => [{ text: [...`${b.current ? '✓' : b.local ? '🌿' : '☁️'} ${b.name}`].slice(0, 60).join(''), callback_data: `gt:bs:${page * PAGE + i}` }]);
|
|
68
|
+
if (pages > 1) rows.push(pager('gt:br', page, pages));
|
|
69
|
+
if (canManageFiles(st.userId)) rows.push([{ text: t('git.br.new', lang), callback_data: 'gt:bn' }]);
|
|
70
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
71
|
+
return { text: th('git.br.head', lang, { branch: hCode(current ?? '—') }), markup: { inline_keyboard: rows } };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Изменения одного файла: короткие — в сообщении, длинные — файлом; содержимое файлов с секретами не показывается. */
|
|
75
|
+
async function showDiff(st, project, file, opts, lang, edit) {
|
|
76
|
+
const back = { inline_keyboard: [[{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }]] };
|
|
77
|
+
const title = `${MARK[file.kind] ?? '✏️'} ${hCode(file.path).html}`;
|
|
78
|
+
if (isSecretName(`/${file.path}`)) return edit({ text: th('git.diff.secret', lang, { path: hCode(file.path) }), markup: back });
|
|
79
|
+
const diff = await fileDiff(project, file, opts);
|
|
80
|
+
if (!diff) return edit({ text: `${title}\n\n${th('git.diff.empty', lang)}`, markup: back });
|
|
81
|
+
if (diff.length <= DIFF_INLINE_MAX) return edit({ text: `${title}\n<pre><code class="language-diff">${escHtml(diff)}</code></pre>`, markup: back });
|
|
82
|
+
// большой diff — файлом через каталог исходящих пользователя; после отправки файл не нужен
|
|
83
|
+
const dir = outboxDir(st.userId);
|
|
84
|
+
mkdirSync(dir, { recursive: true });
|
|
85
|
+
const path = join(dir, `${safeFileName(basename(file.path))}.diff`);
|
|
86
|
+
writeFileSync(path, diff.length > DIFF_FILE_MAX ? `${diff.slice(0, DIFF_FILE_MAX)}\n… (truncated)\n` : `${diff}\n`);
|
|
87
|
+
try {
|
|
88
|
+
await sendFile(st.to, path);
|
|
89
|
+
} finally {
|
|
90
|
+
rmSync(path, { force: true });
|
|
91
|
+
}
|
|
92
|
+
return edit({ text: th('git.diff.sent', lang, { path: hCode(file.path) }), markup: back });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Список коммитов: ещё не отправленных ('o') или ждущих на сервере ('i'). */
|
|
96
|
+
async function commitsView(project, opts, which, lang) {
|
|
97
|
+
const list = await commitList(project, which === 'i' ? 'in' : 'out', opts);
|
|
98
|
+
const lines = list.map((c) => `<code>${escHtml(c.hash)}</code> ${escHtml(c.date)} · ${escHtml(c.author)}\n${escHtml(c.subject)}`);
|
|
99
|
+
const head = th(which === 'i' ? 'git.cm.in' : 'git.cm.out', lang, { n: list.length });
|
|
100
|
+
return { text: `${head}\n\n${lines.length ? lines.join('\n\n') : `<i>${th('git.cm.none', lang)}</i>`}`, markup: { inline_keyboard: [[{ text: t('git.ch.back', lang), callback_data: 'gt:ch:0' }]] } };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Кнопки экранов «Изменения» и «Ветки».
|
|
105
|
+
* @param {object} h помощники из gitUi: {action, arg, lang, ack, edit, project, repoOf, gitOpts}
|
|
106
|
+
*/
|
|
107
|
+
export async function onRepoCallback(st, cb, h) {
|
|
108
|
+
const { action, arg, lang, ack, edit, project } = h;
|
|
109
|
+
if (!project) return ack(t('state.projectGone', lang));
|
|
110
|
+
try {
|
|
111
|
+
const repo = await h.repoOf(st, project);
|
|
112
|
+
if (!repo) return (await ack(), edit({ text: th('git.noRepo', lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } }));
|
|
113
|
+
const opts = h.gitOpts(st, project, repo);
|
|
114
|
+
if (action === 'ch') return (await ack(), edit(await changesView(st, project, repo, opts, Number(arg) || 0, lang)));
|
|
115
|
+
if (action === 'cm') return (await ack(), edit(await commitsView(project, opts, arg, lang)));
|
|
116
|
+
if (action === 'cf') {
|
|
117
|
+
const file = st.gitChanges?.[Number(arg)];
|
|
118
|
+
if (!file) return ack(t('git.diff.gone', lang));
|
|
119
|
+
await ack();
|
|
120
|
+
return await showDiff(st, project, file, opts, lang, edit);
|
|
121
|
+
}
|
|
122
|
+
if (action === 'br') return (await ack(), edit(await branchesView(st, project, repo, opts, Number(arg) || 0, lang, { sync: true })));
|
|
123
|
+
// ---- переключение и создание ветки меняют проект ----
|
|
124
|
+
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
125
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
126
|
+
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
127
|
+
if (action === 'bn') {
|
|
128
|
+
await ack();
|
|
129
|
+
st.pendingInput = { kind: 'gitBranch', at: Date.now() };
|
|
130
|
+
return say(st.to, th('git.br.nameAsk', lang, { branch: hCode(repo.state.branch ?? '—') }), { parse_mode: 'HTML', reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } });
|
|
131
|
+
}
|
|
132
|
+
const branch = st.gitBranches?.[Number(arg)];
|
|
133
|
+
if (!branch) return ack(t('proj.stale', lang));
|
|
134
|
+
if (branch.current) return ack(t('git.br.same', lang));
|
|
135
|
+
// несохранённые изменения git либо не даст унести, либо молча перенесёт в другую ветку — сначала их нужно сохранить
|
|
136
|
+
if (repo.state.changed) {
|
|
137
|
+
await ack();
|
|
138
|
+
const markup = { inline_keyboard: [[{ text: t('git.save', lang), callback_data: 'gt:save' }], [{ text: t('btn.back', lang), callback_data: 'gt:br:0' }]] };
|
|
139
|
+
return edit({ text: th('git.br.dirty', lang, { n: repo.state.changed, name: hCode(branch.name) }), markup });
|
|
140
|
+
}
|
|
141
|
+
await ack();
|
|
142
|
+
st.gitBusy = true;
|
|
143
|
+
try {
|
|
144
|
+
await switchBranch(project, branch, opts);
|
|
145
|
+
} finally {
|
|
146
|
+
st.gitBusy = false;
|
|
147
|
+
}
|
|
148
|
+
// файлы проекта сменились целиком: сессия агента с прежним представлением о них продолжаться не должна
|
|
149
|
+
endAgent(st, 'branch');
|
|
150
|
+
log('git: ветка переключена:', st.userId, project, '→', branch.name);
|
|
151
|
+
const v = await branchesView(st, project, repo, opts, 0, lang);
|
|
152
|
+
return edit({ text: `${th('git.br.switched', lang, { name: hCode(branch.name) })}\n\n${v.text}`, markup: v.markup });
|
|
153
|
+
} catch (e) {
|
|
154
|
+
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
155
|
+
await ack();
|
|
156
|
+
return edit({ text: failText(e, lang), markup: { inline_keyboard: [[{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Название новой ветки от пользователя (после кнопки «Новая ветка»): создаёт ветку от текущей и переключается на неё.
|
|
162
|
+
* Несохранённые изменения остаются в рабочей папке, сессия агента продолжается — файлы те же.
|
|
163
|
+
* @param {object} h {wait, now, lang, project, repoOf, gitOpts}
|
|
164
|
+
* @returns {Promise<boolean>} true — текст обработан здесь
|
|
165
|
+
*/
|
|
166
|
+
export async function onBranchInput(st, text, h) {
|
|
167
|
+
const { lang, project } = h;
|
|
168
|
+
const html = { parse_mode: 'HTML' };
|
|
169
|
+
if (!project || !canManageFiles(st.userId)) return false;
|
|
170
|
+
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
171
|
+
try {
|
|
172
|
+
const repo = await h.repoOf(st, project);
|
|
173
|
+
if (!repo) return (await say(st.to, th('git.noRepo', lang), html), true);
|
|
174
|
+
const opts = h.gitOpts(st, project, repo);
|
|
175
|
+
const name = await branchName(text, { cwd: project, ...opts });
|
|
176
|
+
if (!name) {
|
|
177
|
+
st.pendingInput = { ...h.wait, at: h.now }; // название не подошло — ждём другое
|
|
178
|
+
return (await say(st.to, t('git.br.badName', lang), { reply_markup: { inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] } }), true);
|
|
179
|
+
}
|
|
180
|
+
await createBranch(project, name, opts);
|
|
181
|
+
log('git: ветка создана:', st.userId, project, name);
|
|
182
|
+
const markup = { inline_keyboard: [[{ text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }, { text: t('btn.back', lang), callback_data: 'gt:v' }]] };
|
|
183
|
+
await say(st.to, th('git.br.created', lang, { name: hCode(name) }), { ...html, reply_markup: markup });
|
|
184
|
+
} catch (e) {
|
|
185
|
+
log('git: новая ветка:', e.message, '| пользователь', st.userId);
|
|
186
|
+
await say(st.to, failText(e, lang), html);
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
package/src/gitUi.mjs
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// Команда /git: аккаунты GitHub и GitLab пользователя (вход по токену доступа), клонирование репозитория кнопками,
|
|
2
|
+
// состояние репозитория проекта, «Получить», «Отправить», «Сохранить и отправить».
|
|
3
|
+
// Токен вводится сообщением, которое не передаётся агенту и удаляется из чата; команды git с входом выполняет бот.
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { db, langOf, log, say } from './ctx.mjs';
|
|
6
|
+
import { canManageFiles } from './filesUi.mjs';
|
|
7
|
+
import { GitError, cloneRepo, commitAll, fetchRepo, gitAvailable, gitCommand, gitEnv, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
|
|
8
|
+
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
9
|
+
import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
|
|
10
|
+
import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
11
|
+
import { LOCALES, errText, t } from './i18n.mjs';
|
|
12
|
+
import { ROOT, folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
|
|
13
|
+
import { canCreateProject, selectProject } from './projectsUi.mjs';
|
|
14
|
+
import { agentSandbox } from './sandbox.mjs';
|
|
15
|
+
import { isAdmin, rootOf, sandboxed, userPath } from './state.mjs';
|
|
16
|
+
import { dest, tg } from './telegram.mjs';
|
|
17
|
+
import { hCode, th } from './ui.mjs';
|
|
18
|
+
|
|
19
|
+
const HTML = { parse_mode: 'HTML', link_preview_options: { is_disabled: true } };
|
|
20
|
+
/** Сколько бот ждёт токен, описание изменений или строку поиска. */
|
|
21
|
+
export const GIT_WAIT_MS = 10 * 60_000;
|
|
22
|
+
|
|
23
|
+
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
|
|
24
|
+
const dateOf = (iso, lang) => (iso ? new Date(iso).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' }) : '—');
|
|
25
|
+
|
|
26
|
+
/** Папка проекта диалога, если она доступна, иначе null. */
|
|
27
|
+
const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Как запускать git для этого пользователя: окружение (автор коммитов, вход в сервис), песочница сотрудника
|
|
31
|
+
* (если она включена) и строки, которые нужно вычистить из сообщений об ошибках.
|
|
32
|
+
*/
|
|
33
|
+
function gitOpts(st, cwd, { host = null, account = null } = {}) {
|
|
34
|
+
const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
|
|
35
|
+
const auth = host && account ? authConfig(host, account.token) : [];
|
|
36
|
+
const root = rootOf(st.userId);
|
|
37
|
+
const wrap = sandboxed(st.userId)
|
|
38
|
+
? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
|
|
39
|
+
: null;
|
|
40
|
+
return { env: gitEnv({ identity: identityOf(who), auth }), wrap, hide: account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Репозиторий проекта и его сервис: {state, host, account} или null, если проект не репозиторий (или репозиторий выше корня пользователя). */
|
|
44
|
+
async function repoOf(st, project) {
|
|
45
|
+
const state = await repoState(project, gitOpts(st, project));
|
|
46
|
+
if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
|
|
47
|
+
const host = hostFor(state.remote);
|
|
48
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
49
|
+
return { state, host, account };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Экран /git: состояние репозитория проекта, аккаунты, кнопки. Текст — HTML.
|
|
54
|
+
* sync — сначала свериться с сервером (git fetch), чтобы «новых на сервере» было настоящим числом: при открытии экрана
|
|
55
|
+
* и по кнопке «Обновить». Пока агент выполняет запрос или идёт другая операция git, сверка пропускается.
|
|
56
|
+
*/
|
|
57
|
+
export async function gitView(st, lang = langOf(st.userId), { sync = false } = {}) {
|
|
58
|
+
const project = projectOf(st);
|
|
59
|
+
const hosts = allHosts();
|
|
60
|
+
const accounts = accountsOf(st.userId);
|
|
61
|
+
const lines = [th('git.head', lang, { p: hCode(project ? userPath(st.userId, project, lang) : '—') })];
|
|
62
|
+
const rows = [];
|
|
63
|
+
const load = () => (project ? repoOf(st, project).catch((e) => (log('git: состояние:', e.message), null)) : null);
|
|
64
|
+
let repo = await load();
|
|
65
|
+
let syncError = null;
|
|
66
|
+
if (sync && repo?.account && !st.busy && !st.gitBusy) {
|
|
67
|
+
try {
|
|
68
|
+
await fetchRepo(project, gitOpts(st, project, repo));
|
|
69
|
+
repo = await load();
|
|
70
|
+
} catch (e) {
|
|
71
|
+
log('git: сверка с сервером:', e.message, '| пользователь', st.userId);
|
|
72
|
+
syncError = e.message;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (repo) {
|
|
76
|
+
const s = repo.state;
|
|
77
|
+
lines.push(th('git.repo', lang, { branch: s.branch ?? '—', changed: s.changed, ahead: s.ahead, behind: s.behind, remote: hCode(s.remote ? showRemote(s.remote) : '—') }));
|
|
78
|
+
if (syncError) lines.push(th('git.syncFail', lang, { msg: syncError }));
|
|
79
|
+
if (repo.account) {
|
|
80
|
+
if (canManageFiles(st.userId)) {
|
|
81
|
+
rows.push([{ text: t('git.pull', lang), callback_data: 'gt:pull' }, { text: t('git.push', lang), callback_data: 'gt:push' }]);
|
|
82
|
+
rows.push([{ text: t('git.save', lang), callback_data: 'gt:save', style: 'success' }]);
|
|
83
|
+
}
|
|
84
|
+
} else if (repo.host) lines.push(th('git.needAccount', lang, { host: repo.host.label }));
|
|
85
|
+
else lines.push(th(s.remote ? 'git.foreign' : 'git.noRemote', lang));
|
|
86
|
+
// что изменено и какие есть ветки — можно смотреть без агента и без аккаунта
|
|
87
|
+
rows.push([{ text: t('git.changesBtn', lang), callback_data: 'gt:ch:0' }, { text: t('git.branchesBtn', lang), callback_data: 'gt:br:0' }]);
|
|
88
|
+
} else lines.push(th('git.noRepo', lang));
|
|
89
|
+
lines.push(accounts.length ? [t('git.accounts', lang), ...accounts.map(({ host, account }) => th('git.accLine', lang, { host: host.label, login: account.login }))].join('\n') : th('git.noAccounts', lang));
|
|
90
|
+
if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
|
|
91
|
+
for (const h of hosts) {
|
|
92
|
+
const acc = accounts.find((x) => x.host.id === h.id)?.account;
|
|
93
|
+
rows.push([acc ? { text: t('git.accBtn', lang, { host: h.label, login: acc.login }), callback_data: `gt:a:${h.id}` } : { text: t('git.connect', lang, { host: h.label }), callback_data: `gt:c:${h.id}` }]);
|
|
94
|
+
}
|
|
95
|
+
// свои серверы (GitLab, GitHub Enterprise) добавляет администратор — прямо здесь, без правки настроек
|
|
96
|
+
rows.push([...(isAdmin(st.userId) ? [{ text: t('git.hostsBtn', lang), callback_data: 'gt:h' }] : []), { text: t('btn.refresh', lang), callback_data: 'gt:v' }]);
|
|
97
|
+
return { text: lines.join('\n\n'), markup: { inline_keyboard: rows } };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const KIND_LABEL = { gitlab: 'GitLab', github: 'GitHub Enterprise' };
|
|
101
|
+
|
|
102
|
+
/** Экран администратора «Свои серверы»: список, добавление GitLab или GitHub Enterprise, название, удаление. */
|
|
103
|
+
function hostsView(lang, note = '') {
|
|
104
|
+
const own = allHosts().filter((h) => h.custom);
|
|
105
|
+
const list = own.length
|
|
106
|
+
? own.map((h) => th('git.hosts.line', lang, { label: h.label, url: h.web, kind: KIND_LABEL[h.kind] }) + (h.fromEnv ? th('git.hosts.env', lang) : '')).join('\n')
|
|
107
|
+
: `<i>${th('git.hosts.none', lang)}</i>`;
|
|
108
|
+
const rows = own.filter((h) => !h.fromEnv).map((h) => [{ text: `✏️ ${h.label}`, callback_data: `gt:hn:${h.id}` }, { text: `🗑 ${t('git.hosts.remove', lang)}`, callback_data: `gt:hd:${h.id}` }]);
|
|
109
|
+
rows.push([{ text: t('git.hosts.addGitlab', lang), callback_data: 'gt:ha:gitlab' }, { text: t('git.hosts.addGithub', lang), callback_data: 'gt:ha:github' }]);
|
|
110
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
111
|
+
return { text: `${note ? `${note}\n\n` : ''}${th('git.hosts.head', lang)}\n\n${list}`, markup: { inline_keyboard: rows } };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** /git */
|
|
115
|
+
export async function handleGit(st) {
|
|
116
|
+
const lang = langOf(st.userId);
|
|
117
|
+
if (!gitAvailable()) return say(st.to, t('git.none', lang));
|
|
118
|
+
const v = await gitView(st, lang, { sync: true });
|
|
119
|
+
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Текст ошибки git или сервиса для пользователя. */
|
|
123
|
+
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
124
|
+
|
|
125
|
+
/** Куда клонировать: личное пространство сотрудника, иначе — папка рядом с текущим проектом (или корень). */
|
|
126
|
+
function cloneBase(st) {
|
|
127
|
+
const root = rootOf(st.userId);
|
|
128
|
+
if (isPersonalRoot(root)) return insideRoot(root, root);
|
|
129
|
+
return insideRoot(navStart(st.project, root), root) ?? (root ? insideRoot(root, root) : null);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k:<номер> по запомненному списку. */
|
|
133
|
+
async function reposView(st, host, account, { page = 0, search = '' } = {}, lang) {
|
|
134
|
+
const { items, more } = await listRepos(host, account.token, { page, search });
|
|
135
|
+
st.gitRepos = { host: host.id, items, page, search };
|
|
136
|
+
const base = cloneBase(st);
|
|
137
|
+
const rows = items.map((r, i) => [{ text: [...`${r.private ? '🔒' : '📂'} ${r.name}`].slice(0, 60).join(''), callback_data: `gt:k:${i}` }]);
|
|
138
|
+
const nav = [];
|
|
139
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `gt:r:${host.id}:${page - 1}` });
|
|
140
|
+
if (more) nav.push({ text: '▶', callback_data: `gt:r:${host.id}:${page + 1}` });
|
|
141
|
+
if (nav.length) rows.push(nav);
|
|
142
|
+
rows.push([{ text: t('git.search', lang), callback_data: `gt:s:${host.id}` }, { text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
143
|
+
const head = th('git.repos', lang, { host: host.label, q: search ? ` «${search}»` : '', dir: hCode(base ? userPath(st.userId, base, lang) : '—') });
|
|
144
|
+
return { text: items.length ? head : `${head}\n\n<i>${th('git.reposNone', lang)}</i>`, markup: { inline_keyboard: rows } };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Клонирует выбранный репозиторий в пространство пользователя и выбирает его проектом. */
|
|
148
|
+
async function cloneChosen(st, repo, host, account, lang, edit) {
|
|
149
|
+
const base = cloneBase(st);
|
|
150
|
+
const name = folderName(repoFolder(repo.url));
|
|
151
|
+
if (!base || !name) return edit({ text: th('git.cloneBadName', lang) });
|
|
152
|
+
const target = join(base, name);
|
|
153
|
+
if (insideRoot(target, rootOf(st.userId))) return edit({ text: th('git.cloneExists', lang, { name: hCode(name), dir: hCode(userPath(st.userId, base, lang)) }) });
|
|
154
|
+
await edit({ text: th('git.cloning', lang, { name: hCode(repo.name) }) });
|
|
155
|
+
try {
|
|
156
|
+
await cloneRepo(repo.url, name, { cwd: base, ...gitOpts(st, base, { host, account }) });
|
|
157
|
+
} catch (e) {
|
|
158
|
+
log('git: клонирование:', e.message, '| пользователь', st.userId);
|
|
159
|
+
return edit({ text: failText(e, lang) });
|
|
160
|
+
}
|
|
161
|
+
const dir = insideRoot(target, rootOf(st.userId));
|
|
162
|
+
if (!dir) return edit({ text: th('git.cloneBadName', lang) });
|
|
163
|
+
log('репозиторий клонирован:', st.userId, repo.name, dir);
|
|
164
|
+
await edit({ text: th('git.cloned', lang, { name: hCode(repo.name), p: hCode(userPath(st.userId, dir, lang)) }) });
|
|
165
|
+
return selectProject(st, dir);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Операция с репозиторием проекта: 'pull', 'push', 'pushf' (отправить, несмотря на секреты в коммитах) или 'save'
|
|
170
|
+
* (закоммитить всё с описанием message и отправить). Итог пишется в сообщение edit вместе с обновлённым экраном.
|
|
171
|
+
*/
|
|
172
|
+
async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
173
|
+
const project = projectOf(st);
|
|
174
|
+
const repo = project ? await repoOf(st, project) : null;
|
|
175
|
+
if (!repo?.account) return edit(await gitView(st, lang));
|
|
176
|
+
const opts = gitOpts(st, project, repo);
|
|
177
|
+
const done = async (text) => {
|
|
178
|
+
const v = await gitView(st, lang);
|
|
179
|
+
return edit({ text: `${text}\n\n${v.text}`, markup: v.markup });
|
|
180
|
+
};
|
|
181
|
+
st.gitBusy = true;
|
|
182
|
+
try {
|
|
183
|
+
if (action === 'pull') {
|
|
184
|
+
await edit({ text: th('git.pulling', lang) });
|
|
185
|
+
const result = await pullRepo(project, opts);
|
|
186
|
+
log('git: получено:', st.userId, project, '|', result);
|
|
187
|
+
return await done(th(`git.pull.${result}`, lang));
|
|
188
|
+
}
|
|
189
|
+
let note = '';
|
|
190
|
+
if (action === 'save') {
|
|
191
|
+
await edit({ text: th('git.saving', lang) });
|
|
192
|
+
const r = await commitAll(project, message, opts);
|
|
193
|
+
if (r.skipped.length) note += `\n${th('git.skipped', lang, { files: r.skipped.join(', ') })}`;
|
|
194
|
+
if (r.tracked.length) note += `\n${th('git.tracked', lang, { files: r.tracked.join(', ') })}`;
|
|
195
|
+
const after = await repoState(project, opts);
|
|
196
|
+
if (!r.committed && !after?.ahead && after?.upstream) return await done(th('git.savedNothing', lang) + note);
|
|
197
|
+
} else await edit({ text: th('git.pushing', lang) });
|
|
198
|
+
// секреты в коммитах, которые сделал агент: перед отправкой — предупреждение и явное согласие
|
|
199
|
+
if (action !== 'pushf') {
|
|
200
|
+
const secrets = await unpushedSecrets(project, opts);
|
|
201
|
+
if (secrets.length) {
|
|
202
|
+
const markup = { inline_keyboard: [[{ text: t('git.pushAnyway', lang), callback_data: 'gt:pushf' }, { text: t('btn.cancel', lang), callback_data: 'gt:v' }]] };
|
|
203
|
+
return await edit({ text: th('git.secretsWarn', lang, { files: secrets.slice(0, 20).join('\n') }) + note, markup });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const state = await repoState(project, opts);
|
|
207
|
+
if (state?.upstream && !state.ahead) return await done(th('git.nothingToPush', lang) + note);
|
|
208
|
+
try {
|
|
209
|
+
await pushRepo(project, opts);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
if (/rejected|non-fast-forward|fetch first/i.test(`${e.message} ${e.stderr ?? ''}`)) return await done(th('git.pushRejected', lang) + note);
|
|
212
|
+
throw e;
|
|
213
|
+
}
|
|
214
|
+
log('git: отправлено:', st.userId, project);
|
|
215
|
+
return await done(th(action === 'save' ? 'git.saved' : 'git.pushed', lang) + note);
|
|
216
|
+
} catch (e) {
|
|
217
|
+
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
218
|
+
return await done(failText(e, lang));
|
|
219
|
+
} finally {
|
|
220
|
+
st.gitBusy = false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Кнопки /git (gt:<действие>[:<аргумент>[:<страница>]]). */
|
|
225
|
+
export async function onGitCallback(st, cb) {
|
|
226
|
+
const [, action, arg, pageStr] = (cb.data || '').split(':');
|
|
227
|
+
const lang = langOf(st.userId);
|
|
228
|
+
const chatId = cb.message?.chat?.id ?? st.chatId;
|
|
229
|
+
const messageId = cb.message?.message_id;
|
|
230
|
+
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text, show_alert: true } : {}) }).catch(() => {});
|
|
231
|
+
const edit = (v) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => /not modified/i.test(e.message) || log('git:', e.message));
|
|
232
|
+
if (!gitAvailable()) return ack(t('git.none', lang));
|
|
233
|
+
if (action === 'x') {
|
|
234
|
+
st.pendingInput = null;
|
|
235
|
+
await ack();
|
|
236
|
+
return edit({ text: th('files.cancelled', lang) });
|
|
237
|
+
}
|
|
238
|
+
if (action === 'v') {
|
|
239
|
+
await ack();
|
|
240
|
+
return edit(await gitView(st, lang, { sync: true }));
|
|
241
|
+
}
|
|
242
|
+
// ---- свои серверы: только администратор ----
|
|
243
|
+
if (['h', 'ha', 'hn', 'hd', 'hD'].includes(action)) {
|
|
244
|
+
if (!isAdmin(st.userId)) return ack(t('admin.only', lang));
|
|
245
|
+
if (action === 'h') return (await ack(), edit(hostsView(lang)));
|
|
246
|
+
if (action === 'ha' && KIND_LABEL[arg]) {
|
|
247
|
+
await ack();
|
|
248
|
+
st.pendingInput = { kind: 'gitHostUrl', hostKind: arg, at: Date.now() };
|
|
249
|
+
return say(st.to, t('git.hosts.urlAsk', lang, { kind: KIND_LABEL[arg] }), { reply_markup: cancelMarkup(lang) });
|
|
250
|
+
}
|
|
251
|
+
const own = findHost(arg);
|
|
252
|
+
if (!own?.custom || own.fromEnv) return ack(t('proj.stale', lang));
|
|
253
|
+
if (action === 'hn') {
|
|
254
|
+
await ack();
|
|
255
|
+
st.pendingInput = { kind: 'gitHostName', host: own.id, at: Date.now() };
|
|
256
|
+
return say(st.to, t('git.hosts.nameAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
257
|
+
}
|
|
258
|
+
if (action === 'hd') {
|
|
259
|
+
await ack();
|
|
260
|
+
return edit({ text: th('git.hosts.deleteAsk', lang, { label: own.label }), markup: { inline_keyboard: [[{ text: t('git.hosts.remove', lang), callback_data: `gt:hD:${own.id}` }, { text: t('btn.cancel', lang), callback_data: 'gt:h' }]] } });
|
|
261
|
+
}
|
|
262
|
+
const n = removeCustomHost(own.id);
|
|
263
|
+
log('свой сервер git убран:', own.web, '| отключено аккаунтов', n);
|
|
264
|
+
await ack();
|
|
265
|
+
return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
|
|
266
|
+
}
|
|
267
|
+
// экраны «Изменения» и «Ветки» — gitRepoUi
|
|
268
|
+
if (REPO_ACTIONS.includes(action)) return onRepoCallback(st, cb, { action, arg, lang, ack, edit, project: projectOf(st), repoOf, gitOpts });
|
|
269
|
+
const host = findHost(arg);
|
|
270
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
271
|
+
try {
|
|
272
|
+
// ---- аккаунты ----
|
|
273
|
+
if (action === 'c' && host) {
|
|
274
|
+
await ack();
|
|
275
|
+
st.pendingInput = { kind: 'gitToken', host: host.id, at: Date.now() };
|
|
276
|
+
return say(st.to, th('git.tokenAsk', lang, { host: host.label, url: host.tokenUrl, scopes: hCode(host.scopes) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
277
|
+
}
|
|
278
|
+
if ((action === 'a' || action === 'd') && account) {
|
|
279
|
+
await ack();
|
|
280
|
+
const text = th(action === 'd' ? 'git.disconnectAsk' : 'git.accCard', lang, { host: host.label, login: account.login, name: account.name ?? '', email: hCode(account.email ?? '—'), date: dateOf(account.expires_at, lang) });
|
|
281
|
+
const rows = action === 'd'
|
|
282
|
+
? [[{ text: t('git.disconnect', lang), callback_data: `gt:D:${host.id}` }, { text: t('btn.cancel', lang), callback_data: `gt:a:${host.id}` }]]
|
|
283
|
+
: [[{ text: t('git.disconnect', lang), callback_data: `gt:d:${host.id}` }], [{ text: t('btn.back', lang), callback_data: 'gt:v' }]];
|
|
284
|
+
return edit({ text, markup: { inline_keyboard: rows } });
|
|
285
|
+
}
|
|
286
|
+
if (action === 'D' && account) {
|
|
287
|
+
db.deleteGitAccount(st.userId, host.id);
|
|
288
|
+
log('аккаунт git отключён:', st.userId, host.id);
|
|
289
|
+
await ack(t('git.disconnected', lang, { host: host.label }));
|
|
290
|
+
return edit(await gitView(st, lang));
|
|
291
|
+
}
|
|
292
|
+
// ---- клонирование ----
|
|
293
|
+
if (action === 'cl') {
|
|
294
|
+
if (!canCreateProject(st.userId)) return ack(t('files.noRights', lang));
|
|
295
|
+
const list = accountsOf(st.userId);
|
|
296
|
+
if (!list.length) return ack(t('git.connectFirst', lang));
|
|
297
|
+
await ack();
|
|
298
|
+
if (list.length === 1) return edit(await reposView(st, list[0].host, list[0].account, {}, lang));
|
|
299
|
+
return edit({ text: th('git.pickHost', lang), markup: { inline_keyboard: [...list.map((x) => [{ text: x.host.label, callback_data: `gt:r:${x.host.id}:0` }]), [{ text: t('btn.back', lang), callback_data: 'gt:v' }]] } });
|
|
300
|
+
}
|
|
301
|
+
if (action === 'r' && account) {
|
|
302
|
+
await ack();
|
|
303
|
+
const search = st.gitRepos?.host === host.id ? st.gitRepos.search : '';
|
|
304
|
+
return edit(await reposView(st, host, account, { page: Number(pageStr) || 0, search }, lang));
|
|
305
|
+
}
|
|
306
|
+
if (action === 's' && account) {
|
|
307
|
+
await ack();
|
|
308
|
+
st.pendingInput = { kind: 'gitSearch', host: host.id, at: Date.now() };
|
|
309
|
+
return say(st.to, t('git.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
310
|
+
}
|
|
311
|
+
if (action === 'k') {
|
|
312
|
+
const list = st.gitRepos;
|
|
313
|
+
const repo = list?.items[Number(arg)];
|
|
314
|
+
const h = findHost(list?.host);
|
|
315
|
+
const acc = h ? db.getGitAccount(st.userId, h.id) : null;
|
|
316
|
+
if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
|
|
317
|
+
if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
|
|
318
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
319
|
+
await ack();
|
|
320
|
+
st.gitBusy = true;
|
|
321
|
+
try {
|
|
322
|
+
return await cloneChosen(st, repo, h, acc, lang, edit);
|
|
323
|
+
} finally {
|
|
324
|
+
st.gitBusy = false;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
// ---- репозиторий проекта ----
|
|
328
|
+
if (['pull', 'push', 'pushf', 'save', 'savenow'].includes(action)) {
|
|
329
|
+
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
330
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
331
|
+
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
332
|
+
await ack();
|
|
333
|
+
if (action === 'save') {
|
|
334
|
+
st.pendingInput = { kind: 'gitMessage', at: Date.now() };
|
|
335
|
+
const markup = { inline_keyboard: [[{ text: t('git.noMessage', lang), callback_data: 'gt:savenow' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
|
|
336
|
+
return say(st.to, t('git.messageAsk', lang), { reply_markup: markup });
|
|
337
|
+
}
|
|
338
|
+
if (action === 'savenow') {
|
|
339
|
+
st.pendingInput = null;
|
|
340
|
+
return repoAction(st, 'save', lang, edit, { message: t('git.autoMessage', lang, { date: dateOf(new Date().toISOString(), lang) }) });
|
|
341
|
+
}
|
|
342
|
+
return repoAction(st, action, lang, edit);
|
|
343
|
+
}
|
|
344
|
+
return ack(t('proj.stale', lang));
|
|
345
|
+
} catch (e) {
|
|
346
|
+
log('git:', e.message, '| пользователь', st.userId);
|
|
347
|
+
await ack();
|
|
348
|
+
return edit({ text: failText(e, lang) });
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Удаляет сообщение пользователя (с токеном): копии в чате остаться не должно. */
|
|
353
|
+
const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_id: st.chatId, message_id: messageId }).catch((e) => log('git: сообщение не удалено:', e.message)) : null);
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Текст пользователя, пока бот ждёт токен доступа, строку поиска репозитория или описание изменений. true — текст
|
|
357
|
+
* обработан здесь и агенту не передаётся. Токен агенту не уходит никогда: даже если ожидание истекло, сообщение
|
|
358
|
+
* удаляется, а не превращается в запрос.
|
|
359
|
+
*/
|
|
360
|
+
export async function onGitInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
361
|
+
const wait = st.pendingInput;
|
|
362
|
+
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch'].includes(wait?.kind)) return false;
|
|
363
|
+
const lang = langOf(st.userId);
|
|
364
|
+
const expired = now - wait.at > GIT_WAIT_MS;
|
|
365
|
+
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
366
|
+
|
|
367
|
+
if (wait.kind === 'gitToken') {
|
|
368
|
+
await dropMessage(st, messageId);
|
|
369
|
+
const host = findHost(wait.host);
|
|
370
|
+
if (expired || !host) {
|
|
371
|
+
st.pendingInput = null;
|
|
372
|
+
return (await say(st.to, t('git.tokenExpired', lang)), true);
|
|
373
|
+
}
|
|
374
|
+
const token = text.trim();
|
|
375
|
+
if (/\s/.test(token) || token.length < 10) return (await say(st.to, t('git.tokenBad', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
376
|
+
let profile;
|
|
377
|
+
try {
|
|
378
|
+
profile = await fetchProfile(host, token);
|
|
379
|
+
} catch (e) {
|
|
380
|
+
log('git: проверка токена:', e.message, '| пользователь', st.userId);
|
|
381
|
+
const textFail = e instanceof HostError && e.code === 'auth' ? t('git.tokenBad', lang) : t('git.tokenFail', lang, { msg: e.message });
|
|
382
|
+
return (await say(st.to, textFail, { reply_markup: cancelMarkup(lang) }), true); // ожидание остаётся: можно прислать ещё раз
|
|
383
|
+
}
|
|
384
|
+
st.pendingInput = null;
|
|
385
|
+
if (!db.saveGitAccount(st.userId, { host: host.id, login: profile.login, name: profile.name, email: profile.email, token, expiresAt: profile.expiresAt })) {
|
|
386
|
+
return (await say(st.to, t('access.saveFail', lang)), true);
|
|
387
|
+
}
|
|
388
|
+
log('аккаунт git подключён:', st.userId, host.id, profile.login);
|
|
389
|
+
const lack = missingScopes(host, profile.scopes);
|
|
390
|
+
const parts = [
|
|
391
|
+
th('git.connected', lang, { host: host.label, login: profile.login, name: profile.name }),
|
|
392
|
+
...(profile.expiresAt ? [th('git.expires', lang, { date: dateOf(profile.expiresAt, lang) })] : []),
|
|
393
|
+
...(lack.length ? [th('git.scopesWarn', lang, { scopes: lack.join(', ') })] : []),
|
|
394
|
+
];
|
|
395
|
+
await send({ text: parts.join('\n') });
|
|
396
|
+
await send(await gitView(st, lang));
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
st.pendingInput = null;
|
|
401
|
+
if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
|
|
402
|
+
if (wait.kind === 'gitBranch') return onBranchInput(st, text, { wait, now, lang, project: projectOf(st), repoOf, gitOpts });
|
|
403
|
+
// свои серверы: адрес нового сервера или новое название — только от администратора
|
|
404
|
+
if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
|
|
405
|
+
if (!isAdmin(st.userId)) return false;
|
|
406
|
+
if (wait.kind === 'gitHostName') {
|
|
407
|
+
renameCustomHost(wait.host, text);
|
|
408
|
+
return (await send(hostsView(lang)), true);
|
|
409
|
+
}
|
|
410
|
+
const again = () => (st.pendingInput = { ...wait, at: now }); // адрес не подошёл — ждём другой
|
|
411
|
+
const candidate = customHost(wait.hostKind, text);
|
|
412
|
+
if (!candidate) return (again(), await say(st.to, t('git.hosts.badUrl', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
413
|
+
const probe = await probeHost(candidate);
|
|
414
|
+
if (!probe.ok) {
|
|
415
|
+
again();
|
|
416
|
+
return (await say(st.to, t('git.hosts.probeFail', lang, { url: candidate.web, kind: KIND_LABEL[candidate.kind], msg: probe.error }), { reply_markup: cancelMarkup(lang) }), true);
|
|
417
|
+
}
|
|
418
|
+
const added = addCustomHost(wait.hostKind, candidate.web);
|
|
419
|
+
if (added.error) return (await send(hostsView(lang, th('git.hosts.exists', lang))), true);
|
|
420
|
+
log('свой сервер git добавлен:', added.host.kind, added.host.web, '| администратор', st.userId);
|
|
421
|
+
return (await send(hostsView(lang, th('git.hosts.added', lang, { label: added.host.label }))), true);
|
|
422
|
+
}
|
|
423
|
+
if (wait.kind === 'gitSearch') {
|
|
424
|
+
const host = findHost(wait.host);
|
|
425
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
426
|
+
if (!account) return false;
|
|
427
|
+
try {
|
|
428
|
+
await send(await reposView(st, host, account, { search: text.trim().slice(0, 60) }, lang));
|
|
429
|
+
} catch (e) {
|
|
430
|
+
await send({ text: failText(e, lang) });
|
|
431
|
+
}
|
|
432
|
+
return true;
|
|
433
|
+
}
|
|
434
|
+
// описание изменений: первая строка, не длиннее 200 символов
|
|
435
|
+
const message = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || t('git.autoMessage', lang, { date: dateOf(new Date().toISOString(), lang) });
|
|
436
|
+
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
437
|
+
const progress = await tg('sendMessage', { ...dest(st.to), text: th('git.saving', lang), ...HTML }).catch(() => null);
|
|
438
|
+
const edit = (v) =>
|
|
439
|
+
progress
|
|
440
|
+
? tg('editMessageText', { chat_id: st.chatId, message_id: progress.message_id, text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => /not modified/i.test(e.message) || log('git:', e.message))
|
|
441
|
+
: send(v);
|
|
442
|
+
await repoAction(st, 'save', lang, edit, { message });
|
|
443
|
+
return true;
|
|
444
|
+
}
|