yjbdcController.js 53 KB

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