yjbdcController.js 41 KB

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