102 lines
4.6 KiB
JavaScript
102 lines
4.6 KiB
JavaScript
// 代码托管 REST 调用(默认 Gitea):校验令牌、取账号、按需创建仓库。只用原生 fetch。
|
||
let API = (process.env.DSH_GIT_API || '').replace(/\/+$/, '')
|
||
let NAME = 'Gitea'
|
||
|
||
/** 设置 API 根地址,比如 http://主机:3000/api/v1 */
|
||
export function setApiBase(base) {
|
||
if (typeof base === 'string' && base.trim() !== '') API = base.trim().replace(/\/+$/, '')
|
||
}
|
||
export function setProviderName(name) {
|
||
if (typeof name === 'string' && name.trim() !== '') NAME = name.trim()
|
||
}
|
||
const UA = 'dsh-go-gitea-upload/1.0'
|
||
|
||
export class RemoteError extends Error {
|
||
constructor(message, { status = 0, code = '' } = {}) {
|
||
super(message)
|
||
this.name = 'RemoteError'
|
||
this.status = status
|
||
this.code = code
|
||
}
|
||
}
|
||
|
||
function headers(token, extra = {}) {
|
||
return {
|
||
accept: 'application/json',
|
||
authorization: `token ${token}`,
|
||
'user-agent': UA,
|
||
...extra
|
||
}
|
||
}
|
||
|
||
async function request(path, { token, method = 'GET', body, timeoutMs = 25000 } = {}) {
|
||
let res
|
||
try {
|
||
if (API === '') throw new RemoteError('还没有配置 Gitea 地址,请在插件配置里填 apiBase(例如 http://主机:3000/api/v1)', { code: 'no-base' })
|
||
res = await fetch(`${API}${path}`, {
|
||
method,
|
||
headers: headers(token, body === undefined ? {} : { 'content-type': 'application/json' }),
|
||
body: body === undefined ? undefined : JSON.stringify(body),
|
||
signal: AbortSignal.timeout(timeoutMs)
|
||
})
|
||
} catch (error) {
|
||
const reason = error?.name === 'TimeoutError' ? '请求超时' : '连不上 ${NAME}'
|
||
throw new RemoteError(`${reason},请检查手机/服务器网络,或稍后重试。`, { code: 'network' })
|
||
}
|
||
const text = await res.text().catch(() => '')
|
||
let json = null
|
||
try { json = text === '' ? null : JSON.parse(text) } catch {}
|
||
if (res.ok) return json
|
||
const detail = typeof json?.message === 'string' ? json.message : text.slice(0, 200)
|
||
if (res.status === 401) throw new RemoteError(`${NAME} 令牌无效或已过期,请重新生成令牌。`, { status: 401, code: 'bad-token' })
|
||
if (res.status === 403) {
|
||
const limited = String(json?.message || '').toLowerCase().includes('rate limit')
|
||
throw new RemoteError(limited ? `${NAME} 接口被限流,过一会儿再试。` : `${NAME} 拒绝了这个操作(403):${detail}`, { status: 403, code: limited ? 'rate-limit' : 'forbidden' })
|
||
}
|
||
if (res.status === 404) throw new RemoteError(`找不到 ${NAME} 资源(404):${detail}`, { status: 404, code: 'not-found' })
|
||
if (res.status === 422) throw new RemoteError(`${NAME} 不接受这次请求(422):${detail}`, { status: 422, code: 'invalid' })
|
||
throw new RemoteError(`${NAME} 返回 ${res.status}:${detail}`, { status: res.status, code: 'http' })
|
||
}
|
||
|
||
/** 校验令牌并返回账号名。 */
|
||
export async function getLogin(token) {
|
||
const me = await request('/user', { token })
|
||
if (typeof me?.login !== 'string' || me.login === '') throw new RemoteError(`${NAME} 没有返回账号名,令牌可能权限不足。`, { code: 'bad-token' })
|
||
return me.login
|
||
}
|
||
|
||
/** 保证仓库存在;已存在就复用。返回 { url, cloneUrl, created }。 */
|
||
export async function ensureRepo({ token, login, name, privateRepo = true, description = '' }) {
|
||
// 先问一下仓库在不在:已经推过一次的项目不必每次都调创建接口,
|
||
// 也避开远端对「内容创建」的二次限流(那种情况下 POST 会被 403)。
|
||
try {
|
||
const existing = await request(`/repos/${login}/${name}`, { token })
|
||
if (existing && existing.html_url) {
|
||
return { url: existing.html_url, cloneUrl: existing.clone_url, created: false }
|
||
}
|
||
} catch (error) {
|
||
if (!(error instanceof RemoteError) || error.status !== 404) throw error
|
||
}
|
||
try {
|
||
const repo = await request('/user/repos', {
|
||
token,
|
||
method: 'POST',
|
||
body: { name, description: description.slice(0, 350), private: privateRepo, auto_init: false, has_issues: true, has_wiki: false }
|
||
})
|
||
return { url: repo.html_url, cloneUrl: repo.clone_url, created: true }
|
||
} catch (error) {
|
||
if (!(error instanceof RemoteError) || error.status !== 422) throw error
|
||
// 同名仓库已存在:复用(可能是之前上传过的)。
|
||
let repo
|
||
try {
|
||
repo = await request(`/repos/${login}/${name}`, { token })
|
||
} catch (inner) {
|
||
throw new RemoteError(`仓库名 ${name} 已被占用且无法访问,请改名后重试。`, { code: 'name-taken' })
|
||
}
|
||
if (repo?.full_name?.toLowerCase() !== `${login}/${name}`.toLowerCase()) {
|
||
throw new RemoteError(`仓库名 ${name} 已被其它账号占用。`, { code: 'name-taken' })
|
||
}
|
||
return { url: repo.html_url, cloneUrl: repo.clone_url, created: false }
|
||
}
|
||
}
|