123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690 |
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.Context.Configuration;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Helper.Common.JsonHelper;
- using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
- using TEAMModelOS.SDK.DI;
- using System.Net.Http;
- using TEAMModelOS.SDK.Helper.Security.ShaHash;
- using TEAMModelOS.SDK.Extension;
- using System.IdentityModel.Tokens.Jwt;
- using Microsoft.AspNetCore.Authorization;
- using TEAMModelOS.Filter;
- using StackExchange.Redis;
- using Azure.Messaging.ServiceBus;
- using static TEAMModelOS.SDK.DI.AzureStorageBlobExtensions;
- using System.Linq;
- using Microsoft.AspNetCore.Http;
- using TEAMModelOS.SDK.Context.Constant.Common;
- using HTEXLib.COMM.Helpers;
- using TEAMModelOS.Models;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.SDK.Models;
- using Azure.Cosmos;
- namespace TEAMModelOS.Controllers.Core
- {
- [Route("blob")]
- [ApiController]
- public class BlobController : ControllerBase
- {
- private readonly AzureStorageFactory _azureStorage;
- private readonly IHttpClientFactory _clientFactory;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureCosmosFactory _azureCosmos;
- public IConfiguration _configuration { get; set; }
- public BlobController(AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IHttpClientFactory clientFactory, AzureRedisFactory azureRedis, IConfiguration configuration,
- DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureCosmosFactory azureCosmos)
- {
- _azureStorage = azureStorage;
- _clientFactory = clientFactory;
- _serviceBus = serviceBus;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureCosmos = azureCosmos;
- }
- /// <summary>
- /// 上传文件到指定的0-public
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("public-upload")]
- //[AuthToken(Roles = "teacher,admin")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<IActionResult> PublicUpload([FromForm] IFormFile file)
- {
- var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
- string fileExt = FileType.GetExtention(file.FileName).ToLower();
- if (ContentTypeDict.dict.ContainsKey($".{fileExt}"))
- {
- var url= await _azureStorage.UploadFileByContainer("0-public", file.OpenReadStream(), "school", $"{Guid.NewGuid()}.{fileExt}", false);
- return Ok(new { url });
- }
- else {
- return BadRequest();
- }
-
- }
- /// <summary>
- /// 获取某个容器的只读权限
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("sas-r")]
- public IActionResult BlobSasR(BlobSas request)
- {
- ///返回金钥过期时间
- // Dictionary<string, object> dict = await azureBlobDBRepository.GetBlobSasUri(request.@params,true);
- // dict.Add(d.Key, d.Value);
- return Ok(_azureStorage.GetContainerSasUri(request, true));
- }
- /// <summary>
- /// 某个文件的上传SAS rcw权限
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("sas-rcwld")]
- public IActionResult BlobSasRCW(BlobSas request)
- {
- ///返回金钥过期时间
- // Dictionary<string,object> dict= await azureBlobDBRepository.GetBlobSasUri(request.@params,false);
- // Dictionary<string, object> dict = ;
- //dict.Add(d.Key, d.Value);
- return Ok(_azureStorage.GetContainerSasUri(request, false));
- }
-
- /// <summary>
- /// 删除prefix
- ///
- /// {"cntr":"","prefix":"res/test"}
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("delete-prefix")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> DeletePrefix(JsonElement json)
- {
- var (id,_,_,school) = HttpContext.GetAuthTokenInfo();
- string blobContainerName = null;
- string prefix = null;
- if (json.TryGetProperty("cntr", out JsonElement cntr)&& cntr.ValueKind.Equals(JsonValueKind.String)) {
- var cntrs= cntr.GetString();
-
- if (cntrs.Equals(id))
- {
- blobContainerName = id;
- }
- else if(cntrs.Equals(school))
- {
- blobContainerName = school;
- }
- else
- {
- return BadRequest("只能删除本人管理的文件夹");
- }
- }
- if (json.TryGetProperty("prefix", out JsonElement prefixjson) && prefixjson.ValueKind.Equals(JsonValueKind.String))
- {
- prefix = prefixjson.GetString();
- }
- if (prefix != null && blobContainerName != null)
- {
- var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, prefix);
- string u ="";
- string[] uls = System.Web.HttpUtility.UrlDecode($"{prefixjson}", Encoding.UTF8).Split("/");
- if (uls != null)
- {
- u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
- }
- var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root =u, name = $"{blobContainerName}" }.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "BlobRoot");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- return Ok(new { status });
- }
- else {
- return BadRequest();
- }
-
- }
-
- /// <summary>
- /// 删除多个Url
- ///
- /// {"cntr":"","urls":["res/test/1.json","res/test/2.json"]}
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("delete-blobs")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> DeleteBlobs(JsonElement json)
- {
- var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
- string blobContainerName = null;
- List<Uri> uris = null;
- if (json.TryGetProperty("cntr", out JsonElement cntr))
- {
- var cntrs = cntr.ToString();
- if (cntrs.Equals(id))
- {
- blobContainerName = id;
- }
- else if (cntrs.Equals(school))
- {
- blobContainerName = school;
- }
- else {
- return BadRequest("只能删除本人管理的文件");
- }
- }
- bool flag = true;
- if (json.TryGetProperty("urls", out JsonElement urlsjson)) {
- uris= urlsjson.ToObject<List<Uri>>();
- uris.ForEach(x => {
- (string, string) a = BlobUrlString(x.ToString());
- string ContainerName = a.Item1;
- string BlobName = a.Item2;
- if (ContainerName!=blobContainerName) {
- flag = false;
- }
- });
- }
- if (flag)
- {
- if (blobContainerName != null && uris != null && uris.Count > 0)
- {
- var urls = urlsjson.ToObject<List<string>>();
- var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, uris);
- //释放的空间
- HashSet<string> root = new HashSet<string>();
- foreach (var x in urls)
- {
- string[] uls = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8).Split("/");
- if (uls != null)
- {
- string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
- root.Add(u);
- }
- }
- root.ToList().ForEach(async x => {
- var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = x, name = $"{blobContainerName}" }.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "BlobRoot");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- });
- return Ok(new { status });
- }
- else
- {
- return BadRequest();
- }
- }
- else {
- return BadRequest("只能删除本人管理的文件");
- }
- }
- /// <summary>
- /// 链接只读(读)
- /// </summary>
- /// <param name="azureBlobSASDto"></param>
- /// <returns></returns>
- [HttpPost("sas-url-r")]
- public IActionResult GetContainerSASRead(JsonElement azureBlobSASDto)
- {
- azureBlobSASDto.TryGetProperty("url", out JsonElement azureBlobSAS);
- //string azureBlobSAS = azureBlobSASDto;
- (string, string) a = BlobUrlString(azureBlobSAS.ToString());
- string ContainerName = a.Item1;
- string BlobName = a.Item2;
- bool flg = IsBlobName(BlobName);
- if (flg)
- {
- return Ok(_azureStorage.GetBlobSasUriRead(ContainerName, BlobName));
- }
- else
- {
- return BadRequest("文件名错误");
- };
- }
-
-
- /// <summary>
- /// 获取文件内容
- /// </summary>
- /// <param name="azureBlobSASDto"></param>
- /// <returns></returns>
- [HttpPost("get-text")]
- public async Task<IActionResult> GetText(JsonElement request)
- {
- request.TryGetProperty("code", out JsonElement code);
- string azureBlobSAS = System.Web.HttpUtility.UrlDecode(code.ToString(), Encoding.UTF8);
- (string, string) a = BlobUrlString(azureBlobSAS);
- string ContainerName = a.Item1;
- string BlobName = a.Item2;
- bool flg = IsBlobName(BlobName);
- if (flg)
- {
- //TODO 需驗證
- BlobAuth blobAuth= _azureStorage.GetBlobSasUriRead(ContainerName, BlobName);
- var response= await _clientFactory.CreateClient().GetAsync(new Uri(blobAuth.url + blobAuth.sas));
- response.EnsureSuccessStatusCode();
- using var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
- return Ok(json.RootElement);
- }
- else
- {
- return BadRequest("文件名错误");
- };
- }
-
- /// <summary>
- /// 获取容器的 分类及总量
- /// </summary>
- /// <param name="azureBlobSASDto"></param>
- /// <returns></returns>
- [HttpPost("get-blobsize")]
- public async Task<ActionResult> GetBlobsSize(JsonElement request)
- {
- try
- {
- request.TryGetProperty("containerName", out JsonElement containerName);
- request.TryGetProperty("cache", out JsonElement cache);
- var name =containerName.GetString();
- if (cache.GetBoolean())
- {
- long blobsize = 0;
- RedisValue value = default;
- value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", name);
- if (value != default && !value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetInt64(out blobsize))
- {
- }
- }
- else
- {
- var client = _azureStorage.GetBlobContainerClient(name);
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- return Ok(new { size = size.Item1, catalog = size.Item2 });
- }
- Dictionary<string, double> catalog = new Dictionary<string, double>();
- SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{name}");
- if (Scores != null)
- {
- foreach (var score in Scores)
- {
- double val = score.Score;
- string key = score.Element.ToString();
- catalog.Add(key, val);
- }
- return Ok(new { size = blobsize, catalog = catalog });
- }
- else {
- var client = _azureStorage.GetBlobContainerClient(name);
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- return Ok(new { size = size.Item1, catalog = size.Item2 });
- }
- }
- else {
- var client = _azureStorage.GetBlobContainerClient(name);
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- return Ok(new { size = size.Item1, catalog = size.Item2 });
- }
-
- }
- catch (Exception ex){
- await _dingDing.SendBotMsg($"IES5,{_option.Location},blon/get-blobsize()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- return BadRequest();
- }
- //TODO 不要了
- /// <summary>
- /// 测试单个文本内容的上传
- /// {"containerName":"hbcn","urls":["video/xxx.mp4","res/xxx.png"],"prefix":["res/xxx","res/aaa"]}
- /// </summary>
- /// <param name="azureBlobSASDto"></param>
- /// <returns></returns>
- [HttpPost("check-blobsize")]
- public async Task<ActionResult> checkBlobsSize(JsonElement request)
- {
- request.TryGetProperty("containerName", out JsonElement containerName);
- request.TryGetProperty("urls", out JsonElement optUrls);
- request.TryGetProperty("prefix", out JsonElement prefixjs);
- var name = containerName.GetString();
- var urls = optUrls.ValueKind.Equals(JsonValueKind.Array) ? optUrls.ToObject<List<string>>() : null ;
- var client = _azureStorage.GetBlobContainerClient(name);
- var urlsSize = await client.GetBlobsSize(urls);
- List<OptUrl> prefixSize = new List<OptUrl>();
- var prefixs = prefixjs.ValueKind.Equals(JsonValueKind.Array) ? prefixjs.ToObject<List<string>>() : new List<string>();
- foreach(var prefix in prefixs) {
- var size = await client.GetBlobsSize(System.Web.HttpUtility.UrlDecode(prefix, Encoding.UTF8));
- prefixSize.Add(new OptUrl { url = prefix, size = size.Value });
- }
- return Ok(new { urlsSize , prefixSize });
- }
- /*
- *
- {
- "containerName": "hbcn",
- "cache": true,
- "optUrls": [
- {
- "url": "video%2F37Z888piCvm9.mp4",
- "size": 1000
- }
- ]
- }
- */
- //TODO 不要了
- /// <summary>
- /// 测试单个文本内容的上传
- /// {"containerName":"hbcn","uploadSize":5000,"optUrls":[{"url":"video/37Z888piCvm9.mp4","size":0},{}]}
- /// </summary>
- /// <param name="azureBlobSASDto"></param>
- /// <returns></returns>
- [HttpPost("update-blobsize")]
- public async Task<ActionResult> updateBlobsSize(JsonElement request)
- {
- request.TryGetProperty("containerName", out JsonElement containerName);
- request.TryGetProperty("optUrls", out JsonElement optUrls);
- var name = containerName.GetString();
- var urls = optUrls.ToObject<List<OptUrl>>();
- var client = _azureStorage.GetBlobContainerClient(name);
- var disSize = urls.Select(x => x.size).Sum();
- RedisValue value = default;
- long blobSize = 0;
- value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", name);
- if (value != default && !value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetInt64(out blobSize))
- {
- }
- }
- long? useSize = blobSize + disSize;
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, useSize);
- Dictionary<string, double?> catalog = new Dictionary<string, double?>();
- HashSet<string> root = new HashSet<string>();
- foreach (var x in urls) {
- string[] uls = System.Web.HttpUtility.UrlDecode(x.url, Encoding.UTF8).Split("/");
- if (uls != null)
- {
- string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
- root.Add(u);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, x.size);
- catalog[u] = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{name}", u);
- if (catalog[u] < 0)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
- catalog[u] = 0;
- }
- }
- }
- var messageBlob = new ServiceBusMessage(new {id=Guid.NewGuid().ToString(), progress = "update", root= root.ToArray(), name=name}.ToJsonString());;
- messageBlob.ApplicationProperties.Add("name", "Blob");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- return Ok(new { size=useSize, catalog });
- }
- /// <summary>
- /// {"name":"hbcn","urls":["root/xxxx/xxx.json","root/xxxx/xxx.json"]}
- /// </summary>
- /// <param name="azureBlobSASDto"></param>
- /// <returns></returns>
- [HttpPost("refresh-blobsize")]
- public async Task<ActionResult> RefreshBlob(JsonElement request) {
- try {
- request.TryGetProperty("name", out JsonElement name);
- request.TryGetProperty("urls", out JsonElement jurls);
- var urls = jurls.ToObject<List<string>>();
- HashSet<string> root = new HashSet<string>();
- foreach (var x in urls)
- {
- string[] uls = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8).Split("/");
- if (uls != null) {
- string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
- root.Add(u);
- }
- }
- root.ToList().ForEach(async x => {
- var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root =x, name = $"{name}" }.ToJsonString()); ;
- messageBlob.ApplicationProperties.Add("name", "BlobRoot");
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
- });
- return Ok(new { status = 200 });
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},blon/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- return Ok(new { status = 500 });
- }
- private static (string, string) BlobUrlString(string sasUrl)
- {
- sasUrl = sasUrl.Substring(8);
- string[] sasUrls = sasUrl.Split("/");
- string ContainerName;
- ContainerName = sasUrls[1].Clone().ToString();
- string item = sasUrls[0] + "/" + sasUrls[1] + "/";
- string blob = sasUrl.Replace(item, "");
- return (ContainerName, blob);
- }
- public static bool IsBlobName(string BlobName)
- {
- return System.Text.RegularExpressions.Regex.IsMatch(BlobName,
- @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("bloblog-list")]
- public async Task<ActionResult> BloblogList(JsonElement request) {
- List<Bloblog> bloblogs = new List<Bloblog>();
- try
- {
- request.TryGetProperty("name", out JsonElement name);
- request.TryGetProperty("type", out JsonElement type);
- request.TryGetProperty("scope", out JsonElement scope);
- request.TryGetProperty("periodId", out JsonElement periodId);
- var client = _azureCosmos.GetCosmosClient();
-
- if (scope.GetString().Equals("school"))
- {
- var queryslt = new StringBuilder($"SELECT value(c) FROM c join A1 in c.periodId WHERE c.type='{type}' and A1 in ('{periodId}') ");
-
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Bloblog>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
- {
- bloblogs.Add(item);
- }
- }
- else if (scope.GetString().Equals("private"))
- {
- var queryslt = new StringBuilder($"SELECT value(c) FROM c WHERE c.type='{type}' ");
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Bloblog>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
- {
- bloblogs.Add(item);
- }
- }
- return Ok(new { bloblogs = bloblogs });
- }
- catch (Exception ex) {
- return Ok(new { bloblogs = bloblogs });
- }
- }
- /*
- 新增 编辑接口
- {
- "periodId": "",
- "scope": "school",
- "name": "hbcn",
- "url": "video/xxx.png",
- "opt": "add",
- }
- */
- /*
- {
- "scope": "school",
- "name": "hbcn",
- "opt": "del",
- "id": "19ccce98-c524-4ea7-aabc-887d1391e551"
- }
- */
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("bloblog-opt")]
- public async Task<ActionResult> BloblogOpt(JsonElement request) {
- try
- {
- request.TryGetProperty("periodId", out JsonElement periodId);
- request.TryGetProperty("subjectId", out JsonElement subjectId);
- request.TryGetProperty("gradeId", out JsonElement gradeId);
- request.TryGetProperty("scope", out JsonElement scope);
- request.TryGetProperty("name", out JsonElement name);
- request.TryGetProperty("url", out JsonElement jurl);
- request.TryGetProperty("opt", out JsonElement opt);
- request.TryGetProperty("id", out JsonElement id);
-
- //获取文件的大小
- var client = _azureCosmos.GetCosmosClient();
- if (opt.GetString().Equals("add"))
- {
- var url = System.Web.HttpUtility.UrlDecode(jurl.GetString(), Encoding.UTF8);
- string[] uls = url.Split("/");
- var u = "";
- if (uls != null)
- {
- u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
- }
- var size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(url);
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //地址相同的,直接更新
- bool exsit = false;
- try {
- var queryslt = $"SELECT value(c) FROM c WHERE c.url='{url}'";
- if (scope.GetString().Equals("school"))
- {
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
- {
- item.time = now;
- item.size = size != null && size.HasValue ? size.Value : 0;
- item.periodId = periodId.ValueKind.Equals(JsonValueKind.Array) && periodId.ToObject<List<string>>().IsNotEmpty() ? periodId.ToObject<List<string>>() : new List<string> { "" };
- item.subjectId = subjectId.ValueKind.Equals(JsonValueKind.Array) && subjectId.ToObject<List<string>>().IsNotEmpty() ? subjectId.ToObject<List<string>>() : new List<string> { "" };
- item.gradeId = gradeId.ValueKind.Equals(JsonValueKind.Array) && gradeId.ToObject<List<string>>().IsNotEmpty() ? gradeId.ToObject<List<string>>() : new List<string> { "" };
- await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Bloblog>(item, item.id, new Azure.Cosmos.PartitionKey(item.code));
- exsit = true;
- }
- }
- else if (scope.GetString().Equals("private")) {
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
- {
- item.time = now;
- item.size = size != null && size.HasValue ? size.Value : 0;
- item.periodId = periodId.ValueKind.Equals(JsonValueKind.Array) && periodId.ToObject<List<string>>().IsNotEmpty() ? periodId.ToObject<List<string>>() : new List<string> { "" };
- item.subjectId = subjectId.ValueKind.Equals(JsonValueKind.Array) && subjectId.ToObject<List<string>>().IsNotEmpty() ? subjectId.ToObject<List<string>>() : new List<string> { "" };
- item.gradeId = gradeId.ValueKind.Equals(JsonValueKind.Array) && gradeId.ToObject<List<string>>().IsNotEmpty() ? gradeId.ToObject<List<string>>() : new List<string> { "" };
- await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Bloblog>(item, item.id, new Azure.Cosmos.PartitionKey(item.code));
- exsit = true;
- }
- }
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},blob/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- if (!exsit) {
- var blob = new Bloblog
- {
- id = Guid.NewGuid().ToString(),
- pk = "Bloblog",
- code = $"Bloblog-{name}",
- url = url,
- time = now,
- size = size != null && size.HasValue ? size.Value : 0,
- periodId = periodId.ValueKind.Equals(JsonValueKind.Array) && periodId.ToObject<List<string>>().IsNotEmpty() ? periodId.ToObject<List<string>>() : new List<string> { "" } ,
- subjectId= subjectId.ValueKind.Equals(JsonValueKind.Array)&& subjectId.ToObject<List<string>>() .IsNotEmpty()? subjectId.ToObject<List<string>>() : new List<string> { ""},
- gradeId = gradeId.ValueKind.Equals(JsonValueKind.Array) && gradeId.ToObject<List<string>>().IsNotEmpty() ? gradeId.ToObject<List<string>>() : new List<string> { "" },
- type = u
- };
- if (scope.GetString().Equals("school"))
- {
- await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
- }
- else if (scope.GetString().Equals("private"))
- {
- await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
- }
- }
- }
- else if (opt.GetString().Equals("del"))
- {
- if (scope.GetString().Equals("school"))
- {
- await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"Bloblog-{name}"));
- }
- else if (scope.GetString().Equals("private"))
- {
- await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"Bloblog-{name}"));
- }
- }
- else { return BadRequest(); }
- return Ok(new { status = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},blob/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- return Ok(new { status = 200 });
- }
- }
- }
|