mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 00:51:51 +08:00
feat: 新增实验性微信卡片分享与自动部署能力
补充 Cloudflare Worker、R2 存储、微信 JS-SDK 签名与上传鉴权 增加自动部署 Skill 和配置引导文档 优化报告工具栏、微信卡片弹窗及窄屏响应式布局 补充 Worker 鉴权、卡片生成、过期清理与安全转义测试
This commit is contained in:
1 parent
eb4cb30fb5
commit
cd2fb09e02
45 files changed
+3832
-69
No files matched your search
@@ -135,6 +135,12 @@ import { KnowledgeSearchService } from './knowledge/knowledge-search-service'
|
||||
import { AiSearchPipelineService } from './services/ai-search-pipeline-service'
|
||||
import { runLegacySafeStorageHelper } from './legacy-safe-storage-helper'
|
||||
import { runFirstLaunchMigration } from './app-data-migration'
|
||||
import { WechatShareConfigStore } from './wechat-share-config-store'
|
||||
import { WechatShareCardService } from './wechat-share-card-service'
|
||||
import type {
|
||||
PublishWechatShareCardRequest,
|
||||
WechatShareServiceConfig
|
||||
} from '../shared/wechat-share-card'
|
||||
|
||||
// electron-vite can close the child's stdout/stderr after spawning Electron.
|
||||
// Plain console.error then throws EPIPE on a closed pipe and crashes the IPC
|
||||
@@ -154,6 +160,8 @@ const imageKeyConfigService = new ImageKeyConfigService()
|
||||
const aiProviderService = new AIProviderService()
|
||||
const keyServiceMac = new KeyServiceMac()
|
||||
const keyServiceWin = new KeyServiceWin()
|
||||
const wechatShareConfigStore = new WechatShareConfigStore()
|
||||
const wechatShareCardService = new WechatShareCardService(wechatShareConfigStore)
|
||||
let tray: Tray | null = null
|
||||
let recallArchiveMonitor: RecallArchiveMonitor | null = null
|
||||
let recallProtectionGeneration = 0
|
||||
@@ -1201,6 +1209,14 @@ app.whenReady().then(async () => {
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('wechat-share:getConfig', async () => wechatShareConfigStore.status())
|
||||
ipcMain.handle('wechat-share:saveConfig', async (_, config: WechatShareServiceConfig) =>
|
||||
wechatShareConfigStore.save(config)
|
||||
)
|
||||
ipcMain.handle('wechat-share:publish', async (_, request: PublishWechatShareCardRequest) =>
|
||||
wechatShareCardService.publish(request)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'db:getVoiceData',
|
||||
async (_, sessionId: string, localId: number, createTime: number, svrId?: string | number) => {
|
||||
|
||||
@@ -81,6 +81,7 @@ const normalizeRecord = async (
|
||||
const pngStatus = await fileStatus(record.pngPath)
|
||||
return {
|
||||
...record,
|
||||
textModelName: record.textModelName || record.modelName,
|
||||
jsonPath,
|
||||
htmlStatus,
|
||||
pngStatus,
|
||||
@@ -181,6 +182,8 @@ export async function saveGeneratedReport(
|
||||
pngStatus: savedPngPath ? 'ready' : 'missing',
|
||||
imageSize: await readPngSize(savedPngPath),
|
||||
duration: request.duration,
|
||||
textModelName: request.textModelName || request.modelName,
|
||||
imageModelName: request.imageModelName,
|
||||
modelName: request.modelName,
|
||||
tokenUsage: request.tokenUsage,
|
||||
fileSize: {
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
AIProviderSummary,
|
||||
AiSearchProviderStatus,
|
||||
AIRuntimeModelConfig,
|
||||
AIVisionRuntimeConfig,
|
||||
AIVisionTestRequest,
|
||||
AIVisionTestResult,
|
||||
LegacyAIConfig
|
||||
@@ -74,6 +75,60 @@ export class AIProviderService {
|
||||
}
|
||||
}
|
||||
|
||||
getVisionRuntimeConfig(): AIVisionRuntimeConfig {
|
||||
const result = this.list()
|
||||
const defaultProvider = result.providers.find((item) => item.id === result.defaultProviderId)
|
||||
const defaultModel = defaultProvider?.models.find(
|
||||
(item) => item.id === defaultProvider.defaultModel
|
||||
)
|
||||
if (
|
||||
defaultProvider &&
|
||||
defaultModel &&
|
||||
(defaultProvider.hasApiKey || !needsApiKey(defaultProvider)) &&
|
||||
(defaultModel.capabilities.vision || defaultModel.capabilities.ocr)
|
||||
) {
|
||||
return {
|
||||
providerId: defaultProvider.id,
|
||||
providerName: defaultProvider.name,
|
||||
model: defaultModel.id,
|
||||
modelName: defaultModel.name || defaultModel.id,
|
||||
configured: true,
|
||||
status: defaultProvider.status,
|
||||
timeoutMs: defaultProvider.advanced.timeoutMs,
|
||||
source: 'default-model'
|
||||
}
|
||||
}
|
||||
|
||||
for (const provider of result.providers) {
|
||||
if (!provider.hasApiKey && needsApiKey(provider)) continue
|
||||
const model =
|
||||
provider.models.find(
|
||||
(item) =>
|
||||
item.id === provider.defaultModel && (item.capabilities.vision || item.capabilities.ocr)
|
||||
) || provider.models.find((item) => item.capabilities.vision || item.capabilities.ocr)
|
||||
if (!model) continue
|
||||
return {
|
||||
providerId: provider.id,
|
||||
providerName: provider.name,
|
||||
model: model.id,
|
||||
modelName: model.name || model.id,
|
||||
configured: true,
|
||||
status: provider.status,
|
||||
timeoutMs: provider.advanced.timeoutMs,
|
||||
source: 'vision-capability'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
providerName: '尚未配置',
|
||||
model: '',
|
||||
modelName: '尚未验证图片理解模型',
|
||||
configured: false,
|
||||
status: 'untested',
|
||||
source: 'unavailable'
|
||||
}
|
||||
}
|
||||
|
||||
getAiSearchProviderStatus(providerId?: string): AiSearchProviderStatus {
|
||||
const result = this.list()
|
||||
const provider =
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//
|
||||
// 设计原则:
|
||||
// 1. base64 不走 IPC,只在 main 内部流转(renderer 只看到 ImageInsight 结构化结果)
|
||||
// 2. 同图(imageHash)走缓存,绝不重复调 AI
|
||||
// 2. 同图(imageHash)在 10 分钟内走缓存,过期后重新调 AI
|
||||
// 3. 失败不抛,日志记录 + 返回原状(不阻塞日报)
|
||||
// 4. 日报最多识别 3 张达到热点门槛的图片;缓存命中即返回,未命中并发调 AI
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
} from '../../shared/image-insight'
|
||||
import {
|
||||
calculateImageHeatScore,
|
||||
isFreshImageInsight,
|
||||
isHotImageCandidate
|
||||
} from '../../shared/image-insight'
|
||||
|
||||
@@ -46,6 +47,13 @@ export interface ImageCandidateInput {
|
||||
|
||||
interface ProviderServiceLike {
|
||||
list(): ProviderSummaryLike
|
||||
getVisionRuntimeConfig(): {
|
||||
providerId?: string
|
||||
providerName: string
|
||||
model: string
|
||||
modelName: string
|
||||
configured: boolean
|
||||
}
|
||||
analyzeImage(
|
||||
messages: Array<{
|
||||
role: string
|
||||
@@ -81,7 +89,7 @@ interface ProviderSummaryLike {
|
||||
class ImageInsightService {
|
||||
private providerService: ProviderServiceLike | null = null
|
||||
private decryptService: DecryptServiceLike | null = null
|
||||
/** 最近一次实际使用的默认 AI provider/model,仅用于写入分析元数据 */
|
||||
/** 最近一次实际使用的视觉 provider/model,仅用于写入分析元数据 */
|
||||
private runtimeProviderId: string | undefined = undefined
|
||||
private runtimeModelId: string | undefined = undefined
|
||||
|
||||
@@ -97,13 +105,11 @@ class ImageInsightService {
|
||||
this.runtimeProviderId,
|
||||
this.runtimeModelId
|
||||
)
|
||||
// 读取默认 provider/model(后续 analyze 时使用)
|
||||
// 读取当前视觉 provider/model(后续 analyze 时仍会刷新,避免配置变化后继续用旧模型)
|
||||
try {
|
||||
const list = deps.providerService.list()
|
||||
const provider =
|
||||
list.providers.find((p) => p.id === list.defaultProviderId) || list.providers[0]
|
||||
this.runtimeProviderId = provider?.id
|
||||
this.runtimeModelId = provider?.defaultModel
|
||||
const runtime = deps.providerService.getVisionRuntimeConfig()
|
||||
this.runtimeProviderId = runtime.providerId
|
||||
this.runtimeModelId = runtime.model || undefined
|
||||
console.log(
|
||||
'[ImageInsightService] bind loaded default provider=%s model=%s',
|
||||
this.runtimeProviderId,
|
||||
@@ -145,7 +151,7 @@ class ImageInsightService {
|
||||
|
||||
/**
|
||||
* 主入口:分析一张图片。
|
||||
* 1. 通过 imageHash 查缓存,命中即返回
|
||||
* 1. 通过 imageHash 查 10 分钟缓存,新鲜则返回
|
||||
* 2. 未命中:解密图片 → 调 AI → 解析响应 → 落库 → 返回
|
||||
* 3. 任意步骤失败:记录日志,返回 success=false,**不抛**
|
||||
*/
|
||||
@@ -153,8 +159,15 @@ class ImageInsightService {
|
||||
try {
|
||||
if (!request.force) {
|
||||
const cached = imageInsightsStore.getByHash(request.imageHash)
|
||||
if (isFreshImageInsight(cached)) {
|
||||
return { success: true, insight: cached || undefined, fromCache: true }
|
||||
}
|
||||
if (cached) {
|
||||
return { success: true, insight: cached, fromCache: true }
|
||||
console.log(
|
||||
'[ImageInsightService] cache expired hash=%s ageMs=%d',
|
||||
request.imageHash,
|
||||
Date.now() - Number(cached.updatedAt || 0)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,11 +197,24 @@ class ImageInsightService {
|
||||
}
|
||||
]
|
||||
|
||||
const list = this.providerService.list()
|
||||
const provider =
|
||||
list.providers.find((item) => item.id === list.defaultProviderId) || list.providers[0]
|
||||
this.runtimeProviderId = provider?.id
|
||||
this.runtimeModelId = provider?.defaultModel
|
||||
const runtime =
|
||||
request.providerId && request.modelId
|
||||
? {
|
||||
providerId: request.providerId,
|
||||
model: request.modelId,
|
||||
configured: true
|
||||
}
|
||||
: this.providerService.getVisionRuntimeConfig()
|
||||
if (!runtime.configured || !runtime.providerId || !runtime.model) {
|
||||
return { success: false, error: '尚未配置或验证支持图片理解的 AI 模型' }
|
||||
}
|
||||
this.runtimeProviderId = runtime.providerId
|
||||
this.runtimeModelId = runtime.model
|
||||
console.log(
|
||||
'[ImageInsightService] analyze using vision provider=%s model=%s',
|
||||
this.runtimeProviderId,
|
||||
this.runtimeModelId
|
||||
)
|
||||
const result = await this.providerService.analyzeImage(messages, {
|
||||
providerId: this.runtimeProviderId,
|
||||
modelId: this.runtimeModelId
|
||||
@@ -273,7 +299,7 @@ class ImageInsightService {
|
||||
heatScore
|
||||
}
|
||||
const cached = imageInsightsStore.getByHash(hash)
|
||||
if (cached) candidate.insight = cached
|
||||
if (isFreshImageInsight(cached) && cached) candidate.insight = cached
|
||||
candidates.push(candidate)
|
||||
}
|
||||
candidates.sort((a, b) => b.heatScore - a.heatScore)
|
||||
@@ -286,7 +312,6 @@ class ImageInsightService {
|
||||
listBySession(sessionId: string, limit?: number): ImageInsight[] {
|
||||
return imageInsightsStore.listBySession(sessionId, limit)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const imageInsightService = new ImageInsightService()
|
||||
@@ -0,0 +1,73 @@
|
||||
import { nativeImage } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import QRCode from 'qrcode'
|
||||
import type {
|
||||
PublishWechatShareCardRequest,
|
||||
PublishWechatShareCardResult
|
||||
} from '../shared/wechat-share-card'
|
||||
import { WechatShareConfigStore } from './wechat-share-config-store'
|
||||
|
||||
const MAX_REPORT_BYTES = 25 * 1024 * 1024
|
||||
|
||||
export class WechatShareCardService {
|
||||
constructor(private readonly configStore: WechatShareConfigStore) {}
|
||||
|
||||
async publish(request: PublishWechatShareCardRequest): Promise<PublishWechatShareCardResult> {
|
||||
try {
|
||||
const config = await this.configStore.loadRaw()
|
||||
if (!config) return { success: false, error: '请先配置微信卡片服务' }
|
||||
const png = await fs.readFile(request.pngPath)
|
||||
if (!png.length) return { success: false, error: '日报图片为空' }
|
||||
if (png.length > MAX_REPORT_BYTES) return { success: false, error: '日报图片不能超过 25 MB' }
|
||||
|
||||
const source = nativeImage.createFromBuffer(png)
|
||||
if (source.isEmpty()) return { success: false, error: '无法读取日报图片' }
|
||||
const size = source.getSize()
|
||||
const squareSize = Math.min(size.width, size.height)
|
||||
const thumbnail = source
|
||||
.crop({ x: 0, y: 0, width: squareSize, height: squareSize })
|
||||
.resize({ width: 360, height: 360, quality: 'best' })
|
||||
.toJPEG(84)
|
||||
|
||||
const response = await fetch(`${config.serviceUrl}/api/cards`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.uploadToken}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: request.title.trim().slice(0, 64),
|
||||
description: request.description.trim().slice(0, 120),
|
||||
expiresInDays: Math.max(1, Math.min(30, request.expiresInDays || 7)),
|
||||
imageBase64: png.toString('base64'),
|
||||
thumbnailBase64: thumbnail.toString('base64')
|
||||
}),
|
||||
signal: AbortSignal.timeout(90_000)
|
||||
})
|
||||
const payload = (await response.json().catch(() => ({}))) as {
|
||||
cardId?: string
|
||||
shareUrl?: string
|
||||
viewUrl?: string
|
||||
expiresAt?: string
|
||||
error?: string
|
||||
}
|
||||
if (!response.ok || !payload.shareUrl) {
|
||||
return { success: false, error: payload.error || `卡片服务返回 HTTP ${response.status}` }
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
cardId: payload.cardId,
|
||||
shareUrl: payload.shareUrl,
|
||||
viewUrl: payload.viewUrl,
|
||||
expiresAt: payload.expiresAt,
|
||||
qrCodeDataUrl: await QRCode.toDataURL(payload.shareUrl, {
|
||||
width: 360,
|
||||
margin: 2,
|
||||
errorCorrectionLevel: 'M'
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { app, safeStorage } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import type {
|
||||
WechatShareServiceConfig,
|
||||
WechatShareServiceConfigResult
|
||||
} from '../shared/wechat-share-card'
|
||||
|
||||
const normalizeUrl = (value: string): string => value.trim().replace(/\/+$/, '')
|
||||
|
||||
const validate = (config: WechatShareServiceConfig): string | null => {
|
||||
try {
|
||||
const url = new URL(normalizeUrl(config.serviceUrl))
|
||||
if (url.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(url.hostname)) {
|
||||
return '卡片服务必须使用 HTTPS'
|
||||
}
|
||||
} catch {
|
||||
return '卡片服务地址无效'
|
||||
}
|
||||
if (config.uploadToken.trim().length < 24) return '上传密钥至少需要 24 个字符'
|
||||
return null
|
||||
}
|
||||
|
||||
export class WechatShareConfigStore {
|
||||
private get filePath(): string {
|
||||
return path.join(app.getPath('userData'), 'wechat-share-service.bin')
|
||||
}
|
||||
|
||||
async loadRaw(): Promise<WechatShareServiceConfig | null> {
|
||||
if (!(await fs.pathExists(this.filePath))) return null
|
||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('系统安全存储不可用')
|
||||
const encrypted = await fs.readFile(this.filePath)
|
||||
const parsed = JSON.parse(safeStorage.decryptString(encrypted)) as WechatShareServiceConfig
|
||||
const error = validate(parsed)
|
||||
if (error) throw new Error(error)
|
||||
return { serviceUrl: normalizeUrl(parsed.serviceUrl), uploadToken: parsed.uploadToken.trim() }
|
||||
}
|
||||
|
||||
async status(): Promise<WechatShareServiceConfigResult> {
|
||||
try {
|
||||
const config = await this.loadRaw()
|
||||
return {
|
||||
success: true,
|
||||
configured: Boolean(config),
|
||||
serviceUrl: config?.serviceUrl
|
||||
}
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
async save(config: WechatShareServiceConfig): Promise<WechatShareServiceConfigResult> {
|
||||
const normalized = {
|
||||
serviceUrl: normalizeUrl(config.serviceUrl),
|
||||
uploadToken: config.uploadToken.trim()
|
||||
}
|
||||
const error = validate(normalized)
|
||||
if (error) return { success: false, error }
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return { success: false, error: '系统安全存储不可用' }
|
||||
}
|
||||
await fs.ensureDir(path.dirname(this.filePath))
|
||||
await fs.writeFile(this.filePath, safeStorage.encryptString(JSON.stringify(normalized)), {
|
||||
mode: 0o600
|
||||
})
|
||||
await fs.chmod(this.filePath, 0o600)
|
||||
return { success: true, configured: true, serviceUrl: normalized.serviceUrl }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user