TmdUserService.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. {
  14. TmdUser tmdUser = null;
  15. try
  16. {
  17. tmdUser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(tmdid, partitionKey: new PartitionKey("Base"));
  18. tmdUser.picture = string.IsNullOrEmpty(picture) ? picture : tmdUser.picture;
  19. tmdUser.name = string.IsNullOrEmpty(name) ? name : tmdUser.name;
  20. var school = tmdUser.schools.Find(x => x.schoolId.Equals(schoolId));
  21. if (school == null)
  22. {
  23. tmdUser.schools.Add(new TmdUser.School { schoolId = schoolId, name = schoolName, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
  24. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(tmdUser, tmdid, partitionKey: new PartitionKey("Base"));
  25. }
  26. else
  27. {
  28. school.name = schoolName;
  29. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(tmdUser, tmdid, partitionKey: new PartitionKey("Base"));
  30. }
  31. }
  32. catch (CosmosException ex)
  33. {
  34. if (ex.Status == 404)
  35. {
  36. tmdUser = new TmdUser()
  37. {
  38. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  39. id = tmdid,
  40. code = "Base",
  41. schools = new List<TmdUser.School>() {
  42. new TmdUser.School {
  43. schoolId = schoolId, status = "join", name = schoolName, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  44. }
  45. },
  46. defaultSchool = schoolId,
  47. picture = picture,
  48. name = name,
  49. ttl = -1
  50. };
  51. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(tmdUser, partitionKey: new PartitionKey(tmdUser.code));
  52. }
  53. }
  54. return tmdUser;
  55. }
  56. public static async Task<TmdUser> LeaveSchool(CosmosClient client, string tmdid, string schoolId)
  57. {
  58. TmdUser tmdUser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(tmdid, partitionKey: new PartitionKey("Base"));
  59. var school = tmdUser.schools.Find(x => x.schoolId.Equals(schoolId));
  60. if (school != null)
  61. {
  62. tmdUser.schools.Remove(school);
  63. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(tmdUser, tmdid, partitionKey: new PartitionKey("Base"));
  64. }
  65. return tmdUser;
  66. }
  67. }
  68. }