ScreenService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. using HTEXScreen.Service.AzureRedis;
  2. using PuppeteerSharp;
  3. using PuppeteerSharp.Media;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Text.Json;
  7. using System.Text.Json.Nodes;
  8. using System.Text.RegularExpressions;
  9. using System.Web;
  10. using TEAMModelOS.SDK.DI;
  11. namespace HTEXScreen.Service
  12. {
  13. public class ScreenService
  14. {
  15. public static async Task UpdateStuArtPDF(IEnumerable<string> urls, ScreenshotDto screenshot, AzureRedisFactory _azureRedisFactory, AzureCosmosFactory _azureCosmosFactory) {
  16. var env = screenshot.env.Equals("release") ? "Default" : "Test";
  17. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  18. List<Task<Azure.Response>> responses = new List<Task<Azure.Response>>();
  19. List<Task<bool>> redisSaves = new List<Task<bool>>();
  20. foreach (var url in urls)
  21. {
  22. //https://teammodeltest.blob.core.chinacloudapi.cn/hbcn/art/e9a5ec36-7299-45dc-9517-7457960346c4/report/202106005.pdf
  23. var uri = HttpUtility.UrlDecode(url);
  24. var paths = uri.Split("/hbcn/art/");
  25. if (paths.Length == 2) {
  26. var ps= paths[1].Split("/");
  27. if (ps.Length == 3) {
  28. string key = $"ArtPDF:{ps[0]}";
  29. string field = ps[2].Replace(".pdf", "");
  30. var value = _azureRedisFactory.GetRedisClient(8, env).HashGet(key, field);
  31. if (value.HasValue && !value.IsNullOrEmpty)
  32. {
  33. JsonNode node = JsonNode.Parse(value.ToString());
  34. if (node != null) {
  35. var pdfNode= node["pdf"];
  36. var id = node["id"];
  37. var code = node["code"];
  38. if (pdfNode != null)
  39. {
  40. pdfNode["url"] = uri;
  41. pdfNode["blob"] = $"/art/{paths[1]}";
  42. pdfNode["createTime"] = now;
  43. pdfNode["prime"] = true;//此处的作用是判断是否已经生成OK.
  44. node["pdf"] = pdfNode;
  45. }
  46. else {
  47. pdfNode = new JsonObject();
  48. pdfNode["url"] = uri;
  49. pdfNode["blob"] = $"/art/{paths[1]}";
  50. pdfNode["createTime"] = now;
  51. pdfNode["prime"] = true;//此处的作用是判断是否已经生成OK.
  52. node["pdf"] = pdfNode;
  53. }
  54. string json = node.ToJsonString();
  55. redisSaves.Add(_azureRedisFactory.GetRedisClient(8, env).HashSetAsync(key, field, json));
  56. byte[] bytes = Encoding.UTF8.GetBytes(json);
  57. var memoryStream = new MemoryStream(bytes);
  58. responses.Add(_azureCosmosFactory.GetCosmosClient(null,env).GetContainer("TEAMModelOS", "Student").ReplaceItemStreamAsync(memoryStream, $"{id}", new Azure.Cosmos.PartitionKey($"{code}")));
  59. }
  60. }
  61. }
  62. }
  63. }
  64. await Task.WhenAll(redisSaves);
  65. await Task.WhenAll(responses);
  66. }
  67. public static async Task<List<(string name ,string url )>> ScreenshotPdf(ScreenshotDto screenshot, AzureStorageFactory _azureStorage) {
  68. //W3C School教程 https://www.w3cschool.cn/puppeteer/puppeteer-rip537tj.html
  69. // 进入容器的命令 docker exec -it f9e27d175498 /bin/bash
  70. //依赖包 https://blog.csdn.net/weixin_45447477/article/details/115188938
  71. //sudo apt-get install libgdk-pixbuf2.0-0 libgdk-pixbuf-xlib-2.0-0 libdbusmenu-gtk3-4 libdbusmenu-glib4 libindicator3-7 ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils -y
  72. //解决ubuntu18上使用puppeteer https://blog.csdn.net/qq_42414062/article/details/114539378
  73. //https://www.hardkoded.com/blog/running-puppeteer-sharp-azure-functions 使用。
  74. //string url = "https://teammodelos.blob.core.chinacloudapi.cn/0-public/pie-borderRadius.html";
  75. Browser browser = null;
  76. try
  77. {
  78. var bfOptions = new BrowserFetcherOptions();
  79. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  80. {
  81. string dir = "/app";
  82. if (!Directory.Exists(dir))
  83. {
  84. Directory.CreateDirectory(dir);
  85. }
  86. bfOptions.Path = dir;
  87. }
  88. var bf = new BrowserFetcher(bfOptions);
  89. var revisionInfo = bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision).Result;
  90. string BrowserExecutablePath = revisionInfo.ExecutablePath;
  91. browser = await Puppeteer.LaunchAsync(new LaunchOptions
  92. {
  93. ExecutablePath = BrowserExecutablePath,
  94. Headless = true,
  95. Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }
  96. });
  97. double unitPX = 37.7813;
  98. ViewPortOptions viewPortOptions = new ViewPortOptions
  99. {
  100. // Width = (int)Math.Ceiling(unitPX * 21),
  101. // Height = (int)Math.Ceiling(unitPX * 29.7 * 1)
  102. };
  103. //ViewPortOptions viewPortOptions = new ViewPortOptions
  104. //{
  105. // Width = screenshot.width,
  106. // Height = screenshot.height
  107. //};
  108. PdfOptions pdfOptions = new PdfOptions { DisplayHeaderFooter = true, FooterTemplate = "", PreferCSSPageSize = true, Format = PaperFormat.A4 };
  109. //ScreenshotOptions screenshotOptions= new ScreenshotOptions { FullPage = fullPage, BurstMode = true };
  110. List<(string anme ,string url )> urls = new List<(string name, string url)>();
  111. if (screenshot.urls.Count <= screenshot.pagesize)
  112. {
  113. urls.AddRange(await PageToPdfStream(_azureStorage,screenshot.urls, screenshot.fileNameKey, screenshot.cnt, screenshot.root, screenshot.env, browser, viewPortOptions, pdfOptions));
  114. }
  115. else
  116. {
  117. List<Task<List<(string name ,string url )>>> tasks = new List<Task<List<(string name, string url)>>>();
  118. int pages = (screenshot.urls.Count + screenshot.pagesize) / screenshot.pagesize;
  119. for (int i = 0; i < pages; i++)
  120. {
  121. var lists = screenshot.urls.Skip((i) * screenshot.pagesize).Take(screenshot.pagesize).ToList();
  122. tasks.Add(PageToPdfStream(_azureStorage,lists, screenshot.fileNameKey, screenshot.cnt, screenshot.root, screenshot.env, browser, viewPortOptions, pdfOptions));
  123. }
  124. var tsk = await Task.WhenAll(tasks);
  125. foreach (var ts in tsk)
  126. {
  127. urls.AddRange(ts);
  128. }
  129. }
  130. //browser.NewPageAsync();
  131. //foreach (var url in screenshot.urls) {
  132. // var page = await browser.NewPageAsync();
  133. // await page.SetViewportAsync(viewPortOptions);
  134. // string file = $"E://pdfs//{Guid.NewGuid().ToString()}.pdf";
  135. // var respons = await page.GoToAsync(System.Web.HttpUtility.UrlDecode(url), WaitUntilNavigation.Networkidle2);
  136. // if (respons.Ok)
  137. // {
  138. // await page.PdfAsync(file, pdfOptions);
  139. // // string base64 = await page.ScreenshotBase64Async(screenshotOptions);
  140. // }
  141. //}
  142. //关闭浏览器
  143. await browser.CloseAsync();
  144. await browser.DisposeAsync();
  145. return urls;
  146. }
  147. catch (Exception ex)
  148. {
  149. StreamWriter file = new StreamWriter("erorr_log.txt", append: true);
  150. await file.WriteLineAsync($"ScreenService {JsonSerializer.Serialize(screenshot)}-----{ex.Message}----{ex.StackTrace}");
  151. file.Close();
  152. return new List<(string name, string url)>();
  153. //return BadRequest($"{ex.Message}\n{ex.StackTrace}");
  154. }
  155. finally
  156. {
  157. if (browser != null && !browser.IsClosed)
  158. {
  159. await browser.CloseAsync();
  160. await browser.DisposeAsync();
  161. }
  162. }
  163. }
  164. private static async Task<List<(string name ,string url )>> PageToPdfStream(AzureStorageFactory _azureStorage,List<string> urls, string fileNameKey, string cnt, string root, string env, Browser browser, ViewPortOptions viewPortOptions, PdfOptions pdfOptions)
  165. {
  166. string name = env.Equals("release") ? "Default" : "Test";
  167. List<Task<Page>> pages = new List<Task<Page>>();
  168. urls.ForEach(x => {
  169. pages.Add(browser.NewPageAsync());
  170. });
  171. var page_tasks = await Task.WhenAll(pages);
  172. List<Task<Response>> responses = new List<Task<Response>>();
  173. page_tasks.ToList().ForEach(x => {
  174. x.SetViewportAsync(viewPortOptions);
  175. });
  176. for (int i = 0; i < urls.Count; i++)
  177. {
  178. responses.Add(page_tasks[i].GoToAsync(urls[i], 30000, new WaitUntilNavigation[] { WaitUntilNavigation.Networkidle2 }));
  179. }
  180. var responses_tasks = await Task.WhenAll(responses);
  181. //List<Task<Stream>> streams = new List<Task<Stream>>();
  182. List<Task> tasks = new List<Task>();
  183. List<Task<(string name , string url )>> uploads = new List<Task<(string name, string url)>>();
  184. foreach (var page_task in page_tasks)
  185. {
  186. string url = page_task.Url;
  187. string[] paths = HttpUtility.UrlDecode(url).Split("/");
  188. var reg = $"(?<=\\b{fileNameKey}=)[^&]*";
  189. Regex regex = new Regex(reg);
  190. string decode = HttpUtility.UrlDecode(url);
  191. Match match = Regex.Match(decode, reg);
  192. string id = "";
  193. while (match.Success)
  194. {
  195. id = id + $"{match.Value}";
  196. match = match.NextMatch();
  197. }
  198. //需要解析参数。paths[paths.Length-1]
  199. Stream stream = await page_task.PdfStreamAsync(pdfOptions);
  200. if (string.IsNullOrWhiteSpace(cnt))
  201. {
  202. uploads.Add(_azureStorage.GetBlobContainerClient("teammodelos", name).UploadFileByContainer(stream, root, $"{id}.pdf", true));
  203. }
  204. else
  205. {
  206. uploads.Add(_azureStorage.GetBlobContainerClient(cnt, name).UploadFileByContainer(stream, root, $"{id}.pdf", true));
  207. }
  208. }
  209. (string name ,string url )[] uploadUrls = await Task.WhenAll(uploads);
  210. page_tasks.ToList().ForEach(x => {
  211. tasks.Add(x.DisposeAsync().AsTask());
  212. });
  213. await Task.WhenAll(tasks);
  214. return uploadUrls.ToList();
  215. }
  216. }
  217. public class ScreenshotDto
  218. {
  219. public int width { get; set; } = 1920;
  220. public int height { get; set; } = 1080;
  221. public string? url { get; set; }
  222. /// <summary>
  223. /// 批量地址
  224. /// </summary>
  225. public List<string> urls { get; set; } = new List<string>();
  226. /// <summary>
  227. /// 提取参数的唯一id作为文件名
  228. /// </summary>
  229. public string? fileNameKey { get; set; }
  230. /// <summary>
  231. /// 存在哪个容器里
  232. /// </summary>
  233. public string? cnt { get; set; }
  234. public int delay { get; set; }
  235. public int pagesize { get; set; } = 5;
  236. public string? root { get; set; }
  237. public string? env { get; set; } = "release";
  238. public string? msgId { get; set; }
  239. }
  240. }