'use strict'; const Service = require('egg').Service; const crypto = require('crypto'); const https = require('https'); const OCR_HOST = 'ocr.tencentcloudapi.com'; const OCR_SERVICE = 'ocr'; const OCR_VERSION = '2018-11-19'; const OCR_ACTION = 'LicensePlateOCR'; const MAX_IMAGE_BYTES = 7 * 1024 * 1024; class LicensePlateService extends Service { /** * 获取腾讯云公共配置。 * * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, * 以保证历史配置方式仍然可用。 * * @return {Object} 腾讯云公共配置对象 */ getTencentCloudConfig() { const tencentCloudConfig = this.config.tencentCloud || {}; const cosConfig = this.config.cos || {}; return { appId: tencentCloudConfig.appId ?? cosConfig.appId, secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, }; } /** * 获取腾讯云 OCR 的默认区域。 * * @return {string} 腾讯云区域标识 */ getTencentCloudRegion() { const tencentCloudConfig = this.config.tencentCloud || {}; const cosConfig = this.config.cos || {}; return tencentCloudConfig.region || cosConfig.region || 'ap-guangzhou'; } /** * 规范化并校验 base64 图片。 * * @param {string} imageBase64 前端传入的 base64 图片 * @return {{ base64: string, buffer: Buffer, size: number }} 规范化后的图片信息 */ normalizeBase64Image(imageBase64) { const rawValue = String(imageBase64 || '').trim(); if (!rawValue) { throw new Error('base64 图片不能为空'); } const normalizedBase64 = rawValue .replace(/^data:[^;]+;base64,/i, '') .replace(/\s+/g, ''); if (!normalizedBase64) { throw new Error('base64 图片不能为空'); } if (!/^[A-Za-z0-9+/=]+$/.test(normalizedBase64)) { throw new Error('base64 图片格式不正确'); } const buffer = Buffer.from(normalizedBase64, 'base64'); if (!buffer.length) { throw new Error('base64 图片解码失败'); } if (buffer.length > MAX_IMAGE_BYTES) { throw new Error('图片大小不能超过 7MB'); } const normalizedWithoutPadding = normalizedBase64.replace(/=+$/u, ''); const roundTripWithoutPadding = buffer.toString('base64').replace(/=+$/u, ''); if (normalizedWithoutPadding !== roundTripWithoutPadding) { throw new Error('base64 图片格式不正确'); } return { base64: normalizedBase64, buffer, size: buffer.length, }; } /** * 生成腾讯云 TC3 请求签名。 * * @param {Object} options 请求参数 * @param {string} options.action 腾讯云动作名 * @param {string} options.service 腾讯云服务名 * @param {string} options.version 腾讯云接口版本 * @param {string} options.region 腾讯云区域 * @param {Object} options.payload 请求体 * @return {{ requestOptions: Object, payloadString: string }} 请求配置 */ buildTencentCloudRequest({ action, service, version, region, payload }) { const { secretId, secretKey } = this.getTencentCloudConfig(); if (!secretId || !secretKey) { throw new Error('腾讯云密钥未配置'); } const timestamp = Math.floor(Date.now() / 1000); const date = new Date(timestamp * 1000).toISOString().slice(0, 10); const payloadString = JSON.stringify(payload || {}); const hashedRequestPayload = crypto.createHash('sha256').update(payloadString).digest('hex'); const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${OCR_HOST}\n`; const signedHeaders = 'content-type;host'; const canonicalRequest = [ 'POST', '/', '', canonicalHeaders, signedHeaders, hashedRequestPayload, ].join('\n'); const credentialScope = `${date}/${service}/tc3_request`; const stringToSign = [ 'TC3-HMAC-SHA256', timestamp, credentialScope, crypto.createHash('sha256').update(canonicalRequest).digest('hex'), ].join('\n'); const secretDate = crypto.createHmac('sha256', `TC3${secretKey}`).update(date).digest(); const secretService = crypto.createHmac('sha256', secretDate).update(service).digest(); const secretSigning = crypto.createHmac('sha256', secretService).update('tc3_request').digest(); const signature = crypto.createHmac('sha256', secretSigning).update(stringToSign).digest('hex'); const authorization = `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; return { payloadString, requestOptions: { hostname: OCR_HOST, method: 'POST', path: '/', headers: { Authorization: authorization, 'Content-Type': 'application/json; charset=utf-8', Host: OCR_HOST, 'X-TC-Action': action, 'X-TC-Version': version, 'X-TC-Timestamp': String(timestamp), 'X-TC-Region': region, }, }, }; } /** * 发送腾讯云请求并解析 JSON 响应。 * * @param {Object} requestConfig 请求配置 * @param {Object} requestConfig.requestOptions https 请求参数 * @param {string} requestConfig.payloadString 请求体字符串 * @return {Promise} 腾讯云响应对象 */ async sendTencentCloudRequest(requestConfig) { const { requestOptions, payloadString } = requestConfig; const responseText = await new Promise((resolve, reject) => { const request = https.request(requestOptions, response => { response.setEncoding('utf8'); let responseBody = ''; response.on('data', chunk => { responseBody += chunk; }); response.on('end', () => { resolve(responseBody); }); }); request.on('error', reject); request.setTimeout(30000, () => { request.destroy(new Error('腾讯云车牌识别请求超时')); }); request.write(payloadString); request.end(); }); let parsedResponse; try { parsedResponse = JSON.parse(responseText); } catch (error) { throw new Error(`腾讯云响应解析失败: ${error.message}`); } const responsePayload = parsedResponse && parsedResponse.Response ? parsedResponse.Response : parsedResponse; if (responsePayload && responsePayload.Error) { const { Code = 'TencentCloudError', Message = '腾讯云接口调用失败' } = responsePayload.Error; throw new Error(`${Code}: ${Message}`); } return parsedResponse; } /** * 识别车牌号码。 * * @param {string} imageBase64 前端传入的 base64 图片 * @return {Promise} 车牌识别结果 */ async recognizeLicensePlate(imageBase64) { const { base64 } = this.normalizeBase64Image(imageBase64); const region = this.getTencentCloudRegion(); const requestConfig = this.buildTencentCloudRequest({ action: OCR_ACTION, service: OCR_SERVICE, version: OCR_VERSION, region, payload: { ImageBase64: base64, }, }); const response = await this.sendTencentCloudRequest(requestConfig); return this.formatLicensePlateResult(response); } /** * 统一整理腾讯云车牌识别响应。 * * @param {Object} response 腾讯云响应 * @return {Object} 归一化后的识别结果 */ formatLicensePlateResult(response) { const responseData = response && response.Response ? response.Response : response || {}; const licensePlate = String( responseData.LicensePlate || responseData.Number || responseData.PlateNumber || responseData.CarPlateNumber || '' ).trim(); return { licensePlate, }; } } module.exports = LicensePlateService;