TmdUserService.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Azure.Cosmos;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using TEAMModelOS.SDK.DI;
  7. using TEAMModelOS.SDK.Models;
  8. namespace TEAMModelOS.SDK
  9. {
  10. public class TmdUserService
  11. {
  12. public static async Task<TmdUser> JoinSchool(CosmosClient client, string tmdid,string picture,string name , string schoolId, string schoolName) {
  13. TmdUser tmdUser = null;
  14. try {
  15. tmdUser= await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(tmdid, partitionKey: new PartitionKey("Base"));
  16. tmdUser.picture = string.IsNullOrEmpty(picture) ? picture:tmdUser.picture;
  17. tmdUser.name = string.IsNullOrEmpty(name) ? name : tmdUser.name;
  18. var school= tmdUser.schools.Find(x => x.schoolId.Equals(schoolId));
  19. if (school == null)
  20. {
  21. tmdUser.schools.Add(new TmdUser.School { schoolId = schoolId, name = schoolName, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
  22. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(tmdUser, tmdid, partitionKey: new PartitionKey("Base"));
  23. }
  24. else {
  25. school.name = schoolName;
  26. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(tmdUser, tmdid, partitionKey: new PartitionKey("Base"));
  27. }
  28. } catch (CosmosException ex) {
  29. if (ex.Status == 404) {
  30. tmdUser = new TmdUser()
  31. {
  32. id = tmdid,
  33. code = "Base",
  34. schools = new List<TmdUser.School>() {
  35. new TmdUser.School {
  36. schoolId = schoolId, status = "join", name = schoolName, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  37. }
  38. },
  39. defaultSchool=schoolId,
  40. picture=picture,
  41. name=name,
  42. ttl=-1
  43. };
  44. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(tmdUser, partitionKey: new PartitionKey(tmdUser.code));
  45. }
  46. }
  47. return tmdUser;
  48. }
  49. public static async Task<TmdUser> LeaveSchool(CosmosClient client, string tmdid, string schoolId)
  50. {
  51. TmdUser tmdUser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(tmdid, partitionKey: new PartitionKey("Base"));
  52. var school = tmdUser.schools.Find(x => x.schoolId.Equals(schoolId));
  53. if (school != null)
  54. {
  55. tmdUser.schools.Remove(school);
  56. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(tmdUser, tmdid, partitionKey: new PartitionKey("Base"));
  57. }
  58. return tmdUser;
  59. }
  60. }
  61. }