1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018 |
- using Azure.Messaging.ServiceBus;
- using Azure.Storage.Blobs.Models;
- using Microsoft.Azure.Cosmos;
- using StackExchange.Redis;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Json;
- using System.Text;
- using System.Text.Json;
- using System.Text.Json.Nodes;
- using System.Threading.Tasks;
- using System.Web;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using static TEAMModelOS.SDK.CoreAPIHttpService;
- using TEAMModelOS.SDK.Models;
- using Microsoft.Extensions.Configuration;
- using System.Net.Http.Headers;
- using Azure.Storage.Sas;
- using TEAMModelOS.SDK.Models.Service;
- using Azure.Core;
- using TEAMModelOS.SDK.Models.Cosmos;
- using System.Configuration;
- using Google.Protobuf.WellKnownTypes;
- namespace TEAMModelOS.SDK
- {
- public static class GenPDFService
- {
-
- public static async Task GenPdf( AzureRedisFactory _azureRedis, AzureCosmosFactory _azureCosmos,
- IConfiguration _configuration, IHttpClientFactory _httpClient, AzureStorageFactory _azureStorage,
- DingDing _dingDing, SnowflakeId _snowflakeId,string json )
- {
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- Console.WriteLine($"開始:{now}");
- string apiUri = "http://52.130.252.100:13000";
- PDFGenQueue genQueueData =json.ToObject<PDFGenQueue>();
- RedisValue redisValue = await _azureRedis.GetRedisClient(8).HashGetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id);
- PDFGenRedis genRedis = null;
- if (redisValue!=default)
- {
- genRedis = redisValue.ToString().ToObject<PDFGenRedis>();
- //计算等待了多久的时间才开始生成。
- var wait = now- genRedis.join;
- genRedis.wait = wait;
- genRedis.status= 1;
- await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
- var client = _httpClient.CreateClient();
- ///再加5秒
- client.Timeout= TimeSpan.FromMilliseconds(genQueueData.timeout+ genQueueData.delay+5000);
- try
- {
- string urlpdf = $"{apiUri}/api/pdf";
- string jsonElement = new
- {
- pageUrl = genQueueData.pageUrl,
- timeout = genQueueData.timeout,
- delay = genQueueData.delay,
- checkPageCompleteJs = genQueueData.checkPageCompleteJs
- }.ToJsonString();
- var request = new HttpRequestMessage
- {
- Method = new HttpMethod("POST"),
- RequestUri = new Uri(urlpdf),
- Content = new StringContent(jsonElement)
- };
- var mediaTypeHeader = new MediaTypeHeaderValue("application/json")
- {
- CharSet = "UTF-8"
- };
- request.Content.Headers.ContentType = mediaTypeHeader;
- HttpResponseMessage responseMessage = await client.SendAsync(request);
- if (responseMessage.IsSuccessStatusCode)
- {
- string content = await responseMessage.Content.ReadAsStringAsync();
- JsonNode jsonNode = content.ToObject<JsonNode>();
- var code = jsonNode["code"];
- var file = jsonNode["data"]?["file"];
- if (code!=null && $"{code}".Equals("0") && file!= null && !string.IsNullOrWhiteSpace($"{file}"))
- {
- try
- {
- Stream stream = await client.GetStreamAsync($"{apiUri}/{file}");
- Uri uri = new Uri(genQueueData.pageUrl);
- var query = HttpUtility.ParseQueryString(uri.Query);
- string? url = query["url"];
- if (!string.IsNullOrWhiteSpace(url))
- {
- url= HttpUtility.UrlDecode(url);
- uri = new Uri(url);
- string host = uri.Host;
- var blobServiceClient = _azureStorage.GetBlobServiceClient();
- if (blobServiceClient.Uri.Host.Equals(host))
- {
- // 获取容器名,它是路径的第一个部分
- string containerName = uri.Segments[1].TrimEnd('/');
- // 获取文件的完整同级目录,这是文件路径中除了文件名和扩展名之外的部分
- // 由于文件名是路径的最后一个部分,我们可以通过连接除了最后一个部分之外的所有部分来获取目录路径
- string directoryPath = string.Join("", uri.Segments, 2, uri.Segments.Length - 3);
- string? fileName = Path.GetFileNameWithoutExtension(uri.AbsolutePath);
- string blobPath = $"{directoryPath}{fileName}.pdf";
- var blockBlob = _azureStorage.GetBlobContainerClient(containerName).GetBlobClient(blobPath);
- string content_type = "application/octet-stream";
- ContentTypeDict.dict.TryGetValue(".pdf", out string? contenttype);
- if (!string.IsNullOrEmpty(contenttype))
- {
- content_type = contenttype;
- }
- await blockBlob.UploadAsync(stream, true);
- blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
- genRedis.blob= blockBlob.Name;
- genRedis.status=2;
- }
- else
- {
- genRedis.status=6;
- }
- }
- else
- {
- genRedis.status=6;
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json}", GroupNames.醍摩豆服務運維群組);
- genRedis.status=6;
- }
- }
- else
- {
- if (code!= null && $"{code}".Equals("99999"))
- {
- genRedis.status= 4;
- }
- else
- {
- genRedis.status= 3;
- }
- }
- }
- else
- {
- genRedis.status= 3;
- }
- }
- catch (TaskCanceledException ex)
- {
- if (ex.CancellationToken.IsCancellationRequested)
- {
- // Console.WriteLine("请求被取消。");
- genRedis.status= 5;
- }
- else
- {
- //Console.WriteLine("请求超时。");
- genRedis.status= 4;
- }
- }
- catch (Exception ex)
- {
- genRedis.status=3;
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPDF()\n{ex.Message}\n{ex.StackTrace}\n\n{json}", GroupNames.醍摩豆服務運維群組);
- }
- }
- else
- {
- genRedis= new PDFGenRedis { id =genQueueData.id, status= 5, cost=0, join=now, wait=0, name= genQueueData.name };
- //被取消的
- }
- long nowNew = DateTimeOffset.Now.ToUnixTimeMilliseconds();
- genRedis.cost=nowNew-now;
- await _azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{genQueueData.sessionId}", genQueueData.id, genRedis.ToJsonString());
- //如果全部 生成,需要发送通知
- HashEntry[] datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"PDFGen:{genQueueData.sessionId}");
- List<PDFGenRedis> dbgenRedis = new List<PDFGenRedis>();
- List<string> notifyUsers = new List<string>();
- string taskName = string.Empty;
- string taskType = string.Empty;
- if (datas!= null && datas.Length > 0)
- {
- foreach (var item in datas)
- {
- if (!$"{item.Name}".Contains("notifyUsers"))
- {
- dbgenRedis.Add(item.Value.ToString().ToObject<PDFGenRedis>());
- }
- else
- {
- var jsonData = item.Value.ToString().ToObject<JsonElement>();
- notifyUsers= jsonData.GetProperty("notifyUsers").ToObject<List<string>>();
- taskType = jsonData.GetProperty("taskType").ToString();
- taskName = jsonData.GetProperty("taskName").ToString();
- }
- }
- }
- if (notifyUsers.IsNotEmpty())
- {
- string lang = Environment.GetEnvironmentVariable("Option:Location")!.Contains("China") ? "zh-cn" : "en-us";
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", notifyUsers.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- 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; });
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- string location = "China";
- if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("China"))
- {
- location = "China";
- }
- else if (Environment.GetEnvironmentVariable("Option:Location")!.Contains("Global"))
- {
- location = "Global";
- }
- var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
- var client = _httpClient.CreateClient();
- if (client.DefaultRequestHeaders.Contains("Authorization"))
- {
- client.DefaultRequestHeaders.Remove("Authorization");
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- else
- {
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- //检查dbgenRedis的状态是否全部已经不是0和1
- var unfinished = dbgenRedis.FindAll(x => (x.status==0||x.status==1));
- if (unfinished==null || unfinished.Count==0)
- {
- // 数据大于60一个班,发送报告的总耗时等概要信息, 小于60的发送 生成报告的细则消息,小于五个的,可以列出报告的链接.
- long joinTime = dbgenRedis.Min(x => x.join);
- long totalTime = (now-joinTime)/1000;
- long costTime = dbgenRedis.Sum(x => x.cost)/1000;
- long avgTime = costTime / dbgenRedis.Count;
- long maxTime = dbgenRedis.Max(x => x.cost)/1000;
- long minTime = dbgenRedis.Min(x => x.cost)/1000;
- long statusOk = dbgenRedis.Where(x => x.status==2).Count();
- long statusFailed = dbgenRedis.Where(x => x.status!=2).Count();
- string key = "pdf-gen-notify-higher60";
- if (dbgenRedis.Count>60)
- {
- key = "pdf-gen-notify-higher60";
- }
- else
- {
- key ="pdf-gen-notify-below60";
- }
- foreach (var teacher in idNameCodes)
- {
- string path = Path.Combine("", $"Lang/{teacher.code}.json");
- var sampleJson = File.ReadAllText(path);
- JsonElement jsonElement = sampleJson.ToObject<JsonElement>();
- JsonElement msgsJson = jsonElement.GetProperty(key);
- List<string> msgs = msgsJson.ToObject<List<string>>();
- string msg1 = msgs[1].Replace("{tmdname}", teacher.name).Replace("{taskName}", taskName).Replace("{totalTime}", $"{totalTime}")
- .Replace("{avgTime}", $"{avgTime}").Replace("{maxTime}", $"{maxTime}").Replace("{minTime}", $"{minTime}").Replace("{statusOk}", $"{statusOk}").Replace("{statusFailed}", $"{statusFailed}");
- StringBuilder sb = new StringBuilder($"{msg1}");
- if (dbgenRedis.Count<=60)
- {
- string status = string.Empty;
- dbgenRedis.ForEach(x => {
- switch (x.status)
- {
- case 0:
- status= teacher.code.Equals("zh-cn") ? "未执行" : teacher.code.Equals("zh-tw") ? "未執行" : "unexecuted";
- break;
- case 1:
- status= teacher.code.Equals("zh-cn") ? "执行中" : teacher.code.Equals("zh-tw") ? "執行中" : "executing";
- break;
- case 2:
- status= teacher.code.Equals("zh-cn") ? "成功" : teacher.code.Equals("zh-tw") ? "成功" : "success";
- break;
- case 3:
- status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
- break;
- case 4:
- status= teacher.code.Equals("zh-cn") ? "超时" : teacher.code.Equals("zh-tw") ? "超時" : "timeout";
- break;
- case 5:
- status= teacher.code.Equals("zh-cn") ? "取消" : teacher.code.Equals("zh-tw") ? "取消" : "canceled";
- break;
- case 6:
- status= teacher.code.Equals("zh-cn") ? "存放异常" : teacher.code.Equals("zh-tw") ? "存放異常" : "SaveError";
- break;
- default:
- status= teacher.code.Equals("zh-cn") ? "失败" : teacher.code.Equals("zh-tw") ? "失敗" : "failed";
- break;
- }
- 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}");
- sb.Append(msg2);
- });
- }
- NotifyData notifyData = new NotifyData
- {
- hubName = "hita5",
- sender = "IES",
- tags = new List<string> { $"{teacher.id}_{Constant.NotifyType_IES5_Course}" },
- title = msgs[0],
- eventId = $"{key}_{_snowflakeId.NextId()}",
- eventName =msgs[0],
- data = "{\"value\":{}}",
- body=sb.ToString(),
- };
- string result = "";
- try
- {
- HttpResponseMessage responseMessage = await client.PostAsJsonAsync($"{url}/service/PushNotify", notifyData);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string content = await responseMessage.Content.ReadAsStringAsync();
- result = content;
- }
- else
- {
- result = $"{responseMessage.StatusCode},推送返回的状态码。";
- }
- }
- catch (Exception exm)
- {
- _= _dingDing.SendBotMsg($"{location}站点发送消息异常,{exm.Message}\n{exm.StackTrace}:\n{url}/service/PushNotify \nheader: {token.AccessToken} \nresult:{result}\n params:{notifyData.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- }
- }
- }
- Console.WriteLine($"結束:{now}");
- return;
- }
- /// <summary>
- /// 加入PDF生成队列服务
- /// https://github.com/wuxue107/bookjs-eazy https://github.com/wuxue107/screenshot-api-server
- /// </summary>
- /// <param name="azureRedis"></param>
- /// <param name="data"></param>
- /// <returns></returns>
- public static async Task<(int total,int add )> AddGenPdfQueue( AzureRedisFactory azureRedis, GenPDFData data,ClientDevice device)
- {
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<PDFGenRedis> genRedis = new List<PDFGenRedis>();
- List<PDFGenRedis> dbgenRedis = new List<PDFGenRedis>();
- HashEntry[] datas = await azureRedis.GetRedisClient(8).HashGetAllAsync($"PDFGen:{data.sessionId}");
- List<string> notifyUsers = new List<string>();
- if (datas!= null && datas.Length > 0)
- {
- foreach (var item in datas)
- {
- if (!$"{item.Name}".Contains("notifyUsers"))
- {
- dbgenRedis.Add(item.Value.ToString().ToObject<PDFGenRedis>());
- }
- else {
- var json = item.Value.ToString().ToObject<JsonElement>();
- notifyUsers= json.GetProperty("notifyUsers").ToObject<List<string>>();
- }
- }
- }
- if (data.notifyUsers.IsNotEmpty())
- {
- notifyUsers.AddRange(data.notifyUsers);
- notifyUsers= notifyUsers.Distinct().ToList();
- }
- var dataVal = new GenPDFSchema { notifyUsers= notifyUsers, taskName= data.taskName, taskType = data.taskType };
- //Redis记录需要通知的用户
- await azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{data.sessionId}", "notifyUsers",JsonSerializer.Serialize(dataVal));
- //Redis记录需要生成PDF的数量
- int countProcess= 0;
- foreach (var item in data.datas)
- {
- var dbData = dbgenRedis.Find(x => x.id.Equals(item.id));
- if (dbData!=null)
- {
-
- //if (dbData.status==0|| dbData.status==1)
- //{
- // //不变的
- // countProcess+=1;
- //}
- //else
- {
- //需要变更的
- dbData.status = 0;
- dbData.cost=0;
- dbData.join= now;
- dbData.wait=0;
- dbData.name=item.name;
- dbData.url= item.url;
- dbData.scope = data.scope;
- dbData.owner= data.owner;
- dbData.env= data.env;
- genRedis.Add(dbData);
- }
- }
- else {
- genRedis.Add(new PDFGenRedis {
- id = item.id,
- status=0,
- cost=0,
- wait=0,
- join=now,
- name=item.name,
- url= item.url,
- scope=data.scope,
- owner= data.owner,
- env= data.env,
- });
- }
- }
- //过期时间 当前个数+ reddis的个数
- foreach (var item in genRedis)
- {
- countProcess+=1;
- await azureRedis.GetRedisClient(8).HashSetAsync($"PDFGen:{data.sessionId}", item.id, item.ToJsonString());
- PDFGenQueue genQueue = new PDFGenQueue
- {
- id = item.id,
- checkPageCompleteJs= data.checkPageCompleteJs,
- delay=data.delay,
- html= data.html,
- pageUrl= $"{data.pageUrl}?url={HttpUtility.UrlEncode(item.url)}",
- sessionId= data.sessionId,
- timeout =data.timeout,
- name=item.name,
- env= data.env,
- };
- //string message = JsonSerializer.Serialize(genQueue);
- //从头部压入元素,队列先进先出
- await azureRedis.GetRedisClient(8).ListLeftPushAsync($"PDFGen:Queue:{device.deviceId}", genQueue.ToJsonString());
- //var serviceBusMessage = new ServiceBusMessage(message);
- //serviceBusMessage.ApplicationProperties.Add("name", "BlobRoot");
- //await azureServiceBus.GetServiceBusClient().SendMessageAsync("dep-genpdf", serviceBusMessage);
- }
- long expire = (data.delay + data.timeout) * countProcess+30*60*1000;
- var tiemSpan = TimeSpan.FromMilliseconds(expire);
- await azureRedis.GetRedisClient(8).KeyExpireAsync($"PDFGen:{data.sessionId}", tiemSpan);
-
- return ( countProcess , genRedis.Count() );
- }
-
- public static async Task<(List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults, ArtEvaluation art)> GenArtStudentPdf( AzureRedisFactory _azureRedis, AzureCosmosFactory _azureCosmos,
- CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, AzureStorageFactory _azureStorage, IConfiguration _configuration, List<string> studentIds,string _artId,string _schoolId,string headLang)
- {
- try
- {
- string _schoolCode = $"{_schoolId}";
- ArtEvaluation art = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ArtEvaluation>($"{_artId}", new PartitionKey($"Art-{_schoolId}"));
- (List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults) = await ArtService.GenStuArtPDF(studentIds, $"{_artId}", art, $"{_schoolId}", $"{headLang}", _azureCosmos, _coreAPIHttpService, _dingDing);
- foreach (var artResult in artResults)
- {
- if (artResult.pdf == null || string.IsNullOrWhiteSpace(artResult.pdf.blob) || string.IsNullOrWhiteSpace(artResult.pdf.url))
- {
- artResult.pdf = new Attachment
- {
- // name = $"{artResult.studentId}.pdf",
- extension = "pdf",
- type = "doc",
- cnt = artResult.school,
- prime = false,//此处的作用是判断是否已经生成OK.
- };
- }
- else
- {
- artResult.pdf.prime = false;//此处的作用是判断是否已经生成OK.
- }
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ArtPDF:{_artId}:{_schoolCode}", artResult.studentId, artResult.ToJsonString());
- }
- //2个小时。
- await _azureRedis.GetRedisClient(8).KeyExpireAsync($"ArtPDF:{_artId}:{_schoolCode}", new TimeSpan(2, 0, 0));
- List<Task<string>> uploads = new List<Task<string>>();
- studentPdfs.ForEach(x =>
- {
- x.blob = $"art/{x.artId}/report/{x.studentId}.json";
- var urlSas = _azureStorage.GetBlobSAS($"{_schoolCode}", x.blob, BlobSasPermissions.Write|BlobSasPermissions.Read, hour: 24);
- x.blobFullUrl=urlSas.fullUri;
- uploads.Add(_azureStorage.GetBlobContainerClient($"{_schoolCode}").UploadFileByContainer(x.ToJsonString(), "art", $"{x.artId}/report/{x.studentId}.json", true));
- });
- var uploadJsonUrls = await Task.WhenAll(uploads);
- return (studentPdfs, artResults,art);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- return (null, null, null);
- }
- /// <summary>
- /// 生成PDF导出模板的数据文件。
- /// </summary>
- /// <param name="_azureRedis"></param>
- /// <param name="_configuration"></param>
- /// <param name="_artId"></param>
- /// <param name="art"></param>
- /// <param name="studentPdfs"></param>
- /// <param name="_httpClient"></param>
- /// <param name="dingDing"></param>
- /// <returns></returns>
- public static async Task PushScreenTask(AzureRedisFactory _azureRedis, IConfiguration _configuration, string _artId,
- ArtEvaluation art, List<ArtStudentPdf> studentPdfs,IHttpClientFactory _httpClient,DingDing dingDing)
- {
- string env = ScreenConstant.env_release;
- if (_configuration.GetValue<string>("Option:Location").Contains("Test", StringComparison.OrdinalIgnoreCase) ||
- _configuration.GetValue<string>("Option:Location").Contains("Dep", StringComparison.OrdinalIgnoreCase))
- {
- env = ScreenConstant.env_develop;
- }
- string ComplexAPI= _configuration.GetValue<string>("HTEX.Complex.API");
- try {
- var client= _httpClient.CreateClient();
- client.Timeout= new TimeSpan(0, 0, 30);
- HttpResponseMessage message = await client.PostAsJsonAsync($"{ComplexAPI}/api/screen/push-task", new GenPDFData
- {
- env =env,
- timeout=30000,
- delay=1000,
- checkPageCompleteJs=true,
- sessionId=$"{_artId}",
- taskName = art.name,
- taskType="Art",
- owner=art.owner,
- scope=art.scope,
- pageUrl="https://teammodeltest.blob.core.chinacloudapi.cn/0-public/bookjs/art/index.html",
- datas= studentPdfs.Select(x => new PDFData { id= x.studentId, name=x.studentName, url =x.blobFullUrl }).ToList()
- });
- if (message.IsSuccessStatusCode)
- {
- }
- else {
- await dingDing.SendBotMsg($"艺术评测任务添加接口状态返回异常,状态:{message.StatusCode}", GroupNames.成都开发測試群組);
- }
- }
- catch(Exception ex){
- await dingDing.SendBotMsg($"艺术评测任务添加异常:{ex.Message},{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
-
- //Console.WriteLine($"{addData.total},{addData.add}");
- }
- }
- public class GenPDFData
- {
- /// <summary>
- /// 数据装载后的页面 要制作为PDF的网页 (pageUrl 、html 参数二选一)
- /// </summary>
- public string pageUrl { get; set; }
- /// <summary>
- /// 要截图的网页HTML (pageUrl 、html 参数二选一) "html" : "<div>bookjs-eazy</div>",
- /// </summary>
- public string html { get; set; }
- /// <summary>
- /// 超时时间
- /// </summary>
- public long timeout { get; set; } = 30000;
- /// <summary>
- /// 页面完成后(checkPageCompleteJs返回为true后)延迟的时间,可选,默认:0
- /// </summary>
- public long delay { get; set; } = 2000;
- /// <summary>
- /// // 检查页面是否渲染完成的js表达式,可选,默认: "true"
- /// </summary>
- public bool checkPageCompleteJs { get; set; }
- /// <summary>
- /// 生成会话id, 活动id
- /// </summary>
- public string sessionId { get; set; }
- public List<PDFData> datas { get; set; } = new List<PDFData>();
- /// <summary>
- /// 通知用户
- /// </summary>
- public List<string> notifyUsers { get; set; } = new List<string>();
- /// <summary>
- /// 活动的名称
- /// </summary>
- public string taskName { get; set; }
- /// <summary>
- /// 艺术评测报告Art,评测报告Exam,问卷报告Survey,投票报告Vote,为空 则无法回调更新状态
- /// </summary>
- public string taskType { get; set;}
- /// <summary>
- /// 数据所有者
- /// </summary>
- public string owner { get; set; }
- /// <summary>
- /// 数据范围
- /// </summary>
- public string scope { get; set; }
- public string env { get; set; }
- }
- public class GenPDFSchema
- {
- public List<string> notifyUsers { get; set; } = new List<string>();
- public string taskName { get; set; }
- public string taskType { get; set; }
- }
- public class PDFData{
- /// <summary>
- /// 学生id
- /// </summary>
- public string id { get; set; }
- /// <summary>
- /// 数据链接
- /// </summary>
- public string url { get; set; }
- /// <summary>
- /// 学生名称
- /// </summary>
- public string name { get; set; }
- }
- /// <summary>
- /// redis 存储数据,超时时间设置为status=0 的count timeout* count+ delay*count
- /// </summary>
- public class PDFGenRedis
- {
- /// <summary>
- /// 学生id
- /// </summary>
- public string id { get; set; }
- /// <summary>
- /// 学生名称
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 执行生成 毫秒
- /// </summary>
- public long cost { get; set;}
- /// <summary>
- /// 等候时间
- /// </summary>
- public long wait { get; set;}
- /// <summary>
- /// 加入时间
- /// </summary>
- public long join { get; set; }
- /// <summary>
- /// 上传成功后的文件
- /// </summary>
- public string blob { get; set; }
- /// <summary>
- /// 數據的url
- /// </summary>
- public string url { get; set; }
- /// <summary>
- /// 0 未执行,1 执行中,2 执行成功,3 执行失败,4超时,5 取消,6 存放异常
- /// </summary>
- public int status { get; set; } = 0;
- /// <summary>
- /// 状态信息
- /// </summary>
- public string msg { get; set; }
- /// <summary>
- /// 数据所有者
- /// </summary>
- public string owner { get; set; }
- /// <summary>
- /// 数据范围
- /// </summary>
- public string scope { get; set; }
- /// <summary>
- /// 环境变量
- /// </summary>
- public string env { get; set; }
- }
- /// <summary>
- /// // 拼接上接口的前缀 http://localhost:3000/ 就是完整PDF地址
- // http://localhost:3000/pdf/1614458263411-glduu.pdf
- // 拼接上接口的前缀 http://localhost:3000/download/可以就可生成在浏览器上的下载链接
- // http://localhost:3000/download/pdf/1614458263411-glduu.pdf
- // 拼接上http://localhost:3000/static/js/pdfjs/web/viewer.html?file=/pdf/1614458263411-glduu.pdf
- // 可使用pdfjs库进行预览
- //
- //## -e MAX_BROWSER=[num] 环境变量可选,最大的puppeteer实例数,忽略选项则默认值:1 , 值auto:[可用内存]/200M
- //## -e PDF_KEEP_DAY=[num] 自动删除num天之前产生的文件目录,默认0: 不删除文件
- //sudo 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
- /// </summary>
- public class PDFGenQueue
- {
- /// <summary>
- /// 环境变量
- /// </summary>
- public string env { get; set;}
- /// <summary>
- /// 姓名
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 学生id
- /// </summary>
- public string id { get; set; }
- /// <summary>
- /// 数据装载后的页面 要制作为PDF的网页 (pageUrl 、html 参数二选一)
- /// </summary>
- public string pageUrl { get; set; }
- /// <summary>
- /// 要截图的网页HTML (pageUrl 、html 参数二选一) "html" : "<div>bookjs-eazy</div>",
- /// </summary>
- public string html { get; set; }
- /// <summary>
- /// 超时时间
- /// </summary>
- public long timeout { get; set; } = 30000;
- /// <summary>
- /// 页面完成后(checkPageCompleteJs返回为true后)延迟的时间,可选,默认:0
- /// </summary>
- public long delay { get; set; } = 2000;
- /// <summary>
- /// // 检查页面是否渲染完成的js表达式,可选,默认: "true"
- /// </summary>
- public bool checkPageCompleteJs { get; set; }
- /// <summary>
- /// 生成会话id, 活动id
- /// </summary>
- public string sessionId { get; set; }
- /// <summary>
- /// blob的sas
- /// </summary>
- public string blobSas { get; set; }
- /// <summary>
- /// blob名称
- /// </summary>
- public string blobName { get; set; }
- /// <summary>
- /// 容器名称
- /// </summary>
- public string cntName { get; set; }
- /// <summary>
- /// 完整blob地址
- /// </summary>
- public string blobFullUrl { get; set; }
- }
- public static class HybridConstant
- {
- public static readonly string busy = "busy";
- public static readonly string idle = "idle";
- public static readonly string error = "error";
- public static readonly string offline = "offline";
- public static readonly string grant_type = "hybrid-cloud";
- public static readonly string env_release = "release";
- public static readonly string env_develop = "develop";
- /// <summary>
- /// 冗余时间
- /// </summary>
- public static readonly long time_excess = 5000;
- }
- public class HybridClient : ClientDevice
- {
- /// <summary>
- /// 授权类型,hybrid-cloud
- /// </summary>
- public string? grant_type { get; set; }
- /// <summary>
- /// 客户端id
- /// </summary>
- public string? clientid { get; set; }
- /// <summary>
- /// SignalR的连接ID 不建议暴露。
- /// </summary>
- public string? connid { get; set; }
- /// <summary>
- /// 状态 busy 忙碌,free 空闲,down 离线,error 错误
- /// </summary>
- public string? status { get; set; }
- /// <summary>
- /// 最后更新时间
- /// </summary>
- public long last_time { get; set; }
- /// <summary>
- /// 超时时间,单位毫秒
- /// </summary>
- public long timeout { get; set; } = 30000;
- /// <summary>
- /// 延迟时间,单位毫秒
- /// </summary>
- public long delay { get; set; } = 3000;
- }
- public class ScreenClient : ClientDevice
- {
- /// <summary>
- /// 授权类型,bookjs_api
- /// </summary>
- public string? grant_type { get; set; }
- /// <summary>
- /// 客户端id
- /// </summary>
- public string? clientid { get; set; }
- /// <summary>
- /// SignalR的连接ID 不建议暴露。
- /// </summary>
- public string? connid { get; set; }
- /// <summary>
- /// 状态 busy 忙碌,free 空闲,down 离线,error 错误
- /// </summary>
- public string? status { get; set; }
- /// <summary>
- /// 最后更新时间
- /// </summary>
- public long last_time { get; set; }
- /// <summary>
- /// 任务完成数
- /// </summary>
- public int taskComplete { get; set; }
- /// <summary>
- /// 超时时间,单位毫秒
- /// </summary>
- public long timeout { get; set; } = 30000;
- /// <summary>
- /// 延迟时间,单位毫秒
- /// </summary>
- public long delay { get; set; } = 3000;
- /// <summary>
- /// PDF服务地址
- /// </summary>
- public string? screenUrl { get; set; }
- }
- public class SignalRClient
- {
- /// <summary>
- /// 授权类型,bookjs_api
- /// </summary>
- public string? grant_type { get; set; }
- /// <summary>
- /// 客户端id
- /// </summary>
- public string? clientid { get; set; }
- /// <summary>
- /// SignalR的连接ID 不建议暴露。
- /// </summary>
- public string? connid { get; set; }
- public string? serverid { get; set;}
- }
- public interface IClient
- {
- Task ReceiveMessage(MessageBody message);
- Task ReceiveConnection(MessageBody message);
- Task ReceiveDisConnection(MessageBody message);
- }
- public abstract class MessageBody
- {
- public MessageBody()
- {
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- }
- /// <summary>
- /// 连接id
- /// </summary>
- public virtual string? connid { get; set; }
- /// <summary>
- /// 客户端id
- /// </summary>
- public virtual string? clientid { get; set; }
- /// <summary>
- /// 状态 busy 忙碌,free 空闲,down 离线,error 错误
- /// </summary>
- public virtual string? status { get; set; }
- /// <summary>
- /// 消息内容
- /// </summary>
- public virtual string? content { get; set; }
- /// <summary>
- /// 消息创建时间
- /// </summary>
- public virtual long time { get; }
- /// <summary>
- /// 授权类型,bookjs_api
- /// </summary>
- public virtual string? grant_type { get; set; }
- /// <summary>
- /// 消息类型
- /// </summary>
- public virtual MessageType message_type { get; set; }
-
- }
- /// <summary>
- /// 连接消息
- /// </summary>
- public class ConnectionMessage : MessageBody
- {
- }
- /// <summary>
- /// 断开连接消息
- /// </summary>
- public class DisConnectionMessage : MessageBody
- {
- }
- /// <summary>
- /// 业务处理消息
- /// </summary>
- public class ScreenProcessMessage : MessageBody
- {
- public string msg { get; set; }
- public int result { get; set; }
- }
- public static class ScreenConstant
- {
- public static readonly string busy = "busy";
- public static readonly string idle = "idle";
- public static readonly string error = "error";
- public static readonly string offline = "offline";
- public static readonly string grant_type = "bookjs_api";
- public static readonly string env_release = "release";
- public static readonly string env_develop = "develop";
- /// <summary>
- /// 冗余时间
- /// </summary>
- public static readonly long time_excess = 5000;
- }
- public enum MessageType {
- conn_success,//连接成功
- conn_error,// 连接失败
- task_send_success,// 任务发送成功
- task_send_error,// 任务发送失败
- task_execute_success,// 任务执行成功
- task_execute_error,// 任务执行失败
- }
- public class ClientDevice
- {
- /// <summary>
- /// 机器名
- /// </summary>
- public string? name { get; set; }
- /// <summary>
- /// 操作系统
- /// </summary>
- public string? os { get; set; }
- /// <summary>
- /// CPU核心数量
- /// </summary>
- public int cpu { get; set; }
- /// <summary>
- /// 内存大小
- /// </summary>
- public long ram { get; set;}
- /// <summary>
- /// 远程ip
- /// </summary>
- public string? remote { get; set; }
- /// <summary>
- /// 端口,可能有多个端口
- /// </summary>
- public string? port { get; set; }
- /// <summary>
- /// 地区
- /// </summary>
- public string? region { get; set; }
- /// <summary>
- /// 网卡 IP信息
- /// </summary>
- public List<Network> networks { get; set; } = new List<Network>();
-
- /// <summary>
- /// 设备id
- /// </summary>
- public string? deviceId { get; set; }
- }
- public class Network
- {
- public string? name { get; set; }
- public string? mac { get; set; }
- public string? ip { get; set; }
- }
- }
|