Browse Source

Add client HiTeach Init ing,部分更新

JAELYS 4 years ago
parent
commit
5f2c73cf7c

+ 13 - 13
TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosExtensions.cs

@@ -26,19 +26,19 @@ namespace TEAMModelOS.SDK.DI
     public static class AzureCosmosExtensions
     {
         /// <summary>
-        /// 缓存前缀
+        /// 閬f箶餄濊�
         /// </summary>
         private const string CacheCosmosPrefix = "cosmos:";
         /// <summary>
-        /// ttl时长 1秒
+        /// ttl奀酗 1鏃
         /// </summary>
         private const int ttl = 1;
         /// <summary>
-        /// 分页大小
+        /// 鐓︾彍婀�嫟
         /// </summary>
         private const int pageSize = 200;
         /// <summary>
-        /// 超时时间
+        /// 閉奀奀潔
         /// </summary>
         private const int timeoutSeconds = 86400;
         public static int RU(this Response response)
@@ -515,7 +515,7 @@ namespace TEAMModelOS.SDK.DI
             }
             else
             {
-                throw new BizException("参数为空", 500);
+                throw new BizException("绲辨潊宄堣�", 500);
             }
 
         }
@@ -525,15 +525,15 @@ namespace TEAMModelOS.SDK.DI
             string pk =AzureCosmosUtil. GetPartitionKey<T>();
             AzureCosmosModel container = await azureCosmosFactory.InitializeCollection<T>();
             List<IdPk> idPks = new List<IdPk>();
-            //log4net 日志記錄
+            //log4net 餇熺ォ??
             string uuidKey = Guid.NewGuid().ToString();
-            string logkey = "\r\n【" + uuidKey + "】\r\n";
+            string logkey = "\r\n▽" + uuidKey + "▼\r\n";
             LogHelper.Info(default(object),
                            logkey
-                           + "删除------->>\r\n"
-                           + "表:"
+                           + "鍒夊:------->>\r\n"
+                           + "妗躲劑"
                            + type.Name + "\r\n"
-                           + "数据:"
+                           + "杅擂ㄩ"
                            + enyites.ToApiJson()
                            + "\r\n" + logkey);
             if (container.monitor)
@@ -606,7 +606,7 @@ namespace TEAMModelOS.SDK.DI
                 }
                 else
                 {
-                    throw new BizException("未找到ID匹配的数据,删除失败");
+                    throw new BizException("甯ゆ�鍠処D餁甸�鑵旀潊鎿傘剾鍒夊:鍥�晼");
                 }
             }
             else
@@ -666,11 +666,11 @@ namespace TEAMModelOS.SDK.DI
             }
             else
             {
-                throw new BizException("查询参数必须设置 .pk ", ResponseCode.PARAMS_ERROR);
+                throw new BizException("鑴ゆ垯绲辨潊鏂涘墪鎵㈢� .pk ", ResponseCode.PARAMS_ERROR);
             }
         }
         /// <summary>
-        /// 按TTL删除
+        /// 鍋孴TL鍒夊:
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <param name="list"></param>

+ 3 - 4
TEAMModelOS.SDK/DI/AzureStorage/AzureStorageFactory.cs

@@ -80,9 +80,8 @@ namespace TEAMModelOS.SDK.DI
         /// <summary>
         /// 取得Blob Container SAS (有效期預設一天)
         /// </summary>
-        /// <param name="containerName">容器名稱</param>
-        /// <param name="blobName"></param>
-        /// <param name="blobContainerSasPermissions"></param>
+        /// <param name="containerName">容器名稱</param>        
+        /// <param name="blobContainerSasPermissions">權限(可多選)Flags</param>
         /// <param name="name"></param>
         /// <returns></returns>
         public (string uri ,string sas) GetBlobContainerSAS(string containerName, BlobContainerSasPermissions blobContainerSasPermissions, string name = "Default")
@@ -125,7 +124,7 @@ namespace TEAMModelOS.SDK.DI
         /// </summary>
         /// <param name="containerName">容器名稱</param>
         /// <param name="blobName"></param>
-        /// <param name="blobSasPermissions"></param>
+        /// <param name="blobSasPermissions">權限(可多選)Flags</param>
         /// <param name="name"></param>
         /// <returns></returns>
         public string GetBlobSAS(string containerName, string blobName, BlobSasPermissions blobSasPermissions, string name = "Default")

+ 1 - 1
TEAMModelOS.SDK/TEAMModelOS.SDK.csproj

@@ -29,7 +29,7 @@
     <PackageReference Include="Grpc.Core" Version="2.27.0" />
     <PackageReference Include="HtmlAgilityPack" Version="1.11.23" />
     <PackageReference Include="IdentityModel" Version="4.2.0" />
-    <PackageReference Include="Jaeger" Version="0.3.7" />
+    <PackageReference Include="Jaeger" Version="[0.3.7]" />
     <PackageReference Include="LiteDB" Version="5.0.5" />
     <PackageReference Include="log4net" Version="2.0.8" />
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.6" />

+ 70 - 15
TEAMModelOS/Controllers/Client/HiTeachController.cs

@@ -1,54 +1,109 @@
+using Azure.Cosmos;
+using Azure.Storage.Blobs.Models;
+using Azure.Storage.Sas;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.Extensions.Options;
 using System;
 using System.Collections.Generic;
+using System.IdentityModel.Tokens.Jwt;
+using System.IO;
 using System.Linq;
+using System.Text;
+using System.Text.Json;
 using System.Threading.Tasks;
 using TEAMModelOS.Models;
 using TEAMModelOS.SDK.DI;
-//using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
-//using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
-using TEAMModelOS.SDK.Helper.Common.JsonHelper;
-using TEAMModelOS.SDK.Helper.Common.LogHelper;
-using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
-using TEAMModelOS.SDK.Module.AzureBlob.Interfaces;
+using TEAMModelOS.SDK.Extension;
 
 namespace TEAMModelOS.Controllers.Client
 {
-   
+    //[Authorize(Roles = "HiTeach")]
     [Route("hiteach")]
     [ApiController]
     public class HiTeachController : ControllerBase
     {
-
+        private readonly AzureStorageFactory _azureStorage;
+        private readonly AzureRedisFactory _azureRedis;
+        private readonly AzureCosmosFactory _azureCosmos;
         private readonly DingDing _dingDing;
         private readonly Option _option;
 
-        public HiTeachController(DingDing dingDing, IOptionsSnapshot<Option> option)
+        public HiTeachController(
+            AzureStorageFactory azureStorage,
+            AzureRedisFactory azureRedis,
+            AzureCosmosFactory azureCosmos,
+            DingDing dingDing,
+            IOptionsSnapshot<Option> option)
         {
+            _azureStorage = azureStorage;
+            _azureRedis = azureRedis;
+            _azureCosmos = azureCosmos;
             _dingDing = dingDing;
             _option = option?.Value;
         }
-       
-        [Authorize(Roles = "HiTeach")]
+
         [ProducesResponseType(StatusCodes.Status200OK)]
         [ProducesResponseType(StatusCodes.Status400BadRequest)]
         [ProducesDefaultResponseType]
         [HttpPost("init")]
-        public async Task<IActionResult> Init()
+        public async Task<IActionResult> Init(JsonElement init)
         {
+            //Debug
+            //string json = System.Text.Json.JsonSerializer.Serialize(id_token);
             try
             {
+                if (!init.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
+                var jwt = new JwtSecurityToken(id_token.GetString());
+                if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
+                var id = jwt.Payload.Sub;
+                jwt.Payload.TryGetValue("name", out object name);
+                jwt.Payload.TryGetValue("picture", out object picture);
+                object school = null;
+                //查找Teacher數據
+                var response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOSTemp", "Teacher").ReadItemStreamAsync(id, new PartitionKey("Base"));
+                if (response.Status == 200)
+                {
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    if (json.RootElement.TryGetProperty("schools", out JsonElement schools))
+                    {
+                        school = schools.ToObject<object>();                        
+                    }
+                }
+                else
+                {
+                    //如果沒有,則初始化Teacher基本資料到Cosmos
+                    using var stream = new MemoryStream();
+                    using var writer = new Utf8JsonWriter(stream); //new JsonWriterOptions() { Indented = true }
+                    writer.WriteStartObject();
+                    writer.WriteString("code", "Base");
+                    writer.WriteString("id", id);
+                    writer.WriteString("name", name?.ToString());
+                    writer.WriteString("picture", picture?.ToString());
+                    writer.WriteStartArray("schools");
+                    writer.WriteEndArray();
+                    writer.WriteEndObject();
+                    writer.Flush();
+                    //Debug
+                    //string teacher = Encoding.UTF8.GetString(stream.ToArray());
+                    response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOSTemp", "Teacher").CreateItemStreamAsync(stream, new PartitionKey("Base"));
+                }
+                //TODK 取得Teacher 個人相關數據(課程清單、虛擬教室名單等),學校數據另外API處理,多校切換時不同
+                //待實作
+
+                //取得Teacher Blob 容器位置及SAS 
+                var container = _azureStorage.GetBlobContainerClient(id);
+                await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
+                var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read);
+                return Ok(new { blob_uri, blob_sas, school });
 
             }
             catch (Exception ex)
             {
-                await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},Channel/Create()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
+                //await _dingDing.SendBotMsg($"CoreAPI2,{_option.Location},hiteach/init()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
-            }
-            return Ok();
+            }            
         }
     }
 }

+ 41 - 0
TEAMModelOS/Controllers/Client/Models/Class.cs

@@ -0,0 +1,41 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace TEAMModelOS.Controllers.Client.Models
+{
+    public class ChannelRequest
+    {  
+        /// <summary>
+        /// 請填Client Name (HiTeach、HiTeachCC)
+        /// </summary>
+        [Required]
+        public string id_token { get; set; }
+
+       
+        
+
+        /// <summary>
+        /// 教室PIN碼
+        /// </summary>
+        [Required]
+        public string pin { get; set; }
+
+        /// <summary>
+        /// 區網IP,動態申請可不填
+        /// </summary>
+        public string local_ip { get; set; }
+
+        /// <summary>
+        /// 教室評道號碼,如無傳入為動態頻道號碼,一天過期
+        /// </summary>
+        public string channel { get; set; }
+
+        /// <summary>
+        /// 如有學校簡碼請輸入
+        /// </summary>
+        public string school_code { get; set; }
+    }
+}

+ 1 - 1
TEAMModelOS/Startup.cs

@@ -80,7 +80,7 @@ namespace TEAMModelOS
                     };
                 });
             
-            services.AddAzureStorage(Configuration.GetValue<string>("Azure:Starage:ConnectionString"));
+            services.AddAzureStorage(Configuration.GetValue<string>("Azure:Starage:ConnectionString"));            
             services.AddAzureRedis( Configuration.GetValue<string>("Azure:Redis:ConnectionString"));            
             services.AddAzureCosmos(Configuration.GetValue<string>("Azure:Cosmos:ConnectionString"));
             services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);