yjbdcController.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. import moment from 'moment';
  2. import fs from 'fs';
  3. import { promises as fsPromises } from 'fs';
  4. import commonModel from '../../model/commonModel.js';
  5. import config from '../../config/index.js';
  6. import _ from 'lodash';
  7. import axios from 'axios';
  8. import { Encrypt, Decrypt } from '../../util/crypto/index.js';
  9. import { stringUtils } from '../../util/stringClass.js';
  10. import WXBizDataCrypt from '../../util/WXBizDataCrypt.js';
  11. import { globalCache } from '../../util/GlobalCache.js';
  12. import constantClass from '../../util/constant/index.js';
  13. import yjbdc from '../../model/yjbdc.js';
  14. import aiController from './aiController.js';
  15. import machineTranslationAPI from './machineTranslation.js';
  16. import PDFDocument from 'pdfkit';
  17. import tencentcloud from 'tencentcloud-sdk-nodejs-ocr';
  18. const OcrClient = tencentcloud.ocr.v20181119.Client;
  19. const ONE_DAY_MAX_BUILD_COUNT = 12;//一天最大生成数
  20. //AI生成文章
  21. export async function GenerateArticle(ctx) {
  22. const url = 'GenerateArticle?UserID=' + ctx.query.UserID;
  23. let result = globalCache.get(url);
  24. // 检查是否是队列状态而不是正在处理状态
  25. if (result && result.isQueued) {
  26. // 如果是队列状态,继续处理
  27. result = 0;
  28. }
  29. if (result === 0) {
  30. const params = ctx.request.body;
  31. const words = params.Words;
  32. let articleStyle = params.ArticleStyle;
  33. if (words) {
  34. //生成中
  35. result = { errcode: 10000, result: "-2" };
  36. globalCache.set(url, result, config.BufferMemoryTime);
  37. console.log("生成中,暂停生成60秒");
  38. const menuConfig = constantClass.GetYJBDCGenerateConfig();
  39. //console.log("content:"+content);
  40. let level = "";
  41. if (!params.Level || params.Level == "" || params.Level == undefined || params.Level >= "6") {
  42. params.Level = 0;
  43. }
  44. level = menuConfig.Level[Number(params.Level)].Name;
  45. let articleStyleContent = "";
  46. for (let i = 0; i < menuConfig.ArticleStyle.length; i++) {
  47. if (params.ArticleStyle == menuConfig.ArticleStyle[i].Name) {
  48. articleStyleContent = menuConfig.ArticleStyle[i].Content;
  49. }
  50. }
  51. //console.log("Level:"+level);
  52. let content = {
  53. "instruction": "用单词(" + words + ")生成" + level + "难度的文章。",
  54. "requirements": [
  55. "200-300词,要求:" + articleStyle + "(" + articleStyleContent + ")",
  56. "每句分数组提供中英双语,ArticleEnglish必须纯英文不含中文,ArticleChinese必须纯中文不含未翻译的英文单词",
  57. "所有单词至少出现一次(允许变形)",
  58. "生成5道四选一阅读题(含答案)",
  59. "提供用户单词在文中中文翻译",
  60. "所有字段必须完整出现,任何缺失需立即补全并维持原顺序,特别是Question中的所有字段(QuestionEnglish、QuestionChinese、OptionsEnglish、OptionsChinese、Answer)都必须存在"
  61. ],
  62. "output_format": {
  63. "ArticleEnglish": ["句子1", "句子2..."],
  64. "ArticleChinese": ["翻译1", "翻译2..."],
  65. "WordChinese": ["单词1:翻译1", "单词2:翻译2..."],
  66. "Question": [{
  67. "QuestionEnglish": "题干",
  68. "QuestionChinese": "题干翻译",
  69. "OptionsEnglish": ["A.选项", "B.选项", "C.选项", "D.选项"],
  70. "OptionsChinese": ["A.译", "B.译", "C.译", "D.译"],
  71. "Answer": "正确选项字母"
  72. }]
  73. }
  74. };
  75. content = JSON.stringify(content);
  76. // 从请求参数中获取AI提供者,如果没有指定则使用默认值
  77. let aiProvider = '';
  78. for (let i = 0; i < menuConfig.AIVersion.length; i++) {
  79. if (menuConfig.AIVersion[i].Version == params.AIVersion) {
  80. aiProvider = menuConfig.AIVersion[i].Model;
  81. break;
  82. }
  83. }
  84. //给用户一些比较好的体验
  85. // 按照权重概率分配AI提供商:40%概率使用ali-Moonshot-Kimi-K2-Instruct,60%概率使用doubao-kimi-k2-250711
  86. aiProvider = stringUtils.weightedRandom({
  87. // 'ali-Moonshot-Kimi-K2-Instruct': 40,
  88. // 'ali-Moonshot-Kimi-K2-Instruct': 60,
  89. //'doubao-deepseek-v3-250324': 100,
  90. //'doubao-kimi-k2-250711': 100,
  91. //'doubao-deepseek-v3-2-251201': 100,
  92. //'doubao-seed-1-8-251228': 100,
  93. 'doubao-1-5-lite-32k-250115':100,
  94. //'ali-Moonshot-kimi-k2.5': 100,
  95. });
  96. try {
  97. //开始时间
  98. let timeStart = new Date().getTime();
  99. // 使用aiController生成文章
  100. let result2 = await aiController.generateArticle(content, aiProvider);
  101. //console.log(result2);
  102. //debugger;
  103. // 校验和修复JSON结构
  104. result2 = aiController.validateAndFixJSON(result2);
  105. //console.log("JSON结构已校验和修复");
  106. result2 = aiController.normalizeArticleFields(result2);
  107. // 解析JSON以增强FormsOfWords
  108. const jsonObj = JSON.parse(result2);
  109. // 增强FormsOfWords,检测文章中单词的变形形式和拼写错误
  110. const enhancedJsonObj = aiController.enhanceFormsOfWords(jsonObj, words);
  111. // 再次确保中文句子被正确分类
  112. if (enhancedJsonObj.ArticleEnglish && Array.isArray(enhancedJsonObj.ArticleEnglish)) {
  113. const englishSentences = [];
  114. const chineseSentences = [];
  115. // 遍历ArticleEnglish数组,分离英文和中文句子
  116. enhancedJsonObj.ArticleEnglish.forEach(sentence => {
  117. // 检查句子是否包含中文字符
  118. if (/[\u4e00-\u9fa5]/.test(sentence)) {
  119. chineseSentences.push(sentence);
  120. } else {
  121. englishSentences.push(sentence);
  122. }
  123. });
  124. // 更新ArticleEnglish数组,只保留英文句子
  125. enhancedJsonObj.ArticleEnglish = englishSentences;
  126. // 如果ArticleChinese不存在或不是数组,则创建它
  127. if (!enhancedJsonObj.ArticleChinese || !Array.isArray(enhancedJsonObj.ArticleChinese)) {
  128. enhancedJsonObj.ArticleChinese = [];
  129. }
  130. // 将中文句子添加到ArticleChinese数组中
  131. chineseSentences.forEach(sentence => {
  132. if (!enhancedJsonObj.ArticleChinese.includes(sentence)) {
  133. enhancedJsonObj.ArticleChinese.push(sentence);
  134. }
  135. });
  136. }
  137. // 将增强后的对象转回JSON字符串
  138. result2 = JSON.stringify(enhancedJsonObj);
  139. //console.log("FormsOfWords已增强,添加了单词变形和拼写错误检测");
  140. // 记录增强后的单词数量
  141. if (enhancedJsonObj.FormsOfWords && Array.isArray(enhancedJsonObj.FormsOfWords)) {
  142. console.log(`增强了${enhancedJsonObj.FormsOfWords.length}个单词的变形形式`);
  143. }
  144. let timeEnd = new Date().getTime();
  145. let param2 = {};
  146. param2.UserID = ctx.query.UserID;
  147. param2.CreateTime = moment().format('YYYY-MM-DD HH:mm:ss');
  148. param2.Words = words;
  149. param2.Level = params.Level;
  150. param2.articleStyle = articleStyle;
  151. param2.AIProvider = aiProvider;
  152. param2.BuildStr = content;
  153. param2.GenerateTime = Math.round((timeEnd - timeStart) / 1000);
  154. console.log("生成时间:" + param2.GenerateTime + "秒");
  155. // 尝试解析JSON以获取ArticleStart
  156. const jsonObj2 = JSON.parse(result2);
  157. param2.ArticleStart = jsonObj2.ArticleEnglish && jsonObj2.ArticleEnglish.length > 0 ? jsonObj2.ArticleEnglish.join("\r\n") : "No content available";
  158. // 去除JSON字符串中的所有换行符(\r\n, \n, \r)
  159. param2.JSONString = JSON.stringify(result2.replace(/[\r\n]+/g, ''));
  160. param2.Flag = 0;
  161. let idInsert = await yjbdc.AddArticleInfo(param2);
  162. //result = { errcode: 10000, result: result2 };
  163. let result3 = {};
  164. result3.ID = idInsert.insertId;
  165. result3.Content = result2;
  166. result3.IsNew = true;
  167. result = { errcode: 10000, result: result3 };
  168. globalCache.delete(url);
  169. console.log("删除缓存,恢复生成");
  170. }
  171. catch (err) {
  172. console.error("AI生成错误:" + err);
  173. result = { errcode: 10000, result: "-1" };
  174. }
  175. }
  176. else {
  177. console.log("空单词串");
  178. result = { errcode: 10000, result: "-1" };
  179. }
  180. }
  181. ctx.body = result;
  182. }
  183. //小程序登录
  184. export async function YJBDCLogin(ctx) {
  185. let param = ctx.request.body;
  186. if (param.param) {
  187. const paramStr = Decrypt(param.param, config.urlSecrets.aes_key, config.urlSecrets.aes_iv);
  188. //console.log("paramStr:"+paramStr);
  189. param = JSON.parse(paramStr);
  190. }
  191. const code = param.Code;
  192. //console.log("code:"+code);
  193. const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wx.yjbdc_appid}&secret=${config.wx.yjbdc_appsecret}&js_code=${code}&grant_type=authorization_code`;
  194. let result = await axios.get(url)
  195. .then(res => {
  196. const json = res.data;
  197. //console.log("json:"+json);
  198. if (json && json.openid) {
  199. param.OpenID = json.openid;
  200. param.sessionKey = json.session_key;
  201. if (json.unionid)
  202. param.UnionID = json.unionid;
  203. return { errcode: 10000 };
  204. }
  205. else {
  206. return json;
  207. }
  208. })
  209. .catch(err => {
  210. return { errcode: 101, errStr: err };
  211. });
  212. if (result.errcode == 10000) {
  213. delete param.Code;
  214. if (param.sessionKey && param.iv && param.encryptedData) {
  215. //console.log("param.sessionKey:"+param.sessionKey);
  216. const pc = new WXBizDataCrypt(config.wx.yjbdc_appid, param.sessionKey);
  217. const dataUnionID = pc.decryptData(param.encryptedData, param.iv);
  218. //console.log(dataUnionID);
  219. param.UnionID = dataUnionID.unionId;
  220. }
  221. delete param.sessionKey;
  222. delete param.iv;
  223. delete param.encryptedData;
  224. //todo
  225. //param.OpenID="o4UHq4gaNlHfdTWxgl3fTgC1mFsI";
  226. let userList = await yjbdc.GetUsersInfo(param);
  227. if (userList.length > 0) {
  228. param.LastLoginTime = new Date();
  229. const time1 = moment(userList[0].ProductServiceTime).format('YYYY-MM-DD HH:mm:ss');
  230. const time3 = moment().format('YYYY-MM-DD HH:mm:ss');
  231. if (time1 < time3)
  232. param.IsMember = 0;
  233. delete param.Introducer;
  234. delete param.UserSource;
  235. delete param.SourceID;
  236. //console.log(param.NickName);
  237. if (param.NickName == "陌生用户") {
  238. delete param.NickName;
  239. delete param.AvatarUrl;
  240. delete param.Language;
  241. delete param.Gender;
  242. delete param.City;
  243. delete param.Province;
  244. delete param.Country;
  245. }
  246. await yjbdc.UpdateUsers(param);
  247. userList = await yjbdc.GetUsersInfo(param);
  248. }
  249. else {
  250. param.NickName = "陌生用户";
  251. param.AvatarUrl = "../images/userface_default.png";
  252. param.CreateTime = new Date();
  253. param.LastLoginTime = param.CreateTime;
  254. param.ProductServiceTime = param.CreateTime;
  255. const inseredID = await yjbdc.AddUsers(param);
  256. userList = await yjbdc.GetUsersInfo(param);
  257. }
  258. delete userList[0].OpenID;
  259. delete userList[0].UnionID;
  260. //产品支付是否显示
  261. if (param.ProgramVersion) {
  262. let param2 = {
  263. ProgramID: 186,
  264. Version: param.ProgramVersion,
  265. };
  266. let result3 = await commonModel.GetProductVersionList(param2);
  267. if (result3) {
  268. if ((param2.Version == result3[0].Version && result3[0].IsShowPay <= 0)
  269. || param2.Version > result3[0].Version) {
  270. userList[0].IsShow = result3[0].IsShowPay;
  271. }
  272. else {
  273. userList[0].IsShow = 1;
  274. }
  275. //针对iphone测试用户,永远是无支付状态
  276. if (userList[0].Brand == 'iPhone' && userList[0].WXLanguage == 'en-US'
  277. && userList[0].UserSource == '1001' && userList[0].IsPay == 0) {
  278. userList[0].IsShow = 0;
  279. }
  280. //针对微信测试用户,永远是无支付状态
  281. if ((userList[0].UserSource == '1001' && userList[0].System == "iOS 10.0.1")
  282. || (!userList[0].UserSource && (!userList[0].LastUserSource || userList[0].LastUserSource > 10000))
  283. || userList[0].NickName.indexOf("dgztest") >= 0) {
  284. userList[0].IsShow = -1;
  285. }
  286. if (userList[0].IsMember === 1)
  287. userList[0].IsShow = 1;
  288. }
  289. }
  290. result = { errcode: 10000, result: userList[0] };
  291. }
  292. ctx.body = result;
  293. }
  294. //OCR获取单词
  295. export async function OCRImageData(ctx) {
  296. const params = ctx.request.body;
  297. const clientConfig = {
  298. credential: {
  299. secretId: config.tencentcloud.secretId,
  300. secretKey: config.tencentcloud.secretKey,
  301. },
  302. region: "ap-guangzhou",
  303. profile: {
  304. httpProfile: {
  305. endpoint: "ocr.tencentcloudapi.com",
  306. },
  307. },
  308. };
  309. // 实例化要请求产品的client对象,clientProfile是可选的
  310. const client = new OcrClient(clientConfig);
  311. const result = await client.GeneralBasicOCR(params);
  312. let param2 = {};
  313. param2.UserID = ctx.query.UserID;
  314. param2.CreateTime = moment().format('YYYY-MM-DD HH:mm:ss');
  315. param2.Params = JSON.stringify(params);
  316. param2.JSONString = JSON.stringify(result);
  317. await yjbdc.AddOCRInfo(param2);
  318. ctx.body = { "errcode": 10000, result };
  319. }
  320. export async function GetYJBDCGenerateConfig(ctx) {
  321. const param = {
  322. UserID: ctx.query.UserID || 0,
  323. };
  324. let result = constantClass.GetYJBDCGenerateConfig();
  325. for (let i = 0; i < result.Level.length; i++) {
  326. delete result.Level[i].English;
  327. }
  328. for (let i = 0; i < result.ArticleStyle.length; i++) {
  329. delete result.ArticleStyle[i].English;
  330. delete result.ArticleStyle[i].Content;
  331. }
  332. if (param.UserID > 3) {
  333. result.AIVersion.splice(2, result.AIVersion.length - 2);
  334. if (param.UserID == 185) {
  335. const configArr = constantClass.GetYJBDCGenerateConfig();
  336. result.AIVersion.push(configArr.AIVersion[5]);
  337. }
  338. // if (param.UserID<4){
  339. // const configArr=constantClass.GetYJBDCGenerateConfig();
  340. // result.AIVersion.push(configArr.AIVersion[6]);
  341. // }
  342. }
  343. ctx.body = { "errcode": 10000, result: result };
  344. }
  345. //获得文章列表或具体文章
  346. export async function GetYJBDCArticleList(ctx) {
  347. const param = {
  348. UserID: ctx.query.UserID || 0,
  349. ID: ctx.query.ID || 0,
  350. IsFine: ctx.query.IsFine || 0,//是否是精选文章
  351. IsTodayCount: ctx.query.IsTodayCount || false,
  352. IsNew: ctx.query.IsNew || 0,
  353. PageID: ctx.query.PageID || 999999,
  354. PageCount: ctx.query.PageCount || 10,
  355. };
  356. if (param.IsFine)
  357. param.PageCount = 9999;
  358. // 尝试从缓存获取
  359. const url = 'GetYJBDCArticleList?IsFine=' + param.IsFine + '&UserID=' + param.UserID + '&ID=' + param.ID;
  360. let result = globalCache.get(url);
  361. if (param.IsNew == 1)
  362. result = 0;
  363. if (result === 0) {
  364. result = await yjbdc.GetYJBDCArticleList(param);
  365. let menuConfig = constantClass.GetYJBDCGenerateConfig();
  366. let recommendIndices = [];
  367. if (param.IsFine){
  368. // 随机选择三个不重复的索引用于今日推荐
  369. if (result.length > 3) {
  370. let n=0;
  371. while (recommendIndices.length < 3) {
  372. const randomIndex = Math.floor(Math.random() * (result.length - 4)) + 4; // 从第5条开始随机选择
  373. if (!recommendIndices.includes(randomIndex)) {
  374. recommendIndices.push(randomIndex);
  375. }
  376. n++;
  377. if (n>100000){
  378. break;
  379. }
  380. }
  381. } else {
  382. // 如果结果少于3个,全部标记为推荐
  383. for (let i = 0; i < result.length; i++) {
  384. recommendIndices.push(i);
  385. }
  386. }
  387. }
  388. for (let i = 0; i < result.length; i++) {
  389. let item = result[i];
  390. item.CreateTime = moment(item.CreateTime).format("YYYY年MM月DD日 HH:mm");
  391. //debugger;
  392. item.LevelStr = menuConfig.Level[item.Level].Name;
  393. // 添加今日推荐标记
  394. if (param.IsFine)
  395. item.IsRecommend = recommendIndices.includes(i);
  396. }
  397. globalCache.set(url, result, config.BufferMemoryTime);
  398. console.log("缓存" + config.BufferMemoryTime + "秒");
  399. }
  400. // console.log(result.length);
  401. if (param.IsTodayCount && !param.ID) {
  402. let count = 0, unReadCount = 0;
  403. const today = moment().format("YYYY年MM月DD日 00:00");
  404. for (let i = 0; i < result.length; i++) {
  405. if (result[i].CreateTime >= today)
  406. count++;
  407. if (result[i].Flag == 0 && result[i].ReadCount == 0)
  408. unReadCount++;
  409. }
  410. let maxcount = ONE_DAY_MAX_BUILD_COUNT;
  411. if (param.UserID < 4) {
  412. maxcount = 100;
  413. }
  414. result = {
  415. TodayCount: count,
  416. MaxCount: maxcount,
  417. UnReadCount: unReadCount,
  418. };
  419. }
  420. else if (!param.ID) {
  421. let arr = [], count = 0, total = 0;
  422. for (let i = 0; i < result.length; i++) {
  423. if (result[i].Flag == 0) {
  424. if (param.PageID > result[i].ID && count < param.PageCount) {
  425. arr.push(result[i]);
  426. count++;
  427. }
  428. total++;
  429. }
  430. }
  431. result = arr;
  432. if (result.length > 0)
  433. result[0].RowsCount = total;
  434. }
  435. // console.log(result.length);
  436. // console.log(result.TodayCount);
  437. ctx.body = { "errcode": 10000, result: result };
  438. }
  439. //删除生成的文章
  440. export async function DeleteYJBDCArticleList(ctx) {
  441. const param = {
  442. UserID: ctx.query.UserID || 0,
  443. ID: ctx.query.ID || 0,
  444. Flag: -1,
  445. };
  446. if (param.ID > 0) {
  447. const url = 'GetYJBDCArticleList?UserID=' + param.UserID + "&ID=0";
  448. globalCache.delete(url);
  449. await yjbdc.UpdateYJBDCArticle(param);
  450. }
  451. ctx.body = { "errcode": 10000 };
  452. }
  453. // 更新文章数据(目前仅用于网站)
  454. export async function UpdateYJBDCArticle(ctx) {
  455. const param = ctx.request.body;
  456. if (param.ID > 0 && param.UserID < 12 && param.Source == "web") {
  457. const url = 'GetYJBDCArticleList?IsFine=0&UserID=' + param.UserID + "&ID=0";
  458. globalCache.delete(url);
  459. const url2 = 'GetYJBDCArticleList?IsFine=0&UserID=' + param.UserID + "&ID=" + param.ID;
  460. globalCache.delete(url2);
  461. delete param.LevelStr;
  462. delete param.CreateTime;
  463. delete param.IsRecommend;
  464. await yjbdc.UpdateYJBDCArticle(param);
  465. }
  466. ctx.body = { "errcode": 10000 };
  467. }
  468. //更新阅读数
  469. export async function UpdateYJBDCArticleReadCount(ctx) {
  470. const param = {
  471. UserID: ctx.query.UserID || 0,
  472. ID: ctx.query.ID || 0,
  473. ReadCount: 1,
  474. };
  475. if (param.ID > 0) {
  476. await yjbdc.UpdateYJBDCArticle(param);
  477. }
  478. ctx.body = { "errcode": 10000 };
  479. }
  480. export async function AddOrDeleteYJBDCUserCollect(ctx) {
  481. const param = {
  482. UserID: ctx.query.UserID || 0,
  483. Word: ctx.query.Word || '',
  484. CreateTime: moment().format("YYYY-MM-DD HH:mm:ss"),
  485. };
  486. let list = await yjbdc.GetYJBDCUserCollect(param);
  487. if (list && list.length > 0)
  488. await yjbdc.DeleteYJBDCUserCollect(param);
  489. else
  490. await yjbdc.AddYJBDCUserCollect(param);
  491. let param2 = {}
  492. param2.UserID = param.UserID;
  493. let result = await yjbdc.GetYJBDCUserCollect(param2);
  494. ctx.body = { "errcode": 10000, result: result };
  495. }
  496. export async function DeleteYJBDCUserCollect(ctx) {
  497. const param = {
  498. UserID: ctx.query.UserID || 0,
  499. WordArr: ctx.query.WordArr || "",
  500. };
  501. let arr = param.WordArr.split(",");
  502. for (let i = 0; i < arr.length; i++) {
  503. let obj = {};
  504. obj.UserID = param.UserID;
  505. obj.Word = arr[i];
  506. await yjbdc.DeleteYJBDCUserCollect(obj);
  507. }
  508. let param2 = {}
  509. param2.UserID = param.UserID;
  510. let result = await yjbdc.GetYJBDCUserCollect(param2);
  511. ctx.body = { "errcode": 10000, result: result };
  512. }
  513. export async function GetYJBDCUserCollect(ctx) {
  514. const param = {
  515. UserID: ctx.query.UserID || 0,
  516. };
  517. let list = await yjbdc.GetYJBDCUserCollect(param);
  518. ctx.body = { "errcode": 10000, result: list };
  519. }
  520. //生成PDF
  521. export async function GeneratePDF(ctx) {
  522. const params = ctx.request.body;
  523. if (!params || !params.Content) {
  524. ctx.status = 400;
  525. ctx.body = { error: 'Invalid request body: Content is required' };
  526. return;
  527. }
  528. const content = params.Content;
  529. const menuConfig = constantClass.GetYJBDCGenerateConfig();
  530. try {
  531. // 创建新的 PDF 文档 - 使用A4尺寸
  532. const doc = new PDFDocument({
  533. size: 'A4', // 使用标准A4尺寸 (595.28 x 841.89 points)
  534. margins: {
  535. top: 0,
  536. bottom: 0,
  537. left: 0,
  538. right: 0
  539. },
  540. autoFirstPage: true
  541. });
  542. // 注册中文字体
  543. doc.registerFont('ChineseFont', './public/fonts/方正黑体简体.TTF');
  544. // 定义字体选择函数
  545. const selectFont = (text, defaultFont = 'Helvetica') => {
  546. if (/[\u4E00-\u9FFF]/.test(text)) {
  547. return 'ChineseFont';
  548. }
  549. return defaultFont;
  550. };
  551. // 收集生成的 PDF 数据
  552. const chunks = [];
  553. doc.on('data', (chunk) => chunks.push(chunk));
  554. // 像素到点(pt)的转换函数
  555. const pixelToPt = (pixel) => pixel * (595.28 / 2100);
  556. // 获取文章内容
  557. let articleText = "";
  558. if (content.ArticleEnglish) {
  559. articleText = Array.isArray(content.ArticleEnglish) ?
  560. content.ArticleEnglish.join(" ") : content.ArticleEnglish;
  561. } else {
  562. articleText = "No content available";
  563. }
  564. articleText = articleText.replace(/<[^>]*>/g, '');
  565. articleText = articleText.replace(/(^|[,.]\s+)'([^']+)'/g, '$1"$2"');
  566. // 获取单词列表
  567. let words = [];
  568. if (content.Words) {
  569. words = typeof content.Words === 'string' ?
  570. content.Words.split(",") :
  571. (Array.isArray(content.Words) ? content.Words : []);
  572. }
  573. // 获取问题列表
  574. let questions = [];
  575. if (content.Question && Array.isArray(content.Question)) {
  576. questions = content.Question;
  577. }
  578. let articleStyleArr = menuConfig.ArticleStyle;
  579. let articleStyle = "Story";
  580. for (let i = 0; i < articleStyleArr.length; i++) {
  581. if (articleStyleArr[i].Name == content.ArticleStyle) {
  582. articleStyle = articleStyleArr[i].English;
  583. break;
  584. }
  585. }
  586. // 1. 标题 - 文章类型
  587. doc.font(selectFont(articleStyle))
  588. .fontSize(pixelToPt(48))
  589. .text(articleStyle,
  590. pixelToPt(120), pixelToPt(110));
  591. // 2. 副标题 - 难度级别
  592. doc.font('Helvetica')
  593. .fontSize(pixelToPt(30))
  594. .text(menuConfig.Level[Number(content.Level)].English || "",
  595. pixelToPt(120), pixelToPt(170));
  596. // 3. 时间
  597. const currentDate = moment().format("YYYY年MM月DD日 HH:mm");
  598. if (params.CreateTime)
  599. currentDate = moment(params.CreateTime).format("YYYY年MM月DD日 HH:mm");
  600. doc.font('ChineseFont')
  601. .fontSize(pixelToPt(30))
  602. .text(currentDate,
  603. pixelToPt(120), pixelToPt(212));
  604. // 4. 黑线
  605. doc.rect(pixelToPt(120), pixelToPt(289), pixelToPt(537), pixelToPt(10))
  606. .fill('black');
  607. // 5. 单词列表
  608. doc.font('Helvetica')
  609. .fontSize(pixelToPt(36));
  610. let wordY = pixelToPt(364);
  611. words.slice(0, 10).forEach(word => {
  612. doc.text(word, pixelToPt(122), wordY, {
  613. width: pixelToPt(535),
  614. align: 'left'
  615. });
  616. wordY += pixelToPt(70);
  617. });
  618. // 6. 文章内容
  619. // 先计算文章内容的行数
  620. doc.font('Helvetica');
  621. // 使用48字号计算文本高度
  622. const fontSize48 = pixelToPt(48);
  623. doc.fontSize(fontSize48);
  624. const textHeight48 = doc.heightOfString(articleText, {
  625. width: pixelToPt(1240),
  626. lineGap: pixelToPt(40.5)
  627. });
  628. // 计算行数 (文本高度 / (字体大小 + 行间距))
  629. const lineHeight = fontSize48 + pixelToPt(40.5);
  630. const lineCount = Math.ceil(textHeight48 / lineHeight);
  631. // 如果行数超过18行,则使用42字号
  632. const fontSize = lineCount > 18 ? pixelToPt(42) : pixelToPt(48);
  633. // 渲染文章内容
  634. doc.fontSize(fontSize)
  635. .text(articleText, pixelToPt(740), pixelToPt(105), {
  636. width: pixelToPt(1240),
  637. lineGap: pixelToPt(40.5)
  638. });
  639. // 7. 黑线
  640. const articleEndY = doc.y;
  641. const wordListEndY = doc.y; // 假设单词列表的Y坐标
  642. const maxY = Math.max(articleEndY, wordListEndY);
  643. // 检查内容是否过长,需要分页
  644. const pageHeight = doc.page.height;
  645. const availableHeight = pageHeight - pixelToPt(400); // 预留底部空间
  646. const needsNewPage = articleEndY > availableHeight;
  647. if (doc && typeof doc.line === 'function') {
  648. doc.line(20, maxY, 200, maxY);
  649. }
  650. // 如果内容过长,则创建新页面
  651. if (needsNewPage) {
  652. // 在第一页底部添加提示
  653. doc.font('Helvetica')
  654. .fontSize(pixelToPt(24))
  655. .text("(Continued on next page...)",
  656. pixelToPt(740), pageHeight - pixelToPt(100), {
  657. align: 'center'
  658. });
  659. // 添加新页面
  660. doc.addPage();
  661. // 在新页面顶部添加标题
  662. doc.font(selectFont(articleStyle))
  663. .fontSize(pixelToPt(36))
  664. .text(articleStyle + " (Continued)",
  665. pixelToPt(120), pixelToPt(50));
  666. // 在新页面添加黑线
  667. doc.rect(pixelToPt(120), pixelToPt(100),
  668. pixelToPt(1860), pixelToPt(10))
  669. .fill('black');
  670. } else {
  671. // 如果不需要分页,正常添加黑线
  672. doc.rect(pixelToPt(120), articleEndY + pixelToPt(41),
  673. pixelToPt(1860), pixelToPt(10))
  674. .fill('black');
  675. }
  676. // 8-13. 问题和答案
  677. if (questions.length > 0) {
  678. // 定义问题的X坐标位置
  679. const questionXPositions = [
  680. pixelToPt(120), // 问题1
  681. pixelToPt(120), // 问题2
  682. pixelToPt(740), // 问题3
  683. pixelToPt(740), // 问题4
  684. pixelToPt(1360) // 问题5
  685. ];
  686. // 存储每列最后一个选项的Y坐标位置
  687. let lastOptionYPositions = {
  688. column1: 0, // 用于跟踪第一列(问题1)的最后位置
  689. column2: 0, // 用于跟踪第二列(问题3)的最后位置
  690. };
  691. // 确定问题的起始Y坐标
  692. // 如果内容过长需要分页,则在新页面上从固定位置开始
  693. // 否则在文章内容下方开始
  694. const questionsStartY = needsNewPage ?
  695. pixelToPt(150) : // 新页面上的起始位置
  696. articleEndY + pixelToPt(130); // 原页面上的起始位置
  697. // 首先渲染问题1、3、5(第一行问题)
  698. const firstRowQuestions = [0, 2, 4]; // 问题1、3、5的索引
  699. for (const i of firstRowQuestions) {
  700. if (i < questions.length && questions[i]) {
  701. const currentX = questionXPositions[i];
  702. const currentY = questionsStartY; // 使用计算出的起始Y坐标
  703. questions[i].QuestionEnglish = questions[i].QuestionEnglish.replace(/(^|[,.]\s+)'([^']+)'/g, '$1"$2"');
  704. // 渲染问题文本
  705. doc.font('Helvetica-Bold')
  706. .fontSize(pixelToPt(36))
  707. .text(`${i + 1}. ${questions[i].QuestionEnglish || `Question ${i + 1}`}`,
  708. currentX, currentY, {
  709. width: pixelToPt(540),
  710. align: 'left'
  711. });
  712. // 获取问题文本渲染后的Y坐标位置
  713. const questionEndY = doc.y;
  714. // 选项起始位置 = 问题结束位置 + 20像素间距
  715. let optionY = questionEndY + pixelToPt(28);
  716. // 渲染选项
  717. const options = questions[i].OptionsEnglish || [];
  718. const optionLabels = ['A', 'B', 'C', 'D'];
  719. // 设置选项标签宽度和选项总宽度
  720. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  721. const totalWidth = pixelToPt(496); // 选项的总宽度
  722. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  723. options.forEach((opt, index) => {
  724. if (index < optionLabels.length) {
  725. // 提取选项内容,移除可能存在的标签前缀
  726. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  727. // 渲染选项标签(A./B./C./D.)
  728. doc.font('Helvetica')
  729. .fontSize(pixelToPt(36))
  730. .text(`${optionLabels[index]}.`, currentX, optionY, {
  731. width: labelWidth,
  732. align: 'left'
  733. });
  734. // 渲染选项内容,确保折行时与内容第一行对齐
  735. doc.font('Helvetica')
  736. .fontSize(pixelToPt(36))
  737. .text(optionContent, currentX + labelWidth, optionY, {
  738. width: contentWidth,
  739. align: 'left'
  740. });
  741. // 更新选项Y坐标,为下一个选项做准备
  742. // 获取当前位置,确保下一个选项在当前选项完全渲染后的位置
  743. optionY = doc.y + pixelToPt(8);
  744. }
  745. });
  746. // 保存该列最后一个选项的Y坐标
  747. if (i === 0) {
  748. lastOptionYPositions.column1 = doc.y;
  749. } else if (i === 2) {
  750. lastOptionYPositions.column2 = doc.y;
  751. }
  752. }
  753. }
  754. // 然后渲染问题2和4(第二行问题)
  755. if (questions.length > 1 && questions[1]) {
  756. // 问题2位于问题1的选项下方60像素处
  757. const question2Y = lastOptionYPositions.column1 + pixelToPt(75);
  758. doc.font('Helvetica-Bold')
  759. .fontSize(pixelToPt(36))
  760. .text(`2. ${questions[1].QuestionEnglish || "Question 2"}`,
  761. questionXPositions[1], question2Y, {
  762. width: pixelToPt(540),
  763. align: 'left'
  764. });
  765. // 获取问题文本渲染后的Y坐标位置
  766. const questionEndY = doc.y;
  767. // 选项起始位置 = 问题结束位置 + 20像素间距
  768. let optionY = questionEndY + pixelToPt(28);
  769. // 渲染选项
  770. const options = questions[1].OptionsEnglish || [];
  771. const optionLabels = ['A', 'B', 'C', 'D'];
  772. // 设置选项标签宽度和选项总宽度
  773. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  774. const totalWidth = pixelToPt(496); // 选项的总宽度
  775. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  776. options.forEach((opt, index) => {
  777. if (index < optionLabels.length) {
  778. // 提取选项内容,移除可能存在的标签前缀
  779. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  780. // 渲染选项标签(A./B./C./D.)
  781. doc.font('Helvetica')
  782. .fontSize(pixelToPt(36))
  783. .text(`${optionLabels[index]}.`, questionXPositions[1], optionY, {
  784. width: labelWidth,
  785. align: 'left'
  786. });
  787. // 渲染选项内容,确保折行时与内容第一行对齐
  788. doc.font('Helvetica')
  789. .fontSize(pixelToPt(36))
  790. .text(optionContent, questionXPositions[1] + labelWidth, optionY, {
  791. width: contentWidth,
  792. align: 'left'
  793. });
  794. // 更新选项Y坐标,为下一个选项做准备
  795. optionY = doc.y + pixelToPt(8);
  796. }
  797. });
  798. }
  799. if (questions.length > 3 && questions[3]) {
  800. // 问题4位于问题3的选项下方60像素处
  801. const question4Y = lastOptionYPositions.column2 + pixelToPt(75);
  802. doc.font('Helvetica-Bold')
  803. .fontSize(pixelToPt(36))
  804. .text(`4. ${questions[3].QuestionEnglish || "Question 4"}`,
  805. questionXPositions[3], question4Y, {
  806. width: pixelToPt(540),
  807. align: 'left'
  808. });
  809. // 获取问题文本渲染后的Y坐标位置
  810. const questionEndY = doc.y;
  811. // 选项起始位置 = 问题结束位置 + 20像素间距
  812. let optionY = questionEndY + pixelToPt(28);
  813. // 渲染选项
  814. const options = questions[3].OptionsEnglish || [];
  815. const optionLabels = ['A', 'B', 'C', 'D'];
  816. // 设置选项标签宽度和选项总宽度
  817. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  818. const totalWidth = pixelToPt(496); // 选项的总宽度
  819. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  820. options.forEach((opt, index) => {
  821. if (index < optionLabels.length) {
  822. // 提取选项内容,移除可能存在的标签前缀
  823. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  824. // 渲染选项标签(A./B./C./D.)
  825. doc.font('Helvetica')
  826. .fontSize(pixelToPt(36))
  827. .text(`${optionLabels[index]}.`, questionXPositions[3], optionY, {
  828. width: labelWidth,
  829. align: 'left'
  830. });
  831. // 渲染选项内容,确保折行时与内容第一行对齐
  832. doc.font('Helvetica')
  833. .fontSize(pixelToPt(36))
  834. .text(optionContent, questionXPositions[3] + labelWidth, optionY, {
  835. width: contentWidth,
  836. align: 'left'
  837. });
  838. // 更新选项Y坐标,为下一个选项做准备
  839. optionY = doc.y + pixelToPt(8);
  840. }
  841. });
  842. }
  843. // 问题5
  844. if (questions.length > 4 && questions[4]) {
  845. const currentX = questionXPositions[4];
  846. // 如果分页,问题5的Y坐标与问题1和3相同
  847. const currentY = questionsStartY;
  848. doc.font('Helvetica-Bold')
  849. .fontSize(pixelToPt(36))
  850. .text(`5. ${questions[4].QuestionEnglish || "Question 5"}`,
  851. currentX, currentY, {
  852. width: pixelToPt(540),
  853. align: 'left'
  854. });
  855. const questionEndY = doc.y;
  856. let optionY = questionEndY + pixelToPt(28);
  857. // 渲染选项
  858. const options = questions[4].OptionsEnglish || [];
  859. const optionLabels = ['A', 'B', 'C', 'D'];
  860. // 设置选项标签宽度和选项总宽度
  861. const labelWidth = pixelToPt(40); // 标签(A./B./C./D.)的宽度
  862. const totalWidth = pixelToPt(496); // 选项的总宽度
  863. const contentWidth = totalWidth - labelWidth; // 选项内容的宽度
  864. options.forEach((opt, index) => {
  865. if (index < optionLabels.length) {
  866. // 提取选项内容,移除可能存在的标签前缀
  867. let optionContent = opt.replace(/^[A-D]\.\s*/, '');
  868. // 渲染选项标签(A./B./C./D.)
  869. doc.font('Helvetica')
  870. .fontSize(pixelToPt(36))
  871. .text(`${optionLabels[index]}.`, currentX, optionY, {
  872. width: labelWidth,
  873. align: 'left'
  874. });
  875. // 渲染选项内容,确保折行时与内容第一行对齐
  876. doc.font('Helvetica')
  877. .fontSize(pixelToPt(36))
  878. .text(optionContent, currentX + labelWidth, optionY, {
  879. width: contentWidth,
  880. align: 'left'
  881. });
  882. // 更新选项Y坐标,为下一个选项做准备
  883. optionY = doc.y + pixelToPt(8);
  884. }
  885. });
  886. }
  887. }
  888. // 14. 虚线
  889. // 计算虚线的位置 - 如果是分页,则在新页面上绘制
  890. const lastContentY = needsNewPage ?
  891. doc.page.height - pixelToPt(190) : // 新页面上的位置
  892. doc.page.height - pixelToPt(190); // 原页面上的位置
  893. doc.strokeColor('#D2D2D2')
  894. .dash(pixelToPt(20), { space: pixelToPt(28) }) // 设置虚线样式:宽20像素,间隔20像素
  895. .lineWidth(pixelToPt(10)) // 线高10像素
  896. .moveTo(pixelToPt(120), lastContentY)
  897. .lineTo(pixelToPt(120) + pixelToPt(1630), lastContentY)
  898. .stroke()
  899. .undash(); // 重置虚线样式
  900. // 15-19. 答案和底部信息
  901. doc.font('Helvetica-Bold') // 使用Helvetica-Bold作为Semibold替代
  902. .fontSize(pixelToPt(36))
  903. .fillColor('black'); // 重置颜色为黑色
  904. const answersY = doc.page.height - pixelToPt(144);
  905. // 获取问题答案
  906. const answers = [];
  907. if (questions.length > 0) {
  908. for (let i = 0; i < Math.min(questions.length, 5); i++) {
  909. const answer = questions[i].Answer || "";
  910. answers.push(`${i + 1}. ${answer}`);
  911. }
  912. }
  913. // 显示答案(如果存在)
  914. const answerPositions = [120, 262, 411, 561, 711];
  915. for (let i = 0; i < Math.min(answers.length, 5); i++) {
  916. doc.text(answers[i], pixelToPt(answerPositions[i]), answersY + 2, {
  917. width: pixelToPt(100),
  918. align: 'left'
  919. });
  920. }
  921. // 20-21. 应用名称
  922. doc.font('ChineseFont')
  923. .fontSize(pixelToPt(36))
  924. .text("语境背单词(微信小程序)", pixelToPt(1338), answersY, {
  925. width: pixelToPt(440),
  926. align: 'right'
  927. });
  928. // 添加二维码图片
  929. try {
  930. // 计算图片位置:距离右边120像素,距离底部100像素
  931. // 由于PDFKit使用左上角坐标系,需要计算左上角坐标
  932. const qrCodeWidth = pixelToPt(200);
  933. const qrCodeHeight = pixelToPt(200);
  934. const qrCodeX = doc.page.width - pixelToPt(120) - qrCodeWidth; // 右边距离转换为左边距离
  935. const qrCodeY = doc.page.height - pixelToPt(100) - qrCodeHeight; // 底部距离转换为顶部距离
  936. // 添加二维码图片
  937. doc.image('./public/images/acode/YJBDC_QRCode.png', qrCodeX, qrCodeY, {
  938. width: qrCodeWidth,
  939. height: qrCodeHeight
  940. });
  941. console.log("QR Code added successfully");
  942. } catch (imgError) {
  943. console.error("Error adding QR Code image:", imgError);
  944. }
  945. // 结束PDF生成
  946. doc.end();
  947. // 等待PDF生成完成
  948. const pdfBuffer = await new Promise((resolve) => {
  949. doc.on('end', () => {
  950. resolve(Buffer.concat(chunks));
  951. });
  952. });
  953. let filename = "语境背单词_" + moment().format("YYMMDD_HHmm");
  954. // 设置响应头
  955. ctx.set('Content-Type', 'application/pdf');
  956. // 使用ASCII文件名作为主文件名,确保兼容性
  957. const asciiFilename = 'yjbdc_' + moment().format("YYMMDD_HHmm") + '.pdf';
  958. // 对中文文件名进行URL编码,用于filename*参数
  959. const encodedFilename = encodeURIComponent(filename + '.pdf');
  960. // 设置Content-Disposition头部,使用标准格式
  961. // 首先提供ASCII文件名,然后提供UTF-8编码的文件名
  962. ctx.set('Content-Disposition', `attachment; filename=${asciiFilename}; filename*=UTF-8''${encodedFilename}`);
  963. ctx.body = pdfBuffer;
  964. } catch (error) {
  965. console.error("Error generating PDF:", error);
  966. ctx.status = 500;
  967. ctx.body = { error: "Failed to generate PDF" };
  968. }
  969. }
  970. //生成二维码
  971. export async function BuildYJBDCQRCode(ctx) {
  972. try {
  973. // 获取微信访问令牌
  974. const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${config.wx.yjbdc_appid}&secret=${config.wx.yjbdc_appsecret}&grant_type=client_credential`;
  975. const tokenResponse = await axios.get(tokenUrl);
  976. const tokenData = tokenResponse.data;
  977. if (!tokenData || !tokenData.access_token) {
  978. ctx.status = 400;
  979. ctx.body = { errcode: 101, errStr: '获取微信访问令牌失败' };
  980. return;
  981. }
  982. const accessToken = tokenData.access_token;
  983. // 生成小程序码
  984. const qrCodeUrl = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
  985. const path = './public/images/acode/';
  986. const imageUrl = 'YJBDC_QRCode.png';
  987. const fullPath = path + imageUrl;
  988. // 确保目录存在
  989. if (!fs.existsSync(path)) {
  990. fs.mkdirSync(path, { recursive: true });
  991. }
  992. const postData = {
  993. width: 280,
  994. scene: "SourceID=187"
  995. };
  996. // 使用axios获取二维码并保存到文件
  997. const qrCodeResponse = await axios({
  998. method: 'POST',
  999. url: qrCodeUrl,
  1000. data: postData,
  1001. responseType: 'stream'
  1002. });
  1003. // 创建写入流
  1004. const writer = fs.createWriteStream(fullPath);
  1005. // 将响应数据写入文件
  1006. qrCodeResponse.data.pipe(writer);
  1007. // 返回成功响应
  1008. ctx.body = { errcode: 10000, message: "二维码生成请求已发送" };
  1009. // 处理文件写入完成事件
  1010. writer.on('finish', () => {
  1011. console.log("二维码生成成功:", fullPath);
  1012. });
  1013. // 处理错误
  1014. writer.on('error', (err) => {
  1015. console.error("二维码文件写入失败:", err);
  1016. });
  1017. } catch (error) {
  1018. console.error("生成二维码失败:", error);
  1019. ctx.status = 500;
  1020. ctx.body = {
  1021. errcode: 500,
  1022. errStr: '生成二维码失败',
  1023. error: error.message
  1024. };
  1025. }
  1026. }
  1027. export async function GetWordChinese(ctx) {
  1028. const param = {
  1029. UserID: ctx.query.UserID || 0,
  1030. Word: ctx.query.Word || '',
  1031. Level: ctx.query.Level || '0'
  1032. };
  1033. if (!param.Word) {
  1034. ctx.body = { "errcode": 10001, "errStr": "单词不能为空" };
  1035. return;
  1036. }
  1037. // 使用单词作为缓存键,为每个单词单独缓存结果
  1038. const cacheKey = `GetWordChinese_${param.Word}_${param.Level}`;
  1039. let result = globalCache.get(cacheKey);
  1040. if (!result) {
  1041. // 缓存未命中,从数据库获取
  1042. result = await yjbdc.GetWordChinese(param);
  1043. // 如果没有找到结果,尝试查找单词的原形
  1044. if (!result || result.length === 0) {
  1045. // 使用stringUtils.getWordBaseForm获取可能的原形
  1046. const possibleBaseWords = stringUtils.getWordAllForms(param.Word);
  1047. // 尝试每个可能的原形
  1048. for (const baseWord of possibleBaseWords) {
  1049. //console.log(`尝试查找单词 ${param.Word} 的可能原形: ${baseWord}`);
  1050. const baseParam = { ...param, Word: baseWord };
  1051. const baseResult = await yjbdc.GetWordChinese(baseParam);
  1052. if (baseResult && baseResult.length > 0) {
  1053. //console.log(`找到单词 ${param.Word} 的原形 ${baseWord}`);
  1054. result = baseResult;
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. // 缓存结果,使用较长的过期时间,因为单词释义很少变化
  1060. if (result && result.length > 0) {
  1061. globalCache.set(cacheKey, result, config.BufferMemoryTimeHighBest);
  1062. //console.log(`缓存单词 ${param.Word} 的释义,7天有效期`);
  1063. }
  1064. }
  1065. // 根据Level筛选合适的单词释义
  1066. let selectedResult = null;
  1067. if (result && result.length > 0) {
  1068. // 将Level转换为数字
  1069. const level = parseInt(param.Level);
  1070. // 根据不同Level筛选结果
  1071. if (level >= 0 && level <= 2) {
  1072. // Level 0-2,返回数组单词第一条
  1073. const filtered = result.filter(item => item.BookID >= 151);
  1074. if (filtered.length > 0) {
  1075. selectedResult = filtered[0];
  1076. } else {
  1077. // 如果没有符合条件的,返回BookID较小的第一条
  1078. selectedResult = result[0];
  1079. }
  1080. } else if (level === 3) {
  1081. // Level 3,优选返回BookID >= 169的
  1082. const filtered = result.filter(item => item.BookID >= 169);
  1083. if (filtered.length > 0) {
  1084. selectedResult = filtered[0];
  1085. } else {
  1086. // 如果没有符合条件的,返回BookID较大的第一条
  1087. result.sort((a, b) => b.BookID - a.BookID);
  1088. selectedResult = result[0];
  1089. }
  1090. } else if (level === 4) {
  1091. // Level 4,优选返回BookID >= 173的
  1092. const filtered = result.filter(item => item.BookID >= 173);
  1093. if (filtered.length > 0) {
  1094. selectedResult = filtered[0];
  1095. } else {
  1096. // 如果没有符合条件的,返回BookID较大的第一条
  1097. result.sort((a, b) => b.BookID - a.BookID);
  1098. selectedResult = result[0];
  1099. }
  1100. } else if (level === 5) {
  1101. // Level 5,优选返回BookID >= 178的
  1102. const filtered = result.filter(item => item.BookID >= 178);
  1103. if (filtered.length > 0) {
  1104. selectedResult = filtered[0];
  1105. } else {
  1106. // 如果没有符合条件的,返回BookID较大的第一条
  1107. result.sort((a, b) => b.BookID - a.BookID);
  1108. selectedResult = result[0];
  1109. }
  1110. }
  1111. // 移除 BookID 字段
  1112. if (selectedResult) {
  1113. delete selectedResult.BookID;
  1114. }
  1115. }
  1116. ctx.body = { "errcode": 10000, result: selectedResult };
  1117. }
  1118. export async function GetWordDetail(ctx) {
  1119. const param = {
  1120. UserID: ctx.query.UserID || 0,
  1121. Word: ctx.query.Word || ''
  1122. };
  1123. if (!param.Word) {
  1124. ctx.body = { "errcode": 10001, "errStr": "单词不能为空" };
  1125. return;
  1126. }
  1127. // 使用单词作为缓存键,为每个单词单独缓存结果
  1128. const cacheKey = `GetWordDetail_${param.Word}`;
  1129. let result = globalCache.get(cacheKey);
  1130. if (!result) {
  1131. // 缓存未命中,从数据库获取
  1132. let url = "https://www.kylx365.com/api/GetMiaoguoAISearch2?Word=";
  1133. const tokenurl=url + param.Word;
  1134. result = await axios.get(tokenurl);
  1135. result=result.data.result;
  1136. // 如果没有找到结果,尝试查找单词的原形
  1137. if (!result || result.length === 0) {
  1138. // 使用stringUtils.getWordBaseForm获取可能的原形
  1139. const possibleBaseWords = stringUtils.getWordAllForms(param.Word);
  1140. // 尝试每个可能的原形
  1141. for (const baseWord of possibleBaseWords) {
  1142. //console.log(`尝试查找单词 ${param.Word} 的可能原形: ${baseWord}`);
  1143. const baseParam = { ...param, Word: baseWord };
  1144. const tokenurl=url + baseParam;
  1145. let baseResult = await axios.get(tokenurl);
  1146. baseResult=baseResult.data.result;
  1147. if (baseResult && baseResult.length > 0) {
  1148. //console.log(`找到单词 ${param.Word} 的原形 ${baseWord}`);
  1149. result = baseResult;
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. // 缓存结果,使用较长的过期时间,因为单词释义很少变化
  1155. if (result && result.length > 0) {
  1156. globalCache.set(cacheKey, result, config.BufferMemoryTimeHighBest);
  1157. //console.log(`缓存单词 ${param.Word} 的释义,7天有效期`);
  1158. }
  1159. }
  1160. ctx.body = { "errcode": 10000, result: result };
  1161. }
  1162. export async function YJBDC_Articles_Admin(ctx) {
  1163. //console.log("yjbdc_articles");
  1164. const data = await fsPromises.readFile("./public/mg/yjbdc_articles.html");
  1165. ctx.body = data.toString();
  1166. };
  1167. export async function GetSentenceTranslate(ctx) {
  1168. const url = 'GetSentenceTranslate?Sentence=' + encodeURIComponent(ctx.request.body.Sentence);
  1169. let result = globalCache.get(url);
  1170. // 检查是否是队列状态而不是正在处理状态
  1171. if (result && result.isQueued) {
  1172. // 如果是队列状态,继续处理
  1173. result = 0;
  1174. }
  1175. if (result) {
  1176. ctx.body = result;
  1177. return;
  1178. }
  1179. const param = ctx.request.body;
  1180. // 设置缓存,表示正在处理
  1181. result = { errcode: 10000, result: "-2" };
  1182. globalCache.set(url, result, config.BufferMemoryTime);
  1183. console.log("翻译中,暂存缓存");
  1184. try {
  1185. // 调用翻译API
  1186. const translationResult = await machineTranslationAPI.translateText(param.Sentence);
  1187. //console.log(translationResult);
  1188. result = { "errcode": 10000, result: translationResult.data };
  1189. // 更新缓存
  1190. globalCache.set(url, result, config.BufferMemoryTimeHigh);
  1191. console.log("翻译完成,更新缓存");
  1192. } catch (error) {
  1193. console.error("翻译出错:", error);
  1194. result = { "errcode": 10001, result: "翻译服务出错" };
  1195. // 删除缓存,允许重试
  1196. globalCache.delete(url);
  1197. }
  1198. ctx.body = result;
  1199. };