123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944 |
- 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.Common;
- using System.Configuration;
- 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)
- {
- 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", 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);
- }
- public static async Task PushScreenTask(AzureRedisFactory _azureRedis, IConfiguration _configuration, string _artId, ArtEvaluation art, List<ArtStudentPdf> studentPdfs)
- {
- 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;
- }
- var addData = await GenPDFService.AddGenPdfQueue(_azureRedis,
- 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()
- });
- //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: 不删除文件
- //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 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; }
- }
- 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 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>
- /// 超时时间,单位毫秒
- /// </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 Network
- {
- public string? name { get; set; }
- public string? mac { get; set; }
- public string? ip { get; set; }
- }
- }
|