GenPDFService.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. using Azure.Messaging.ServiceBus;
  2. using Azure.Storage.Blobs.Models;
  3. using Microsoft.Azure.Cosmos;
  4. using StackExchange.Redis;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http;
  12. using System.Net.Http.Json;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Text.Json.Nodes;
  16. using System.Threading.Tasks;
  17. using System.Web;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.Extension;
  20. using static TEAMModelOS.SDK.CoreAPIHttpService;
  21. using TEAMModelOS.SDK.Models;
  22. using Microsoft.Extensions.Configuration;
  23. using System.Net.Http.Headers;
  24. using Azure.Storage.Sas;
  25. using TEAMModelOS.SDK.Models.Service;
  26. using Azure.Core;
  27. using TEAMModelOS.SDK.Models.Cosmos.Common;
  28. using System.Configuration;
  29. using Google.Protobuf.WellKnownTypes;
  30. namespace TEAMModelOS.SDK
  31. {
  32. public static class GenPDFService
  33. {
  34. public static async Task GenPdf( AzureRedisFactory _azureRedis, AzureCosmosFactory _azureCosmos,
  35. IConfiguration _configuration, IHttpClientFactory _httpClient, AzureStorageFactory _azureStorage,
  36. DingDing _dingDing, SnowflakeId _snowflakeId,string json )
  37. {
  38. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  39. Console.WriteLine($"開始:{now}");
  40. string apiUri = "http://52.130.252.100:13000";
  41. PDFGenQueue genQueueData =json.ToObject<PDFGenQueue>();
  42. RedisValue redisValue = await _azureRedis.GetRedisClient(8).HashGetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id);
  43. PDFGenRedis genRedis = null;
  44. if (redisValue!=default)
  45. {
  46. genRedis = redisValue.ToString().ToObject<PDFGenRedis>();
  47. //计算等待了多久的时间才开始生成。
  48. var wait = now- genRedis.join;
  49. genRedis.wait = wait;
  50. genRedis.status= 1;
  51. await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
  52. var client = _httpClient.CreateClient();
  53. ///再加5秒
  54. client.Timeout= TimeSpan.FromMilliseconds(genQueueData.timeout+ genQueueData.delay+5000);
  55. try
  56. {
  57. string urlpdf = $"{apiUri}/api/pdf";
  58. string jsonElement = new
  59. {
  60. pageUrl = genQueueData.pageUrl,
  61. timeout = genQueueData.timeout,
  62. delay = genQueueData.delay,
  63. checkPageCompleteJs = genQueueData.checkPageCompleteJs
  64. }.ToJsonString();
  65. var request = new HttpRequestMessage
  66. {
  67. Method = new HttpMethod("POST"),
  68. RequestUri = new Uri(urlpdf),
  69. Content = new StringContent(jsonElement)
  70. };
  71. var mediaTypeHeader = new MediaTypeHeaderValue("application/json")
  72. {
  73. CharSet = "UTF-8"
  74. };
  75. request.Content.Headers.ContentType = mediaTypeHeader;
  76. HttpResponseMessage responseMessage = await client.SendAsync(request);
  77. if (responseMessage.IsSuccessStatusCode)
  78. {
  79. string content = await responseMessage.Content.ReadAsStringAsync();
  80. JsonNode jsonNode = content.ToObject<JsonNode>();
  81. var code = jsonNode["code"];
  82. var file = jsonNode["data"]?["file"];
  83. if (code!=null && $"{code}".Equals("0") && file!= null && !string.IsNullOrWhiteSpace($"{file}"))
  84. {
  85. try
  86. {
  87. Stream stream = await client.GetStreamAsync($"{apiUri}/{file}");
  88. Uri uri = new Uri(genQueueData.pageUrl);
  89. var query = HttpUtility.ParseQueryString(uri.Query);
  90. string? url = query["url"];
  91. if (!string.IsNullOrWhiteSpace(url))
  92. {
  93. url= HttpUtility.UrlDecode(url);
  94. uri = new Uri(url);
  95. string host = uri.Host;
  96. var blobServiceClient = _azureStorage.GetBlobServiceClient();
  97. if (blobServiceClient.Uri.Host.Equals(host))
  98. {
  99. // 获取容器名,它是路径的第一个部分
  100. string containerName = uri.Segments[1].TrimEnd('/');
  101. // 获取文件的完整同级目录,这是文件路径中除了文件名和扩展名之外的部分
  102. // 由于文件名是路径的最后一个部分,我们可以通过连接除了最后一个部分之外的所有部分来获取目录路径
  103. string directoryPath = string.Join("", uri.Segments, 2, uri.Segments.Length - 3);
  104. string? fileName = Path.GetFileNameWithoutExtension(uri.AbsolutePath);
  105. string blobPath = $"{directoryPath}{fileName}.pdf";
  106. var blockBlob = _azureStorage.GetBlobContainerClient(containerName).GetBlobClient(blobPath);
  107. string content_type = "application/octet-stream";
  108. ContentTypeDict.dict.TryGetValue(".pdf", out string? contenttype);
  109. if (!string.IsNullOrEmpty(contenttype))
  110. {
  111. content_type = contenttype;
  112. }
  113. await blockBlob.UploadAsync(stream, true);
  114. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  115. genRedis.blob= blockBlob.Name;
  116. genRedis.status=2;
  117. }
  118. else
  119. {
  120. genRedis.status=6;
  121. }
  122. }
  123. else
  124. {
  125. genRedis.status=6;
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json}", GroupNames.醍摩豆服務運維群組);
  131. genRedis.status=6;
  132. }
  133. }
  134. else
  135. {
  136. if (code!= null && $"{code}".Equals("99999"))
  137. {
  138. genRedis.status= 4;
  139. }
  140. else
  141. {
  142. genRedis.status= 3;
  143. }
  144. }
  145. }
  146. else
  147. {
  148. genRedis.status= 3;
  149. }
  150. }
  151. catch (TaskCanceledException ex)
  152. {
  153. if (ex.CancellationToken.IsCancellationRequested)
  154. {
  155. // Console.WriteLine("请求被取消。");
  156. genRedis.status= 5;
  157. }
  158. else
  159. {
  160. //Console.WriteLine("请求超时。");
  161. genRedis.status= 4;
  162. }
  163. }
  164. catch (Exception ex)
  165. {
  166. genRedis.status=3;
  167. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json}", GroupNames.醍摩豆服務運維群組);
  168. }
  169. }
  170. else
  171. {
  172. genRedis= new PDFGenRedis { id =genQueueData.id, status= 5, cost=0, join=now, wait=0, name= genQueueData.name };
  173. //被取消的
  174. }
  175. long nowNew = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  176. genRedis.cost=nowNew-now;
  177. await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
  178. //如果全部 生成,需要发送通知
  179. HashEntry[] datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"PDFGen:{genQueueData.sessionId}");
  180. List<PDFGenRedis> dbgenRedis = new List<PDFGenRedis>();
  181. List<string> notifyUsers = new List<string>();
  182. string taskName = string.Empty;
  183. string taskType = string.Empty;
  184. if (datas!= null && datas.Length > 0)
  185. {
  186. foreach (var item in datas)
  187. {
  188. if (!$"{item.Name}".Contains("notifyUsers"))
  189. {
  190. dbgenRedis.Add(item.Value.ToString().ToObject<PDFGenRedis>());
  191. }
  192. else
  193. {
  194. var jsonData = item.Value.ToString().ToObject<JsonElement>();
  195. notifyUsers= jsonData.GetProperty("notifyUsers").ToObject<List<string>>();
  196. taskType = jsonData.GetProperty("taskType").ToString();
  197. taskName = jsonData.GetProperty("taskName").ToString();
  198. }
  199. }
  200. }
  201. if (notifyUsers.IsNotEmpty())
  202. {
  203. string lang = Environment.GetEnvironmentVariable("Option:Location")!.Contains("China") ? "zh-cn" : "en-us";
  204. string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", notifyUsers.Select(x => $"'{x}'"))})";
  205. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  206. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  207. .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  208. {
  209. idNameCodes.Add(item);
  210. }
  211. idNameCodes.FindAll(x => string.IsNullOrWhiteSpace(x.code) || (!x.code.Equals("zh-cn") && !x.code.Equals("zh-tw") && !x.code.Equals("en-us"))).ForEach(x => { x.code = lang; });
  212. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  213. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  214. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  215. string location = "China";
  216. if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("China"))
  217. {
  218. location = "China";
  219. }
  220. else if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("Global"))
  221. {
  222. location = "Global";
  223. }
  224. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
  225. var client = _httpClient.CreateClient();
  226. if (client.DefaultRequestHeaders.Contains("Authorization"))
  227. {
  228. client.DefaultRequestHeaders.Remove("Authorization");
  229. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  230. }
  231. else
  232. {
  233. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  234. }
  235. //检查dbgenRedis的状态是否全部已经不是0和1
  236. var unfinished = dbgenRedis.FindAll(x => (x.status==0||x.status==1));
  237. if (unfinished==null || unfinished.Count==0)
  238. {
  239. // 数据大于60一个班,发送报告的总耗时等概要信息, 小于60的发送 生成报告的细则消息,小于五个的,可以列出报告的链接.
  240. long joinTime = dbgenRedis.Min(x => x.join);
  241. long totalTime = (now-joinTime)/1000;
  242. long costTime = dbgenRedis.Sum(x => x.cost)/1000;
  243. long avgTime = costTime / dbgenRedis.Count;
  244. long maxTime = dbgenRedis.Max(x => x.cost)/1000;
  245. long minTime = dbgenRedis.Min(x => x.cost)/1000;
  246. long statusOk = dbgenRedis.Where(x => x.status==2).Count();
  247. long statusFailed = dbgenRedis.Where(x => x.status!=2).Count();
  248. string key = "pdf-gen-notify-higher60";
  249. if (dbgenRedis.Count>60)
  250. {
  251. key = "pdf-gen-notify-higher60";
  252. }
  253. else
  254. {
  255. key ="pdf-gen-notify-below60";
  256. }
  257. foreach (var teacher in idNameCodes)
  258. {
  259. string path = Path.Combine("", $"Lang/{teacher.code}.json");
  260. var sampleJson = File.ReadAllText(path);
  261. JsonElement jsonElement = sampleJson.ToObject<JsonElement>();
  262. JsonElement msgsJson = jsonElement.GetProperty(key);
  263. List<string> msgs = msgsJson.ToObject<List<string>>();
  264. string msg1 = msgs[1].Replace("{tmdname}", teacher.name).Replace("{taskName}", taskName).Replace("{totalTime}", $"{totalTime}")
  265. .Replace("{avgTime}", $"{avgTime}").Replace("{maxTime}", $"{maxTime}").Replace("{minTime}", $"{minTime}").Replace("{statusOk}", $"{statusOk}").Replace("{statusFailed}", $"{statusFailed}");
  266. StringBuilder sb = new StringBuilder($"{msg1}");
  267. if (dbgenRedis.Count<=60)
  268. {
  269. string status = string.Empty;
  270. dbgenRedis.ForEach(x => {
  271. switch (x.status)
  272. {
  273. case 0:
  274. status= teacher.code.Equals("zh-cn") ? "未执行" : teacher.code.Equals("zh-tw") ? "未執行" : "unexecuted";
  275. break;
  276. case 1:
  277. status= teacher.code.Equals("zh-cn") ? "执行中" : teacher.code.Equals("zh-tw") ? "執行中" : "executing";
  278. break;
  279. case 2:
  280. status= teacher.code.Equals("zh-cn") ? "成功" : teacher.code.Equals("zh-tw") ? "成功" : "success";
  281. break;
  282. case 3:
  283. status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
  284. break;
  285. case 4:
  286. status= teacher.code.Equals("zh-cn") ? "超时" : teacher.code.Equals("zh-tw") ? "超時" : "timeout";
  287. break;
  288. case 5:
  289. status= teacher.code.Equals("zh-cn") ? "取消" : teacher.code.Equals("zh-tw") ? "取消" : "canceled";
  290. break;
  291. case 6:
  292. status= teacher.code.Equals("zh-cn") ? "存放异常" : teacher.code.Equals("zh-tw") ? "存放異常" : "SaveError";
  293. break;
  294. default:
  295. status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
  296. break;
  297. }
  298. string msg2 = msgs[2].Replace("{studentName}", x.name).Replace("{status}", $"{status}").Replace("{wait}", $"{x.wait/1000}").Replace("{cost}", $"{x.cost/1000}").Replace("{total}", $"{(x.wait+x.cost)/1000}");
  299. sb.Append(msg2);
  300. });
  301. }
  302. NotifyData notifyData = new NotifyData
  303. {
  304. hubName = "hita5",
  305. sender = "IES",
  306. tags = new List<string> { $"{teacher.id}_{Constant.NotifyType_IES5_Course}" },
  307. title = msgs[0],
  308. eventId = $"{key}_{_snowflakeId.NextId()}",
  309. eventName =msgs[0],
  310. data = "{\"value\":{}}",
  311. body=sb.ToString(),
  312. };
  313. string result = "";
  314. try
  315. {
  316. HttpResponseMessage responseMessage = await client.PostAsJsonAsync($"{url}/service/PushNotify", notifyData);
  317. if (responseMessage.StatusCode == HttpStatusCode.OK)
  318. {
  319. string content = await responseMessage.Content.ReadAsStringAsync();
  320. result = content;
  321. }
  322. else
  323. {
  324. result = $"{responseMessage.StatusCode},推送返回的状态码。";
  325. }
  326. }
  327. catch (Exception exm)
  328. {
  329. _= _dingDing.SendBotMsg($"{location}站点发送消息异常,{exm.Message}\n{exm.StackTrace}:\n{url}/service/PushNotify \nheader: {token.AccessToken} \nresult:{result}\n params:{notifyData.ToJsonString()}", GroupNames.成都开发測試群組);
  330. }
  331. }
  332. }
  333. }
  334. Console.WriteLine($"結束:{now}");
  335. return;
  336. }
  337. /// <summary>
  338. /// 加入PDF生成队列服务
  339. /// https://github.com/wuxue107/bookjs-eazy https://github.com/wuxue107/screenshot-api-server
  340. /// </summary>
  341. /// <param name="azureRedis"></param>
  342. /// <param name="data"></param>
  343. /// <returns></returns>
  344. public static async Task<(int total,int add )> AddGenPdfQueue( AzureRedisFactory azureRedis, GenPDFData data,ClientDevice device)
  345. {
  346. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  347. List<PDFGenRedis> genRedis = new List<PDFGenRedis>();
  348. List<PDFGenRedis> dbgenRedis = new List<PDFGenRedis>();
  349. HashEntry[] datas = await azureRedis.GetRedisClient(8).HashGetAllAsync($"PDFGen:{data.sessionId}");
  350. List<string> notifyUsers = new List<string>();
  351. if (datas!= null && datas.Length > 0)
  352. {
  353. foreach (var item in datas)
  354. {
  355. if (!$"{item.Name}".Contains("notifyUsers"))
  356. {
  357. dbgenRedis.Add(item.Value.ToString().ToObject<PDFGenRedis>());
  358. }
  359. else {
  360. var json = item.Value.ToString().ToObject<JsonElement>();
  361. notifyUsers= json.GetProperty("notifyUsers").ToObject<List<string>>();
  362. }
  363. }
  364. }
  365. if (data.notifyUsers.IsNotEmpty())
  366. {
  367. notifyUsers.AddRange(data.notifyUsers);
  368. notifyUsers= notifyUsers.Distinct().ToList();
  369. }
  370. var dataVal = new GenPDFSchema { notifyUsers= notifyUsers, taskName= data.taskName, taskType = data.taskType };
  371. //Redis记录需要通知的用户
  372. await azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{data.sessionId}", "notifyUsers",JsonSerializer.Serialize(dataVal));
  373. //Redis记录需要生成PDF的数量
  374. int countProcess= 0;
  375. foreach (var item in data.datas)
  376. {
  377. var dbData = dbgenRedis.Find(x => x.id.Equals(item.id));
  378. if (dbData!=null)
  379. {
  380. //if (dbData.status==0|| dbData.status==1)
  381. //{
  382. // //不变的
  383. // countProcess+=1;
  384. //}
  385. //else
  386. {
  387. //需要变更的
  388. dbData.status = 0;
  389. dbData.cost=0;
  390. dbData.join= now;
  391. dbData.wait=0;
  392. dbData.name=item.name;
  393. dbData.url= item.url;
  394. dbData.scope = data.scope;
  395. dbData.owner= data.owner;
  396. dbData.env= data.env;
  397. genRedis.Add(dbData);
  398. }
  399. }
  400. else {
  401. genRedis.Add(new PDFGenRedis {
  402. id = item.id,
  403. status=0,
  404. cost=0,
  405. wait=0,
  406. join=now,
  407. name=item.name,
  408. url= item.url,
  409. scope=data.scope,
  410. owner= data.owner,
  411. env= data.env,
  412. });
  413. }
  414. }
  415. //过期时间 当前个数+ reddis的个数
  416. foreach (var item in genRedis)
  417. {
  418. countProcess+=1;
  419. await azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{data.sessionId}", item.id, item.ToJsonString());
  420. PDFGenQueue genQueue = new PDFGenQueue
  421. {
  422. id = item.id,
  423. checkPageCompleteJs= data.checkPageCompleteJs,
  424. delay=data.delay,
  425. html= data.html,
  426. pageUrl= $"{data.pageUrl}?url={HttpUtility.UrlEncode(item.url)}",
  427. sessionId= data.sessionId,
  428. timeout =data.timeout,
  429. name=item.name,
  430. env= data.env,
  431. };
  432. //string message = JsonSerializer.Serialize(genQueue);
  433. //从头部压入元素,队列先进先出
  434. await azureRedis.GetRedisClient(8).ListLeftPushAsync($"PDFGen:Queue:{device.deviceId}", genQueue.ToJsonString());
  435. //var serviceBusMessage = new ServiceBusMessage(message);
  436. //serviceBusMessage.ApplicationProperties.Add("name", "BlobRoot");
  437. //await azureServiceBus.GetServiceBusClient().SendMessageAsync("dep-genpdf", serviceBusMessage);
  438. }
  439. long expire = (data.delay + data.timeout) * countProcess+30*60*1000;
  440. var tiemSpan = TimeSpan.FromMilliseconds(expire);
  441. await azureRedis.GetRedisClient(8).KeyExpireAsync($"PDFGen:{data.sessionId}", tiemSpan);
  442. return ( countProcess , genRedis.Count() );
  443. }
  444. public static async Task<(List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults, ArtEvaluation art)> GenArtStudentPdf( AzureRedisFactory _azureRedis, AzureCosmosFactory _azureCosmos,
  445. CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, AzureStorageFactory _azureStorage, IConfiguration _configuration, List<string> studentIds,string _artId,string _schoolId,string headLang)
  446. {
  447. try
  448. {
  449. string _schoolCode = $"{_schoolId}";
  450. ArtEvaluation art = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ArtEvaluation>($"{_artId}", new PartitionKey($"Art-{_schoolId}"));
  451. (List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults) = await ArtService.GenStuArtPDF(studentIds, $"{_artId}", art, $"{_schoolId}", $"{headLang}", _azureCosmos, _coreAPIHttpService, _dingDing);
  452. foreach (var artResult in artResults)
  453. {
  454. if (artResult.pdf == null || string.IsNullOrWhiteSpace(artResult.pdf.blob) || string.IsNullOrWhiteSpace(artResult.pdf.url))
  455. {
  456. artResult.pdf = new Attachment
  457. {
  458. // name = $"{artResult.studentId}.pdf",
  459. extension = "pdf",
  460. type = "doc",
  461. cnt = artResult.school,
  462. prime = false,//此处的作用是判断是否已经生成OK.
  463. };
  464. }
  465. else
  466. {
  467. artResult.pdf.prime = false;//此处的作用是判断是否已经生成OK.
  468. }
  469. await _azureRedis.GetRedisClient(8).HashSetAsync($"ArtPDF:{_artId}:{_schoolCode}", artResult.studentId, artResult.ToJsonString());
  470. }
  471. //2个小时。
  472. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"ArtPDF:{_artId}:{_schoolCode}", new TimeSpan(2, 0, 0));
  473. List<Task<string>> uploads = new List<Task<string>>();
  474. studentPdfs.ForEach(x =>
  475. {
  476. x.blob = $"art/{x.artId}/report/{x.studentId}.json";
  477. var urlSas = _azureStorage.GetBlobSAS($"{_schoolCode}", x.blob, BlobSasPermissions.Write|BlobSasPermissions.Read, hour: 24);
  478. x.blobFullUrl=urlSas.fullUri;
  479. uploads.Add(_azureStorage.GetBlobContainerClient($"{_schoolCode}").UploadFileByContainer(x.ToJsonString(), "art", $"{x.artId}/report/{x.studentId}.json", true));
  480. });
  481. var uploadJsonUrls = await Task.WhenAll(uploads);
  482. return (studentPdfs, artResults,art);
  483. }
  484. catch (Exception ex)
  485. {
  486. await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  487. }
  488. return (null, null, null);
  489. }
  490. public static async Task PushScreenTask(AzureRedisFactory _azureRedis, IConfiguration _configuration, string _artId,
  491. ArtEvaluation art, List<ArtStudentPdf> studentPdfs,IHttpClientFactory _httpClient,DingDing dingDing)
  492. {
  493. string env = ScreenConstant.env_release;
  494. if (_configuration.GetValue<string>("Option:Location").Contains("Test", StringComparison.OrdinalIgnoreCase) ||
  495. _configuration.GetValue<string>("Option:Location").Contains("Dep", StringComparison.OrdinalIgnoreCase))
  496. {
  497. env = ScreenConstant.env_develop;
  498. }
  499. string ComplexAPI= _configuration.GetValue<string>("HTEX.Complex.API");
  500. try {
  501. var client= _httpClient.CreateClient();
  502. client.Timeout= new TimeSpan(0, 0, 30);
  503. HttpResponseMessage message = await client.PostAsJsonAsync($"{ComplexAPI}/api/screen/push-task", new GenPDFData
  504. {
  505. env =env,
  506. timeout=30000,
  507. delay=1000,
  508. checkPageCompleteJs=true,
  509. sessionId=$"{_artId}",
  510. taskName = art.name,
  511. taskType="Art",
  512. owner=art.owner,
  513. scope=art.scope,
  514. pageUrl="https://teammodeltest.blob.core.chinacloudapi.cn/0-public/bookjs/art/index.html",
  515. datas= studentPdfs.Select(x => new PDFData { id= x.studentId, name=x.studentName, url =x.blobFullUrl }).ToList()
  516. });
  517. if (message.IsSuccessStatusCode)
  518. {
  519. }
  520. else {
  521. await dingDing.SendBotMsg($"艺术评测任务添加接口状态返回异常,状态:{message.StatusCode}", GroupNames.成都开发測試群組);
  522. }
  523. }
  524. catch(Exception ex){
  525. await dingDing.SendBotMsg($"艺术评测任务添加异常:{ex.Message},{ex.StackTrace}", GroupNames.成都开发測試群組);
  526. }
  527. //Console.WriteLine($"{addData.total},{addData.add}");
  528. }
  529. }
  530. public class GenPDFData
  531. {
  532. /// <summary>
  533. /// 数据装载后的页面 要制作为PDF的网页 (pageUrl 、html 参数二选一)
  534. /// </summary>
  535. public string pageUrl { get; set; }
  536. /// <summary>
  537. /// 要截图的网页HTML (pageUrl 、html 参数二选一) "html" : "<div>bookjs-eazy</div>",
  538. /// </summary>
  539. public string html { get; set; }
  540. /// <summary>
  541. /// 超时时间
  542. /// </summary>
  543. public long timeout { get; set; } = 30000;
  544. /// <summary>
  545. /// 页面完成后(checkPageCompleteJs返回为true后)延迟的时间,可选,默认:0
  546. /// </summary>
  547. public long delay { get; set; } = 2000;
  548. /// <summary>
  549. /// // 检查页面是否渲染完成的js表达式,可选,默认: "true"
  550. /// </summary>
  551. public bool checkPageCompleteJs { get; set; }
  552. /// <summary>
  553. /// 生成会话id, 活动id
  554. /// </summary>
  555. public string sessionId { get; set; }
  556. public List<PDFData> datas { get; set; } = new List<PDFData>();
  557. /// <summary>
  558. /// 通知用户
  559. /// </summary>
  560. public List<string> notifyUsers { get; set; } = new List<string>();
  561. /// <summary>
  562. /// 活动的名称
  563. /// </summary>
  564. public string taskName { get; set; }
  565. /// <summary>
  566. /// 艺术评测报告Art,评测报告Exam,问卷报告Survey,投票报告Vote,为空 则无法回调更新状态
  567. /// </summary>
  568. public string taskType { get; set;}
  569. /// <summary>
  570. /// 数据所有者
  571. /// </summary>
  572. public string owner { get; set; }
  573. /// <summary>
  574. /// 数据范围
  575. /// </summary>
  576. public string scope { get; set; }
  577. public string env { get; set; }
  578. }
  579. public class GenPDFSchema
  580. {
  581. public List<string> notifyUsers { get; set; } = new List<string>();
  582. public string taskName { get; set; }
  583. public string taskType { get; set; }
  584. }
  585. public class PDFData{
  586. /// <summary>
  587. /// 学生id
  588. /// </summary>
  589. public string id { get; set; }
  590. /// <summary>
  591. /// 数据链接
  592. /// </summary>
  593. public string url { get; set; }
  594. /// <summary>
  595. /// 学生名称
  596. /// </summary>
  597. public string name { get; set; }
  598. }
  599. /// <summary>
  600. /// redis 存储数据,超时时间设置为status=0 的count timeout* count+ delay*count
  601. /// </summary>
  602. public class PDFGenRedis
  603. {
  604. /// <summary>
  605. /// 学生id
  606. /// </summary>
  607. public string id { get; set; }
  608. /// <summary>
  609. /// 学生名称
  610. /// </summary>
  611. public string name { get; set; }
  612. /// <summary>
  613. /// 执行生成 毫秒
  614. /// </summary>
  615. public long cost { get; set;}
  616. /// <summary>
  617. /// 等候时间
  618. /// </summary>
  619. public long wait { get; set;}
  620. /// <summary>
  621. /// 加入时间
  622. /// </summary>
  623. public long join { get; set; }
  624. /// <summary>
  625. /// 上传成功后的文件
  626. /// </summary>
  627. public string blob { get; set; }
  628. /// <summary>
  629. /// 數據的url
  630. /// </summary>
  631. public string url { get; set; }
  632. /// <summary>
  633. /// 0 未执行,1 执行中,2 执行成功,3 执行失败,4超时,5 取消,6 存放异常
  634. /// </summary>
  635. public int status { get; set; } = 0;
  636. /// <summary>
  637. /// 状态信息
  638. /// </summary>
  639. public string msg { get; set; }
  640. /// <summary>
  641. /// 数据所有者
  642. /// </summary>
  643. public string owner { get; set; }
  644. /// <summary>
  645. /// 数据范围
  646. /// </summary>
  647. public string scope { get; set; }
  648. /// <summary>
  649. /// 环境变量
  650. /// </summary>
  651. public string env { get; set; }
  652. }
  653. /// <summary>
  654. /// // 拼接上接口的前缀 http://localhost:3000/ 就是完整PDF地址
  655. // http://localhost:3000/pdf/1614458263411-glduu.pdf
  656. // 拼接上接口的前缀 http://localhost:3000/download/可以就可生成在浏览器上的下载链接
  657. // http://localhost:3000/download/pdf/1614458263411-glduu.pdf
  658. // 拼接上http://localhost:3000/static/js/pdfjs/web/viewer.html?file=/pdf/1614458263411-glduu.pdf
  659. // 可使用pdfjs库进行预览
  660. //
  661. //## -e MAX_BROWSER=[num] 环境变量可选,最大的puppeteer实例数,忽略选项则默认值:1 , 值auto:[可用内存]/200M
  662. //## -e PDF_KEEP_DAY=[num] 自动删除num天之前产生的文件目录,默认0: 不删除文件
  663. //docker run -p 13000:3000 -td --rm -e MAX_BROWSER=2 -e PDF_KEEP_DAY=1 -v ${PWD}:/screenshot-api-server/public --name=screenshot-api-server wuxue107/screenshot-api-server
  664. /// </summary>
  665. public class PDFGenQueue
  666. {
  667. /// <summary>
  668. /// 环境变量
  669. /// </summary>
  670. public string env { get; set;}
  671. /// <summary>
  672. /// 姓名
  673. /// </summary>
  674. public string name { get; set; }
  675. /// <summary>
  676. /// 学生id
  677. /// </summary>
  678. public string id { get; set; }
  679. /// <summary>
  680. /// 数据装载后的页面 要制作为PDF的网页 (pageUrl 、html 参数二选一)
  681. /// </summary>
  682. public string pageUrl { get; set; }
  683. /// <summary>
  684. /// 要截图的网页HTML (pageUrl 、html 参数二选一) "html" : "<div>bookjs-eazy</div>",
  685. /// </summary>
  686. public string html { get; set; }
  687. /// <summary>
  688. /// 超时时间
  689. /// </summary>
  690. public long timeout { get; set; } = 30000;
  691. /// <summary>
  692. /// 页面完成后(checkPageCompleteJs返回为true后)延迟的时间,可选,默认:0
  693. /// </summary>
  694. public long delay { get; set; } = 2000;
  695. /// <summary>
  696. /// // 检查页面是否渲染完成的js表达式,可选,默认: "true"
  697. /// </summary>
  698. public bool checkPageCompleteJs { get; set; }
  699. /// <summary>
  700. /// 生成会话id, 活动id
  701. /// </summary>
  702. public string sessionId { get; set; }
  703. /// <summary>
  704. /// blob的sas
  705. /// </summary>
  706. public string blobSas { get; set; }
  707. /// <summary>
  708. /// blob名称
  709. /// </summary>
  710. public string blobName { get; set; }
  711. /// <summary>
  712. /// 容器名称
  713. /// </summary>
  714. public string cntName { get; set; }
  715. /// <summary>
  716. /// 完整blob地址
  717. /// </summary>
  718. public string blobFullUrl { get; set; }
  719. }
  720. public class ScreenClient : ClientDevice
  721. {
  722. /// <summary>
  723. /// 授权类型,bookjs_api
  724. /// </summary>
  725. public string? grant_type { get; set; }
  726. /// <summary>
  727. /// 客户端id
  728. /// </summary>
  729. public string? clientid { get; set; }
  730. /// <summary>
  731. /// SignalR的连接ID 不建议暴露。
  732. /// </summary>
  733. public string? connid { get; set; }
  734. /// <summary>
  735. /// 状态 busy 忙碌,free 空闲,down 离线,error 错误
  736. /// </summary>
  737. public string? status { get; set; }
  738. /// <summary>
  739. /// 最后更新时间
  740. /// </summary>
  741. public long last_time { get; set; }
  742. /// <summary>
  743. /// 任务完成数
  744. /// </summary>
  745. public int taskComplete { get; set; }
  746. /// <summary>
  747. /// 超时时间,单位毫秒
  748. /// </summary>
  749. public long timeout { get; set; } = 30000;
  750. /// <summary>
  751. /// 延迟时间,单位毫秒
  752. /// </summary>
  753. public long delay { get; set; } = 3000;
  754. /// <summary>
  755. /// PDF服务地址
  756. /// </summary>
  757. public string? screenUrl { get; set; }
  758. }
  759. public class SignalRClient
  760. {
  761. /// <summary>
  762. /// 授权类型,bookjs_api
  763. /// </summary>
  764. public string? grant_type { get; set; }
  765. /// <summary>
  766. /// 客户端id
  767. /// </summary>
  768. public string? clientid { get; set; }
  769. /// <summary>
  770. /// SignalR的连接ID 不建议暴露。
  771. /// </summary>
  772. public string? connid { get; set; }
  773. public string? serverid { get; set;}
  774. }
  775. public interface IClient
  776. {
  777. Task ReceiveMessage(MessageBody message);
  778. Task ReceiveConnection(MessageBody message);
  779. Task ReceiveDisConnection(MessageBody message);
  780. }
  781. public abstract class MessageBody
  782. {
  783. public MessageBody()
  784. {
  785. time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  786. }
  787. /// <summary>
  788. /// 连接id
  789. /// </summary>
  790. public virtual string? connid { get; set; }
  791. /// <summary>
  792. /// 客户端id
  793. /// </summary>
  794. public virtual string? clientid { get; set; }
  795. /// <summary>
  796. /// 状态 busy 忙碌,free 空闲,down 离线,error 错误
  797. /// </summary>
  798. public virtual string? status { get; set; }
  799. /// <summary>
  800. /// 消息内容
  801. /// </summary>
  802. public virtual string? content { get; set; }
  803. /// <summary>
  804. /// 消息创建时间
  805. /// </summary>
  806. public virtual long time { get; }
  807. /// <summary>
  808. /// 授权类型,bookjs_api
  809. /// </summary>
  810. public virtual string? grant_type { get; set; }
  811. /// <summary>
  812. /// 消息类型
  813. /// </summary>
  814. public virtual MessageType message_type { get; set; }
  815. }
  816. /// <summary>
  817. /// 连接消息
  818. /// </summary>
  819. public class ConnectionMessage : MessageBody
  820. {
  821. }
  822. /// <summary>
  823. /// 断开连接消息
  824. /// </summary>
  825. public class DisConnectionMessage : MessageBody
  826. {
  827. }
  828. /// <summary>
  829. /// 业务处理消息
  830. /// </summary>
  831. public class ScreenProcessMessage : MessageBody
  832. {
  833. public string msg { get; set; }
  834. public int result { get; set; }
  835. }
  836. public static class ScreenConstant
  837. {
  838. public static readonly string busy = "busy";
  839. public static readonly string idle = "idle";
  840. public static readonly string error = "error";
  841. public static readonly string offline = "offline";
  842. public static readonly string grant_type = "bookjs_api";
  843. public static readonly string env_release = "release";
  844. public static readonly string env_develop = "develop";
  845. /// <summary>
  846. /// 冗余时间
  847. /// </summary>
  848. public static readonly long time_excess = 5000;
  849. }
  850. public enum MessageType {
  851. conn_success,//连接成功
  852. conn_error,// 连接失败
  853. task_send_success,// 任务发送成功
  854. task_send_error,// 任务发送失败
  855. task_execute_success,// 任务执行成功
  856. task_execute_error,// 任务执行失败
  857. }
  858. public class ClientDevice
  859. {
  860. /// <summary>
  861. /// 机器名
  862. /// </summary>
  863. public string? name { get; set; }
  864. /// <summary>
  865. /// 操作系统
  866. /// </summary>
  867. public string? os { get; set; }
  868. /// <summary>
  869. /// CPU核心数量
  870. /// </summary>
  871. public int cpu { get; set; }
  872. /// <summary>
  873. /// 内存大小
  874. /// </summary>
  875. public long ram { get; set;}
  876. /// <summary>
  877. /// 远程ip
  878. /// </summary>
  879. public string? remote { get; set; }
  880. /// <summary>
  881. /// 端口,可能有多个端口
  882. /// </summary>
  883. public string? port { get; set; }
  884. /// <summary>
  885. /// 地区
  886. /// </summary>
  887. public string? region { get; set; }
  888. /// <summary>
  889. /// 网卡 IP信息
  890. /// </summary>
  891. public List<Network> networks { get; set; } = new List<Network>();
  892. /// <summary>
  893. /// 设备id
  894. /// </summary>
  895. public string? deviceId { get; set; }
  896. }
  897. public class Network
  898. {
  899. public string? name { get; set; }
  900. public string? mac { get; set; }
  901. public string? ip { get; set; }
  902. }
  903. }