InitController.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using Azure.Cosmos;
  2. using Azure.Storage.Blobs.Models;
  3. using Azure.Storage.Sas;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.Extensions.Options;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Dynamic;
  10. using System.IdentityModel.Tokens.Jwt;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text.Json;
  14. using System.Threading.Tasks;
  15. using TEAMModelOS.Models;
  16. using TEAMModelOS.SDK.Models;
  17. using TEAMModelOS.SDK.DI;
  18. using TEAMModelOS.SDK.Extension;
  19. namespace TEAMModelOS.Controllers
  20. {
  21. [ProducesResponseType(StatusCodes.Status200OK)]
  22. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  23. //[Authorize(Roles = "IES5")]
  24. [Route("teacher/init")]
  25. [ApiController]
  26. public class InitController : ControllerBase
  27. {
  28. private readonly AzureCosmosFactory _azureCosmos;
  29. private readonly AzureStorageFactory _azureStorage;
  30. private readonly DingDing _dingDing;
  31. private readonly Option _option;
  32. public InitController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
  33. {
  34. _azureCosmos = azureCosmos;
  35. _azureStorage = azureStorage;
  36. _dingDing = dingDing;
  37. _option = option?.Value;
  38. }
  39. //TODO 此API需處理對應前端返回的相關數據
  40. [ProducesDefaultResponseType]
  41. [HttpPost("get-teacher-info")]
  42. public async Task<IActionResult> GetTeacherInfo(JsonElement request)
  43. {
  44. //Debug
  45. //string json = System.Text.Json.JsonSerializer.Serialize(id_token);
  46. try
  47. {
  48. if (!request.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  49. var jwt = new JwtSecurityToken(id_token.GetString());
  50. //TODO 此驗證IdToken先簡單檢查,後面需向Core ID新API,驗證Token
  51. if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
  52. var id = jwt.Payload.Sub;
  53. jwt.Payload.TryGetValue("name", out object name);
  54. jwt.Payload.TryGetValue("picture", out object picture);
  55. object schools = null;
  56. string defaultschool = null;
  57. //TODO 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
  58. var client = _azureCosmos.GetCosmosClient();
  59. var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id, new PartitionKey("Base"));
  60. //老師個人資料(含初始化)
  61. if (response.Status == 200)
  62. {
  63. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  64. if (json.RootElement.TryGetProperty("schools", out JsonElement value))
  65. {
  66. schools = value.ToObject<object>();
  67. }
  68. //預設學校ID
  69. if (json.RootElement.TryGetProperty("defaultSchool", out JsonElement valueD) && !string.IsNullOrEmpty(valueD.ToString()))
  70. {
  71. defaultschool = valueD.ToString();
  72. }
  73. }
  74. else
  75. {
  76. //如果沒有,則初始化Teacher基本資料到Cosmos
  77. using var stream = new MemoryStream();
  78. using var writer = new Utf8JsonWriter(stream); //new JsonWriterOptions() { Indented = true }
  79. writer.WriteStartObject();
  80. writer.WriteString("pk", "Base");
  81. writer.WriteString("code", "Base");
  82. writer.WriteString("id", id);
  83. writer.WriteString("name", name?.ToString());
  84. writer.WriteString("picture", picture?.ToString());
  85. writer.WriteNumber("size", 1);
  86. writer.WriteNull("defaultSchool");
  87. writer.WriteStartArray("schools");
  88. writer.WriteEndArray();
  89. writer.WriteEndObject();
  90. writer.Flush();
  91. //Debug
  92. //string teacher = Encoding.UTF8.GetString(stream.ToArray());
  93. response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemStreamAsync(stream, new PartitionKey("Base"));
  94. }
  95. //私人課程
  96. List<object> courses = new List<object>();
  97. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id, c.name, c.classes, c.notice ,c.scope from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
  98. {
  99. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  100. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  101. {
  102. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  103. {
  104. courses.Add(obj.ToObject<object>());
  105. }
  106. }
  107. }
  108. //老師個人課綱
  109. List<SyllabusRole> syllabus = new List<SyllabusRole>();
  110. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"SELECT c.id, c.name, c.scope, c.resourceCount, c.itemCount, c.children from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{id}") }))
  111. {
  112. var jsons = await JsonDocument.ParseAsync(item.ContentStream);
  113. if (jsons.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  114. {
  115. foreach (var obj in jsons.RootElement.GetProperty("Documents").EnumerateArray())
  116. {
  117. SyllabusRole syllabusRole = new SyllabusRole();
  118. syllabusRole.id = obj.GetProperty("id").ToString();
  119. syllabusRole.name = obj.GetProperty("name").ToString();
  120. syllabusRole.resourceCount = obj.GetProperty("resourceCount").GetUInt16();
  121. syllabusRole.itemCount = obj.GetProperty("itemCount").GetUInt16();
  122. List<Syllabus> syllabusList = obj.GetProperty("children").ToObject<List<Syllabus>>();
  123. syllabusList.Insert(0, new Syllabus { id = syllabusRole.id, name = syllabusRole.name, pid = "", order = 0 });
  124. syllabusList = syllabusList.OrderBy(x => x.order).ToList();
  125. syllabusRole.structure = CreateSyllabusTree(syllabusList);
  126. syllabus.Add(syllabusRole);
  127. }
  128. //[DEBUG] string jsonString = System.Text.Json.JsonSerializer.Serialize(syllabusRoles);
  129. }
  130. }
  131. //換取AuthToken,提供給前端
  132. var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "teacher", "student" });
  133. //取得Teacher Blob 容器位置及SAS
  134. var container = _azureStorage.GetBlobContainerClient(id);
  135. await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
  136. var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  137. return Ok(new { auth_token, blob_uri, blob_sas, schools, defaultschool, courses });
  138. }
  139. catch (Exception ex)
  140. {
  141. await _dingDing.SendBotMsg($"IES5,{_option.Location},Teacher/GetTeacherInfo()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  142. return BadRequest();
  143. }
  144. }
  145. //TODO 此API需處理對應前端返回的相關數據
  146. [ProducesDefaultResponseType]
  147. [HttpPost("get-school-info")]
  148. public async Task<IActionResult> GetSchoolInfo(JsonElement requert)
  149. {
  150. if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  151. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  152. var jwt = new JwtSecurityToken(id_token.GetString());
  153. if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
  154. var id = jwt.Payload.Sub;
  155. var client = _azureCosmos.GetCosmosClient();
  156. //權限token
  157. jwt.Payload.TryGetValue("name", out object name);
  158. jwt.Payload.TryGetValue("picture", out object picture);
  159. List<string> roles = new List<string>();
  160. List<string> permissions = new List<string>();
  161. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id, new PartitionKey($"Teacher-{school_code}"));
  162. if (response.Status == 200)
  163. {
  164. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  165. if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
  166. {
  167. foreach (var obj in _roles.EnumerateArray())
  168. {
  169. roles.Add(obj.GetString());
  170. }
  171. }
  172. if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
  173. {
  174. foreach (var obj in _permissions.EnumerateArray())
  175. {
  176. permissions.Add(obj.GetString());
  177. }
  178. }
  179. }
  180. else //無此學校資料
  181. {
  182. return BadRequest();
  183. }
  184. if (roles.Count == 0)
  185. {
  186. roles.Add("teacher");
  187. roles.Add("student");
  188. }
  189. //TODO JJ,更新Token时,在取得学校资讯时,没有传入schoolId
  190. var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, schoolID: school_code.ToString(), roles: roles.ToArray(), permissions: permissions.ToArray());
  191. //TODO JJ,调整为取得学校基础设置数据,取代下方學校學制、年級
  192. object school_base = null;
  193. response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
  194. if (response.Status == 200)
  195. {
  196. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  197. school_base = json.RootElement.ToObject<object>();
  198. }
  199. //取得教室
  200. List<object> school_classes = new List<object>();
  201. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT c.id,c.x,c.y,c.name,c.teacher,c.periodId,c.gradeId,c.sn,c.no,c.style,c.status,c.openType,c.scope, ARRAY_LENGTH(c.students) AS studCount FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
  202. {
  203. var jsonc = await JsonDocument.ParseAsync(item.ContentStream);
  204. foreach (var classeinfo in jsonc.RootElement.GetProperty("Documents").EnumerateArray())
  205. {
  206. school_classes.Add(classeinfo.ToObject<object>());
  207. }
  208. }
  209. //List<object> periods = new List<object>();
  210. //List<object> grades = new List<object>();
  211. //var responsesch = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey($"Base"));
  212. //if (responsesch.Status == 200)
  213. //{
  214. // var jsons = await JsonDocument.ParseAsync(responsesch.ContentStream);
  215. // if (jsons.RootElement.TryGetProperty("period", out JsonElement periodJobj))
  216. // {
  217. // foreach (var periodinfo in periodJobj.EnumerateArray())
  218. // {
  219. // dynamic periodExtobj = new ExpandoObject();
  220. // periodExtobj.id = periodinfo.GetProperty("id");
  221. // periodExtobj.name = periodinfo.GetProperty("name");
  222. // periods.Add(periodExtobj);
  223. // if (periodinfo.TryGetProperty("grades", out JsonElement gradesJobj))
  224. // {
  225. // foreach (var gradeinfo in gradesJobj.EnumerateArray())
  226. // {
  227. // dynamic gradeExtobj = new ExpandoObject();
  228. // gradeExtobj.id = gradeinfo.GetProperty("id");
  229. // gradeExtobj.name = gradeinfo.GetProperty("name");
  230. // gradeExtobj.periodId = periodinfo.GetProperty("id");
  231. // grades.Add(gradeExtobj);
  232. // }
  233. // }
  234. // }
  235. // }
  236. //}
  237. //該老師排定的學校課程
  238. List<object> school_courses = new List<object>();
  239. var query = $"SELECT c.id, c.name, c.teacher, cc.course, c.scope FROM c JOIN cc IN c.courses JOIN cct IN cc.teachers WHERE cct.id = '{id}'";
  240. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{school_code}") }))
  241. {
  242. var jsoncm = await JsonDocument.ParseAsync(item.ContentStream);
  243. if (jsoncm.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  244. {
  245. foreach (var obj in jsoncm.RootElement.GetProperty("Documents").EnumerateArray())
  246. {
  247. //班級
  248. string classIdNow = obj.GetProperty("id").ToString();
  249. dynamic classExtobj = new ExpandoObject();
  250. classExtobj.code = $"Class-{school_code}";
  251. classExtobj.id = classIdNow;
  252. classExtobj.name = obj.GetProperty("name").ToString();
  253. classExtobj.teacher = obj.GetProperty("teacher").ToObject<object>();
  254. classExtobj.scope = obj.GetProperty("scope").ToString();
  255. //課程
  256. obj.TryGetProperty("course", out JsonElement courseNow);
  257. string courseIdNow = courseNow.GetProperty("id").ToString();
  258. var courseExist = school_courses.Where((dynamic x) => x.id == courseIdNow).FirstOrDefault();
  259. if (courseExist == null)
  260. {
  261. dynamic courseExtobj = new ExpandoObject();
  262. courseExtobj.id = courseIdNow;
  263. courseExtobj.name = courseNow.GetProperty("name").ToString();
  264. courseExtobj.scope = courseNow.GetProperty("scope").ToString();
  265. courseExtobj.classes = new List<object>();
  266. courseExtobj.classes.Add(classExtobj);
  267. school_courses.Add(courseExtobj);
  268. }
  269. else
  270. {
  271. courseExist.classes.Add(classExtobj);
  272. }
  273. }
  274. }
  275. }
  276. //校本課綱 [式樣未定 先不取]
  277. List<SyllabusRole> school_syllabus = new List<SyllabusRole>();
  278. //await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT c.id, c.name, c.period, c.grade, c.semester, c.subject, c.scope, c.resourceCount, c.itemCount, c.children from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{school_code}") }))
  279. //{
  280. // var jsons = await JsonDocument.ParseAsync(item.ContentStream);
  281. // if (jsons.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  282. // {
  283. // foreach (var obj in jsons.RootElement.GetProperty("Documents").EnumerateArray())
  284. // {
  285. // SyllabusRole syllabusRole = new SyllabusRole();
  286. // syllabusRole.id = obj.GetProperty("id").ToString();
  287. // syllabusRole.name = obj.GetProperty("name").ToString();
  288. // syllabusRole.period = obj.GetProperty("period");
  289. // syllabusRole.grade = obj.GetProperty("grade");
  290. // syllabusRole.semester = obj.GetProperty("semester");
  291. // syllabusRole.subject = obj.GetProperty("subject");
  292. // syllabusRole.resourceCount = obj.GetProperty("resourceCount").GetUInt16();
  293. // syllabusRole.itemCount = obj.GetProperty("itemCount").GetUInt16();
  294. // List<Syllabus> syllabusList = obj.GetProperty("children").ToObject<List<Syllabus>>();
  295. // syllabusList.Insert(0, new Syllabus { id = syllabusRole.id, name = syllabusRole.name, pid = "", order = 0 });
  296. // syllabusList = syllabusList.OrderBy(x => x.order).ToList();
  297. // syllabusRole.structure = CreateSyllabusTree(syllabusList);
  298. // syllabus.Add(syllabusRole);
  299. // }
  300. // //[DEBUG] string jsonString = System.Text.Json.JsonSerializer.Serialize(syllabusRoles);
  301. // }
  302. //}
  303. //取得School Blob 容器位置及SAS
  304. string school_code_blob = school_code.GetString().ToLower();
  305. var container = _azureStorage.GetBlobContainerClient(school_code_blob);
  306. await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建School容器,如存在則不做任何事,保障容器一定存在
  307. var (blob_uri, blob_sas) = (roles.Contains("admin")) ? _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List) : _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
  308. return Ok(new { auth_token, blob_uri, blob_sas, school_base, school_courses, school_syllabus, school_classes });
  309. }
  310. [ProducesDefaultResponseType]
  311. //[AuthToken(Roles = "teacher")]
  312. [HttpPost("get-school-list")]
  313. public async Task<IActionResult> GetSchoolList()
  314. {
  315. var client = _azureCosmos.GetCosmosClient();
  316. List<object> schools = new List<object>();
  317. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select c.id, c.name,c.region,c.province,c.city from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  318. {
  319. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  320. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  321. {
  322. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  323. {
  324. schools.Add(obj.ToObject<object>());
  325. }
  326. }
  327. }
  328. return Ok(new { schools });
  329. }
  330. /// <summary>
  331. /// 申請或同意邀請加入學校
  332. /// </summary>
  333. ///
  334. /// <param name="requert"></param>
  335. /// <returns></returns>
  336. [ProducesDefaultResponseType]
  337. //[AuthToken(Roles = "teacher")]
  338. [HttpPost("join-school")]
  339. public async Task<IActionResult> JoinSchool(JsonElement requert)
  340. {
  341. try
  342. {
  343. if (!requert.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest(); //"invite":學校邀請 "request":老師申請 "join":"成為學校老師"
  344. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  345. if (!requert.TryGetProperty("school_name", out JsonElement school_name)) return BadRequest();
  346. string authtoken = HttpContext.GetXAuth("AuthToken");
  347. if (string.IsNullOrEmpty(authtoken)) return BadRequest();
  348. var jwt = new JwtSecurityToken(authtoken);
  349. var id = jwt.Payload.Sub;
  350. var schoolcode = jwt.Payload.Azp;
  351. var Claims = jwt.Payload.Claims;
  352. jwt.Payload.TryGetValue("name", out object name);
  353. jwt.Payload.TryGetValue("picture", out object picture);
  354. var client = _azureCosmos.GetCosmosClient();
  355. //在老師表找出老師,處理該學校狀態 (老師基本資料應該要存在)
  356. Teacher teacher = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  357. if (teacher.schools == null)
  358. teacher.schools = new List<Teacher.School>();
  359. var school = teacher.schools?.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
  360. if (school != null)
  361. school.status = grant_type.GetString();
  362. else
  363. teacher.schools.Add(new Teacher.School() { schoolId = school_code.GetString(), name = school_name.GetString(), status = grant_type.GetString() });
  364. await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, id, new PartitionKey("Base"));
  365. //在學校表處理該學校教師帳號的狀態
  366. var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id, new PartitionKey($"Teacher-{school_code}"));
  367. if (sresponse.Status == 200)
  368. {
  369. using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
  370. SchoolTeacher steacher = json.ToObject<SchoolTeacher>();
  371. steacher.status = grant_type.GetString();
  372. var response = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(steacher, id, new PartitionKey($"Teacher-{school_code}"));
  373. }
  374. else
  375. {
  376. SchoolTeacher st = new SchoolTeacher()
  377. {
  378. pk = "Teacher",
  379. code = $"Teacher-{school_code}",
  380. createTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
  381. id = id,
  382. name = name.ToString(),
  383. picture = picture?.ToString(), //TODO JJ,原本的判断会出现报错,没检查null却又去ToString
  384. permissions = new List<string>(),
  385. roles = new List<string>(){ "teacher" },
  386. status = grant_type.GetString()
  387. };
  388. var response = await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(st, new PartitionKey($"Teacher-{school_code}"));
  389. }
  390. return Ok();
  391. }
  392. catch (Exception ex)
  393. {
  394. await _dingDing.SendBotMsg($"TEAMModel,{_option.Location},Init/JoinSchool()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  395. return BadRequest();
  396. }
  397. }
  398. //課綱的model先記在下面,待式樣確定後再轉換
  399. private List<SyllabusNode> CreateSyllabusTree(List<Syllabus> syllabuses)
  400. {
  401. List<SyllabusNode> nodes = new List<SyllabusNode>();
  402. foreach (var syllabus in syllabuses)
  403. {
  404. if (syllabus.pid == "")
  405. nodes.Add(new SyllabusNode { id = syllabus.id, name = syllabus.name });
  406. else
  407. {
  408. CreateNode(nodes, syllabus);
  409. }
  410. }
  411. return nodes;
  412. }
  413. private void CreateNode(List<SyllabusNode> nodes, Syllabus parent)
  414. {
  415. foreach (var node in nodes)
  416. {
  417. if (node.id == parent.pid)
  418. {
  419. node.children.Add(new SyllabusNode { id = parent.id, name = parent.name });
  420. }
  421. else
  422. {
  423. CreateNode(node.children, parent);
  424. }
  425. }
  426. }
  427. public class SyllabusRole
  428. {
  429. public string id { get; set; }
  430. public string name { get; set; }
  431. public object period { get; set; }
  432. public object semester { get; set; }
  433. public object grade { get; set; }
  434. public object subject { get; set; }
  435. public int resourceCount { get; set; }
  436. public int itemCount { get; set; }
  437. public object structure { get; set; }
  438. }
  439. public class Syllabus
  440. {
  441. public string id { get; set; }
  442. public string name { get; set; }
  443. public string pid { get; set; }
  444. public int order { get; set; }
  445. }
  446. public class SyllabusNode
  447. {
  448. public string id { get; set; }
  449. public string name { get; set; }
  450. public List<SyllabusNode> children { get; set; }
  451. public SyllabusNode()
  452. {
  453. children = new List<SyllabusNode>();
  454. }
  455. }
  456. }
  457. }