12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356 |
- using Azure;
- using Azure.Cosmos;
- using Azure.Storage.Blobs.Models;
- using DinkToPdf;
- using DinkToPdf.Contracts;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- 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.Threading.Tasks;
- using TEAMModelOS.Controllers.Third.LePei;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.DI.Mail;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Services;
- using static TEAMModelOS.SDK.Models.Teacher;
- using static TEAMModelOS.SDK.SchoolService;
- namespace TEAMModelOS.Controllers
- {
- [Route("test")]
- [ApiController]
- public class TestController : ControllerBase
- {
- private readonly IHttpClientFactory _httpClient;
- public IWebHostEnvironment _environment { get; set; }
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly Option _option;
- private readonly IPSearcher _searcher;
- public IConfiguration _configuration { get; set; }
- private readonly IConverter _converter;
- private readonly HttpTrigger _httpTrigger;
- private readonly AzureServiceBusFactory _azureService;
- private readonly SnowflakeId _snowflakeId;
- private readonly MailFactory _mailFactory;
- public TestController(MailFactory mailFactory,HttpTrigger httpTrigger, IConverter converter, IPSearcher searcher, IOptionsSnapshot<Option> option, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory httpClient, IWebHostEnvironment environment, AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, IConfiguration configuration, AzureServiceBusFactory serviceBus, DingDing dingDing, AzureServiceBusFactory azureService, SnowflakeId snowflakeId)
- {
- _converter = converter;
- _azureCosmos = azureCosmos;
- _azureRedis = azureRedis;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _serviceBus = serviceBus; _configuration = configuration;
- _environment = environment;
- _httpClient = httpClient;
- _option = option.Value;
- _coreAPIHttpService = coreAPIHttpService;
- _searcher = searcher;
- _httpTrigger = httpTrigger;
- _azureService=azureService;
- _snowflakeId=snowflakeId;
- _mailFactory = mailFactory;
- }
- //
- /// <summary>
- /// 移除已经废弃的StuCourse 数据
- /// </summary>
- /// <param name="file"></param>
- /// <param name="periodId"></param>
- /// <returns></returns>
- [HttpPost("test-accumulate")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<IActionResult> RemoveStuCourse(JsonElement json)
- {
- json.TryGetProperty("am", out JsonElement _am);
- json.TryGetProperty("pm", out JsonElement _pm);
- int am = 0;
- int pm = 0;
- _am.TryGetInt32(out am);
- _pm.TryGetInt32(out pm);
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- string location = "";
- if (_option.Location.Contains("China"))
- {
- location = "China";
- }
- else if (_option.Location.Contains("Global"))
- {
- location = "Global";
- }
- var client = _httpClient.CreateClient();
- var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location).Result;
- if (client.DefaultRequestHeaders.Contains("Authorization"))
- {
- client.DefaultRequestHeaders.Remove("Authorization");
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- else
- {
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- List<CodeValue> notifys= await SystemService.AccumulateDaily(_configuration, _azureRedis,_azureCosmos, _coreAPIHttpService,_dingDing,client, _snowflakeId, url,am ,pm );
- return Ok(new { notifys });
- }
- /*
- [
- {
- "id": "99a4a33b-e21b-44ac-80a1-b31dc40496e0",
- "name": "蒲江县提升工程2.0研训平台"
- },
- {
- "id": "f35e0031-a53f-45e5-b307-1cd39446a2cf",
- "name": "金牛区直属学校提升工程2.0研训平台"
- },
- {
- "id": "2c1b01fe-3641-464f-8499-7be95a489b7c",
- "name": "峨边彝族自治县提升工程2.0研训平台"
- },
- {
- "id": "870a5a6b-1ab3-461a-bdeb-baec19780ddb",
- "name": "金牛区非直属学校提升工程2.0研训平台"
- },
- {
- "id": "dd15017a-f361-4346-852e-8eee71d027ad",
- "name": "峨眉山提升工程2.0研训平台"
- },
- {
- "id": "3b5a9b06-a9ec-4bac-b1dd-f73f5519f637",
- "name": "乐山市井研县提升工程2.0研训平台"
- },
- {
- "id": "1680c1c5-14e4-4bc2-b4cb-1749a537a01f",
- "name": "宜宾市筠连县提升工程2.0研训平台"
- },
- {
- "id": "e6fb5d40-bd85-7327-cea8-ea5c642836d2",
- "name": "广安市岳池县提升工程2.0研训平台"
- },
- {
- "id": "b14668be-d2f0-4923-8bf6-a27d9cc9111d",
- "name": "犍为县提升工程2.0研训平台"
- },
- {
- "id": "f49a83de-6156-448a-93b1-f03d0da967d6",
- "name": "宜宾市屏山县提升工程2.0研训平台"
- },
- {
- "id": "4a37997a-12b1-4f21-876b-3d9ba940fe54",
- "name": "宜宾市屏山县提升工程2.0研训平台(非一线)"
- },
- {
- "id": "6104c377-f48f-4d4c-9b38-509f9ccb54db",
- "name": "武胜县提升工程2.0研训平台"
- }
- ]
- */
- /// <summary>
- /// 将区级下所以学校的研修数据封存
- /// </summary>
- /// <param name="data"></param>
- /// <returns></returns>
- [HttpPost("change-blob-to-archive")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<IActionResult> Change(JsonElement data)
- {
- IdName area = null;
- if (data.TryGetProperty("area", out JsonElement _area))
- {
- area= _area.ToObject<IdName>();
- }
- List<ScTeacher> teachers = new List<ScTeacher>();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
- List<int> pids = new List<int>();
- if (data.TryGetProperty("pids", out JsonElement _pids))
- {
- pids=_pids.ToObject<List<int>>();
- }
- if (pids.IsNotEmpty()) {
- foreach (var p in pids)
- {
- List<ScTeacher> teachersTable= await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "ProjectItemID", p } });
- if (teachersTable.IsNotEmpty()) {
- teachers.AddRange(teachersTable);
- }
- }
- }
- HashSet<string> ids = teachers.Where(v => !string.IsNullOrWhiteSpace(v.tmdid)).Select(z => z.tmdid).ToHashSet();
- List<SchoolEconomy> economies = new List<SchoolEconomy>(0);
- if (area!= null)
- {
- string sql = $"select value c from c where c.areaId ='{area.id}'";
- List<School> schools = new List<School>();
- var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sql, "Base");
- if (result.list.IsNotEmpty())
- {
- schools.AddRange(result.list);
- }
- foreach (var school in schools)
- {
- double? ScoresYxpt = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{school.id}", "yxpt");
- double? ScoresTrain = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{school.id}", "train");
- double total = ((ScoresYxpt.HasValue ? ScoresYxpt.Value : 0)+(ScoresTrain.HasValue ? ScoresTrain.Value : 0))*1.0 /1073741824; //GB
- List<string> yxpts = await _azureStorage.GetBlobContainerClient(school.id).List("yxpt");
- HashSet<string> archive = new HashSet<string>();
- if (yxpts.IsNotEmpty()) {
- foreach (var uri in yxpts)
- {
- if (ids!=null && ids.Count>0)
- {
- bool has = false;
- foreach (var id in ids)
- {
- if (uri.Contains(id))
- {
- has = true;
- break;
- }
- }
- if (!has)
- {
- archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
- }
- }
- else
- {
- archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
- }
- }
- }
-
- List<string> trains = await _azureStorage.GetBlobContainerClient(school.id).List("train");
- if (trains.IsNotEmpty())
- {
- foreach (var uri in trains)
- {
- if (ids!=null && ids.Count>0)
- {
- bool has = false;
- foreach (var id in ids)
- {
- if (uri.Contains(id))
- {
- has = true;
- break;
- }
- }
- if (!has)
- {
- archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
- }
- }
- else
- {
- archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
- }
- }
- }
-
- if (archive.Count==0)
- {
- economies.Add(new SchoolEconomy { schoolId= school.id, schoolName= school.name, areaId=area.id, areaName=area.name, total=0, count=(yxpts!=null ? yxpts.Count : 0)+(trains!=null ? trains.Count : 0), archive=archive.Count });
- }
- else
- {
- //var pages = archive.Page(100);
- //foreach (var page in pages) {
- // if (page.Count()==0) { continue; }
- // try
- // {
- // await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(blobUris: page.Select(z => new Uri(z)), accessTier: AccessTier.Archive);
- // }
- // catch (Exception ex1)
- // {
- // var p20s = page.Page(20);
- // foreach (var p20 in p20s)
- // {
- // if (p20.Count()==0) { continue; }
- // try
- // {
- // await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(blobUris: p20.Select(z => new Uri(z)), accessTier: AccessTier.Archive);
- // }
- // catch (Exception ex2)
- // {
- // var p1s = p20.Page(1);
- // foreach (var p1 in p1s) {
- // if (p1.Count()==0) { continue; }
- // try
- // {
- // string path = p1.First().Replace($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/", "");
- // await _azureStorage.GetBlobContainerClient(school.id).GetBlobClient(path).SetAccessTierAsync(AccessTier.Archive);
- // }
- // catch (Exception ex3)
- // {
- // await _dingDing.SendBotMsg($"错误的链接地址:{p1.ToJsonString()}", GroupNames.成都开发測試群組);
- // }
- // }
- // }
- // }
- // }
- //}
- economies.Add(new SchoolEconomy { schoolId= school.id, schoolName= school.name, areaId=area.id, areaName=area.name, total=total, count=(yxpts!=null ? yxpts.Count : 0)+(trains!=null ? trains.Count : 0), archive=archive.Count });
- }
- }
- AreaEconomy economy = new AreaEconomy {id = area.id ,name = area.name, pk="AreaEconomy",code="AreaEconomy", economies= economies, sum= economies.Select(z => z.total).Sum(), count= economies.Select(z => z.count).Sum(), teachers= ids.ToList() };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).UpsertItemAsync(economy, new PartitionKey("AreaEconomy"));
- return Ok(new { economy });
- }
- else { return Ok(); }
-
- }
- public class AreaEconomy : CosmosEntity
- {
- public AreaEconomy(){
- pk="AreaEconomy";
- code="AreaEconomy";
- }
- public List<int> pids = new List<int>();
- public string name { get; set; }
- public List<SchoolEconomy> economies { get; set; } = new List<SchoolEconomy>();
- public double sum { get; set; }
- public long count { get; set; }
- /// <summary>
- /// 未被封存的教师
- /// </summary>
- public List<string> teachers = new List<string>();
- }
- public class SchoolEconomy {
- public string schoolId { get; set; }
- public string schoolName { get; set; }
- public string areaId { get; set; }
- public string areaName { get; set; }
- public double total { get; set; }
- public long count { get; set; }
- public long archive { get; set; }
- }
- [ProducesDefaultResponseType]
- [HttpPost("test-ru")]
- public async Task<IActionResult> FixSemester(JsonElement json)
- {
- await _azureStorage.GetBlobContainerClient("hscjzx").GetBlobClient("yxpt/standard3/jyzx/1639448922/691a16ca-b45a-4426-8e2d-162484af5d1d/B2-曹-微课方案.pdf").SetAccessTierAsync(AccessTier.Archive);
- await _azureStorage.GetBlobContainerClient("jlstcz").GetBlobClient("yxpt/standard14/jyzx/1657242924/b5625069-b8b7-431b-ab2a-643d9e2f80be/14岁少年沉迷网络,妈妈苦口婆心不起作用,偷偷躲在角落痛哭! 480P(标清)_format_2 (1).mp4").SetAccessTierAsync(AccessTier.Archive);
- //string url1 = HttpUtility.UrlPathEncode("https://teammodeltest.blob.core.chinacloudapi.cn/hscjzx/yxpt/standard3/jyzx/1639448922/691a16ca-b45a-4426-8e2d-162484af5d1d/B2-曹-微课方案.pdf");
- //string url2 = HttpUtility.UrlPathEncode("https://teammodeltest.blob.core.chinacloudapi.cn/jlstcz/yxpt/standard14/jyzx/1657242924/b5625069-b8b7-431b-ab2a-643d9e2f80be/14岁少年沉迷网络,妈妈苦口婆心不起作用,偷偷躲在角落痛哭! 480P(标清)_format_2 (1).mp4");
- //await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(
- // blobUris: new Uri[] { new Uri(url1),
- // new Uri(url2) }, accessTier: AccessTier.Archive);
- double? Scores = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:ssjxx", "yxpt");
- //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "yxpt", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
- //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "train", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
- //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "survey", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
- //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "records", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
- //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "homework", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
- //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "exam", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
- string topicName= "dep-active-task";
- List< string> msgStrs = new List< string>();
- //var client = new ServiceBusAdministrationClient("Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=");
- //var subsPages = client.GetSubscriptionsAsync(topicName);
- //await foreach (var page in subsPages.AsPages()) {
- // var subs= page.Values;
- // foreach (var sub in subs) {
- // var receiver = _azureService.GetServiceBusClient().CreateReceiver( topicName, sub.SubscriptionName, new ServiceBusReceiverOptions
- // {
- // ReceiveMode = ServiceBusReceiveMode.PeekLock
- // });
- // var scheduledMessages = await receiver.PeekMessagesAsync(100);
- // foreach (var message in scheduledMessages)
- // {
- // Console.WriteLine($"Scheduled Message: {message.Body}");
- // Console.WriteLine($"Scheduled Enqueue Time: {message.ScheduledEnqueueTime}");
- // Console.WriteLine("--------------------");
- // }
- // await receiver.CloseAsync();
- // }
- //}
- return Ok(msgStrs);
- //await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient("winteach.cn_nginx.zip").SetAccessTierAsync(AccessTier.Archive);
- //await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(
- // blobUris: new Uri[] { new Uri("https://teammodeltest.blob.core.chinacloudapi.cn/0-public/test.md"),
- // new Uri("https://teammodeltest.blob.core.chinacloudapi.cn/0-public/pay.html") },accessTier:AccessTier.Archive);
- //var cm = _azureRedis.GetConnectionMultiplexer();
- //var keys = cm.GetServer(cm.GetEndPoints()[0]).Keys(cm.GetDatabase(8).Database,"Blob:Catalog*");
- //List<string> ks = new List<string>();
- //foreach (var key in keys)
- //{
- // ks.Add(key.ToString());
- //}
- //var result4 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam'and c.owner='teacher'", null, pageSize: 200);
- //var result0 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam'and c.owner='teacher' and STARTSWITH(c.code,'Exam-')", null, pageSize: 200);
- //var result1 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam' and c.owner='teacher' and contains(c.code,'Exam-')", null, pageSize: 200);
- //var result2 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam' and c.owner='school' and contains(c.code,'Exam-hbc')", null, pageSize: 200);
- //var result3 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam' and c.owner='school' ", "Exam-hbcn", pageSize: 200);
- //return Ok(new { ru4 = result4.ru, count4 = result4.list.Count, ru0 = result0.ru, count0 = result0.list.Count(), ru1 = result1.ru, count1 = result1.list.Count(), ru2 = result2.ru, count2 = result2.list.Count(), ru3 = result3.ru, count3 = result3.list.Count() });
- }
- /// <summary>
- /// 测试五育画像数据推送
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("period")]
- public async Task<IActionResult> period(JsonElement json)
- {
- List<string> names = new List<string>();
- if (json.TryGetProperty("names", out JsonElement _names))
- {
- names= _names.ToObject<List<string>>();
- }
- List<Period> periods = new List<Period>();
- if (json.TryGetProperty("period", out JsonElement _period))
- {
- foreach (var name in names) {
- Period period = _period.ToObject<Period>();
- period.name= name;
- period.id= Guid.NewGuid().ToString();
- period.semesters.ForEach(z => z.id= Guid.NewGuid().ToString());
- period.analysis.type.ForEach(z => z.id= Guid.NewGuid().ToString());
- period.subjectCount=0;
- periods.Add(period);
- }
- }
- return Ok(periods);
- }
- /// <summary>
- /// 测试五育画像数据推送
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("import-table")]
- public async Task<IActionResult> ImportTable(JsonElement json)
- {
- List<LPSchool> schools = json.ToObject<List<LPSchool>>();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
- await table.BatchInsertAsync (schools);
- return Ok(schools);
- }
- /// <summary>
- /// 测试五育画像数据推送
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("test-upsert-student-portrait")]
- public async Task<IActionResult> TestUpsertStudentPortrait(JsonElement json) {
- var data = await _httpTrigger.RequestHttpTrigger(json, _option.Location, "upsert-student-portrait");
- return Ok(data.json.ToObject<JsonElement>());
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("transform-lessonrecord-overalleducation")]
- public async Task<IActionResult> TransformLessonrecordOveralleducation(JsonElement json) {
- //string msg = json.ToString();
- //var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- //var messageChange = new ServiceBusMessage(msg);
- //messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- //await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- string sql = "select value c from c where c.pk='StudentScoreRecord' and c.userType='student' and c.school<>null and c.school<>'' ";
- List<StudentScoreRecord> studentScores = new List<StudentScoreRecord>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<StudentScoreRecord>(sql)) {
- studentScores.Add(item);
- }
- var group = studentScores.GroupBy(z => z.school);
- string schoolSql = $"select value c from c where c.id in ({string.Join(",",group.Select(x=>$"'{x.Key}'"))})";
- var resultScool= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(schoolSql,"Base");
- foreach(var item in group)
- {
- var list = item.ToList();
- var stuids = list.Select(z => z.stuid);
- string studentSql = $"select value c from c where c.id in ({string.Join(",", stuids.Select(x => $"'{x}'"))})";
- var resultStuden = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(studentSql, $"Base-{item.Key}");
-
- foreach (var sturecord in list) {
- HashSet<OverallEducation> overallEducations = new HashSet<OverallEducation>();
- var studentBase = resultStuden.list.Find(x => x.id.Equals(sturecord.stuid, StringComparison.OrdinalIgnoreCase));
- var schoolBase = resultScool.list.Find(x => x.id.Equals(sturecord.school, StringComparison.OrdinalIgnoreCase));
- if (studentBase == null) {
- continue;
- }
- var period = schoolBase.period.Find(x => x.id.Equals($"{studentBase.periodId}"));
- foreach (var record in sturecord.lessonRecords) {
- if (record.time > 1000000000000) {
- (Semester currSemester, int studyYear, DateTimeOffset currSemesterDate, DateTimeOffset date, DateTimeOffset nextSemester) dataSemester = SchoolService.GetSemester(period, record.time);
- string oid = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{sturecord.stuid}";
- string ocode = $"OverallEducation-{sturecord.school}";
- OverallEducation overallEducation = overallEducations.Where(o => o.id.Equals(oid, StringComparison.OrdinalIgnoreCase) && o.code.Equals(ocode, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
- if (overallEducation != null)
- {
- var hasrecord = overallEducation.lessonScore.Find(x => x.lessonId.Equals(record.lessonId));
- if (hasrecord != null)
- {
- hasrecord.gscore = record.gscore;
- hasrecord.pscore = record.pscore;
- hasrecord.tscore = record.tscore;
- hasrecord.tmdid = record.tmdid;
- hasrecord.school = record.school;
- hasrecord.scope = record.scope;
- hasrecord.lessonId = record.lessonId;
- hasrecord.courseId = record.courseId;
- hasrecord.periodId = record.periodId;
- hasrecord.subjectId = record.subjectId;
- hasrecord.time = record.time;
- }
- else
- {
- overallEducation.lessonScore.Add(
- new StudentLessonRecord
- {
- gscore = record.gscore,
- pscore = record.pscore,
- tscore = record.tscore,
- tmdid = record.tmdid,
- school = record.school,
- scope = record.scope,
- lessonId = record.lessonId,
- courseId = record.courseId,
- periodId = record.periodId,
- subjectId = record.subjectId,
- time = record.time
- }
- );
- }
- }
- else {
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemStreamAsync(oid, new PartitionKey(ocode));
- if (response.Status != 200)
- {
- overallEducation = new OverallEducation
- {
- id = oid,
- code = $"OverallEducation-{sturecord.school}",
- pk = "OverallEducation",
- ttl = -1,
- name = studentBase.name,
- classId = studentBase?.classId,
- schoolCode = $"{sturecord.school}",
- semesterId = dataSemester.currSemester.id,
- year = dataSemester.studyYear,
- periodId = $"{period.id}",
- stuYear = studentBase.year,
- studentId = studentBase.id,
- lessonScore = new List<StudentLessonRecord>
- {
- new StudentLessonRecord
- {
- gscore = record.gscore,
- pscore = record.pscore,
- tscore = record.tscore,
- tmdid = record.tmdid,
- school = record.school,
- scope = record.scope,
- lessonId = record.lessonId,
- courseId = record.courseId,
- periodId = record.periodId,
- subjectId = record.subjectId,
- time= record.time
- }
- }
- };
- }
- else
- {
- overallEducation = JsonDocument.Parse(response.Content).RootElement.ToObject<OverallEducation>();
- var hasrecord = overallEducation.lessonScore.Find(x => x.lessonId.Equals(record.lessonId));
- if (hasrecord != null)
- {
- hasrecord.gscore = record.gscore;
- hasrecord.pscore = record.pscore;
- hasrecord.tscore = record.tscore;
- hasrecord.tmdid = record.tmdid;
- hasrecord.school = record.school;
- hasrecord.scope = record.scope;
- hasrecord.lessonId = record.lessonId;
- hasrecord.courseId = record.courseId;
- hasrecord.periodId = record.periodId;
- hasrecord.subjectId = record.subjectId;
- hasrecord.time = record.time;
- }
- else
- {
- overallEducation.lessonScore.Add(
- new StudentLessonRecord
- {
- gscore = record.gscore,
- pscore = record.pscore,
- tscore = record.tscore,
- tmdid = record.tmdid,
- school = record.school,
- scope = record.scope,
- lessonId = record.lessonId,
- courseId = record.courseId,
- periodId = record.periodId,
- subjectId = record.subjectId,
- time = record.time
- }
- );
- }
- }
- overallEducations.Add(overallEducation);
- }
- }
- }
- foreach (var overallEducation in overallEducations) {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(overallEducation, partitionKey: new PartitionKey(overallEducation.code));
- }
- }
- }
- return Ok();
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("check-art-result")]
- public async Task<IActionResult> CheckArtResult(JsonElement json)
- {
- List<StudentArtResult> art_idNames = new List<StudentArtResult>();
- string sqlSchool = "select value c from c where c.areaId='7a51072f-b329-4e74-99e0-ba0407ba8926'";
- List<School> schools = new List<School>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIterator<School>(sqlSchool, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- schools.Add(item);
- }
- string sql = @"SELECT value c FROM c where c.pk='ArtResult' and c.artId in('770fbaaa-a9e8-4d45-a322-3c6d6e50a8f7',
- '1e59bb5f-984f-406d-83a2-48ef1ce60a75',
- '33fc9276-60c1-4663-8c42-2e44a138a874',
- '4eada95b-a408-4a66-bd6c-c61c6057d505',
- 'f61b32c6-2f86-4ae6-ac25-1961df0f443a',
- '4d974b69-e104-45db-8047-b4cbc43ebc98',
- 'efb8f6ed-74b9-43b7-b8e5-c61d92441ed9',
- '070d8ce5-253c-404b-80b7-12cbc234ddae',
- 'fdd6c34b-44c2-42e9-9cd4-66c01b7103da',
- 'b1cf6fed-a4ea-4d06-b15d-3941fba973de',
- '67cd2be9-e307-4d35-8249-6d4e7380d15c',
- 'f0481d0e-ab74-4117-8600-a375a206e283',
- '7a809ab3-4081-4a23-8127-9a362f9af8ff',
- '673684e2-1dc3-48d9-a21f-207cc40a68ba',
- '35e4da67-0fb9-4683-9fac-9c9b1c197f24',
- '893b9871-8518-4f70-97e5-58ceb4c1b504',
- '0cd4ea92-4697-468a-a2fd-2f0e1cd53525',
- 'd9fec69f-2532-408b-bc25-98a33edf7200',
- '02b68eed-29f2-49c1-a91f-c1e35dd8ce64',
- 'edaf8c12-9b0b-4b31-baff-3e9b926b401a',
- '472bbdc9-c287-4b18-9502-7f34d15172a8',
- '41f67e3c-6c7f-46e9-bc39-ec8d6ae9a495',
- 'ffea1c6b-3fb7-40d4-921b-e1dc46d15410',
- '079fa190-fc18-46b9-bcb9-a4b6e2cd902d',
- 'a0e778e8-2590-431e-b761-4929fa143762',
- '374a571a-6d5c-4a8a-ab57-6e79b8b8ff0a',
- '1db3838e-d7cd-4c77-af70-d3854262d33e',
- '7b8a2f53-3b90-48f1-bd0b-bb5be843656a',
- 'e5c24756-1ea3-46cf-8f0f-357ec280e42c',
- '1b713f31-7e0b-4cb5-84f1-0342db618a6d',
- '1794bc46-d0fb-4ea9-8ff8-2f813affe495',
- 'b9d54179-7eaf-426b-a44f-9018e6c4ffa7',
- '3145e47a-21e5-4cdf-a992-72b9e47c7bad',
- 'bdaab0b2-f8d0-4c1b-821c-95b4a2371c42',
- 'd39f74df-dc65-44d4-8463-41af1a4b186d',
- '79e83de1-4e64-4ef3-b24e-fe4e877e683b',
- 'bf3aaff3-1a86-42c8-89d7-4b9d6147d37f',
- 'ad3742eb-9e46-43f8-9644-ecb498082810',
- '66a3d74b-3946-42c3-a2d2-0bc6704c86ec',
- 'ec75e499-f432-41d4-b6dd-5548358b657d',
- '70ef5724-f875-4e2e-bda8-58fd2457c2a7',
- '60c03852-8c97-4cb0-a232-e0734eaebe96',
- '4eefe05d-3df9-4f27-804b-53dd7bc5f4ab',
- 'b82ff879-5474-4b31-b3e6-3174361a4fd0',
- '09489fef-5490-4b5e-802b-74d1be2c5515',
- '1a7d8d51-f828-4f15-9859-33937b41b9e4',
- '9e591e75-538e-426d-862d-b043c13e822a',
- '71cd894a-e82d-49ff-a204-a64a2eb6f332',
- '70103a11-095b-4d01-b3ea-0ed2e388445f',
- 'b40d4952-396d-49f3-ba2d-6aeba1d940d9',
- '149a12ae-7c5d-444c-ac34-17af88cf653e',
- '8c1b2180-4a81-4f6b-989a-b971dbeae082',
- '079107f5-7bf5-4955-a39c-85dec9715e60',
- 'f9abe967-dbce-46d7-a60f-d9a2e6866ec6',
- 'b4684520-cf0c-473c-aa3a-ea5ba5d398d3',
- '0839abf0-07e7-4c0d-b818-54d451a6265a',
- '6abc82c7-928b-43bf-8c5d-f5a5d7c55a4d',
- '544577d3-c4b0-491f-a041-18cc07e711ca',
- '2efddd68-0bbc-4dba-a594-f7f8532f519d',
- '725f2665-1015-4563-9044-f4061accdf67',
- '739aa426-a359-4515-85ef-1efe605c0b73',
- '8dcde32c-3a77-4bf5-84a3-ec4d7a78413d',
- '4a396e8b-babb-47ee-b6ed-db2124d5c39d',
- '55f4594b-c13b-48b8-82f1-563751d48e9e',
- '3cc1bd57-bf4e-4933-ac6b-7cdb0e8e2dc1',
- '380511bf-2b15-4b90-b8c8-3464c2c6e18c',
- '12378c30-0c1d-4c84-8deb-5aaffaa2b45c',
- 'e247abc3-7083-4de5-a492-46e09e9bb341',
- 'ef826295-7a00-483d-945b-589c8fc0baf9',
- 'c1b056c5-0ebf-454a-bb56-3f6024e837d2',
- 'c513fe45-767c-4632-b6d3-9631c9bf8854',
- '9f7d087e-ba53-4167-9776-1e33a9a1cb61',
- 'b5f1a3f0-975f-441c-b6d0-3b8513b96d24',
- '92560ac8-a3a5-4aff-85e6-b7f72fc7e2fb',
- '898a7705-47f3-4f3b-a01e-1ec609ad4abf',
- '4c4349a0-ade4-4793-a435-15de7f3c299e',
- '473707f1-6f43-4611-adca-263604aa8e58',
- '88ee65ec-ec5c-4c5a-8539-8a8e931508ce',
- '4b12c255-5f44-4056-8ab6-d33721394ab2',
- '1f2f9ad3-e465-4152-afce-26715e3902af',
- 'bba7590c-735a-41c3-a501-ab4285fc36e8',
- '51c7426f-934f-4a18-bc1f-053e994969cc',
- '9ec15578-a78b-4f9d-ae8c-f15677d03d0a',
- '6fc632fe-5833-4c26-a079-70f9a3fa1957',
- '86a886f5-e540-4f57-abfd-cee4e3d328ab',
- '66e50efa-c3c4-4e3e-8892-5ebdec85a008',
- '2b66ee3b-e74a-446a-a92d-9cdc11a43123',
- '09533510-ec3a-4c45-8220-097a2a7e4237',
- 'be879d1f-1ccd-4e5f-9871-449a736a9279',
- '2371ba86-0598-44eb-99de-c73b7cca15db',
- '77f87528-e5c0-4ddf-80ea-43d383f5e58e',
- '9b7aa0c9-6393-4337-95cd-2bf0c57a662c',
- '93811e7f-fa3f-4487-9310-ef28ba3530f4',
- '43ecedc4-45fa-4ab7-b87b-357be07b19fa',
- 'a7fa4f17-9a9e-4d0b-bca7-2edfdcd75afb',
- '3682bc09-96ab-4d17-9010-b9fc31dc72bd',
- '04eff65e-3e19-4b57-b3ba-f1f63f52b8ba',
- '9eaea71a-97c8-456d-afc4-97d00e2e83bd',
- 'e3d846fd-c9e7-44b1-966d-ba74b4953f54',
- '2db6561b-3657-418a-ba18-b726a86d1fb1',
- '93b32d4b-a918-4940-bcef-00fbeceff525',
- '18e6f96a-c4d3-4cca-9248-f7c9099c6706',
- '3e1866ed-c9d0-415f-a080-ed1b34704110',
- 'd4ee5661-646b-4a58-b2b8-ad309666d64e',
- 'b678edb6-4717-423f-a8ac-6abc80eeab97',
- 'e8d68e11-d1e9-4bc7-8e22-e426f50f70a2',
- '8e96efbd-b990-4e2e-ad43-49e9dae73794',
- '72793b29-c939-4201-82b8-7ded1e6c6fe5',
- '59b5a6bc-ae2a-4157-b262-bf7a4858aace',
- 'e6b642ef-4239-4063-b471-da5b987b6aeb',
- 'f5ebf426-b4bc-4744-a2f3-a35a22c6c326',
- 'a7e80ecb-2a53-4879-a0f4-d313f78d3c01',
- 'cf32535a-b754-4cee-a51d-be4dc2220a2f',
- '521c66d6-00cc-4ec6-b391-0d9ce1995c42',
- '523b17d0-629f-44de-8f24-0c3915493fb0',
- '771b45c4-dde0-4d6a-ba69-6d8f537e4c1f',
- 'f9b374fd-1af4-4623-b117-c75fa4e7f4f8',
- '479f343e-51b7-49bd-8ebb-cb81af8ae7b0',
- 'cc992aae-2942-4836-9351-cedbd1cc4e61',
- '3f5d1192-4c56-43a6-9140-18043d6c41e5',
- 'dffad9b6-f3f2-4470-be45-94c81af04a02',
- '39289aa9-2506-4d04-866e-e6eec9b4d9db',
- '243299ec-6a98-43ac-b3db-272f5abbbd78',
- '9f715766-ef6a-479d-895d-945952a8ff6e',
- '2ff9bd86-8621-4f04-b560-abff5a202232',
- '75da24ed-8196-4eb1-8413-3916d7b271a3',
- '6adc96f3-c6e5-4a8d-a33f-5bbcbb92b296',
- '0b2dcfbc-d334-4032-b354-f6fa98a57d99',
- 'e2110a26-3af6-4c53-8b38-51ed4b415d48',
- '85e4c259-f531-43dd-a2b8-76cb750f8604',
- '1a6731a3-cc57-4463-84e1-bca0917c2399',
- 'd574dac8-4440-48f0-af37-b982db545ea3',
- '753ca661-d930-4f33-bce3-5385c310744f',
- 'e70800f3-836b-43e9-aa8c-c5e789d7054e',
- '32a94a0c-c14c-4208-8bd1-0d84c69d690e',
- 'f5d242b3-db25-4877-8a63-4d4dcf8f8f2c',
- '87399fcb-34fb-494b-b74f-02979a665dc0',
- '85796371-1079-4fff-947d-671720377e72',
- '40f04a01-e373-430a-a1f5-cbb8fbcff4cb',
- '6e6a3d09-c65d-4996-bd96-035f5d19e634',
- 'd340ea8f-e869-46d5-8813-5cce7991edea',
- '8a72592b-09fb-4910-b4e9-c76ef039b44f',
- '740b8b24-c7f5-4df5-a13a-92a1c37619bc',
- 'c19ef79f-d3f3-4125-8e1a-83cee110e03b',
- '1894992c-2575-4949-971d-c84669fcfd06',
- '4d51ace2-9f18-4f01-be7b-1ab4694e62dd',
- 'c1564967-890f-49e2-983a-933df4cbf8d0',
- 'aff088da-91e6-400a-ab84-c6cf300b361f',
- 'b0557e5e-41c5-4273-b793-dcb8a0613e6f',
- 'd0317e30-bcc4-4b03-9417-4dba3a216105',
- '86a28ef8-f3fc-44ef-942b-a9a658bb0731',
- '53623415-70e8-44f6-9ea6-bd709e40984c',
- '9ee23eee-850c-4cb0-8147-829ae0502705',
- 'd6fbfc1e-6093-4e70-8432-453246c80eb3',
- 'ac0e96dd-ec15-4b39-834d-1000ac3aa4c4',
- '1e8c9744-8054-405b-997c-de13e58967a4',
- 'c87c282c-6a83-40d1-86bc-af3045c0c41a',
- '4c221226-f490-4657-bd98-cf24bba48d7e',
- 'fd218bdd-7c18-41d6-a592-59a4c3ee98fe',
- '0c916db0-f7fa-4abc-a548-ca81cb416e59',
- '9f3c9615-3066-45d8-99a9-eacc8f6d692d',
- '6ed5074e-c7df-49f1-84c8-bb6276db9d1d',
- 'c2eb2c78-60d3-4616-9215-5ca810c58e4d',
- '4aef197d-5c62-4bce-aab2-804c87db5b28',
- '3231a06f-118a-437f-b863-4ffcba56d03a',
- 'a827a795-f86e-46eb-8369-f63b061d87d9',
- 'd4fd8c14-81d1-41b3-b652-f1dfb107d0d6',
- 'a0f2b207-0ef7-4ca4-b595-12f46b4b8434',
- '115f8e21-ebdb-4241-9c34-91fbef1b6fb9',
- '34c8923a-0230-448a-9d06-a8f2922520a3',
- '04803687-4689-45a6-b19e-4d3a39ccc348',
- '8bb657c9-7638-4ab9-af92-a4370d53960e',
- '1e766445-9971-4358-86be-fba295460866',
- '367c0575-b150-44eb-b447-5468d4d833fe',
- '2a379010-1f57-43f7-8f99-1f254ad93c26',
- '496adcc6-2897-4f16-9e9b-75fbcfd313a0',
- 'c32a4e86-637f-4c68-8824-2d4370eea5ee',
- 'b03b9f85-6d51-4c9c-a354-22bd3aa67462',
- '829a1242-f1e0-4154-aacf-362c021172f2',
- '4a451d51-b96c-4740-9018-7d22bbd842cf',
- '497a3b9a-55da-4991-af53-657c04edd0b3',
- 'b89b915f-f4ea-44f6-ae3a-e45af1942022',
- '781c4777-a869-4857-b052-71cbecbf6e35',
- '16a1d9aa-4bba-4c6f-86e5-7f7a281e7cd2',
- 'a5125445-cd2c-44b1-af19-addd25b8eeef',
- '81f574b9-9da2-43ae-ac6c-54ceb637c1fa',
- '1d469b5a-386c-4ace-9477-826c2d9d2b5d',
- '4fb0c252-5df1-44f9-a6e4-40078740a4e8',
- '1d7574e8-cf7c-460f-aad9-b4eec908121c',
- 'b0d23d24-a66f-4fb7-badc-980bebe0118d',
- 'e9570402-e4db-4a7c-9d5c-c5f95ad8ed0a',
- 'b08a57bc-6f1a-491c-a126-490ad5c8f90c',
- '583f3908-5caf-4703-84c6-e32cbbafca1e',
- '271cf872-cc61-493d-a595-be644bb2e098',
- 'a031cf56-0aa1-40c1-a325-14f6f1204cad',
- '3f492d1f-d95d-4947-8944-1e47fbe6abb4',
- '44d282b7-413f-4f1a-b5cf-5b9b81acbb6a',
- 'cef3a415-dc3f-4143-b905-5b1bac1b10c9',
- '37fe497b-1ba6-46e7-a9b9-fd70993b9753',
- 'c0db0c30-590c-42bd-bac7-d065a05843cd',
- '19532426-9ee6-4cc0-8d7b-7c5753b95b64',
- '7421dcb4-14d3-4656-9257-a2b287ff41a8',
- 'bd5805f7-a7eb-4189-8e48-9b3978d22362',
- '012861ec-8bbb-42e2-9e39-349a5b172c21',
- '731daff9-ccf2-48d3-88bc-ff02ec7ff2f9',
- '5b47d6c3-df81-4456-a165-4af6ee34c375',
- '2129126a-838f-4e3d-a8a4-1bf9e8d70ce8',
- 'acb84287-1cf7-4aa5-8892-e92beb6f6871',
- 'b2d337e4-16b4-459d-9d7f-922458e2671c',
- 'c63b9cd7-bce4-4c80-91c2-c305916d3d22',
- '1a7d052b-97b6-40ab-9b45-3e163710ea10',
- 'bd096e5e-0dc3-4b2e-9e4a-ffc3ac2a8e8b',
- '1afbab3e-193c-408c-b024-3365730d1698',
- '6e268ebe-aa65-4fa0-8fc1-877d0688cf8d',
- '89675ae3-9773-4b37-bc69-6a926f608b0e',
- 'd96a0716-89e1-4b5b-b02a-0cb438bd4933',
- '693e024a-1b71-4c9e-868e-ad9524728988',
- '5fb1ad4b-7a79-4a55-b627-3d1354a22754',
- 'c050b6d6-5f1a-4f3f-9385-521d9f992f11',
- '62051b3d-1a64-4509-914c-a382f573c050',
- '8b6c6a22-3a4c-48f4-bba4-57db1af2ec2e',
- 'ca5d3896-35ad-4848-ad2a-beb04263999d',
- '1bac6904-2f36-45f5-9e8e-894e28a5674d',
- '89f1a5f6-3c29-4338-8a00-5645dbaa80ad',
- 'def9d072-fee5-44f6-bc18-5b2750d4efc5',
- '032e2e84-6154-49ee-8d4d-e3b3b631595b',
- '6cb4e7ba-9be8-4c8a-bf4a-437faf96c084',
- 'd6df2ed5-8963-42c0-8832-537a210e900e',
- 'ec647fea-a650-4b18-b267-3f8d9d104c23',
- '10374436-b76b-4d73-853e-abe12b8f0079',
- '8b87190e-3fd1-40d3-9a7f-efb986cd7fa5',
- '30803959-1b88-4b8a-8716-d74e58f2eacd',
- 'b7c69c8d-b4c0-4523-ac73-f9629d2b5c37',
- 'da21dd7d-fe43-474f-bcd0-e2819b71ab40',
- 'ae97438f-afc8-4f01-90da-da5fbbc7b759',
- '95920cea-040e-40a0-a9fa-ea7e48945e5e',
- 'bf0ec2c2-b1b5-41a4-990b-ebd32e64bcc5',
- '06add3e9-8566-44b0-8962-6f1377410b48',
- '1a56021a-b4e5-45e0-83e5-7ec707097271',
- 'd35c54ea-3985-484f-9a3a-abc4be8fc774',
- 'a7c3bd26-ac43-4a61-99fe-428ea141a826',
- '414a46cb-4e88-4217-adfd-395f3f4cb12c',
- '241729ee-cfe7-4ee2-868e-3f617fd62bba',
- 'c05c28db-8b03-4d0c-8a37-c0e36c6fd0e8',
- '5b72fe37-3bc6-4563-9a1e-bfd62b692980',
- '73609b0e-1bc7-4c64-a39e-df52a34a5325',
- '477bba0c-d64f-4543-90eb-481183874bf8',
- 'd2d5be63-6e49-46d5-ae96-3b106b907902',
- '9091e31c-28c6-4a31-9958-36d0875ef8d7',
- '4fedd41a-d3d2-475d-8804-8c716ac4e160',
- '5d322e5c-ad86-42b2-a20d-1fa0e3279361',
- '99297e99-3b10-4353-a691-02492f2b88d1',
- '5b1206de-1b99-4b96-8e98-5c85ca630cea',
- '65d501e8-4663-4ae8-a07e-59b30b75a645',
- 'b53311e3-5276-45d6-87a1-36bf28b653be',
- '6bd75463-1dec-4001-ab24-cd2e07986759',
- '9b3201a9-ce44-41a7-8ad5-6769f726c2d0',
- '0acf8a5d-0feb-4497-9a0a-e95f86138157',
- '522597e8-bada-4c5b-bdf2-06af764a4bfe',
- '1fca91fb-3e03-438e-8f1b-a9b77b14634c',
- 'c8bd6ef8-ff2e-40c5-8f15-973caea0ed58',
- 'ba318882-7eeb-42a0-bfcb-09ac71fc0046',
- '0e1d09bd-f176-4e21-9f55-b821703a7b24',
- '3f58f289-a206-4fbd-93c6-0752d3d0a250',
- 'fd23121d-959d-443c-ac22-4cf7cac3751c',
- 'd3b4384a-290e-4cb0-bfda-b34097d5ca72',
- '2d7b5467-0e74-40ae-ab21-bf29ee3fe02c',
- 'd3db6faa-4b07-460a-bcbd-48dcc109fbc4',
- 'e5d14fe7-a5a0-4610-b1b7-87c9d936c7ff',
- 'f386b6f5-1fd2-4a2e-8ec0-6762ddd5c477',
- '60c09883-dff1-49ee-bafb-1991aab238aa',
- '6664e420-91ad-4c89-9955-313b163f722e',
- 'b81724c3-c045-436b-9d55-f528918de742',
- '5de09e10-e4bd-4df2-8628-9e432b17ec65',
- 'af93606e-5dbc-4401-99e6-adea66903418',
- 'fe7998e5-0a31-45a8-aab0-1867092d855c',
- 'd64bdffe-8388-4a9c-a3f9-bbd1b75ea224',
- 'c8845227-73ea-45fe-920c-be3e166b04c3',
- '6087c06a-10fc-4c92-adb3-95f85423fe2e',
- '6c64f697-21cf-4d58-8810-d0306e0c5dc4',
- 'bc2ee64e-cb01-4101-9d2d-fd37f31fd881',
- 'c076b996-1f81-4f4a-8c04-a1a69348863f',
- 'f2fab9c5-2a57-4f0a-8b48-000fc08eec98',
- 'b496b620-713e-4312-8d80-4f89d10187de',
- '6995deff-b9e8-479b-84fc-d981efab4d3b',
- 'cd7e8c81-231f-42ab-a30d-7665e9097a71',
- '38452e41-1ec3-40ca-ac3a-2579e47e5f16',
- '16e904e2-b77b-4723-86ee-ba85a9d3762f',
- '9e5e308a-c291-4feb-a225-336f0f949489',
- '8391694a-dccb-48eb-8d3b-56401e5fb030',
- 'f210dd0a-e288-477a-9a16-d622cc92a818',
- '17908451-473c-4fd8-848c-23ef7846fa43',
- 'cea1ec2e-02e6-4777-b931-b2042b3f1230',
- '70fd95b8-be8c-4545-a46f-6c050449a822',
- '057d4f31-3338-4d7b-869c-98fcb114153d',
- '8d032ab5-c7db-4ceb-9a37-f55f8a59416c',
- '5e8a8ffe-73ac-4a29-9bcc-a03c06b25b2e',
- '55fd11e2-047f-4acf-9533-22023684dd58',
- '45a4b0c1-dbbf-423e-b287-d44c71089f69',
- 'c52cd0d3-4385-4efb-8f33-f947564a70cb',
- '07d593c2-9ad7-4ae5-b471-b3e2622c940b',
- 'adf77ae2-63f7-4732-82d0-29d434f83445',
- 'bdee46ba-fab6-485d-ad89-fda5578859cc',
- 'f8b9bccc-1c4f-433d-9917-f4ad007f7105',
- '7d2bd01e-5435-4dbd-8e9b-897e777691f6',
- '56cacfd9-aeef-4477-abb9-2a22e0a92ae7',
- '891c7363-60c7-4aa5-846e-e7e3913e37d4',
- '376c26d3-8ebc-4c10-a5c1-aef9606318a8',
- '3efc8c68-3cee-4bc6-bdcd-ffc4c1a3437b',
- '1a7e5fda-eb4c-4f62-ad2d-b3e04e0e725a',
- 'dd4b0cd7-73d4-46fa-bf19-12e35f64be43',
- 'ccf206a1-fcc8-4552-b12f-ebed670cff73',
- 'c275d71f-cdb3-443c-82ab-821dd80500ea',
- 'e269c78b-2b0c-4fd1-bc0f-2ff671151030',
- '41e4371e-7495-4008-9951-7b3ab843429e',
- 'c54ac4b5-9267-4087-b724-6b0d44713162',
- 'e43fb790-aa3f-4209-838d-d830a9c5fd53',
- '982f3d88-bfe1-46c8-ac95-7adbd06a98f1',
- '8ded07a1-1dda-4dea-8e0d-05475693642c',
- 'edb7d6b2-4d86-486f-b4b6-bac71fe6c460',
- 'c3416899-550b-4e1a-93f5-690dcf67cd6b',
- '89a915cf-aee4-4472-91e6-7f33d5ef490b',
- 'c3587e4c-020a-4bef-8ad5-bcbb9a7ea485',
- '91e8d5b4-8b73-470b-b900-7cd8f5508e82'
- )";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<StudentArtResult>(sql))
- {
- art_idNames.Add(item);
- }
- List<dynamic> unfinish = new List<dynamic>();
- ConcurrentDictionary<string, int> schoolFinish = new ConcurrentDictionary<string, int>();
- ConcurrentDictionary<string, int> schoolUnFinish = new ConcurrentDictionary<string, int>();
- List<Class> classes = new List<Class>();
- foreach (var z in art_idNames)
- {
- var data = z.results.Where(x => (x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_21") && x.score == -1)
- || (x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_21") && x.score == -1)
- || (x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_22") && x.score == -1)
- || (x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_22") && x.files.IsEmpty())
- );
- if (data.Any())
- {
- var p21 = z.results.FindAll(x => x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_21"))?.First();
- var p22 = z.results.FindAll(x => x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_22"))?.First();
- int p22source = 0, p21source = 0, m21source = 0, m22source = 0;
- if (p21.score > -1)
- {
- p21source = 1;
- }
- if (p22.files.IsNotEmpty())
- {
- p22source = p22.files.Count;
- }
- var m21 = z.results.FindAll(x => x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_21"))?.First();
- if (m21.score > -1)
- {
- m21source = 1;
- }
- var m22 = z.results.FindAll(x => x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_22"))?.First();
- if (m22.score > -1)
- {
- m22source = 1;
- }
- string className = "";
- string periodName = "";
- string schoolName = "";
- School school = schools.Find(a => a.id.Equals(z.school));
- schoolName = school?.name;
- if (!string.IsNullOrWhiteSpace(z.classIds?.First()))
- {
- var clasz = classes.Find(x => x.id.Equals(z.classIds?.First()));
- if (clasz == null)
- {
- clasz = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(z.classIds.First(), new PartitionKey($"Class-{z.school}"));
- classes.Add(clasz);
- }
- className = clasz?.name;
- var period = school?.period?.Where(m => m.id.Equals(clasz.periodId));
- if (period.Any())
- {
- periodName = period.First().name + "-" + period.First().periodType;
- }
- }
- unfinish.Add(new { z.school, schoolName = schoolName, z.studentId, z.studentName, z.artId, periodName, classname = className, p21source, p22source, m21source, m22source, taskId = m22?.taskId });
- if (schoolUnFinish.ContainsKey(schoolName))
- {
- schoolUnFinish[schoolName]++;
- }
- else { schoolUnFinish.TryAdd(schoolName, 1); }
- }
- else
- {
- School school = schools.Find(a => a.id.Equals(z.school));
- string schoolName = school?.name;
- if (schoolFinish.ContainsKey(schoolName))
- {
- schoolFinish[schoolName]++;
- }
- else { schoolFinish.TryAdd(schoolName, 1); }
- }
- }
- return Ok(new { unfinish, schoolFinish , schoolUnFinish });
- }
- [ProducesDefaultResponseType]
- [HttpPost("check-ems")]
- public async Task<IActionResult> CheckPjx(JsonElement json)
- {
-
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
- int itemId = 0;
- if (json.TryGetProperty("itemId", out JsonElement _itemId)) {
- itemId= _itemId.GetInt32();
- }
- List< ScTeacher > teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "ProjectItemID", itemId } });
- List<dynamic> unbind = new List<dynamic>();
- List<dynamic> unupload_rzcl = new List<dynamic>();
- List<dynamic> uploads_rzcl = new List<dynamic>();
- List<dynamic> unupload_video = new List<dynamic>();
- List<dynamic> uploads_video = new List<dynamic>();
-
- foreach (var teacher in teachers)
- {
- if (!string.IsNullOrWhiteSpace(teacher.schoolCode) && !string.IsNullOrWhiteSpace(teacher.tmdid))
- {
- int upcont = 0;
- string sql = "select value c from c where c.currency=1";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<AbilitySub>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilitySub-{teacher.schoolCode}-{teacher.tmdid}") }))
- {
- if (item.uploads.IsNotEmpty())
- {
- upcont++;
- uploads_rzcl.Add(new { teacher.TeacherName,teacher.SchoolName,teacher.PXID,time= DateTimeOffset.FromUnixTimeMilliseconds(item.uploads.OrderByDescending(m => m.time).FirstOrDefault().time).ToString("yyyy-MM-dd HH:mm:ss"), teacher?.tmdid });
- }
- }
- if(upcont<3)
- {
- unupload_rzcl.Add(new { teacher.TeacherName, teacher.SchoolName, teacher.PXID ,teacher?.tmdid});
- }
- string sql_video =$"select value c from c where c.id='{teacher.tmdid}'";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<ClassVideo>(queryText: sql_video, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ClassVideo-{teacher.schoolCode}") }))
- {
- if (item.files.IsNotEmpty())
- {
- uploads_video.Add(new { teacher.TeacherName, teacher.SchoolName, teacher.PXID, time = DateTimeOffset.FromUnixTimeMilliseconds(item.files.OrderByDescending(m => m.time).FirstOrDefault().time).ToString("yyyy-MM-dd HH:mm:ss"), teacher?.tmdid });
- }
- else
- {
- unupload_video.Add(new { teacher.TeacherName, teacher.SchoolName, teacher.PXID, teacher?.tmdid });
- }
- }
- }
- else {
- unbind.Add(new { teacher.TeacherName,teacher.SchoolName,teacher.PXID});
- }
- }
- Dictionary<string, object> dict = new Dictionary<string, object>();
- var tchs= teachers.GroupBy(z => z.areaId).Select(b => new { areaId = b.Key, schools = b.Select(v=>v.schoolCode).ToHashSet(), pushTeachers = b.Where(c=>!string.IsNullOrWhiteSpace(c.tmdid)).Select(d=>d.tmdid)});
- return Ok(new { unbind , unupload_rzcl, uploads_rzcl, uploads_video, unupload_video , tchs });
- }
- [ProducesDefaultResponseType]
- [HttpPost("sendmsg")]
- public async Task<IActionResult> Sendmsg(JsonElement json)
- {
- byte[] bytes = Encoding.UTF8.GetBytes(json.GetRawText());
- var memoryStream = new MemoryStream(bytes);
- Azure.Response res = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemStreamAsync(memoryStream, new PartitionKey("Base12"));
- if (res.Status == 201)
- {
- return Ok(201);
- }
- //var messageBlobPDF = new ServiceBusMessage(new { userType = "tmdid", bizType = "OfflineRecord" }.ToJsonString());
- //await _serviceBus.GetServiceBusClient().SendMessageAsync("screenpdf", messageBlobPDF);
- return Ok();
- }
- [ProducesDefaultResponseType]
- [HttpPost("get-subTime")]
- public async Task<IActionResult> GetSubTime(JsonElement request) {
- if (!request.TryGetProperty("ids", out JsonElement id)) return BadRequest();
- List<string> ids = id.ToObject<List<string>>();
- var queryClass = $"select c.time from c ";
- var client = _azureCosmos.GetCosmosClient();
- List<(string td, long tt)> ht = new();
- foreach (string tmdId in ids) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryClass,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"HomeworkRecord-{tmdId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
- while (accounts.MoveNext())
- {
- JsonElement account = accounts.Current;
- account.TryGetProperty("time", out JsonElement time);
- ht.Add((tmdId,time.GetInt64()));
- }
- }
- }
- }
- var home = ht.Select(x => new
- {
- id = x.td,
- time = DateTimeOffset.FromUnixTimeMilliseconds(x.tt).ToString("yyyy-MM-dd HH:mm")
- //time = DateTimeHelper.FromUnixTimestampOffSet(x.tt,8).ToString("yyyy-MM-dd HH:mm")
- });
- return Ok(home);
- }
- [ProducesDefaultResponseType]
- [HttpPost("get-semester")]
- public async Task<IActionResult> GetSemester(JsonElement json)
- {
- List<Semester> semesterList = new List<Semester>();
- semesterList.Add(
- new Semester
- {
- id = Guid.NewGuid().ToString(),
- name = "第二学期",
- start = 0,
- month = 3,
- day = 1
- });
- semesterList.Add(
- new Semester
- {
- id = Guid.NewGuid().ToString(),
- name = "第一学期",
- start = 1,
- month = 9,
- day = 1
- });
- //semesterList.Add(
- // new Semester
- // {
- // id = "q",
- // name = "第四学期",
- // start = 0,
- // month = 7,
- // day = 1
- // });
- //semesterList.Add(
- // new Semester
- // {
- // id = "q",
- // name = "第三学期",
- // start = 0,
- // month = 4,
- // day = 1
- // });
- semesterList = SortSemester(semesterList);
- return Ok(semesterList);
- }
- private List<Semester> SortSemester(List<Semester> semesterList)
- {
- int Year = DateTimeOffset.UtcNow.Year;
- List<KeyValuePair<int, Semester>> pairs = new List<KeyValuePair<int, Semester>>();
- semesterList.ForEach(se => {
- string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
- string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
- int order = int.Parse($"{Year}{sm}{sd}");
- pairs.Add(new KeyValuePair<int, Semester>(order, se));
- });
- var orderPairs = pairs.OrderBy(z => z.Key);
- semesterList = orderPairs.Select(z => z.Value).ToList();
- int startIndex = semesterList.FindIndex(z => z.start == 1);
- if (startIndex == -1)
- {
- //未设置学期的情况默认9月份开始的。
- startIndex = semesterList.FindIndex(z => z.month == 9);
- //如果还未找到,就以排序结果为准
- if (startIndex == -1)
- {
- startIndex = 0;
- }
- }
- if (startIndex > 0)
- {
- List<Semester> before = semesterList.Take(startIndex).ToList();
- List<Semester> after = semesterList.Skip(startIndex).ToList();
- semesterList = new List<Semester>();
- semesterList.AddRange(after);
- semesterList.AddRange(before);
- return semesterList;
- }
- else
- {
- return semesterList;
- }
- }
- /*
- [
- {"method":"台北市","params":{"CountryId":"TW","CityId":"30"}},1
- {"method":"新北市","params":{"CountryId":"TW","CityId":"01"}},1
- {"method":"桃园市","params":{"CountryId":"TW","CityId":"03"}},1
- {"method":"台中市","params":{"CountryId":"TW","CityId":"66"}},1
- {"method":"台南市","params":{"CountryId":"TW","CityId":"67"}},1
- {"method":"高雄市","params":{"CountryId":"TW","CityId":"64"}},1
- {"method":"基隆市","params":{"CountryId":"TW","CityId":"17"}},1
- {"method":"新竹市","params":{"CountryId":"TW","CityId":"18"}},1
- {"method":"嘉义市","params":{"CountryId":"TW","CityId":"20"}},1
- {"method":"新竹县","params":{"CountryId":"TW","CityId":"04"}},1
- {"method":"苗栗县","params":{"CountryId":"TW","CityId":"05"}},1
- {"method":"彰化县","params":{"CountryId":"TW","CityId":"07"}},1
- {"method":"南投县","params":{"CountryId":"TW","CityId":"08"}},1
- {"method":"云林县","params":{"CountryId":"TW","CityId":"09"}},1
- {"method":"嘉义县","params":{"CountryId":"TW","CityId":"10"}},1
- {"method":"屏东县","params":{"CountryId":"TW","CityId":"13"}},1
- {"method":"宜兰县","params":{"CountryId":"TW","CityId":"02"}},1
- {"method":"花莲县","params":{"CountryId":"TW","CityId":"15"}},1
- {"method":"台东县","params":{"CountryId":"TW","CityId":"14"}},1
- {"method":"澎湖县","params":{"CountryId":"TW","CityId":"16"}},1
- {"method":"金门县","params":{"CountryId":"TW","CityId":"71"}},
- {"method":"连江县","params":{"CountryId":"TW","CityId":"72"}}
- ]
-
- */
- /// <summary>
- /// 测试blob多线程写入同一个文件
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schools")]
- public async Task<IActionResult> GetSchools(JsonElement json)
- {
- string msg = "{\"standard\":\"standard3\",\"tmdids\":[\"1635136038\"],\"school\":\"pbjyey\",\"update\":[\"TeacherAbility\"],\"statistics\":0}";
- try
- {
- TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
- var client = _azureCosmos.GetCosmosClient();
- string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
- string selsql = $"select value(c) from c {insql} ";
- List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
- {
- teacherTrains.Add(item);
- }
- if (change.statistics != 1)
- {
- List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
- teacherTrains.ForEach(x =>
- {
- x.update.UnionWith(change.update);
- task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
- });
- await task.TaskPage(5);
- var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
- if (unchange != null)
- {
- task.Clear();
- unchange.ToList().ForEach(x =>
- {
- TeacherTrain teacherTrain = new TeacherTrain
- {
- pk = "TeacherTrain",
- id = x,
- code = $"TeacherTrain-{change.school}",
- tmdid = x,
- school = change.school,
- update = new HashSet<string> { StatisticsService.TeacherAbility,
- StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
- };
- teacherTrain.update.UnionWith(change.update);
- task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
- });
- await task.TaskPage(1);
- }
- }
- else
- {
- Area area = null;
- string sql = $"select value(c) from c where c.standard='{change.standard}'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
- {
- area = item;
- }
- AreaSetting setting = null;
- if (area != null)
- {
- try
- {
- //优先找校级
- setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- try
- {
- setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- setting = null;
- }
- }
- }
- if (setting == null)
- {
- setting = new AreaSetting
- {
- allTime = 50,
- classTime = 5,
- submitTime = 15,
- onlineTime = 20,
- offlineTime = 10,
- lessonMinutes = 45,
- };
- }
- List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
- teacherTrains.ForEach(x =>
- {
- x.update.UnionWith(change.update);
- task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
- });
- await task.TaskPage(1);
- var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
- if (unchange != null)
- {
- task.Clear();
- unchange.ToList().ForEach(x =>
- {
- task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
- {
- pk = "TeacherTrain",
- id = x,
- code = $"TeacherTrain-{change.school}",
- tmdid = x,
- school = change.school,
- update = new HashSet<string> { StatisticsService.TeacherAbility,
- StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
- }, setting, area, client, null));
- });
- await task.TaskPage(1);
- }
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\nCosmosException{ex.Status}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- /*
- string path = $"{_environment.ContentRootPath}/JsonFile/Core/city.json";
- StreamReader streamReader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
- StringBuilder stringBuilder = new StringBuilder();
- string text;
- while ((text = streamReader.ReadLine()) != null)
- {
- stringBuilder.Append(text.ToString());
- }
- streamReader.Close();
- string input = stringBuilder.ToString();
- List<string> region = new List<string>() {
- "110000", "110100", "110200",
- "120000", "120100", "120200",
- "310000", "310100", "310200",
- "500000", "500100", "810100",
- "810200", "810300", "820100",
- "820200", "820300"
- };
- List<string> cityids = new List<string>() {
- "30","01","03","66","67","64","17","18","20","04","05","07","08","09","10","13","02","15","14","16","71","72"
- };
- Dictionary<string, List<CodeName>> regions = input.ToObject<Dictionary<string, List<CodeName>>>();
- List<List<string>> datas = new List<List<string>>() { region };
- foreach (var r in regions)
- {
- if (!region.Contains(r.Key) && !r.Key.StartsWith("71"))
- {
- datas.Add(r.Value.Select(x => x.code).ToList());
- }
- }
- List<Task<List<SchoolInfo>>> tasks = new List<Task<List<SchoolInfo>>>();
- //datas.ForEach(x =>
- //{
- // tasks.Add(GetSchoolAsync(x));
- //});
- List<SchoolInfo> schoolInfos = new List<SchoolInfo>();
- //var schools = await Task.WhenAll(tasks);
- //var schools =await GetSchoolAsync(cityids);
- // schoolInfos.AddRange(schools);
- //foreach (var schs in schools)
- //{
- // schoolInfos.AddRange(schs);
- //}
- List<string> nodatas = new List<string>();
- foreach (var data in datas) {
- (List<SchoolInfo> schoolIn, List<string> nodata) = await GetSchoolAsync(data);
- schoolInfos.AddRange(schoolIn);
- nodatas.AddRange(nodata);
- }
- await _dingDing.SendBotMsg($"os,test,{nodatas.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- return Ok(schoolInfos);
- */
- return Ok();
- }
- public async Task<(List<SchoolInfo> schoolInfos, List<string> nodata)> GetSchoolAsync(List<string> regions)
- {
- List<SchoolInfo> schools = new List<SchoolInfo>();
- List<string> nodata = new List<string>();
- foreach (var region in regions)
- {
- Dictionary<string, object> data = new Dictionary<string, object>();
- data.Add("method", "api/School/getSchool");
- data.Add("params", new { CountryId = "CN", CityId = region });
- HttpResponseMessage responseMessage = await _httpClient.CreateClient().PostAsJsonAsync("https://contest.teammodel.cn/api/School/getSchool", data);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string Content = await responseMessage.Content.ReadAsStringAsync();
- try
- {
- Content.ToObject<JsonElement>().TryGetProperty("result", out JsonElement content);
- if (content.ValueKind.Equals(JsonValueKind.Object) && content.TryGetProperty("data", out JsonElement _data))
- {
- if (_data.ValueKind.Equals(JsonValueKind.Array))
- {
- List<SchoolInfo> infos = _data.ToObject<List<SchoolInfo>>();
- if (infos.IsNotEmpty())
- {
- schools.AddRange(infos.Where(x => x.name != null && x.cityName != null).ToList());
- }
- }
- else
- {
- nodata.Add(data.ToJsonString());
- continue;
- }
- }
- else
- {
- nodata.Add(data.ToJsonString());
- continue;
- }
- }
- catch (Exception ex)
- {
- nodata.Add(data.ToJsonString());
- throw new Exception(ex.Message, ex.InnerException);
- }
- }
- }
- return (schools, nodata);
- }
- public class SchoolInfo
- {
- public string typeName { get; set; }
- public string provinceName { get; set; }
- public string provinceId { get; set; }
- public string id { get; set; }
- public string name { get; set; }
- public string cityId { get; set; }
- public string cityName { get; set; }
- public string address { get; set; }
- }
- public class CodeName
- {
- public string code { get; set; }
- public string name { get; set; }
- }
- /// <summary>
- /// 测试blob多线程写入同一个文件
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("generate-school-codes")]
- public async Task<IActionResult> GenerateSchoolCodes(JsonElement json)
- {
- List<SchoolData> schoolss = json.GetProperty("schools").ToObject<List<SchoolData>>();
- dynamic data = await SchoolService.GenerateSchoolCode(schoolss, _dingDing, _environment);
- return Ok(data);
- }
-
- private async Task<int> SendNotification()
- {
- // _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- var pa = new { grant_type = "device", client_id = "9794e418-c4ef-4fd5-a42d-accaa2d96d6e", client_secret = "ruL?I79h0w1AZaZXtBaZeZuQLQXLa=:-" };
- HttpResponseMessage responseMessage = await _httpClient.CreateClient().PostAsJsonAsync("https://api2-rc.teammodel.net/oauth2/token", pa);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- return 200;
- }
- else if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
- {
- return 401;
- }
- else
- {
- return 500;
- }
- }
- /// <summary>
- /// 测试redis通配符
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpGet("test-delete-read")]
- public async Task<IActionResult> TestDelete()
- {
- foreach (var cnt in _azureStorage.GetBlobServiceClient().GetBlobContainers())
- {
- Console.WriteLine(cnt.Name);
- }
- await SendNotification();
- var client = _azureCosmos.GetCosmosClient();
- string aaa = "0";
- try
- {
- ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
- Ok(a.GetRawResponse().Status);
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- aaa = "404";
- }
- }
- try
- {
- ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
- Ok(a.GetRawResponse().Status);
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- aaa = aaa + " 404";
- }
- }
- try
- {
- var a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
- Ok(a.Status);
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- aaa = "404";
- }
- }
- try
- {
- var a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
- Ok(a.Status);
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- aaa = aaa + " 404";
- }
- }
- return Ok(new { aaa });
- }
- /// <summary>
- /// 测试redis通配符
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpGet("test-redis")]
- public async Task<IActionResult> TestRedis()
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- List<ItemInfo> items = new List<ItemInfo>();
- var queryslt = $"SELECT value(c) FROM c where c.pid = null ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
- {
- items.Add(item);
- }
- List<ItemCond> itemConds = new List<ItemCond>();
- items.GroupBy(x => x.periodId).Select(y => new { key = y.Key, list = y.ToList() }).ToList().ForEach(z =>
- {
- ItemCond cond = new ItemCond() { id = z.key, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, count = z.list.Count, grades = new List<GradeCount>(), subjects = new List<SubjectItemCount>() };
- z.list.ForEach(y =>
- {
- ItemService.CountItemCond(y, null, cond);
- });
- itemConds.Add(cond);
- });
- itemConds.ForEach(async cond =>
- {
- await client.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ItemCond>(cond, new PartitionKey(cond.code));
- });
- return Ok(new { itemConds });
- }
- catch (Exception ex) { await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-itemcond()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組); }
- return Ok(new { });
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("get-DownloadContent-item")]
- public async Task<IActionResult> DownloadContentItem(JsonElement request)
- {
- ItemBlob itemBlob = null;
- try
- {
- BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"hbcn").GetBlobClient($"/item/12b865c9-a223-278a-2be1-e336b9ead99e/12b865c9-a223-278a-2be1-e336b9ead99e.json")
- .DownloadAsync();
- if (blobDownloadResult != null)
- {
- var json = JsonDocument.Parse(blobDownloadResult.Content);
- itemBlob = json.RootElement.ToObject<ItemBlob>();
- }
- }
- catch (Exception ex)
- {
- itemBlob = null;
- }
- return Ok(new { itemBlob });
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("get-bind-data")]
- public async Task<IActionResult> GetData(JsonElement request)
- {
- var areaId = request.GetProperty("areaId");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
- List<ScTeacher> teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object> { { "PartitionKey", "ScTeacher" }, { "areaId", $"{areaId}" } });
- return Ok(teachers.Select(x => new { x.areaId, x.PXID, x.TID, x.TeacherName, x.tmdid, x.SchoolName, x.DisName }));
- }
- /// 删除
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,teacher")]
- [HttpPost("get-save-log")]
- public async Task<IActionResult> SaveLog(JsonElement request)
- {
- BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient("1595321354").GetBlobClient($"records/271528531841781760/Record/.Recording.json").DownloadContentAsync();
- var json = Recording.Content.ToString();
- var jsonByte = Encoding.UTF8.GetBytes(json);
- Stream stream = new MemoryStream(jsonByte);
- var doc = JsonDocument.Parse(stream);
- School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>("hbcn", new PartitionKey("Base"));
- _ = _azureStorage.SaveLog("find-school", school.ToJsonString(), httpContext: HttpContext, dingDing: _dingDing, scope: "school");
- return Ok(new { doc, school, });
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("get-ip")]
- public async Task<IActionResult> GetIp(JsonElement request)
- {
- try
- {
- BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient("habook").GetBlobClient($"/records/299813002894381056/IES/Base.json").DownloadContentAsync();
- LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
- return Ok(lessonBase);
- }
- catch (RequestFailedException ex) when (ex.Status == 404)
- {
- return BadRequest("文件不存在!");
- }
- LessonBase lessonBases = request.ToObject<LessonBase>();
- //List<TmdInfo> tmds= request.ToObject<List<TmdInfo>>();
- //var content = new StringContent(tmds.Select(x=>x.id).ToJsonString(), Encoding.UTF8, "application/json");
- //string json = await _coreAPIHttpService.GetUserInfos(content);
- //string _researchKey = Regex.Replace($"{request.GetProperty("key")}", "[ \\[ \\] \\^ \\-|()【】/' {}_*×――(^)$%~!@#$…&%¥—+=<>《》!!???::•`·、。,;,.;\"‘’“”-]", " ");
- //string[] mm = Regex.Split(_researchKey, "\\s+", RegexOptions.IgnoreCase);
- //var token = await CoreTokenExtensions.CreateAccessToken("c7317f88-7cea-4e48-ac57-a16071f7b884", "kguxh:V.PLmxBdaI@jnrTrDSth]A3346", "China");
- //string ip = await _searcher.SearchIpAsync($"{request.GetProperty("ip")}");
- // return Ok(new { activity, ip, token.AccessToken,token.TokenType,token.IdToken, mm });
- return Ok(lessonBases);
- }
- /// 删除
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("check-online-record")]
- public async Task<IActionResult> CheckOnlinerecord(JsonElement request)
- {
- string sql = $"select c.id,c.name ,b.schoolId as code from c join b in c.schools where b.areaId='9ae614ba-0771-4502-a56e-0537bc5207c3'";
- List<IdNameCode> codes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<IdNameCode>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- codes.Add(item);
- }
- List<dynamic> data = new List<dynamic>(); ;
- foreach (IdNameCode code in codes)
- {
- try
- {
- TeacherTrain train = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherTrain>(code.id, new PartitionKey($"TeacherTrain-{code.code}"));
- data.Add(new { code.id, code.name, code.code, train.totalTime, train.onlineTime, train.classTime, train.offlineTime });
- }
- catch (Exception ex)
- {
- data.Add(new { code.id, code.name, code.code, totalTime = 0, onlineTime = 0, classTime = 0, offlineTime = 0 });
- }
- }
- return Ok(new { data });
- }
- [HttpPost("test-scteacher")]
- public async Task<IActionResult> TestScteacher(JsonElement json)
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
- List<ScTeacher> teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "areaId", "e6fb5d40-bd85-7327-cea8-ea5c642836d2" }, { "SchoolName", "岳池县大佛初级中学校" } });
- //var techs= teachers.Where(t => string.IsNullOrWhiteSpace(t.tmdid));
- return Ok(teachers);
- }
- [HttpPost("get-token")]
- public async Task<IActionResult> GetToken(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("host", out JsonElement host)) return BadRequest();
- if (!request.TryGetProperty("name", out JsonElement name)) return BadRequest();
- if (!request.TryGetProperty("picture", out JsonElement picture)) return BadRequest();
- if (!request.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
- int timezone = 8;
- if (HttpContext.Request.Headers.TryGetValue("Time-Zone", out var Time_Zone) && int.TryParse(Time_Zone, out int tz))
- {
- timezone=tz;
- }
-
- var auth_token = JwtAuthExtension.CreateAuthToken(host.ToString(), id.ToString(), name.ToString(),
- picture.ToString(), _option.JwtSecretKey,
- scope: "student", Website: "IES",timezone, areaId: areaId.ToString(),schoolID: school.ToString(), roles: new[] { "student" }, expire: 1);
- //var techs= teachers.Where(t => string.IsNullOrWhiteSpace(t.tmdid));
- return Ok(auth_token);
- }
- [HttpPost("test-scteacher-dn")]
- public async Task<IActionResult> TestScteacherDn(JsonElement json)
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
- string sqls = "select distinct value(c.id )from c where c.code='Base' and IS_DEFINED(c.finalScore)=true ";
- //https://teammodelos.blob.core.chinacloudapi.cn/teammodelos
- //https://teammodelos.blob.core.chinacloudapi.cn/teammodelos/yxpt%2Fjinniu%2Fscbind%2F1647432004.json
- List<ScTeacher> teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "areaId", "870a5a6b-1ab3-461a-bdeb-baec19780ddb" } });
- List<string> ids = new List<string>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<string>(sqls, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- ids.Add(item);
- }
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<string> erorr = new List<string>();
- List<ScTeacher> teachersUp = new List<ScTeacher>();
- foreach (var id in ids)
- {
- try
- {
- BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient("teammodelos").GetBlobClient($"/yxpt/jinniu/scbind/{id}.json").DownloadContentAsync();
- ScBindData scBindData = baseblobDownload.Content.ToObjectFromJson<ScBindData>();
- var tcd = teachers.Find(x => x.RowKey.Equals(scBindData.pxid));
- if (tcd != null)
- {
- Teacher teacher = new Teacher
- {
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- pk = "Base",
- code = "Base",
- id = id,
- name = scBindData.username,
- size = 2,
- defaultSchool = tcd.schoolCode,
- schools = new List<TeacherSchool> {
- new TeacherSchool
- {
- schoolId = tcd.schoolCode, status = "join", time = now, name = scBindData.sn, areaId = tcd.areaId
- }
- },
- binds = new List<ThirdBind> {
- new ThirdBind
- {
- type= "scsyxpt",userid=scBindData.userid,username= scBindData.username,account=scBindData.account,data=new List<string>{ scBindData.ToJsonString()}
- }
- }
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(teacher, new PartitionKey("Base"));
- tcd.tmdid = id;
- teachersUp.Add(tcd);
- }
- }
- catch (Exception)
- {
- erorr.Add(id);
- }
- }
- await table.SaveOrUpdateAll(teachersUp);
- return Ok();
- }
- [HttpPost("fix-jinniupujiang-teacher-videotime")]
- public async Task<IActionResult> GetScteacher(JsonElement json)
- {
- if (!json.TryGetProperty("areaId", out JsonElement _areaId)) { return BadRequest(); }
- Area area = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<Area>($"{_areaId}", new PartitionKey("Base-Area"));
- AreaSetting setting = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<AreaSetting>($"{_areaId}", new PartitionKey("AreaSetting"));
- List<string> teachers = new List<string>();
- //获取这个区的教师 //psywgy
- string schoolSql = $"SELECT value c.id FROM c join a in c.schools where a.areaId='{_areaId}' and c.code='Base' ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<string>(schoolSql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- teachers.Add(item);
- }
- //获取这些老师的研修记录
- string tr = $"SELECT distinct value(c) FROM c join a in c.currency.teacherAilities where c.id in ({string.Join(",", teachers.Select(x => $"'{x}'"))}) and c.pk='TeacherTrain' and a.videoTime<300 ";
- List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<TeacherTrain>(tr, requestOptions: new QueryRequestOptions { }))
- {
- if (!item.tmdid.Equals("1528783259") || !item.tmdid.Equals("1530606136"))
- {
- teacherTrains.Add(item);
- }
- }
- //获取这个区的能力点树状结构
- string sql = $" select distinct value(b.id ) from c join b in c.children where c.code='AbilityTask-{area.standard}' ";
- List<string> nodeIdsDB = new List<string>();
- await foreach (var y in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).GetItemQueryIterator<string>
- (sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilityTask-{area.standard}") }))
- {
- nodeIdsDB.Add(y);
- }
- List<AbilitySub> abilitySubs = new List<AbilitySub>();
- List<TeacherVideoTime> teacherVideoTimes = new List<TeacherVideoTime>();
- string ids = teacherTrains.Select(x => x.id).ToJsonString();
- string sqls = $" select value(c) from c where c.code='AbilityTask-{area.standard}'";
- List<AbilityTask> abilityTasks = new List<AbilityTask>();
- Dictionary<string, RecordFileAbility> valuePairs = new Dictionary<string, RecordFileAbility>();
- await foreach (var y in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).GetItemQueryIterator<AbilityTask>
- (sqls, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilityTask-{area.standard}") }))
- {
- abilityTasks.Add(y);
- }
- foreach (var item in teacherTrains)
- {
- List<TeacherAbility> teacherAbility = new List<TeacherAbility>();
- if (item.currency.teacherAilities.Count() > 3)
- {
- //如果选择了大于三个能力点的教师,则优先获取上传了认证材料的的能力点,
- var uploadHas = item.currency.teacherAilities.FindAll(x => x.uploadHas == 1 && x.videoTime < 300);
- if (uploadHas.Any())
- {
- teacherAbility.AddRange(uploadHas);
- }
- if (teacherAbility.Count < 3)
- {
- // 如果仍然未满足数量。则再去获取 没有上传认证材料,但是又有学习时间长的能力点。
- var hasVideoTime = item.currency.teacherAilities.FindAll(x => x.uploadHas != 1 && x.videoTime < 300).OrderByDescending(o => o.videoTime);
- var disCount = 3 - teacherAbility.Count;
- teacherAbility.AddRange(hasVideoTime.Take(disCount));
- }
- }
- else
- {
- teacherAbility.AddRange(item.currency.teacherAilities.Where(ab => ab.videoTime < 300));
- }
- TeacherFile teacherFile = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherFile>(item.id, new PartitionKey($"TeacherFile-{item.code.Replace("TeacherTrain-", "")}"));
- foreach (var ability in teacherAbility)
- {
- TeacherVideoTime teacherVideoTime = new TeacherVideoTime { code = item.code.Replace("TeacherTrain-", ""), id = item.id, abilityId = ability.id, no = ability.no, train_time = ability.videoTime };
- double fileview = 0;
- var filerecord = teacherFile.fileRecords.FindAll(x => x.files.Where(y => y.abilityId.Equals(ability.id)).Count() > 0);
- filerecord.ForEach(x => {
- var file = x.files.FindAll(y => y.abilityId.Equals($"{ability.id}"));
- if (file.IsNotEmpty())
- {
- fileview += x.view;
- }
- });
- double fminut = fileview / 60;
- teacherVideoTime.files_time = fminut;
- var tech = abilityTasks.FindAll(x => x.abilityId.Equals(ability.id));
- // double limit = 0;
- tech.ForEach(task =>
- {
- task.children.ForEach(y =>
- {
- y.rnodes.ForEach(r =>
- {
- if (valuePairs.ContainsKey(r.hash))
- {
- valuePairs.TryGetValue(r.hash, out var value);
- var ablt = value.fileAbilities.Find(z => z.abilityId.Equals(task.abilityId) && z.taskId.Equals(task.id) && z.nodeId.Equals(y.id));
- if (ablt == null)
- {
- value.fileAbilities.Add(new FileAbility { url = r.link, abilityId = task.abilityId, taskId = task.id, nodeId = y.id });
- // limit = limit + r.duration;
- }
- }
- else
- {
- valuePairs.Add(r.hash, new RecordFileAbility
- {
- fileRecord =
- new FileRecord { hash = r.hash, size = r.size.Value, duration = r.duration, view = (int)r.duration, type = r.type, done = true },
- fileAbilities = new List<FileAbility> { new FileAbility { url = r.link, abilityId = task.abilityId, taskId = task.id, nodeId = y.id } }
- });
- // limit = limit + r.duration;
- }
- });
- });
- });
- HashSet<string> childIds = new HashSet<string>();
- foreach (var ps in valuePairs)
- {
- HashSet<string> abilityIds = teacherFile.fileRecords.SelectMany(x => x.files).Select(x => x.abilityId).Where(abid => abid.Equals(ability.id)).ToHashSet();
- double view = 0;
- foreach (var abid in abilityIds)
- {
- var record = teacherFile.fileRecords.FindAll(x => x.files.Where(y => y.abilityId.Equals(abid)).Count() > 0);
- record.ForEach(x => {
- var file = x.files.FindAll(y => y.abilityId.Equals($"{abid}"));
- if (file.IsNotEmpty())
- {
- view += x.view;
- }
- });
- }
- double minut = view / 60;
- teacherVideoTime.after_time = minut;
- if (minut < 300)
- {
- var fils = teacherFile.fileRecords.Find(x => x.hash.Equals(ps.Key));
- if (fils != null)
- {
- ps.Value.fileAbilities.ForEach(x =>
- {
- var a = fils.files.Find(z => z.nodeId.Equals(x.nodeId) && z.abilityId.Equals(x.abilityId));
- if (a == null)
- {
- childIds.Add(x.nodeId);
- fils.files.Add(new FileAbility { url = x.url, abilityId = x.abilityId, taskId = x.taskId, nodeId = x.nodeId });
- }
- });
- }
- else
- {
- ps.Value.fileAbilities.ForEach(x =>
- {
- childIds.Add(x.nodeId);
- });
- teacherFile.fileRecords.Add(new FileRecord
- {
- hash = ps.Value.fileRecord.hash,
- size = ps.Value.fileRecord.size,
- duration = ps.Value.fileRecord.duration,
- view = (int)ps.Value.fileRecord.view,
- type = ps.Value.fileRecord.type,
- done = true,
- files = ps.Value.fileAbilities
- });
- }
- }
- else
- {
- break;
- }
- }
- if (childIds.Any())
- {
- string code = teacherFile.code.Replace("TeacherFile-", "");
- if (!string.IsNullOrWhiteSpace(code))
- {
- try
- {
- AbilitySub abilitySub = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<AbilitySub>(ability.id, new PartitionKey($"AbilitySub-{code}-{teacherFile.id}"));
- var taskIds = abilitySub.taskRcds.Select(x => x.id);
- var notin = childIds.Except(taskIds);
- if (notin.Any())
- {
- abilitySub.taskRcds.AddRange(notin.Select(x => new AbilityTaskRcd { id = x, done = true }));
- abilitySubs.Add(abilitySub);
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(abilitySub, abilitySub.id, new PartitionKey($"AbilitySub-{code}-{teacherFile.id}"));
- }
- catch (Exception ex)
- {
- }
- }
- }
- teacherVideoTimes.Add(teacherVideoTime);
- }
- teacherFile = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherFile>(teacherFile, teacherFile.id, new PartitionKey(teacherFile.code));
- item.update.Add(StatisticsService.TeacherAbility);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(item, item.id, new PartitionKey(item.code));
- }
- var data = teacherVideoTimes.GroupBy(x => x.code).Select(x => new { x.Key, count = x.ToList().Count, list = x.ToList() }).OrderByDescending(x => x.count);
- return Ok(new { data, abilitySubs });
- }
- public class TeacherVideoTime
- {
- public string code { get; set; }
- public string id { get; set; }
- public string abilityId { get; set; }
- public string no { get; set; }
- public double train_time { get; set; }
- public double files_time { get; set; }
- public double after_time { get; set; }
- }
- [HttpPost("get-teacher-video")]
- public async Task<IActionResult> GetScteacherClassVideo(JsonElement json)
- {
- string sql = " SELECT c.id ,c.school as code FROM c where c.pk='ClassVideo' and c.school<>'SYSTEM_NO_SCHOOL' and ARRAY_LENGTH(c.files)>0 ";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<IdNameCode>(sql, requestOptions: new QueryRequestOptions { }))
- {
- idNameCodes.Add(item);
- }
- foreach (var item in idNameCodes)
- {
- try
- {
- TeacherTrain teacherTrain = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherTrain>(item.id, new PartitionKey($"TeacherTrain-{item.code}"));
- if (!teacherTrain.teacherClasses.Any())
- {
- teacherTrain.update.Add("TeacherClass");
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(teacherTrain, teacherTrain.id, new PartitionKey($"TeacherTrain-{item.code}"));
- }
- }
- catch (Exception ex)
- {
- continue;
- }
- }
- return Ok();
- }
- [HttpPost("test-batch")]
- public async Task<IActionResult> TestBatchFUN(JsonElement json)
- {
- List<Task<ItemResponse<TestBatch>>> nameCodes = new List<Task<ItemResponse<TestBatch>>>();
- for (int i = 0; i < 10; i++)
- {
- nameCodes.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- CreateItemAsync(new TestController.TestBatch { id = Guid.NewGuid().ToString(), code = $"TestBatch-{i}", pk = "TestBatch" }, new PartitionKey($"TestBatch-{i}")));
- }
- await Task.WhenAll(nameCodes);
- return Ok();
- }
- public class TestBatch : CosmosEntity
- {
- }
- [HttpPost("export-teacher")]
- public async Task<IActionResult> ExportTeacher(JsonElement json)
- {
- List<string> schools = new()
- {
- "dghznx",
- "cxhhlx",
- "xjaxx",
- "zjqxx",
- "xnygxx",
- "lxxcfx",
- "gxjrxx",
- "cdgxsx",
- "yzxx",
- "kjyxx",
- "wjylxx",
- "dsgjxx",
- "ydzt",
- "xndbxx",
- "sqtszx",
- "cdxczx",
- "ghsyzx",
- "lqsx",
- "cdxxps",
- "xcfx",
- "xyqxx",
- "xncbyy",
- "cdlqjk",
- "lqdmxx",
- "lqyx",
- "pclxxx",
- "cdfzx",
- "xnblxx",
- "ghsx",
- "khdycz",
- "khbmxx",
- "khdecz",
- "khzx",
- "khhbzx",
- "gxxcxx",
- "khhtxx",
- "khdxxx",
- "khsyxx"
- };
- var cosmosClient = _azureCosmos.GetCosmosClient();
- foreach (var item in schools)
- {
- School school = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{item}", new PartitionKey("Base"));
- List<Teacher> teachers = new();
- await foreach (var tch in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(queryText:
- $"SELECT value(c) FROM c join s in c.schools where s.schoolId='{item}' and c.code='Base'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- teachers.Add(tch);
- }
- if (teachers.Count > 0)
- {
- foreach (var teacher in teachers)
- {
- teacher.schools.ForEach(tch => { if (tch.schoolId.Equals(item)) { tch.areaId = school.areaId; } });
- await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- }
- }
- }
- return Ok();
- }
- public class RecordFileAbility
- {
- public FileRecord fileRecord { get; set; }
- public List<FileAbility> fileAbilities { get; set; }
- }
- [HttpPost("test-blob-folder")]
- public async Task<IActionResult> TestBlobFolder(JsonElement json)
- {
- string location = _option.Location;
- bool lockKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"LessonRecord:Unused:Lock:{location}");
- //key不存在的时候 。
- if (!lockKey)
- {
- var schoolKeys = new List<IdCodeCount>();
- var teacherKeys = new List<IdCodeCount>();
- string sql = "select value c.id from c where c.code='Base'";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).
- GetItemQueryIterator<string>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- teacherKeys.Add(new IdCodeCount { id = item, code = "Teacher" });
- }
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
- GetItemQueryIterator<string>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- schoolKeys.Add(new IdCodeCount { id = item, code = "School" });
- }
- string sqlcount = "select value count(1) from c where c.pk='LessonRecord'";
- foreach (var key in schoolKeys)
- {
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
- GetItemQueryIterator<int>(queryText: sqlcount, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"LessonRecord-{key.id}") }))
- {
- key.count = item;
- break;
- }
- }
- foreach (var key in teacherKeys)
- {
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).
- GetItemQueryIterator<int>(queryText: $"select value count(1) from c where c.pk='LessonRecord' and c.tmdid='{key.id}'",
- requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"LessonRecord") }))
- {
- key.count = item;
- break;
- }
- }
- schoolKeys.AddRange(teacherKeys);
- //以下代码作用,用于根据当前拥有的课例数判断区分学校和个人使用课例频率越多的,
- //并均分每次需要处理的学校和个人容器个数,避免每次处理批次花费时间相差太大。
- //将每个批次处理数量级控制在500-1000左右。
- List<IEnumerable<IdCodeCount>> counts = new List<IEnumerable<IdCodeCount>>();
- //501-∞
- var count501_ = schoolKeys.Where(x => x.count >= 501); //至少500条
- counts.AddRange(count501_.Page(1));//1个学校
- //201-500
- var count201_500 = schoolKeys.Where(x => x.count >= 201 && x.count <= 500); //至少402条-1000条
- counts.AddRange(count201_500.Page(2));//2个学校
- //100-200
- var count100_200 = schoolKeys.Where(x => x.count >= 100 && x.count <= 200);//至少500条-1000条
- counts.AddRange(count100_200.Page(5));//5个学校
- //51-99
- var count51_99 = schoolKeys.Where(x => x.count >= 51 && x.count <= 99);//至少500条-990条
- counts.AddRange(count51_99.Page(10));//10个学校
- //21-50
- var count21_50 = schoolKeys.Where(x => x.count >= 21 && x.count <= 50);//至少410条-1000条
- counts.AddRange(count21_50.Page(20));//20个学校
- //10-20
- var count10_20 = schoolKeys.Where(x => x.count >= 10 && x.count <= 20);//至少500条-1000条
- counts.AddRange(count10_20.Page(50));//50个学校
- //5-9
- var count0_9 = schoolKeys.Where(x => x.count >= 5 && x.count <= 9);//至少500条-900条
- counts.AddRange(count0_9.Page(100));//100个学校
- //2-4
- var count2_4 = schoolKeys.Where(x => x.count >= 2 && x.count <= 4);//至少500条-1000条
- counts.AddRange(count2_4.Page(250));
- //0-1
- var count0_1 = schoolKeys.Where(x => x.count >= 0 && x.count <= 1);//至少500,就算没有课例也算一次。
- counts.AddRange(count0_1.Page(500));
- int field = 1;
- counts.Count();
- foreach (var item in counts)
- {
- bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"LessonRecord:Unused:Lock:{location}", field, new { status = 0, item }.ToJsonString());
- field += 1;
- }
- await _dingDing.SendBotMsg($"{location},获取到:{schoolKeys.Count} 个学校和个人的容器\n" +
- $"大概要处理:{schoolKeys.Sum(x => x.count) + schoolKeys.Where(x => x.count >= 0).Count()} 条数据\n" +
- $"将数据分为:{field - 1} 次处理,每次处理500-1000条数据。", GroupNames.醍摩豆服務運維群組);
- }
- return Ok(new { });
- }
- public class IdCodeCount
- {
- public string id { get; set; }
- public string code { get; set; }
- public int count { get; set; }
- }
- /// <summary>
- /// 随机获取三个不同类型的题目
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("gen-pdf")]
- //[Authorize(Roles = Constant.Role_Root)]
- public IActionResult GenPdf(JsonElement json)
- {
- //https://article.itxueyuan.com/JAxOnG
- //http://t.zoukankan.com/hsiang-p-14608694.html
- //https://github.com/rdvojmoc/DinkToPdf
- //https://blog.csdn.net/u011966339/article/details/114964016?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-114964016-blog-118609642.pc_relevant_antiscanv2&spm=1001.2101.3001.4242.1&utm_relevant_index=3
- var html = @"
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset=""UTF-8"">
- <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
- <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
- <title>校本研修活动完成情况</title>
- <style>
- body {
- font-family: ""fangsong"";
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- .tch-table,
- .details-table {
- width: 100%;
- }
- .tch-table table {
- width: 100%;
- margin: 15px 0;
- border: 0;
- }
- .tch-table th {
- background-color: #c5c5c5;
- color: #222222;
-
- }
- .tch-table,
- .tch-table th,
- .tch-table td {
- font-size: 0.95em;
- text-align: center;
- padding: 4px;
- border-collapse: collapse;
- font-weight: bolder;
- }
- .tch-table th,
- .tch-table td {
- border-bottom: 1px solid #918b8c;
- border-width: 1px 0 1px 0;
- }
- .tch-table tr {
- border: 1px solid #ffffff;
- height: 3.2em;
- }
- .title {
- font-weight: bold;
- align-self: flex-start;
- margin: 30px 5px;
- }
- .title::before {
- content: """";
- width: 10px;
- height: 10px;
- background: #3a3a3a;
- display: inline-block;
- margin-right: 10px;
- }
- </style>
- </head>
- <body>
- <h1 style=""text-align:center;font-weight: bold;"">校本研修活动完成情况</h1>
- <p class=""title"">教师信息</p>
- <table class=""tch-table"" id=""tchTable"">
- <tr>
- <th style=""width: 33.3%;"">教师姓名</th>
- <th style=""width: 33.3%;"">机构</th>
- <th style=""width: 33.3%;"">教研组</th>
- </tr>
- <tr>
- <td>张三</td>
- <td>四川省成都市盐道街中学</td>
- <td>高中政治教研组</td>
- </tr>
- </table>
- <p class=""title"">活动明细</p>
- <table class=""tch-table"" id=""acTable"">
- <tr>
- <th style=""width: 25%;"">活动主题</th>
- <th style=""width: 15%;"">活动类型</th>
- <th style=""width: 5%;"">任务学时</th>
- <th style=""width: 5%;"">完成学时</th>
- <th style=""width: 20%;"">活动时间</th>
- <th style=""width: 10%;"">活动内容</th>
- <th style=""width: 10%;"">活动任务</th>
- <th style=""width: 10%;"">状态</th>
- </tr>
- <tr>
- <td>语文学科如何在A1技术支持下进行学情分析</td>
- <td>信息化教学案例展示与分享</td>
- <td>1</td>
- <td>1</td>
- <td>2022-04-07 到 2022-04-14</td>
- <td></td>
- <td>扫码签到、作业提交、问卷反馈、评测活动</td>
- <td>已完成</td>
- </tr>
- </table>
- </body>
- </html>
- ";
- try
- {
- GlobalSettings globalSettings = new GlobalSettings();
- globalSettings.ColorMode = ColorMode.Color;
- globalSettings.Orientation = Orientation.Portrait;
- globalSettings.PaperSize = PaperKind.A4;
- globalSettings.Margins = new MarginSettings { Top = 25, Bottom = 25 };
- ObjectSettings objectSettings = new ObjectSettings();
- objectSettings.PagesCount = true;
- objectSettings.HtmlContent = html;
- //WebSettings webSettings = new WebSettings();
- //webSettings.DefaultEncoding = "utf-8";
- HeaderSettings headerSettings = new HeaderSettings();
- headerSettings.FontSize = 15;
- headerSettings.FontName = "fangsong";
- headerSettings.Right = "";
- // headerSettings.Line = true;
- FooterSettings footerSettings = new FooterSettings();
- footerSettings.FontSize = 12;
- footerSettings.FontName = "Ariel";
- footerSettings.Center = "校本研修活动完成情况([page]/[toPage])页";
- // footerSettings.Line = true;
- objectSettings.HeaderSettings = headerSettings;
- objectSettings.FooterSettings = footerSettings;
- //objectSettings.WebSettings = webSettings;
- HtmlToPdfDocument htmlToPdfDocument = new HtmlToPdfDocument()
- {
- GlobalSettings = globalSettings,
- Objects = { objectSettings },
- };
- var a = _converter.Convert(htmlToPdfDocument);
- MemoryStream m = new MemoryStream(a);
- FileStream fs = new FileStream("F:\\1111111111111\\SimplePdf1.pdf", FileMode.Create, FileAccess.Write, FileShare.Read);
- m.WriteTo(fs);
- m.Close();
- fs.Close();
- var doc = new HtmlToPdfDocument()
- {
- GlobalSettings = {
- ColorMode = ColorMode.Color,
- Orientation = Orientation.Portrait,
- PaperSize = PaperKind.A4,
- Margins = new MarginSettings() { Top = 10 },
- Out = @"F:\test.pdf",
- },
- Objects = {
- new ObjectSettings()
- {
- Page = "https://teammodelos.blob.core.chinacloudapi.cn/0-public/pie-borderRadius.html",
- },
- }
- };
- _converter.Convert(doc);
- return Ok();
- // return Ok(File(a, "application/octet-stream", "SimplePdf.pdf"));
- }
- catch (Exception ex)
- {
- return BadRequest(new { ex = ex.StackTrace, exmsg = ex.Message });
- }
- }
- /*
- //自主學習綱領 資料架構測試
- [HttpPost("test-selflearn-structure")]
- public async Task<IActionResult> TestSelfLearnStructure(JsonElement json)
- {
- string tmid = "1595321354";
- ////個人課程
- //主體
- SelfLearn selfLearnT = new SelfLearn();
- selfLearnT.code = $"SelfLearn-{tmid}";
- selfLearnT.id = "a6dc752f-7cae-44a5-9b7b-92cfe71cea14";
- selfLearnT.scope = "private";
- selfLearnT.name = "測試課程課綱";
- selfLearnT.course = new IdName();
- selfLearnT.course.id = "ae64e6a4-54f3-10df-a7f3-79dbe252d295";
- selfLearnT.course.name = "測試課程001";
- selfLearnT.creatorId = $"{tmid}";
- selfLearnT.creatorName = "Miss Lo";
- selfLearnT.release = true;
- selfLearnT.groupLists.Add(new IdName { id = "a986bf87-da87-4bd3-bd90-19ee9fd52836", name = "測試課程名單" });
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnT);
- //節點:章節
- SelfLearnNode selfLearnNodeTChapter = new SelfLearnNode();
- selfLearnNodeTChapter.code = $"SelfLearn-{tmid}";
- selfLearnNodeTChapter.id = "0990cbb6-3228-41d0-aeb0-62209f37dc0d";
- selfLearnNodeTChapter.name = "第一章節";
- selfLearnNodeTChapter.selfLearnId = selfLearnT.id;
- selfLearnNodeTChapter.nodeType = "chapter";
- selfLearnNodeTChapter.openType = "order";
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeTChapter);
- //節點:項目
- SelfLearnNode selfLearnNodeTContent = new SelfLearnNode();
- selfLearnNodeTContent.code = $"SelfLearn-{tmid}";
- selfLearnNodeTContent.id = "5627184f-e9b4-4ceb-a1d0-47727db569b1";
- selfLearnNodeTContent.name = "四則運算";
- selfLearnNodeTContent.selfLearnId = selfLearnT.id;
- selfLearnNodeTContent.selfLearnNodeId = selfLearnNodeTChapter.id;
- selfLearnNodeTContent.nodeType = "content";
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeTContent);
- //內容:作業
- SelfLearnContentHomework selfLearnTContentHomework = new SelfLearnContentHomework();
- selfLearnTContentHomework.code = $"SelfLearn-{tmid}";
- //內容:評量
- SelfLearnContentExam selfLearnTContentExam = new SelfLearnContentExam();
- selfLearnTContentExam.code = $"SelfLearn-{tmid}";
- selfLearnTContentExam.id = "07e6fdd2-6083-4eb6-ac6d-06421edb0b48";
- selfLearnTContentExam.name = "隨堂測驗1";
- selfLearnTContentExam.selfLearnId = selfLearnT.id;
- selfLearnTContentExam.selfLearnNodeId = selfLearnNodeTContent.id;
- selfLearnTContentExam.contentType = "exam";
- //自主課綱的試卷需要從試題庫拷貝到課綱Blob之下 容器:個人課綱:{個人ID} 路徑:selflearn/{selfLearn本體ID}/paper/{試卷名稱}/{試卷各個檔案}
- ////自主課綱Blob需納管入Blob容量計算系統之下
- List<Dictionary<string, string>> sourcePaperDic = new List<Dictionary<string, string>>();
- sourcePaperDic.Add(new Dictionary<string, string>() { { "id", "184914dd-05e0-04f4-e14a-cfce53545018" }, { "blobContainer", "1595321354" }, { "blob", "paper/個人評量測試卷1" }, { "name", "個人評量測試卷1" } });
- foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperDic)
- {
- string targetScope = "private";
- var sourceBlobContainer = _azureStorage.GetBlobContainerClient(sourcePaperInfoDic["blobContainer"]);
- string sourceBlobPath = (!sourcePaperInfoDic["blob"].EndsWith("/")) ? sourcePaperInfoDic["blob"] + "/" : sourcePaperInfoDic["blob"];
- var destBlobContainer = _azureStorage.GetBlobContainerClient(tmid); //拷貝對象容器
- string destBlobPath = $"/selflearn/{selfLearnT.id}/paper/{sourcePaperInfoDic["name"]}/";
- Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
- if (sourceBlobs.Count() > 0)
- {
- foreach (var blob in sourceBlobs)
- {
- var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
- if (sourceFileBlob.Exists())
- {
- var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
- string fileName = blob.Name.Replace(sourceBlobPath, "");
- string destBlobFilePath = $"{destBlobPath}{fileName}";
- await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
- }
- }
- }
- }
- //內容:評量 DB操作
- PaperSimple paper = new PaperSimple()
- {
- id = "184914dd-05e0-04f4-e14a-cfce53545018",
- subjectId = null,
- code = "Paper-1595321354",
- name = "個人評量測試卷1",
- blob = $"/selflearn/{selfLearnT.id}/paper/個人評量測試卷1/",
- scope = "private",
- multipleRule = 1,
- point = new List<double>() { 50, 50 }, //這裡和題庫的格式不同,需要轉換
- answers = new List<List<string>>() { new List<string>() { "B" }, new List<string>() { "A" } }, //這裡和題庫的格式不同,需要轉換
- type = new List<string>() { "single", "single" }, //這裡和題庫的格式不同,需要轉換
- field = new List<int>() { 1, 1 } //認知層次 這裡須由各題的Blob中取得後轉換
- };
- paper.subjectId = selfLearnT.course.id;
- ExamInfo examT = new ExamInfo();
- examT.pk = "Exam";
- examT.scope = "private";
- examT.owner = "teacher";
- examT.code = $"Exam-{tmid}";
- examT.creatorId = $"{tmid}";
- examT.name = "隨堂測驗1";
- examT.papers.Add(paper);
- selfLearnTContentExam.examInfo = examT;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnTContentExam);
- ////學校課程
- //主體
- SelfLearn selfLearnS = new SelfLearn();
- selfLearnS.pk = "SelfLearn";
- selfLearnS.code = $"SelfLearn-{tmid}";
- selfLearnS.id = "f05f79f2-c58d-4e27-8214-48385e2ac3cd";
- selfLearnS.scope = "private";
- selfLearnS.school = "hbgl";
- selfLearnS.name = "數學一年級上學期課綱";
- selfLearnS.subject = new IdName();
- selfLearnS.subject.id = "c5f96ea0-e65c-f15c-dc59-410da564c185";
- selfLearnS.subject.name = "數學";
- selfLearnS.period = new IdName();
- selfLearnS.period.id = "127e71a7-0ca8-82b8-476b-5269b78066f7";
- selfLearnS.period.name = "測試國中";
- selfLearnS.course = new IdName();
- selfLearnS.course.id = "0d4fa541-ad4f-bee1-c604-764275f6d10e";
- selfLearnS.course.name = "數學一";
- selfLearnS.creatorId = $"{tmid}";
- selfLearnS.creatorName = "Miss Lo";
- selfLearnS.release = true;
- selfLearnS.classes.Add(new IdName { id = "d3090c56-21de-4cc8-a962-a7e7eaa2e913", name = "2023年A班" });
- selfLearnS.groupLists.Add(new IdName { id = "54a39ec1-be0b-43cd-a978-f3133552f291", name = "七年A班" });
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnS);
- //節點:章節
- SelfLearnNode selfLearnNodeSChapter = new SelfLearnNode();
- selfLearnNodeSChapter.code = $"SelfLearn-{tmid}";
- selfLearnNodeSChapter.id = "77172663-aa17-44c6-8259-61870c44121f";
- selfLearnNodeSChapter.name = "第一章節";
- selfLearnNodeSChapter.selfLearnId = selfLearnS.id;
- selfLearnNodeSChapter.nodeType = "chapter";
- selfLearnNodeSChapter.openType = "order";
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeSChapter);
- //節點:項目
- SelfLearnNode selfLearnNodeSContent = new SelfLearnNode();
- selfLearnNodeSContent.code = $"SelfLearn-{tmid}";
- selfLearnNodeSContent.id = "f28c6ecd-38a6-4edb-9160-363a116b8c3b";
- selfLearnNodeSContent.name = "四則運算";
- selfLearnNodeSContent.selfLearnId = selfLearnS.id;
- selfLearnNodeSContent.selfLearnNodeId = selfLearnNodeSChapter.id;
- selfLearnNodeSContent.nodeType = "content";
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeSContent);
- //內容:作業
- SelfLearnContentHomework selfLearnSContentHomework = new SelfLearnContentHomework();
- selfLearnSContentHomework.code = $"SelfLearn-{tmid}";
- //內容:評量
- SelfLearnContentExam selfLearnSContentExam = new SelfLearnContentExam();
- selfLearnSContentExam.code = $"SelfLearn-{tmid}";
- selfLearnSContentExam.id = "3f088f49-fefa-4af5-a324-c577ffb6d1f8";
- selfLearnSContentExam.name = "隨堂測驗1";
- selfLearnSContentExam.selfLearnId = selfLearnS.id;
- selfLearnSContentExam.selfLearnNodeId = selfLearnNodeSContent.id;
- selfLearnSContentExam.contentType = "exam";
- //自主課綱試卷拷貝到課綱
- foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperDic)
- {
- string targetScope = "private";
- var sourceBlobContainer = _azureStorage.GetBlobContainerClient(sourcePaperInfoDic["blobContainer"]);
- string sourceBlobPath = (!sourcePaperInfoDic["blob"].EndsWith("/")) ? sourcePaperInfoDic["blob"] + "/" : sourcePaperInfoDic["blob"];
- var destBlobContainer = _azureStorage.GetBlobContainerClient(tmid); //拷貝對象容器
- string destBlobPath = $"/selflearn/{selfLearnS.id}/paper/{sourcePaperInfoDic["name"]}/";
- Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
- if (sourceBlobs.Count() > 0)
- {
- foreach (var blob in sourceBlobs)
- {
- var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
- if (sourceFileBlob.Exists())
- {
- var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
- string fileName = blob.Name.Replace(sourceBlobPath, "");
- string destBlobFilePath = $"{destBlobPath}{fileName}";
- await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
- }
- }
- }
- }
- paper.blob = $"/selflearn/{selfLearnS.id}/paper/個人評量測試卷1/";
- ExamInfo examS = new ExamInfo();
- examS.pk = "Exam";
- examS.scope = "school";
- examS.owner = "teacher";
- examS.code = $"Exam-{tmid}";
- examS.creatorId = $"{tmid}";
- examS.name = "隨堂測驗1";
- examS.papers.Add(paper);
- selfLearnSContentExam.examInfo = examS;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnSContentExam);
- return Ok();
- }
- //自主學習綱領 生成評量架構測試
- [HttpPost("test-selflearn-create-exam")]
- public async void TestSelfLearnCreateExam(JsonElement json)
- {
- //輸入項:startTime (-1 會以現在時間記入)
- long startTime = (json.TryGetProperty("startTime", out JsonElement startTimeJ)) ? startTimeJ.GetInt64() : -1;
- var client = _azureCosmos.GetCosmosClient();
- string tmid = "1595321354";
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- string code = string.Empty;
- string selfLearnContentExamId = string.Empty;
- SelfLearn selfLearn = new SelfLearn();
- SelfLearnContentExam contentExam = new SelfLearnContentExam();
- //[個人評量學校課程]
- code = $"SelfLearn-{tmid}";
- selfLearnContentExamId = "3f088f49-fefa-4af5-a324-c577ffb6d1f8"; //個人評量學校班級
- contentExam = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearnContentExam>(selfLearnContentExamId, new PartitionKey(code));
- if (contentExam != null)
- {
- string selfLearnId = contentExam.selfLearnId;
- selfLearn = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearn>(selfLearnId, new PartitionKey(code));
- }
- if (!string.IsNullOrWhiteSpace(selfLearn.id))
- {
- //評量的架構只能生成 編制班(複數班) OR 選課班(複數班) 擇一,如果同步對象有編制班也有選課班,需生成兩個評量活動
- int examCount = 0;
- if (selfLearn.classes.Count > 0) examCount++;
- if (selfLearn.groupLists.Count > 0) examCount++;
- List<string> actExamInfoId = new List<string>() { "dbdcddc5-a79e-400f-a0b9-42801b176c21", "0c02b5e7-1aea-4126-b872-10baa2b4db56" };
- for (int i = 0; i < examCount; i++)
- {
- string contentExamJsonStr = System.Text.Json.JsonSerializer.Serialize<ExamInfo>(contentExam.examInfo);
- ExamInfo actExamInfo = System.Text.Json.JsonSerializer.Deserialize<ExamInfo>(contentExamJsonStr); //要生成的Exam
- actExamInfo.id = actExamInfoId[i]; //假設每次生成新的評量;實作的時候應該在Exam埋入自主課綱相關的ID,如果可取得此ID的評量則更新
- actExamInfo.source = "0"; //目前先設定為"線上評量",實際上應讓老師選擇
- actExamInfo.creatorId = tmid;
- actExamInfo.year = DateTimeOffset.UtcNow.Year;
- IdName selfLearnSubject = selfLearn.subject;
- IdName selfLearnCourse = selfLearn.course;
- IdName selfLearnPeriod = selfLearn.period;
- if (contentExam.examInfo.scope.Equals("school")) //學校 編制班、選課班 ※編制班、選課班無法共存只能擇一
- {
- actExamInfo.school = selfLearn.school;
- actExamInfo.period.id = selfLearnPeriod.id;
- actExamInfo.period.name = selfLearnPeriod.name;
- actExamInfo.subjects.Add(new ExamSubject() { id = selfLearnSubject.id, name = selfLearnSubject.name });
- if (actExamInfo.id.Equals("dbdcddc5-a79e-400f-a0b9-42801b176c21")) //編制班
- {
- foreach (IdName classRow in selfLearn.classes)
- {
- actExamInfo.classes.Add(classRow.id);
- List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "class", classRow.id };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- }
- }
- else if (actExamInfo.id.Equals("0c02b5e7-1aea-4126-b872-10baa2b4db56")) //選課班
- {
- foreach (IdName groupRow in selfLearn.groupLists)
- {
- actExamInfo.stuLists.Add(groupRow.id);
- List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "teach", groupRow.id };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- }
- }
- }
- else if (contentExam.examInfo.scope.Equals("private"))
- {
- foreach (IdName groupRow in selfLearn.groupLists)
- {
- actExamInfo.subjects.Add(new ExamSubject() { id = selfLearn.course.id, name = selfLearn.course.name });
- actExamInfo.stuLists.Add(groupRow.id);
- List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", groupRow.id };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- }
- }
- //以下是Blob拷貝程序
- //ExamInfo內容取得、調整
- //※規則 owner:"school" => 校園評測 "teacher" => 個人評測
- //※規則 scope:"school" => 校本班級 "private" => 個人班級
- //※規則 BLOB容器: scope:"school" => {學校ID}下 scope:"private" => {個人ID}下
- //試卷情報字典
- string paperSubjectId = actExamInfo.subjects.First().id;
- List<Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
- foreach (PaperSimple paperInfo in contentExam.examInfo.papers)
- {
- string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
- paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
- string paperBlobContainer = tmid;
- sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blobContainer", paperBlobContainer }, { "subjectId", paperSubjectId }, { "blob", paperBlobPath } });
- }
- //取得自主課綱下的試卷資料(blob)、複製到評測紀錄下
- //Blob搬運
- int paperIndex = 0;
- foreach (Dictionary<string, string> recordPaperInfoDic in sourcePaperInfo)
- {
- string targetScope = actExamInfo.scope; //評測對象 school:校本班級 private:私人課程
- var sourceBlobContainer = _azureStorage.GetBlobContainerClient(recordPaperInfoDic["blobContainer"]);
- string sourceBlobPath = recordPaperInfoDic["blob"];
- string destBlobContainerId = (!string.IsNullOrWhiteSpace(actExamInfo.school) && actExamInfo.scope.Equals("school")) ? actExamInfo.school : actExamInfo.creatorId;
- var destBlobContainer = _azureStorage.GetBlobContainerClient(destBlobContainerId); //拷貝對象容器
- string destBlobPath = $"exam/{actExamInfo.id}/paper/{recordPaperInfoDic["subjectId"]}"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/ ※2022-1-6 式樣變更[原]/paper/{試卷ID}/ [新]/paper/{subjectID}/
- Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
- if (sourceBlobs.Count() > 0)
- {
- foreach (var blob in sourceBlobs)
- {
- var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
- if (sourceFileBlob.Exists())
- {
- var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
- string fileName = blob.Name.Replace(sourceBlobPath, "");
- string destBlobFilePath = $"{destBlobPath}/{fileName}";
- await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
- }
- }
- }
- actExamInfo.papers[paperIndex].blob = destBlobPath;
- actExamInfo.papers[paperIndex].subjectId = selfLearnSubject.id;
- paperIndex++;
- }
- //以下是ExamController生成評量邏輯
- actExamInfo.createTime = now;
- actExamInfo.startTime = startTime;
- if (actExamInfo.startTime <= 0) actExamInfo.startTime = now;
- actExamInfo.endTime = actExamInfo.startTime + 172800000; //結束時間設為2天後 ※實際上應由老師設定
- List<string> classes = ExamService.getClasses(actExamInfo.classes, actExamInfo.stuLists);
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, selfLearn.school);
- actExamInfo.stuCount = tchList.Count;
- actExamInfo.progress = (actExamInfo.startTime > now) ? "pending" : "going";
- var messageBlob = new ServiceBusMessage();
- if (actExamInfo.scope.Equals("school"))
- {
- actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.school).GetBlobsSize($"exam/{actExamInfo.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- string schoolId = string.Empty; //看學生是否有屬於學校,如果有則填入學校ID
- foreach (RMember stuInfo in tchList)
- {
- if (!string.IsNullOrWhiteSpace(stuInfo.schoolId) && string.IsNullOrWhiteSpace(schoolId)) schoolId = stuInfo.schoolId;
- }
- actExamInfo.school = (!string.IsNullOrWhiteSpace(schoolId)) ? schoolId : "SYSTEM_NO_SCHOOL";
- actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.creatorId).GetBlobsSize($"exam/{actExamInfo.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- int n = 0;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in actExamInfo.papers)
- {
- simple.blob = $"/exam/{actExamInfo.id}/paper/{actExamInfo.subjects[n].id}";
- n++;
- simple.sheet = null;
- }
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(actExamInfo, new PartitionKey($"{actExamInfo.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- }
- }
- //[個人評量個人課程]
- //取得自主學習綱領內容、自主學習綱領主體
- code = $"SelfLearn-{tmid}";
- selfLearnContentExamId = "07e6fdd2-6083-4eb6-ac6d-06421edb0b48"; //個人評量個人課程
- contentExam = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearnContentExam>(selfLearnContentExamId, new PartitionKey(code));
- if (contentExam != null)
- {
- string selfLearnId = contentExam.selfLearnId;
- selfLearn = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearn>(selfLearnId, new PartitionKey(code));
- }
- if(!string.IsNullOrWhiteSpace(selfLearn.id))
- {
- //補足實體化需要項目
- //targets.row:
- //個人課程: [0]:課程ID(CourseBase.id)[1]stuListId(GroupList.id)
- //學校課程 編制班[0]:課程ID(CourseBase.id)[1]"class"[2]classId
- //學校課程 選課班[0]:課程ID(CourseBase.id)[1]"teach"[2]stuListId(GroupList.id)
- string contentExamJsonStr = System.Text.Json.JsonSerializer.Serialize<ExamInfo>(contentExam.examInfo);
- ExamInfo actExamInfo = System.Text.Json.JsonSerializer.Deserialize<ExamInfo>(contentExamJsonStr); //要生成的Exam
- actExamInfo.id = "78c4232d-b716-40a7-9901-c85b73da79a2"; //假設每次生成新的評量;實作的時候應該在Exam埋入自主課綱相關的ID,如果可取得此ID的評量則更新
- actExamInfo.source = "0"; //目前先設定為"線上評量",實際上應讓老師選擇
- actExamInfo.creatorId = tmid;
- actExamInfo.year = DateTimeOffset.UtcNow.Year;
- IdName selfLearnSubject = selfLearn.subject;
- IdName selfLearnCourse = selfLearn.course;
- IdName selfLearnPeriod = selfLearn.period;
- if (contentExam.examInfo.scope.Equals("school")) //學校 編制班、選課班
- {
- actExamInfo.school = selfLearn.school;
- actExamInfo.period.id = selfLearnPeriod.id;
- actExamInfo.period.name = selfLearnPeriod.name;
- actExamInfo.subjects.Add(new ExamSubject() { id = selfLearnSubject.id, name = selfLearnSubject.name });
- foreach(IdName classRow in selfLearn.classes)
- {
- actExamInfo.classes.Add(classRow.id);
- List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "class", classRow.id };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- }
- foreach (IdName groupRow in selfLearn.groupLists)
- {
- actExamInfo.stuLists.Add(groupRow.id);
- List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "teach", groupRow.id };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- }
- }
- else if(contentExam.examInfo.scope.Equals("private"))
- {
- foreach (IdName groupRow in selfLearn.groupLists)
- {
- actExamInfo.subjects.Add(new ExamSubject() { id = selfLearn.course.id, name = selfLearn.course.name });
- actExamInfo.stuLists.Add(groupRow.id);
- List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", groupRow.id };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- }
- }
- //以下是Blob拷貝程序
- //ExamInfo內容取得、調整
- //※規則 owner:"school" => 校園評測 "teacher" => 個人評測
- //※規則 scope:"school" => 校本班級 "private" => 個人班級
- //※規則 BLOB容器: scope:"school" => {學校ID}下 scope:"private" => {個人ID}下
- //試卷情報字典
- string paperSubjectId = actExamInfo.subjects.First().id;
- List <Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
- foreach (PaperSimple paperInfo in contentExam.examInfo.papers)
- {
- string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
- paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
- string paperBlobContainer = tmid;
- sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blobContainer", paperBlobContainer }, { "subjectId", paperSubjectId }, { "blob", paperBlobPath } });
- }
- //取得自主課綱下的試卷資料(blob)、複製到評測紀錄下
- //Blob搬運
- int paperIndex = 0;
- foreach (Dictionary<string, string> recordPaperInfoDic in sourcePaperInfo)
- {
- string targetScope = actExamInfo.scope; //評測對象 school:校本班級 private:私人課程
- var sourceBlobContainer = _azureStorage.GetBlobContainerClient(recordPaperInfoDic["blobContainer"]);
- string sourceBlobPath = recordPaperInfoDic["blob"];
- string destBlobContainerId = (!string.IsNullOrWhiteSpace(actExamInfo.school) && actExamInfo.scope.Equals("school")) ? actExamInfo.school : actExamInfo.creatorId;
- var destBlobContainer = _azureStorage.GetBlobContainerClient(destBlobContainerId); //拷貝對象容器
- string destBlobPath = $"exam/{actExamInfo.id}/paper/{recordPaperInfoDic["subjectId"]}"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/ ※2022-1-6 式樣變更[原]/paper/{試卷ID}/ [新]/paper/{subjectID}/
- Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
- if (sourceBlobs.Count() > 0)
- {
- foreach (var blob in sourceBlobs)
- {
- var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
- if (sourceFileBlob.Exists())
- {
- var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
- string fileName = blob.Name.Replace(sourceBlobPath, "");
- string destBlobFilePath = $"{destBlobPath}/{fileName}";
- await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
- }
- }
- }
- actExamInfo.papers[paperIndex].blob = destBlobPath;
- actExamInfo.papers[paperIndex].subjectId = selfLearn.course.id;
- paperIndex++;
- }
- //以下是ExamController生成評量邏輯
- actExamInfo.createTime = now;
- actExamInfo.startTime = startTime;
- if (actExamInfo.startTime <= 0) actExamInfo.startTime = now;
- actExamInfo.endTime = actExamInfo.startTime + 172800000; //結束時間設為2天後 ※實際上應由老師設定
- List<string> classes = ExamService.getClasses(actExamInfo.classes, actExamInfo.stuLists);
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, selfLearn.school);
- actExamInfo.stuCount = tchList.Count;
- actExamInfo.progress = (actExamInfo.startTime > now) ? "pending" : "going";
- var messageBlob = new ServiceBusMessage();
- if (actExamInfo.scope.Equals("school"))
- {
- actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.school).GetBlobsSize($"exam/{actExamInfo.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.school }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- string schoolId = string.Empty; //看學生是否有屬於學校,如果有則填入學校ID
- foreach (RMember stuInfo in tchList)
- {
- if (!string.IsNullOrWhiteSpace(stuInfo.schoolId) && string.IsNullOrWhiteSpace(schoolId)) schoolId = stuInfo.schoolId;
- }
- actExamInfo.school = (!string.IsNullOrWhiteSpace(schoolId)) ? schoolId: "SYSTEM_NO_SCHOOL";
- actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.creatorId).GetBlobsSize($"exam/{actExamInfo.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.creatorId }, _serviceBus, _configuration, _azureRedis);
- }
- int n = 0;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in actExamInfo.papers)
- {
- simple.blob = $"/exam/{actExamInfo.id}/paper/{actExamInfo.subjects[n].id}";
- n++;
- simple.sheet = null;
- }
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(actExamInfo, new PartitionKey($"{actExamInfo.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- }
- }
- */
- //統測資料架構生成測試
- /*
- [HttpPost("add-joint-exam")]
- public async Task<IActionResult> AddJointExam(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- JointExam jointExam = new JointExam();
- jointExam.code = "JointExam";
- jointExam.id = "daaa3965-db28-49ae-8074-c9d4865b62ad";
- jointExam.creatorId = "1595321354";
- jointExam.name = "統測測試(一)";
- jointExam.scope = "private";
- //課程列表
- ////課程1: [1595321354]"courseId": "e1d817e5-71b3-bc50-52ac-fa828e5f38d6", "groupId": "4dd434a8-a94a-4373-9a05-1a1add533a71",
- JointExam.JointExamGroup jointExamGroup1 = new JointExam.JointExamGroup();
- jointExamGroup1.creatorId = "1595321354";
- JointExam.JointExamGroup.JointExamGroupCourse jointExamGroupCourse1 = new JointExam.JointExamGroup.JointExamGroupCourse();
- jointExamGroupCourse1.courseId = "e1d817e5-71b3-bc50-52ac-fa828e5f38d6";
- jointExamGroupCourse1.courseName = "test";
- jointExamGroupCourse1.groupListIds.Add("4dd434a8-a94a-4373-9a05-1a1add533a71");
- jointExamGroup1.courseLists.Add(jointExamGroupCourse1);
- jointExam.groupLists.Add(jointExamGroup1);
- ////課程2: [1522758684]"courseId": "424eb44d-8904-4e34-bfaf-e138f8e369cb", "groupId": "5bf63f35-f82f-432e-9b78-a4f38b5edb81",
- JointExam.JointExamGroup jointExamGroup2 = new JointExam.JointExamGroup();
- jointExamGroup2.creatorId = "1522758684";
- JointExam.JointExamGroup.JointExamGroupCourse jointExamGroupCourse2 = new JointExam.JointExamGroup.JointExamGroupCourse();
- jointExamGroupCourse2.courseId = "424eb44d-8904-4e34-bfaf-e138f8e369cb";
- jointExamGroupCourse2.courseName = "1522758684個人課程";
- jointExamGroupCourse2.groupListIds.Add("5bf63f35-f82f-432e-9b78-a4f38b5edb81");
- jointExamGroup2.courseLists.Add(jointExamGroupCourse2);
- jointExam.groupLists.Add(jointExamGroup2);
- //試卷
- ///STEP1 Blob拷貝 ※此步驟由前端做
- ///拷貝目標:{TMID/SchoolId}/jointexam/{jointExam.id}/paper/{paperId}
- string paperSourceBlobPath = "paper/語文理解";
- string paperSourceBlobContainer = "tbslgb";
- string paperSourceScope = "school";
- var paperSourceBlobContainerClient = _azureStorage.GetBlobContainerClient(paperSourceBlobContainer);
- string paperId = "1c6a1e85-4b34-b8af-00de-a379bc47a26c";
- string paperTargetBlobPath = $"jointexam/{jointExam.id}/paper/{paperId}";
- string paperTargetBlobContainer = jointExam.creatorId;
- var paperTargetBlobContainerClient = _azureStorage.GetBlobContainerClient(paperTargetBlobContainer);
- Pageable<BlobItem> sourceBlobs = paperSourceBlobContainerClient.GetBlobs(prefix: paperSourceBlobPath);
- if (sourceBlobs.Count() > 0)
- {
- foreach (var blob in sourceBlobs)
- {
- var sourceFileBlob = paperSourceBlobContainerClient.GetBlobClient(blob.Name);
- if (sourceFileBlob.Exists())
- {
- var sourceFileUri = paperSourceBlobContainerClient.GetBlobClient(blob.Name).Uri;
- string fileName = blob.Name.Replace(paperSourceBlobPath, "");
- string destBlobFilePath = $"{paperTargetBlobPath}{fileName}";
- await paperTargetBlobContainerClient.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
- }
- else
- {
- bool paperDataCopyErrFlg = true;
- }
- }
- }
- ///STEP2 document製作
- PaperSimple paper = new PaperSimple() { id= paperId , code = "Paper-tbslgb", name = "語文理解", blob = $"/{paperTargetBlobPath}", scope = "school", multipleRule = 1, point = new List<double>() { 50, 50}, answers = new List<List<string>>() { new List<string>() { "D" }, new List<string>() { "D" } }, knowledge = new List<List<string>>(), type = new List<string>() { "single","single"}, field=new List<int>() { 2, 2 } };
- jointExam.papers.Add(paper);
- //時間
- jointExam.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- jointExam.startTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- jointExam.endTime = DateTimeOffset.UtcNow.AddDays(2).ToUnixTimeMilliseconds();
- jointExam.progress = "going";
- await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync<JointExam>(jointExam, new PartitionKey("JointExam"));
- return Ok();
- }
- */
- //評量統一生成測試
- /*
- [HttpPost("add-exam-byJoint")]
- public async Task<IActionResult> AddExamByJointExam(JsonElement json)
- {
- if (!json.TryGetProperty("jointExamId", out JsonElement _jointExamId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- string tmid = "1595321354";
- JointExam jointExam = new JointExam();
- await foreach (JointExam item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<JointExam>(
- queryText: $"select * from c where c.id = '{_jointExamId}' and c.creatorId = '{tmid}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"JointExam") }))
- {
- jointExam = item;
- }
- if(string.IsNullOrWhiteSpace(jointExam.id))
- {
- return BadRequest();
- }
- //評量資料生成 ExamInfo actExamInfo
- List<ExamInfo> examList = new List<ExamInfo>();
- if(jointExam.groupLists.Count > 0)
- {
- foreach (JointExam.JointExamGroup jointExamGroup in jointExam.groupLists)
- {
- string actExamCreatorId = jointExamGroup.creatorId;
- foreach(JointExam.JointExamGroup.JointExamGroupCourse jointExamGroupCourse in jointExamGroup.courseLists)
- {
- string actExamCourseId = jointExamGroupCourse.courseId;
- string actExamCourseName = jointExamGroupCourse.courseName;
- //評量資料生成
- ExamInfo actExamInfo = new ExamInfo();
- actExamInfo.code = $"Exam-{jointExamGroup.creatorId}";
- actExamInfo.owner = "teacher";
- actExamInfo.scope = jointExam.scope;
- actExamInfo.creatorId = actExamCreatorId;
- actExamInfo.id = Guid.NewGuid().ToString();
- actExamInfo.source = "1"; //目前先設定為"智慧教室評量",實際上應讓老師選擇
- actExamInfo.name = jointExam.name;
- actExamInfo.jointExamId = jointExam.id;
- ///評量stuLists
- foreach (string actGroupId in jointExamGroupCourse.groupListIds)
- {
- actExamInfo.stuLists.Add(actGroupId);
- List<string> targetRow = new List<string>() { actExamCourseId, actGroupId };
- actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
- actExamInfo.subjects.Add(new ExamSubject() { id = actExamCourseId, name = actExamCourseName });
- }
- ///試卷 ※先用統購的試卷記入,生成評量(generateExam)時會做blob的路徑修正
- actExamInfo.papers = JsonConvert.DeserializeObject<List<PaperSimple>>(JsonConvert.SerializeObject(jointExam.papers));
- ///時間
- actExamInfo.year = DateTimeOffset.UtcNow.Year;
- actExamInfo.startTime = jointExam.startTime;
- actExamInfo.endTime = jointExam.endTime;
- examList.Add(actExamInfo);
- }
- }
- }
- //生成評量
- if(examList.Count > 0)
- {
- foreach(ExamInfo exam in examList)
- {
- await generateExam(jointExam, exam);
- }
- }
- return Ok();
- }
- */
- //生成評量(單)
- /*
- private async Task<string> generateExam(JointExam jointExam, ExamInfo exam)
- {
- var client = _azureCosmos.GetCosmosClient();
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- string Result = string.Empty;
- exam.createTime = now;
- if (exam.startTime <= 0) exam.startTime = now;
- List<(string pId, List<string> gid)> ps = new();
- var group = exam.groupLists;
- if (group.Count > 0)
- {
- foreach (var keys in group)
- {
- foreach (KeyValuePair<string, List<string>> pp in keys)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- List<string> classes = ExamService.getClasses(exam.classes, exam.stuLists);
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, exam.school, ps);
- exam.stuCount = tchList.Count;
- string mode = string.Empty;
- Response response = null;
- if (string.IsNullOrEmpty(exam.id))
- {
- mode = "add";
- }
- else
- {
- response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(exam.id, new PartitionKey($"{exam.code}"));
- if (response.Status == 200) mode = "upd";
- else mode = "add";
- }
- //DB操作
- if (mode.Equals("add")) //新建
- {
- if(string.IsNullOrWhiteSpace(exam.id)) exam.id = Guid.NewGuid().ToString();
- exam.progress = (exam.startTime > now) ? "pending" : "going";
- var messageBlob = new ServiceBusMessage();
- exam.size = await _azureStorage.GetBlobContainerClient(exam.creatorId).GetBlobsSize($"exam/{exam.id}"); //統測只允許老師個人,Blob只指向creatorId
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = exam.creatorId }, _serviceBus, _configuration, _azureRedis);
- int n = 0;
- List<string> sheetIds = new List<string>();
- foreach (PaperSimple simple in exam.papers)
- {
- simple.blob = $"/exam/{exam.id}/paper/{exam.subjects[n].id}";
- n++;
- simple.sheet = null;
- }
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(exam, new PartitionKey($"{exam.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
- }
- else if(response != null) //更新
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- ExamInfo info = json.ToObject<ExamInfo>();
- if (info.progress.Equals("going"))
- {
- Result = "活动正在进行中,无法修改";
- }
- var messageBlob = new ServiceBusMessage();
- exam.size = await _azureStorage.GetBlobContainerClient(exam.creatorId).GetBlobsSize($"exam/{exam.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"exam", name = exam.creatorId }, _serviceBus, _configuration, _azureRedis);
- exam.progress = info.progress;
- int n = 0;
- foreach (PaperSimple simple in exam.papers)
- {
- simple.blob = "/exam/" + exam.id + "/paper/" + exam.subjects[n].id;
- n++;
- }
- exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, exam.id, new PartitionKey($"{exam.code}"));
- }
- //Blob操作 ※取得試卷源(blob)、複製到評測紀錄下
- ///試卷源字典
- List<Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
- foreach (PaperSimple paperInfo in jointExam.papers)
- {
- string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
- paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
- sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blob", paperBlobPath }, { "itemcount", paperInfo.point.Count.ToString() } });
- }
- bool paperDataCopyErrFlg = false; //試卷資料拷貝錯誤Flag true:拷貝錯誤
- //Blob拷貝程序
- int paperIndex = 0;
- foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperInfo)
- {
- //拷貝源:Container => jointExam.creatorId Path:papers.blob
- //拷貝對象:Container => exam.creatorId, Path:exam/{exam.id}/paper/{exam.subjects[paperIndex].id}/
- string targetScope = exam.scope; //評測對象 school:校本班級 private:私人課程
- var sourceBlobContainer = _azureStorage.GetBlobContainerClient(jointExam.creatorId);
- var blobPrivateContainer = _azureStorage.GetBlobContainerClient(exam.creatorId);
- string sourceBlobPath = sourcePaperInfoDic["blob"];
- string subjectId = exam.subjects[paperIndex].id;
- string destBlobPath = $"exam/{exam.id}/paper/{subjectId}/"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/
- Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
- if (sourceBlobs.Count() > 0)
- {
- foreach (var blob in sourceBlobs)
- {
- var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
- if (sourceFileBlob.Exists())
- {
- var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
- string fileName = blob.Name.Replace(sourceBlobPath, "");
- string destBlobFilePath = $"{destBlobPath}{fileName}";
- await blobPrivateContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
- }
- else
- {
- paperDataCopyErrFlg = true;
- }
- }
- }
- paperIndex++;
- }
- return Result;
- }
- */
- //統測資料架構
- /*
- public class JointExam : CosmosEntity
- {
- public string creatorId { get; set; }
- public string name { get; set; }
- public List<JointExamClass> classes { get; set; } = new();
- public List<JointExamGroup> groupLists { get; set; } = new();
- public List<PaperSimple> papers { get; set; } = new();
- public string progress { get; set; }
- public long createTime { get; set; }
- public long updateTime { get; set; }
- public long startTime { get; set; }
- public long endTime { get; set; }
- public string scope { get; set; }
- public class JointExamClass
- {
- public string school { get; set; }
- public List<string> classIds { get; set; } = new();
- }
- public class JointExamGroup
- {
- public string creatorId { get; set; }
- public List<JointExamGroupCourse> courseLists { get; set; } = new();
- public class JointExamGroupCourse
- {
- public string courseId { get; set; }
- public string courseName { get; set; }
- public List<string> groupListIds { get; set; } = new();
- }
- }
- }
- */
- }
- }
|