acpgram 1.25.0 → 1.27.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 +41 -1
- package/README.ru.md +44 -0
- package/package.json +1 -1
- package/src/bot.mjs +28 -4
- package/src/db.mjs +31 -0
- package/src/engines.mjs +3 -2
- package/src/files.mjs +11 -0
- package/src/filesUi.mjs +293 -0
- package/src/git.mjs +226 -0
- package/src/gitAccess.mjs +112 -0
- package/src/gitHosts.mjs +195 -0
- package/src/gitUi.mjs +438 -0
- package/src/i18n.mjs +115 -0
- package/src/projectFiles.mjs +168 -0
- package/src/projectsUi.mjs +14 -2
- package/src/state.mjs +2 -0
- package/src/turn.mjs +3 -2
- package/src/ui.mjs +3 -1
package/src/gitHosts.mjs
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Сервисы Git: GitHub, GitLab.com и свои серверы — GitLab и GitHub Enterprise, которые добавляет администратор в /git
|
|
2
|
+
// (или задаёт в настройках: GITLAB_URL, GITHUB_URL). Профиль и репозитории пользователя по его токену доступа и вход
|
|
3
|
+
// для команд git. Только встроенный fetch — без зависимостей.
|
|
4
|
+
//
|
|
5
|
+
// Вход git не пишется ни в настройки репозитория, ни в адрес: он передаётся процессу git через окружение
|
|
6
|
+
// (GIT_CONFIG_*: заголовок Authorization только для адреса своего сервиса) на время одной операции.
|
|
7
|
+
|
|
8
|
+
const TIMEOUT_MS = 15_000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Адрес своего сервера из текста администратора: «https://git.example.com» или с путём («https://host/gitlab»).
|
|
12
|
+
* Только https; завершающие «/», запрос и якорь отбрасываются. Не подходит — null.
|
|
13
|
+
*/
|
|
14
|
+
export function normalizeHostUrl(input) {
|
|
15
|
+
let u;
|
|
16
|
+
try {
|
|
17
|
+
u = new URL(String(input ?? '').trim());
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
if (u.protocol !== 'https:' || !u.hostname.includes('.') || u.username || u.password) return null;
|
|
22
|
+
return `https://${u.host.toLowerCase()}${u.pathname.replace(/\/+$/, '')}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Id своего сервера: вид и адрес («gitlab-git-example-com») — одинаковый, откуда бы сервер ни был задан. */
|
|
26
|
+
const hostId = (kind, web) => `${kind}-${web.replace(/^https:\/\//, '')}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/, '').slice(0, 40);
|
|
27
|
+
|
|
28
|
+
const githubHost = (id, label, web, api) => ({ id, kind: 'github', label, web, api, tokenUrl: `${web}/settings/tokens`, user: 'x-access-token', scopes: 'repo' });
|
|
29
|
+
const gitlabHost = (id, label, web) => ({ id, kind: 'gitlab', label, web, api: `${web}/api/v4`, tokenUrl: `${web}/-/user_settings/personal_access_tokens`, user: 'oauth2', scopes: 'read_api, read_repository, write_repository' });
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Свой сервер: GitLab или GitHub Enterprise по адресу. name — название для кнопок (по умолчанию — имя сервера).
|
|
33
|
+
* @param {'gitlab'|'github'} kind
|
|
34
|
+
* @returns {object|null} null — адрес не подходит или это общий сервис (github.com, gitlab.com)
|
|
35
|
+
*/
|
|
36
|
+
export function customHost(kind, url, name = '') {
|
|
37
|
+
const web = normalizeHostUrl(url);
|
|
38
|
+
if (!web || (kind !== 'gitlab' && kind !== 'github') || /^https:\/\/(www\.)?(github|gitlab)\.com$/.test(web)) return null;
|
|
39
|
+
const label = String(name ?? '').trim().slice(0, 40) || new URL(web).host;
|
|
40
|
+
const host = kind === 'gitlab' ? gitlabHost(hostId(kind, web), label, web) : githubHost(hostId(kind, web), label, web, `${web}/api/v3`);
|
|
41
|
+
return { ...host, custom: true };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Сервисы, к которым можно подключиться: GitHub и GitLab.com — всегда; свои серверы — из настроек (GITLAB_URL и
|
|
46
|
+
* GITLAB_NAME, GITHUB_URL и GITHUB_NAME) и добавленные администратором (extra: [{kind, url, name}]). Один и тот же
|
|
47
|
+
* адрес дважды не попадает. kind — чей API; user — имя пользователя для входа git по токену; fromEnv — задан в настройках.
|
|
48
|
+
* @returns {{id: string, kind: 'github'|'gitlab', label: string, web: string, api: string, tokenUrl: string, user: string, scopes: string, custom?: boolean, fromEnv?: boolean}[]}
|
|
49
|
+
*/
|
|
50
|
+
export function gitHosts(env = process.env, extra = []) {
|
|
51
|
+
const hosts = [githubHost('github', 'GitHub', 'https://github.com', 'https://api.github.com'), gitlabHost('gitlab', 'GitLab.com', 'https://gitlab.com')];
|
|
52
|
+
const add = (h, fromEnv) => {
|
|
53
|
+
if (h && !hosts.some((x) => x.web === h.web)) hosts.push(fromEnv ? { ...h, fromEnv: true } : h);
|
|
54
|
+
};
|
|
55
|
+
add(customHost('gitlab', env.GITLAB_URL, env.GITLAB_NAME), true);
|
|
56
|
+
add(customHost('github', env.GITHUB_URL, env.GITHUB_NAME), true);
|
|
57
|
+
for (const x of Array.isArray(extra) ? extra : []) add(customHost(x?.kind, x?.url, x?.name), false);
|
|
58
|
+
return hosts;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Сервис по id или null. */
|
|
62
|
+
export const hostById = (id, hosts = gitHosts()) => hosts.find((h) => h.id === id) ?? null;
|
|
63
|
+
|
|
64
|
+
/** Сервис, которому принадлежит адрес репозитория (только https), или null. */
|
|
65
|
+
export function hostOfUrl(url, hosts = gitHosts()) {
|
|
66
|
+
const u = String(url ?? '').trim().toLowerCase();
|
|
67
|
+
return hosts.find((h) => u === h.web.toLowerCase() || u.startsWith(`${h.web.toLowerCase()}/`)) ?? null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Похож ли адрес на сервер своего вида: его API отвечает JSON (без токена — обычно отказом 401, это тоже ответ API).
|
|
72
|
+
* @returns {Promise<{ok: true} | {ok: false, error: string}>}
|
|
73
|
+
*/
|
|
74
|
+
export async function probeHost(host, { fetchImpl = fetch } = {}) {
|
|
75
|
+
const url = host.kind === 'gitlab' ? `${host.api}/version` : `${host.api}/meta`;
|
|
76
|
+
let res;
|
|
77
|
+
try {
|
|
78
|
+
res = await fetchImpl(url, { headers: { accept: 'application/json', 'user-agent': 'acpgram' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
79
|
+
} catch (e) {
|
|
80
|
+
return { ok: false, error: e.message };
|
|
81
|
+
}
|
|
82
|
+
const isJson = /json/i.test(res.headers?.get?.('content-type') ?? '');
|
|
83
|
+
return [200, 401, 403].includes(res.status) && isJson ? { ok: true } : { ok: false, error: `HTTP ${res.status}` };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Адрес репозитория для показа: «github.com/owner/repo» (без схемы, входа и «.git»). */
|
|
87
|
+
export const showRemote = (url) => String(url ?? '').trim().replace(/^https?:\/\/([^@/]*@)?/i, '').replace(/\.git$/i, '');
|
|
88
|
+
|
|
89
|
+
/** Имя папки по адресу репозитория: «https://host/group/my-app.git» → «my-app». */
|
|
90
|
+
export const repoFolder = (url) => showRemote(url).split('/').filter(Boolean).pop() ?? '';
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Настройка git для входа по токену: заголовок Authorization только для адресов этого сервиса (на другой адрес —
|
|
94
|
+
* например, после перенаправления или подмены origin — токен не уйдёт). Пары [ключ, значение] для configEnv.
|
|
95
|
+
*/
|
|
96
|
+
export const authConfig = (host, token) => [[`http.${host.web}/.extraheader`, `Authorization: Basic ${Buffer.from(`${host.user}:${token}`).toString('base64')}`]];
|
|
97
|
+
|
|
98
|
+
/** Ошибка обращения к сервису: code — 'auth' (токен не подошёл), 'http' или 'network'. */
|
|
99
|
+
export class HostError extends Error {
|
|
100
|
+
constructor(code, message, status = null) {
|
|
101
|
+
super(message);
|
|
102
|
+
this.code = code;
|
|
103
|
+
this.status = status;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function api(host, token, path, { fetchImpl = fetch } = {}) {
|
|
108
|
+
const headers = host.kind === 'github'
|
|
109
|
+
? { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'acpgram' }
|
|
110
|
+
: { 'private-token': token, accept: 'application/json', 'user-agent': 'acpgram' };
|
|
111
|
+
let res;
|
|
112
|
+
try {
|
|
113
|
+
res = await fetchImpl(`${host.api}${path}`, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
114
|
+
} catch (e) {
|
|
115
|
+
throw new HostError('network', `${host.label}: ${e.message}`);
|
|
116
|
+
}
|
|
117
|
+
if (res.status === 401 || res.status === 403) throw new HostError('auth', `${host.label}: HTTP ${res.status}`, res.status);
|
|
118
|
+
if (!res.ok) throw new HostError('http', `${host.label}: HTTP ${res.status}`, res.status);
|
|
119
|
+
return { data: await res.json(), headers: res.headers };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const isoDate = (v) => {
|
|
123
|
+
const d = v ? new Date(v) : null;
|
|
124
|
+
return d && !Number.isNaN(d.getTime()) ? d.toISOString() : null;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Профиль владельца токена: {login, name, email, expiresAt, scopes}. email — адрес для коммитов (у GitHub без
|
|
129
|
+
* открытого адреса — служебный noreply). scopes — права токена, если сервис их сообщил (иначе null).
|
|
130
|
+
*/
|
|
131
|
+
export async function fetchProfile(host, token, opts) {
|
|
132
|
+
if (host.kind === 'github') {
|
|
133
|
+
const { data, headers } = await api(host, token, '/user', opts);
|
|
134
|
+
const scopes = headers?.get?.('x-oauth-scopes');
|
|
135
|
+
return {
|
|
136
|
+
login: data.login,
|
|
137
|
+
name: data.name || data.login,
|
|
138
|
+
email: data.email || `${data.id}+${data.login}@users.noreply.${new URL(host.web).host}`,
|
|
139
|
+
// «2026-12-01 00:00:00 UTC» — в привычный Date формат
|
|
140
|
+
expiresAt: isoDate(headers?.get?.('github-authentication-token-expiration')?.replace(' UTC', 'Z').replace(' ', 'T')),
|
|
141
|
+
scopes: scopes == null ? null : scopes.split(',').map((s) => s.trim()).filter(Boolean),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const { data } = await api(host, token, '/user', opts);
|
|
145
|
+
// срок и права токена — отдельным запросом; старый GitLab его не знает — тогда без них
|
|
146
|
+
const self = await api(host, token, '/personal_access_tokens/self', opts).then((r) => r.data, () => null);
|
|
147
|
+
return {
|
|
148
|
+
login: data.username,
|
|
149
|
+
name: data.name || data.username,
|
|
150
|
+
email: data.commit_email || data.email || data.public_email || `${data.username}@users.noreply.${new URL(host.web).host}`,
|
|
151
|
+
expiresAt: isoDate(self?.expires_at),
|
|
152
|
+
scopes: Array.isArray(self?.scopes) ? self.scopes : null,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Каких прав токену не хватает для работы с репозиториями (по сообщённым сервисом правам); неизвестно — пусто. */
|
|
157
|
+
export function missingScopes(host, scopes) {
|
|
158
|
+
if (!Array.isArray(scopes)) return [];
|
|
159
|
+
const has = (s) => scopes.includes(s);
|
|
160
|
+
if (host.kind === 'github') return has('repo') || !scopes.length ? [] : ['repo']; // у fine-grained токенов список пуст
|
|
161
|
+
if (has('api')) return [];
|
|
162
|
+
return ['read_api', 'read_repository', 'write_repository'].filter((s) => !has(s));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export const REPOS_PAGE = 10;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Репозитории пользователя, недавно менявшиеся первыми: {items: [{name, url, private}], more}.
|
|
169
|
+
* search — часть названия. У GitHub поиска по своим репозиториям в API нет: берутся первые 300 и отбираются здесь.
|
|
170
|
+
*/
|
|
171
|
+
export async function listRepos(host, token, { search = '', page = 0, perPage = REPOS_PAGE, ...opts } = {}) {
|
|
172
|
+
const q = search.trim().toLowerCase();
|
|
173
|
+
if (host.kind === 'gitlab') {
|
|
174
|
+
const query = `membership=true&simple=true&archived=false&order_by=last_activity_at&per_page=${perPage}&page=${page + 1}${q ? `&search=${encodeURIComponent(q)}` : ''}`;
|
|
175
|
+
const { data, headers } = await api(host, token, `/projects?${query}`, opts);
|
|
176
|
+
const items = data.map((p) => ({ name: p.path_with_namespace, url: p.http_url_to_repo, private: p.visibility !== 'public' }));
|
|
177
|
+
// есть ли следующая страница, GitLab сообщает заголовком; без него — по заполненности страницы
|
|
178
|
+
const next = headers?.get?.('x-next-page');
|
|
179
|
+
return { items, more: next == null ? items.length === perPage : Boolean(next) };
|
|
180
|
+
}
|
|
181
|
+
const gh = (p) => api(host, token, `/user/repos?sort=pushed&per_page=100&page=${p}`, opts).then((r) => r.data);
|
|
182
|
+
const map = (r) => ({ name: r.full_name, url: r.clone_url, private: Boolean(r.private) });
|
|
183
|
+
if (!q) {
|
|
184
|
+
const { data } = await api(host, token, `/user/repos?sort=pushed&per_page=${perPage}&page=${page + 1}`, opts);
|
|
185
|
+
return { items: data.map(map), more: data.length === perPage };
|
|
186
|
+
}
|
|
187
|
+
const all = [];
|
|
188
|
+
for (let p = 1; p <= 3; p++) {
|
|
189
|
+
const chunk = await gh(p);
|
|
190
|
+
all.push(...chunk);
|
|
191
|
+
if (chunk.length < 100) break;
|
|
192
|
+
}
|
|
193
|
+
const found = all.filter((r) => r.full_name.toLowerCase().includes(q)).map(map);
|
|
194
|
+
return { items: found.slice(page * perPage, (page + 1) * perPage), more: found.length > (page + 1) * perPage };
|
|
195
|
+
}
|
package/src/gitUi.mjs
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
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 { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
10
|
+
import { LOCALES, errText, t } from './i18n.mjs';
|
|
11
|
+
import { ROOT, folderName, insideRoot, isPersonalRoot, navStart } from './projects.mjs';
|
|
12
|
+
import { canCreateProject, selectProject } from './projectsUi.mjs';
|
|
13
|
+
import { agentSandbox } from './sandbox.mjs';
|
|
14
|
+
import { isAdmin, rootOf, sandboxed, userPath } from './state.mjs';
|
|
15
|
+
import { dest, tg } from './telegram.mjs';
|
|
16
|
+
import { hCode, th } from './ui.mjs';
|
|
17
|
+
|
|
18
|
+
const HTML = { parse_mode: 'HTML', link_preview_options: { is_disabled: true } };
|
|
19
|
+
/** Сколько бот ждёт токен, описание изменений или строку поиска. */
|
|
20
|
+
export const GIT_WAIT_MS = 10 * 60_000;
|
|
21
|
+
|
|
22
|
+
const cancelMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] });
|
|
23
|
+
const dateOf = (iso, lang) => (iso ? new Date(iso).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' }) : '—');
|
|
24
|
+
|
|
25
|
+
/** Папка проекта диалога, если она доступна, иначе null. */
|
|
26
|
+
const projectOf = (st) => insideRoot(st.project, rootOf(st.userId));
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Как запускать git для этого пользователя: окружение (автор коммитов, вход в сервис), песочница сотрудника
|
|
30
|
+
* (если она включена) и строки, которые нужно вычистить из сообщений об ошибках.
|
|
31
|
+
*/
|
|
32
|
+
function gitOpts(st, cwd, { host = null, account = null } = {}) {
|
|
33
|
+
const who = account ?? accountsOf(st.userId)[0]?.account ?? null;
|
|
34
|
+
const auth = host && account ? authConfig(host, account.token) : [];
|
|
35
|
+
const root = rootOf(st.userId);
|
|
36
|
+
const wrap = sandboxed(st.userId)
|
|
37
|
+
? agentSandbox({ userId: st.userId, cwd, root, command: gitCommand(), protect: isPersonalRoot(root) ? [ROOT] : [] })
|
|
38
|
+
: null;
|
|
39
|
+
return { env: gitEnv({ identity: identityOf(who), auth }), wrap, hide: account ? [account.token, auth[0]?.[1]?.split(' ').pop()] : [] };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Репозиторий проекта и его сервис: {state, host, account} или null, если проект не репозиторий (или репозиторий выше корня пользователя). */
|
|
43
|
+
async function repoOf(st, project) {
|
|
44
|
+
const state = await repoState(project, gitOpts(st, project));
|
|
45
|
+
if (!state || !insideRoot(state.top, rootOf(st.userId))) return null;
|
|
46
|
+
const host = hostFor(state.remote);
|
|
47
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
48
|
+
return { state, host, account };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Экран /git: состояние репозитория проекта, аккаунты, кнопки. Текст — HTML.
|
|
53
|
+
* sync — сначала свериться с сервером (git fetch), чтобы «новых на сервере» было настоящим числом: при открытии экрана
|
|
54
|
+
* и по кнопке «Обновить». Пока агент выполняет запрос или идёт другая операция git, сверка пропускается.
|
|
55
|
+
*/
|
|
56
|
+
export async function gitView(st, lang = langOf(st.userId), { sync = false } = {}) {
|
|
57
|
+
const project = projectOf(st);
|
|
58
|
+
const hosts = allHosts();
|
|
59
|
+
const accounts = accountsOf(st.userId);
|
|
60
|
+
const lines = [th('git.head', lang, { p: hCode(project ? userPath(st.userId, project, lang) : '—') })];
|
|
61
|
+
const rows = [];
|
|
62
|
+
const load = () => (project ? repoOf(st, project).catch((e) => (log('git: состояние:', e.message), null)) : null);
|
|
63
|
+
let repo = await load();
|
|
64
|
+
let syncError = null;
|
|
65
|
+
if (sync && repo?.account && !st.busy && !st.gitBusy) {
|
|
66
|
+
try {
|
|
67
|
+
await fetchRepo(project, gitOpts(st, project, repo));
|
|
68
|
+
repo = await load();
|
|
69
|
+
} catch (e) {
|
|
70
|
+
log('git: сверка с сервером:', e.message, '| пользователь', st.userId);
|
|
71
|
+
syncError = e.message;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (repo) {
|
|
75
|
+
const s = repo.state;
|
|
76
|
+
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) : '—') }));
|
|
77
|
+
if (syncError) lines.push(th('git.syncFail', lang, { msg: syncError }));
|
|
78
|
+
if (repo.account) {
|
|
79
|
+
if (canManageFiles(st.userId)) {
|
|
80
|
+
rows.push([{ text: t('git.pull', lang), callback_data: 'gt:pull' }, { text: t('git.push', lang), callback_data: 'gt:push' }]);
|
|
81
|
+
rows.push([{ text: t('git.save', lang), callback_data: 'gt:save', style: 'success' }]);
|
|
82
|
+
}
|
|
83
|
+
} else if (repo.host) lines.push(th('git.needAccount', lang, { host: repo.host.label }));
|
|
84
|
+
else lines.push(th(s.remote ? 'git.foreign' : 'git.noRemote', lang));
|
|
85
|
+
} else lines.push(th('git.noRepo', lang));
|
|
86
|
+
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));
|
|
87
|
+
if (accounts.length && canCreateProject(st.userId)) rows.push([{ text: t('git.clone', lang), callback_data: 'gt:cl' }]);
|
|
88
|
+
for (const h of hosts) {
|
|
89
|
+
const acc = accounts.find((x) => x.host.id === h.id)?.account;
|
|
90
|
+
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}` }]);
|
|
91
|
+
}
|
|
92
|
+
// свои серверы (GitLab, GitHub Enterprise) добавляет администратор — прямо здесь, без правки настроек
|
|
93
|
+
rows.push([...(isAdmin(st.userId) ? [{ text: t('git.hostsBtn', lang), callback_data: 'gt:h' }] : []), { text: t('btn.refresh', lang), callback_data: 'gt:v' }]);
|
|
94
|
+
return { text: lines.join('\n\n'), markup: { inline_keyboard: rows } };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const KIND_LABEL = { gitlab: 'GitLab', github: 'GitHub Enterprise' };
|
|
98
|
+
|
|
99
|
+
/** Экран администратора «Свои серверы»: список, добавление GitLab или GitHub Enterprise, название, удаление. */
|
|
100
|
+
function hostsView(lang, note = '') {
|
|
101
|
+
const own = allHosts().filter((h) => h.custom);
|
|
102
|
+
const list = own.length
|
|
103
|
+
? 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')
|
|
104
|
+
: `<i>${th('git.hosts.none', lang)}</i>`;
|
|
105
|
+
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}` }]);
|
|
106
|
+
rows.push([{ text: t('git.hosts.addGitlab', lang), callback_data: 'gt:ha:gitlab' }, { text: t('git.hosts.addGithub', lang), callback_data: 'gt:ha:github' }]);
|
|
107
|
+
rows.push([{ text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
108
|
+
return { text: `${note ? `${note}\n\n` : ''}${th('git.hosts.head', lang)}\n\n${list}`, markup: { inline_keyboard: rows } };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** /git */
|
|
112
|
+
export async function handleGit(st) {
|
|
113
|
+
const lang = langOf(st.userId);
|
|
114
|
+
if (!gitAvailable()) return say(st.to, t('git.none', lang));
|
|
115
|
+
const v = await gitView(st, lang, { sync: true });
|
|
116
|
+
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Текст ошибки git или сервиса для пользователя. */
|
|
120
|
+
const failText = (e, lang) => th('git.opFail', lang, { msg: e instanceof GitError || e instanceof HostError ? e.message : errText(e, lang) });
|
|
121
|
+
|
|
122
|
+
/** Куда клонировать: личное пространство сотрудника, иначе — папка рядом с текущим проектом (или корень). */
|
|
123
|
+
function cloneBase(st) {
|
|
124
|
+
const root = rootOf(st.userId);
|
|
125
|
+
if (isPersonalRoot(root)) return insideRoot(root, root);
|
|
126
|
+
return insideRoot(navStart(st.project, root), root) ?? (root ? insideRoot(root, root) : null);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Список репозиториев сервиса кнопками (страница, поиск). Выбор — gt:k:<номер> по запомненному списку. */
|
|
130
|
+
async function reposView(st, host, account, { page = 0, search = '' } = {}, lang) {
|
|
131
|
+
const { items, more } = await listRepos(host, account.token, { page, search });
|
|
132
|
+
st.gitRepos = { host: host.id, items, page, search };
|
|
133
|
+
const base = cloneBase(st);
|
|
134
|
+
const rows = items.map((r, i) => [{ text: [...`${r.private ? '🔒' : '📂'} ${r.name}`].slice(0, 60).join(''), callback_data: `gt:k:${i}` }]);
|
|
135
|
+
const nav = [];
|
|
136
|
+
if (page > 0) nav.push({ text: '◀', callback_data: `gt:r:${host.id}:${page - 1}` });
|
|
137
|
+
if (more) nav.push({ text: '▶', callback_data: `gt:r:${host.id}:${page + 1}` });
|
|
138
|
+
if (nav.length) rows.push(nav);
|
|
139
|
+
rows.push([{ text: t('git.search', lang), callback_data: `gt:s:${host.id}` }, { text: t('btn.back', lang), callback_data: 'gt:v' }]);
|
|
140
|
+
const head = th('git.repos', lang, { host: host.label, q: search ? ` «${search}»` : '', dir: hCode(base ? userPath(st.userId, base, lang) : '—') });
|
|
141
|
+
return { text: items.length ? head : `${head}\n\n<i>${th('git.reposNone', lang)}</i>`, markup: { inline_keyboard: rows } };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Клонирует выбранный репозиторий в пространство пользователя и выбирает его проектом. */
|
|
145
|
+
async function cloneChosen(st, repo, host, account, lang, edit) {
|
|
146
|
+
const base = cloneBase(st);
|
|
147
|
+
const name = folderName(repoFolder(repo.url));
|
|
148
|
+
if (!base || !name) return edit({ text: th('git.cloneBadName', lang) });
|
|
149
|
+
const target = join(base, name);
|
|
150
|
+
if (insideRoot(target, rootOf(st.userId))) return edit({ text: th('git.cloneExists', lang, { name: hCode(name), dir: hCode(userPath(st.userId, base, lang)) }) });
|
|
151
|
+
await edit({ text: th('git.cloning', lang, { name: hCode(repo.name) }) });
|
|
152
|
+
try {
|
|
153
|
+
await cloneRepo(repo.url, name, { cwd: base, ...gitOpts(st, base, { host, account }) });
|
|
154
|
+
} catch (e) {
|
|
155
|
+
log('git: клонирование:', e.message, '| пользователь', st.userId);
|
|
156
|
+
return edit({ text: failText(e, lang) });
|
|
157
|
+
}
|
|
158
|
+
const dir = insideRoot(target, rootOf(st.userId));
|
|
159
|
+
if (!dir) return edit({ text: th('git.cloneBadName', lang) });
|
|
160
|
+
log('репозиторий клонирован:', st.userId, repo.name, dir);
|
|
161
|
+
await edit({ text: th('git.cloned', lang, { name: hCode(repo.name), p: hCode(userPath(st.userId, dir, lang)) }) });
|
|
162
|
+
return selectProject(st, dir);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Операция с репозиторием проекта: 'pull', 'push', 'pushf' (отправить, несмотря на секреты в коммитах) или 'save'
|
|
167
|
+
* (закоммитить всё с описанием message и отправить). Итог пишется в сообщение edit вместе с обновлённым экраном.
|
|
168
|
+
*/
|
|
169
|
+
async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
170
|
+
const project = projectOf(st);
|
|
171
|
+
const repo = project ? await repoOf(st, project) : null;
|
|
172
|
+
if (!repo?.account) return edit(await gitView(st, lang));
|
|
173
|
+
const opts = gitOpts(st, project, repo);
|
|
174
|
+
const done = async (text) => {
|
|
175
|
+
const v = await gitView(st, lang);
|
|
176
|
+
return edit({ text: `${text}\n\n${v.text}`, markup: v.markup });
|
|
177
|
+
};
|
|
178
|
+
st.gitBusy = true;
|
|
179
|
+
try {
|
|
180
|
+
if (action === 'pull') {
|
|
181
|
+
await edit({ text: th('git.pulling', lang) });
|
|
182
|
+
const result = await pullRepo(project, opts);
|
|
183
|
+
log('git: получено:', st.userId, project, '|', result);
|
|
184
|
+
return await done(th(`git.pull.${result}`, lang));
|
|
185
|
+
}
|
|
186
|
+
let note = '';
|
|
187
|
+
if (action === 'save') {
|
|
188
|
+
await edit({ text: th('git.saving', lang) });
|
|
189
|
+
const r = await commitAll(project, message, opts);
|
|
190
|
+
if (r.skipped.length) note += `\n${th('git.skipped', lang, { files: r.skipped.join(', ') })}`;
|
|
191
|
+
if (r.tracked.length) note += `\n${th('git.tracked', lang, { files: r.tracked.join(', ') })}`;
|
|
192
|
+
const after = await repoState(project, opts);
|
|
193
|
+
if (!r.committed && !after?.ahead && after?.upstream) return await done(th('git.savedNothing', lang) + note);
|
|
194
|
+
} else await edit({ text: th('git.pushing', lang) });
|
|
195
|
+
// секреты в коммитах, которые сделал агент: перед отправкой — предупреждение и явное согласие
|
|
196
|
+
if (action !== 'pushf') {
|
|
197
|
+
const secrets = await unpushedSecrets(project, opts);
|
|
198
|
+
if (secrets.length) {
|
|
199
|
+
const markup = { inline_keyboard: [[{ text: t('git.pushAnyway', lang), callback_data: 'gt:pushf' }, { text: t('btn.cancel', lang), callback_data: 'gt:v' }]] };
|
|
200
|
+
return await edit({ text: th('git.secretsWarn', lang, { files: secrets.slice(0, 20).join('\n') }) + note, markup });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const state = await repoState(project, opts);
|
|
204
|
+
if (state?.upstream && !state.ahead) return await done(th('git.nothingToPush', lang) + note);
|
|
205
|
+
try {
|
|
206
|
+
await pushRepo(project, opts);
|
|
207
|
+
} catch (e) {
|
|
208
|
+
if (/rejected|non-fast-forward|fetch first/i.test(`${e.message} ${e.stderr ?? ''}`)) return await done(th('git.pushRejected', lang) + note);
|
|
209
|
+
throw e;
|
|
210
|
+
}
|
|
211
|
+
log('git: отправлено:', st.userId, project);
|
|
212
|
+
return await done(th(action === 'save' ? 'git.saved' : 'git.pushed', lang) + note);
|
|
213
|
+
} catch (e) {
|
|
214
|
+
log(`git: ${action}:`, e.message, '| пользователь', st.userId);
|
|
215
|
+
return await done(failText(e, lang));
|
|
216
|
+
} finally {
|
|
217
|
+
st.gitBusy = false;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Кнопки /git (gt:<действие>[:<аргумент>[:<страница>]]). */
|
|
222
|
+
export async function onGitCallback(st, cb) {
|
|
223
|
+
const [, action, arg, pageStr] = (cb.data || '').split(':');
|
|
224
|
+
const lang = langOf(st.userId);
|
|
225
|
+
const chatId = cb.message?.chat?.id ?? st.chatId;
|
|
226
|
+
const messageId = cb.message?.message_id;
|
|
227
|
+
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text, show_alert: true } : {}) }).catch(() => {});
|
|
228
|
+
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));
|
|
229
|
+
if (!gitAvailable()) return ack(t('git.none', lang));
|
|
230
|
+
if (action === 'x') {
|
|
231
|
+
st.pendingInput = null;
|
|
232
|
+
await ack();
|
|
233
|
+
return edit({ text: th('files.cancelled', lang) });
|
|
234
|
+
}
|
|
235
|
+
if (action === 'v') {
|
|
236
|
+
await ack();
|
|
237
|
+
return edit(await gitView(st, lang, { sync: true }));
|
|
238
|
+
}
|
|
239
|
+
// ---- свои серверы: только администратор ----
|
|
240
|
+
if (['h', 'ha', 'hn', 'hd', 'hD'].includes(action)) {
|
|
241
|
+
if (!isAdmin(st.userId)) return ack(t('admin.only', lang));
|
|
242
|
+
if (action === 'h') return (await ack(), edit(hostsView(lang)));
|
|
243
|
+
if (action === 'ha' && KIND_LABEL[arg]) {
|
|
244
|
+
await ack();
|
|
245
|
+
st.pendingInput = { kind: 'gitHostUrl', hostKind: arg, at: Date.now() };
|
|
246
|
+
return say(st.to, t('git.hosts.urlAsk', lang, { kind: KIND_LABEL[arg] }), { reply_markup: cancelMarkup(lang) });
|
|
247
|
+
}
|
|
248
|
+
const own = findHost(arg);
|
|
249
|
+
if (!own?.custom || own.fromEnv) return ack(t('proj.stale', lang));
|
|
250
|
+
if (action === 'hn') {
|
|
251
|
+
await ack();
|
|
252
|
+
st.pendingInput = { kind: 'gitHostName', host: own.id, at: Date.now() };
|
|
253
|
+
return say(st.to, t('git.hosts.nameAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
254
|
+
}
|
|
255
|
+
if (action === 'hd') {
|
|
256
|
+
await ack();
|
|
257
|
+
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' }]] } });
|
|
258
|
+
}
|
|
259
|
+
const n = removeCustomHost(own.id);
|
|
260
|
+
log('свой сервер git убран:', own.web, '| отключено аккаунтов', n);
|
|
261
|
+
await ack();
|
|
262
|
+
return edit(hostsView(lang, th('git.hosts.deleted', lang, { label: own.label, n: n ?? 0 })));
|
|
263
|
+
}
|
|
264
|
+
const host = findHost(arg);
|
|
265
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
266
|
+
try {
|
|
267
|
+
// ---- аккаунты ----
|
|
268
|
+
if (action === 'c' && host) {
|
|
269
|
+
await ack();
|
|
270
|
+
st.pendingInput = { kind: 'gitToken', host: host.id, at: Date.now() };
|
|
271
|
+
return say(st.to, th('git.tokenAsk', lang, { host: host.label, url: host.tokenUrl, scopes: hCode(host.scopes) }), { ...HTML, reply_markup: cancelMarkup(lang) });
|
|
272
|
+
}
|
|
273
|
+
if ((action === 'a' || action === 'd') && account) {
|
|
274
|
+
await ack();
|
|
275
|
+
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) });
|
|
276
|
+
const rows = action === 'd'
|
|
277
|
+
? [[{ text: t('git.disconnect', lang), callback_data: `gt:D:${host.id}` }, { text: t('btn.cancel', lang), callback_data: `gt:a:${host.id}` }]]
|
|
278
|
+
: [[{ text: t('git.disconnect', lang), callback_data: `gt:d:${host.id}` }], [{ text: t('btn.back', lang), callback_data: 'gt:v' }]];
|
|
279
|
+
return edit({ text, markup: { inline_keyboard: rows } });
|
|
280
|
+
}
|
|
281
|
+
if (action === 'D' && account) {
|
|
282
|
+
db.deleteGitAccount(st.userId, host.id);
|
|
283
|
+
log('аккаунт git отключён:', st.userId, host.id);
|
|
284
|
+
await ack(t('git.disconnected', lang, { host: host.label }));
|
|
285
|
+
return edit(await gitView(st, lang));
|
|
286
|
+
}
|
|
287
|
+
// ---- клонирование ----
|
|
288
|
+
if (action === 'cl') {
|
|
289
|
+
if (!canCreateProject(st.userId)) return ack(t('files.noRights', lang));
|
|
290
|
+
const list = accountsOf(st.userId);
|
|
291
|
+
if (!list.length) return ack(t('git.connectFirst', lang));
|
|
292
|
+
await ack();
|
|
293
|
+
if (list.length === 1) return edit(await reposView(st, list[0].host, list[0].account, {}, lang));
|
|
294
|
+
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' }]] } });
|
|
295
|
+
}
|
|
296
|
+
if (action === 'r' && account) {
|
|
297
|
+
await ack();
|
|
298
|
+
const search = st.gitRepos?.host === host.id ? st.gitRepos.search : '';
|
|
299
|
+
return edit(await reposView(st, host, account, { page: Number(pageStr) || 0, search }, lang));
|
|
300
|
+
}
|
|
301
|
+
if (action === 's' && account) {
|
|
302
|
+
await ack();
|
|
303
|
+
st.pendingInput = { kind: 'gitSearch', host: host.id, at: Date.now() };
|
|
304
|
+
return say(st.to, t('git.searchAsk', lang), { reply_markup: cancelMarkup(lang) });
|
|
305
|
+
}
|
|
306
|
+
if (action === 'k') {
|
|
307
|
+
const list = st.gitRepos;
|
|
308
|
+
const repo = list?.items[Number(arg)];
|
|
309
|
+
const h = findHost(list?.host);
|
|
310
|
+
const acc = h ? db.getGitAccount(st.userId, h.id) : null;
|
|
311
|
+
if (!repo || !acc || !canCreateProject(st.userId)) return ack(t('proj.stale', lang));
|
|
312
|
+
if (hostFor(repo.url)?.id !== h.id) return ack(t('proj.stale', lang)); // адрес обязан принадлежать своему сервису
|
|
313
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
314
|
+
await ack();
|
|
315
|
+
st.gitBusy = true;
|
|
316
|
+
try {
|
|
317
|
+
return await cloneChosen(st, repo, h, acc, lang, edit);
|
|
318
|
+
} finally {
|
|
319
|
+
st.gitBusy = false;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// ---- репозиторий проекта ----
|
|
323
|
+
if (['pull', 'push', 'pushf', 'save', 'savenow'].includes(action)) {
|
|
324
|
+
if (!canManageFiles(st.userId)) return ack(t('files.noRights', lang));
|
|
325
|
+
if (st.gitBusy) return ack(t('git.busy', lang));
|
|
326
|
+
if (st.busy) return ack(t('git.agentBusy', lang));
|
|
327
|
+
await ack();
|
|
328
|
+
if (action === 'save') {
|
|
329
|
+
st.pendingInput = { kind: 'gitMessage', at: Date.now() };
|
|
330
|
+
const markup = { inline_keyboard: [[{ text: t('git.noMessage', lang), callback_data: 'gt:savenow' }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] };
|
|
331
|
+
return say(st.to, t('git.messageAsk', lang), { reply_markup: markup });
|
|
332
|
+
}
|
|
333
|
+
if (action === 'savenow') {
|
|
334
|
+
st.pendingInput = null;
|
|
335
|
+
return repoAction(st, 'save', lang, edit, { message: t('git.autoMessage', lang, { date: dateOf(new Date().toISOString(), lang) }) });
|
|
336
|
+
}
|
|
337
|
+
return repoAction(st, action, lang, edit);
|
|
338
|
+
}
|
|
339
|
+
return ack(t('proj.stale', lang));
|
|
340
|
+
} catch (e) {
|
|
341
|
+
log('git:', e.message, '| пользователь', st.userId);
|
|
342
|
+
await ack();
|
|
343
|
+
return edit({ text: failText(e, lang) });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Удаляет сообщение пользователя (с токеном): копии в чате остаться не должно. */
|
|
348
|
+
const dropMessage = (st, messageId) => (messageId ? tg('deleteMessage', { chat_id: st.chatId, message_id: messageId }).catch((e) => log('git: сообщение не удалено:', e.message)) : null);
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Текст пользователя, пока бот ждёт токен доступа, строку поиска репозитория или описание изменений. true — текст
|
|
352
|
+
* обработан здесь и агенту не передаётся. Токен агенту не уходит никогда: даже если ожидание истекло, сообщение
|
|
353
|
+
* удаляется, а не превращается в запрос.
|
|
354
|
+
*/
|
|
355
|
+
export async function onGitInput(st, text, { messageId, now = Date.now() } = {}) {
|
|
356
|
+
const wait = st.pendingInput;
|
|
357
|
+
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName'].includes(wait?.kind)) return false;
|
|
358
|
+
const lang = langOf(st.userId);
|
|
359
|
+
const expired = now - wait.at > GIT_WAIT_MS;
|
|
360
|
+
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
361
|
+
|
|
362
|
+
if (wait.kind === 'gitToken') {
|
|
363
|
+
await dropMessage(st, messageId);
|
|
364
|
+
const host = findHost(wait.host);
|
|
365
|
+
if (expired || !host) {
|
|
366
|
+
st.pendingInput = null;
|
|
367
|
+
return (await say(st.to, t('git.tokenExpired', lang)), true);
|
|
368
|
+
}
|
|
369
|
+
const token = text.trim();
|
|
370
|
+
if (/\s/.test(token) || token.length < 10) return (await say(st.to, t('git.tokenBad', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
371
|
+
let profile;
|
|
372
|
+
try {
|
|
373
|
+
profile = await fetchProfile(host, token);
|
|
374
|
+
} catch (e) {
|
|
375
|
+
log('git: проверка токена:', e.message, '| пользователь', st.userId);
|
|
376
|
+
const textFail = e instanceof HostError && e.code === 'auth' ? t('git.tokenBad', lang) : t('git.tokenFail', lang, { msg: e.message });
|
|
377
|
+
return (await say(st.to, textFail, { reply_markup: cancelMarkup(lang) }), true); // ожидание остаётся: можно прислать ещё раз
|
|
378
|
+
}
|
|
379
|
+
st.pendingInput = null;
|
|
380
|
+
if (!db.saveGitAccount(st.userId, { host: host.id, login: profile.login, name: profile.name, email: profile.email, token, expiresAt: profile.expiresAt })) {
|
|
381
|
+
return (await say(st.to, t('access.saveFail', lang)), true);
|
|
382
|
+
}
|
|
383
|
+
log('аккаунт git подключён:', st.userId, host.id, profile.login);
|
|
384
|
+
const lack = missingScopes(host, profile.scopes);
|
|
385
|
+
const parts = [
|
|
386
|
+
th('git.connected', lang, { host: host.label, login: profile.login, name: profile.name }),
|
|
387
|
+
...(profile.expiresAt ? [th('git.expires', lang, { date: dateOf(profile.expiresAt, lang) })] : []),
|
|
388
|
+
...(lack.length ? [th('git.scopesWarn', lang, { scopes: lack.join(', ') })] : []),
|
|
389
|
+
];
|
|
390
|
+
await send({ text: parts.join('\n') });
|
|
391
|
+
await send(await gitView(st, lang));
|
|
392
|
+
return true;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
st.pendingInput = null;
|
|
396
|
+
if (expired) return false; // адрес сервера, строка поиска и описание изменений — не секреты: позже это обычный запрос агенту
|
|
397
|
+
// свои серверы: адрес нового сервера или новое название — только от администратора
|
|
398
|
+
if (wait.kind === 'gitHostUrl' || wait.kind === 'gitHostName') {
|
|
399
|
+
if (!isAdmin(st.userId)) return false;
|
|
400
|
+
if (wait.kind === 'gitHostName') {
|
|
401
|
+
renameCustomHost(wait.host, text);
|
|
402
|
+
return (await send(hostsView(lang)), true);
|
|
403
|
+
}
|
|
404
|
+
const again = () => (st.pendingInput = { ...wait, at: now }); // адрес не подошёл — ждём другой
|
|
405
|
+
const candidate = customHost(wait.hostKind, text);
|
|
406
|
+
if (!candidate) return (again(), await say(st.to, t('git.hosts.badUrl', lang), { reply_markup: cancelMarkup(lang) }), true);
|
|
407
|
+
const probe = await probeHost(candidate);
|
|
408
|
+
if (!probe.ok) {
|
|
409
|
+
again();
|
|
410
|
+
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);
|
|
411
|
+
}
|
|
412
|
+
const added = addCustomHost(wait.hostKind, candidate.web);
|
|
413
|
+
if (added.error) return (await send(hostsView(lang, th('git.hosts.exists', lang))), true);
|
|
414
|
+
log('свой сервер git добавлен:', added.host.kind, added.host.web, '| администратор', st.userId);
|
|
415
|
+
return (await send(hostsView(lang, th('git.hosts.added', lang, { label: added.host.label }))), true);
|
|
416
|
+
}
|
|
417
|
+
if (wait.kind === 'gitSearch') {
|
|
418
|
+
const host = findHost(wait.host);
|
|
419
|
+
const account = host ? db.getGitAccount(st.userId, host.id) : null;
|
|
420
|
+
if (!account) return false;
|
|
421
|
+
try {
|
|
422
|
+
await send(await reposView(st, host, account, { search: text.trim().slice(0, 60) }, lang));
|
|
423
|
+
} catch (e) {
|
|
424
|
+
await send({ text: failText(e, lang) });
|
|
425
|
+
}
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
// описание изменений: первая строка, не длиннее 200 символов
|
|
429
|
+
const message = [...text.trim().split(/\r?\n/)[0]].slice(0, 200).join('') || t('git.autoMessage', lang, { date: dateOf(new Date().toISOString(), lang) });
|
|
430
|
+
if (st.gitBusy || st.busy) return (await say(st.to, t(st.busy ? 'git.agentBusy' : 'git.busy', lang)), true);
|
|
431
|
+
const progress = await tg('sendMessage', { ...dest(st.to), text: th('git.saving', lang), ...HTML }).catch(() => null);
|
|
432
|
+
const edit = (v) =>
|
|
433
|
+
progress
|
|
434
|
+
? 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))
|
|
435
|
+
: send(v);
|
|
436
|
+
await repoAction(st, 'save', lang, edit, { message });
|
|
437
|
+
return true;
|
|
438
|
+
}
|