Исправить сетевые запросы обновлений через прокси
All checks were successful
Release / release (push) Successful in 2m47s
All checks were successful
Release / release (push) Successful in 2m47s
This commit is contained in:
parent
41bc7ca1f4
commit
092fdb484b
2 changed files with 35 additions and 50 deletions
17
src/main/services/update-network.ts
Normal file
17
src/main/services/update-network.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { app, net } from 'electron'
|
||||
|
||||
export async function fetchUpdate(url: string): Promise<Response> {
|
||||
// Сетевой стек Chromium учитывает системный прокси и доверенные сертификаты.
|
||||
const response: Response = await net.fetch(url, {
|
||||
headers: {
|
||||
'User-Agent': `AeroMail/${app.getVersion()}`,
|
||||
'Cache-Control': 'no-cache'
|
||||
},
|
||||
credentials: 'omit'
|
||||
})
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel()
|
||||
throw new Error(`Сервер обновлений вернул HTTP ${response.status}`)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
import { app, BrowserWindow } from 'electron'
|
||||
import { Readable, Transform, type TransformCallback } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import { fetchUpdate } from './update-network'
|
||||
import { createWriteStream, chmodSync, mkdirSync, writeFileSync, realpathSync, existsSync } from 'fs'
|
||||
import { join, dirname } from 'path'
|
||||
import { homedir, tmpdir } from 'os'
|
||||
import { spawn } from 'child_process'
|
||||
import https from 'https'
|
||||
import http from 'http'
|
||||
import { URL } from 'url'
|
||||
|
||||
const REPO_API = 'https://git.vodyanoysh.ru/api/v1/repos/vodyanoy/aero-mail/releases/latest'
|
||||
|
||||
|
|
@ -31,62 +31,30 @@ function compareSemver(a: string, b: string): number {
|
|||
return aPat - bPat
|
||||
}
|
||||
|
||||
function fetchJson<T>(url: string): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url)
|
||||
https.get(
|
||||
{ hostname: parsed.hostname, path: parsed.pathname + parsed.search, headers: { 'User-Agent': `AeroMail/${app.getVersion()}` } },
|
||||
(res) => {
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${res.statusCode}`))
|
||||
res.resume()
|
||||
return
|
||||
}
|
||||
let data = ''
|
||||
res.on('data', (chunk: string) => { data += chunk })
|
||||
res.on('end', () => {
|
||||
try { resolve(JSON.parse(data) as T) } catch (e) { reject(e) }
|
||||
})
|
||||
}
|
||||
).on('error', reject)
|
||||
})
|
||||
async function fetchJson<T>(url: string): Promise<T> {
|
||||
const response: Response = await fetchUpdate(url)
|
||||
return await response.json() as T
|
||||
}
|
||||
|
||||
function downloadFile(
|
||||
async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
totalSize: number,
|
||||
onProgress: (percent: number, transferred: number, total: number) => void
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const follow = (currentUrl: string): void => {
|
||||
const parsed = new URL(currentUrl)
|
||||
const proto = parsed.protocol === 'https:' ? https : http
|
||||
proto.get(currentUrl, { headers: { 'User-Agent': `AeroMail/${app.getVersion()}` } }, (res) => {
|
||||
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
|
||||
follow(res.headers.location!)
|
||||
return
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`Download failed: HTTP ${res.statusCode}`))
|
||||
res.resume()
|
||||
return
|
||||
}
|
||||
const file = createWriteStream(destPath)
|
||||
let transferred = 0
|
||||
res.on('data', (chunk: Buffer) => {
|
||||
transferred += chunk.length
|
||||
const percent = totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 0
|
||||
onProgress(percent, transferred, totalSize)
|
||||
})
|
||||
res.pipe(file)
|
||||
file.on('finish', () => file.close(() => resolve()))
|
||||
file.on('error', (e) => { reject(e) })
|
||||
res.on('error', (e) => { reject(e) })
|
||||
}).on('error', reject)
|
||||
const response: Response = await fetchUpdate(url)
|
||||
if (!response.body) throw new Error('Сервер обновлений вернул пустой ответ')
|
||||
|
||||
let transferred: number = 0
|
||||
const trackProgress: Transform = new Transform({
|
||||
transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {
|
||||
transferred += chunk.length
|
||||
const percent: number = totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 0
|
||||
onProgress(percent, transferred, totalSize)
|
||||
callback(null, chunk)
|
||||
}
|
||||
follow(url)
|
||||
})
|
||||
await pipeline(Readable.fromWeb(response.body), trackProgress, createWriteStream(destPath))
|
||||
}
|
||||
|
||||
// Запускает детачнутый sh-скрипт, который ждёт смерти текущего процесса,
|
||||
|
|
|
|||
Loading…
Reference in a new issue