Forráskód Böngészése

add short url conv

JAELYS 3 éve
szülő
commit
0c74bc0a5c

+ 1 - 1
TEAMModelOS.SDK/DI/AzureStorage/AzureStorageTableExtensions.cs

@@ -66,7 +66,7 @@ namespace TEAMModelOS.SDK.DI
             }
             else
             {
-                return default(T);
+                return default;
             }
         }
 

+ 1 - 8
TEAMModelOS.SDK/Helper/Security/Base64Crypt/Base64Crypt.cs

@@ -14,14 +14,7 @@ namespace TEAMModelOS.SDK.Helper.Security.Base64Crypt
         public static string EncodeBase64(Encoding encode, string source)
         {
             byte[] bytes = encode.GetBytes(source);
-            try
-            {
-                source = Convert.ToBase64String(bytes);
-            }
-            catch (System.Exception e)
-            {
-                String s = e.StackTrace;
-            }
+            source = Convert.ToBase64String(bytes);
             return source;
         }
 

+ 1 - 1
TEAMModelOS.SDK/Helper/Security/Md5Hash/Md5Hash.cs

@@ -75,7 +75,7 @@ namespace TEAMModelOS.SDK
                 return "";
             }
             FileStream stream = File.OpenRead(path);
-            byte[] data2 = md5.ComputeHash(stream);
+            byte[] data2 = md5.ComputeHash(stream);           
             return GetbyteToString(data2);
             //return BitConverter.ToString(data2).Replace("-", "").ToLower();
         }

+ 15 - 0
TEAMModelOS.SDK/Models/Table/ShortUrl.cs

@@ -0,0 +1,15 @@
+using Microsoft.Azure.Cosmos.Table;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using TEAMModelOS.SDK.Context.Attributes.Azure;
+using TEAMModelOS.SDK.DI;
+
+namespace TEAMModelOS.SDK.Models
+{
+    [TableName(Name = "ShortUrl")]
+    public class ShortUrl : TableEntity
+    { 
+        public string Url { get; set; }      
+    }
+}

+ 91 - 11
TEAMModelOS/Controllers/System/CoreController.cs

@@ -10,6 +10,7 @@ using System.IO;
 using System.Linq;
 using System.Net.Http;
 using System.Reflection;
+using System.Text;
 using System.Text.Json;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
@@ -18,6 +19,7 @@ using TEAMModelOS.Models.Request;
 using TEAMModelOS.SDK;
 using TEAMModelOS.SDK.DI;
 using TEAMModelOS.SDK.Extension;
+using TEAMModelOS.SDK.Models;
 using TEAMModelOS.SDK.Models.Service;
 using TEAMModelOS.SDK.PngQuant;
 
@@ -33,9 +35,9 @@ namespace TEAMModelOS.Controllers
         private readonly Option _option;
         private readonly HttpClient _httpClient;
         private readonly IPSearcher _searcher;
-        public CoreController(IPSearcher searcher,AzureRedisFactory azureRedis, AzureStorageFactory azureStorage , DingDing dingDing, IOptionsSnapshot<Option> option, HttpClient httpClient)
+        public CoreController(IPSearcher searcher, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, HttpClient httpClient)
         {
-            _searcher= searcher;
+            _searcher = searcher;
             _azureStorage = azureStorage;
             _dingDing = dingDing;
             _option = option?.Value;
@@ -44,7 +46,7 @@ namespace TEAMModelOS.Controllers
         }
 
         [HttpPost("apply-school")]
-        
+
         public async Task<IActionResult> ApplySchool(ApplySchool request)
         {
             string msg = $"有新学校申请。\n" +
@@ -65,15 +67,15 @@ namespace TEAMModelOS.Controllers
         [RequestSizeLimit(100_000_000)] //最大100m左右
         public async Task<IActionResult> RandomCode(JsonElement request)
         {
-          
+
             if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();//学校编码 或者醍摩豆id
             string _num09 = "123456789";
             string no = $"{Utils.CreatSaltString(6, _num09)}";
-            var Expire =DateTime.UtcNow.AddHours(1);
+            var Expire = DateTime.UtcNow.AddHours(1);
             string key = $"Random:Code:{no}-{code}";
-            await _azureRedis.GetRedisClient(8).StringSetAsync(key, new { code=code,no=no, Expire = Expire.Ticks }.ToJsonString());
+            await _azureRedis.GetRedisClient(8).StringSetAsync(key, new { code = code, no = no, Expire = Expire.Ticks }.ToJsonString());
             _azureRedis.GetRedisClient(8).KeyExpire(key, Expire);
-            return Ok(new { random=no });
+            return Ok(new { random = no });
         }
 
         [HttpPost("system-info")]
@@ -82,11 +84,11 @@ namespace TEAMModelOS.Controllers
         {
             Type attr = this.GetType();
             string currentDirectory = Path.GetDirectoryName(attr.Assembly.Location);
-            Assembly assembly = Assembly.LoadFrom( $"{currentDirectory}\\TEAMModelOS.dll");
-            var description= assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
+            Assembly assembly = Assembly.LoadFrom($"{currentDirectory}\\TEAMModelOS.dll");
+            var description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
             //var v1 = Assembly.GetEntryAssembly().GetName().Version;
             //var v2 = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
-           // var description = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
+            // var description = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
             var version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
             long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
             //Console.WriteLine($"Assembly.GetEntryAssembly().GetName().Version: " +
@@ -112,7 +114,7 @@ namespace TEAMModelOS.Controllers
             string ip = IpPort.Split(":")[0];
             string region = await _searcher.SearchIpAsync(ip);
 
-            return Ok(new { version, description, nowtime , region,ip });
+            return Ok(new { version, description, nowtime, region, ip });
         }
         /// <summary>
         /// 等待P1V3,啟動Dcoker,支持EMF GDI+
@@ -212,6 +214,84 @@ namespace TEAMModelOS.Controllers
             return Ok(respons);
 
         }
+
+        /// <summary>
+        /// 取得短網址
+        /// </summary>       
+        [HttpPost("get-short-url")]
+        public async Task<IActionResult> GetShortUrl(JsonElement request)
+        {
+            if (!request.TryGetProperty("url", out JsonElement url)) return BadRequest();
+            try
+            {
+                var uri = new Uri(url.GetString());
+                string md5url = Md5Hash.GetMd5String(uri.AbsolutePath);
+
+                char[] chars = new char[]
+               {
+                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
+                'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
+                'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
+                'y', 'z', '0', '1', '2', '3', '4', '5',
+                '6', '7', '8', '9', 'A', 'B', 'C', 'D',
+                'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
+                'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
+                'U', 'V', 'W', 'X', 'Y', 'Z'
+               };
+
+                //把加密字元按照8位一組16進位制與0x3FFFFFFF進行位與運算
+                int hexint = 0x3FFFFFFF & Convert.ToInt32(string.Concat("0x", md5url.AsSpan(0, 8)), 16);
+                StringBuilder outShort = new();
+                for (int j = 0; j < 6; j++)
+                {
+                    //把得到的值與0x0000003D進行位與運算,取得字元陣列chars索引
+                    int index = 0x0000003D & hexint;
+                    //把取得的字元相加
+                    outShort.Append(chars[index]);
+                    //每次迴圈按位右移5位
+                    hexint >>= 5;
+                }
+                var result = outShort.ToString();
+                var table = _azureStorage.GetCloudTableClient().GetTableReference("ShortUrl");
+                ShortUrl su = new() { PartitionKey = uri.Host, RowKey = result, Url = uri.AbsoluteUri };
+                await table.SaveOrUpdate<ShortUrl>(su);
+
+                return Ok(new { result });
+            }
+            catch
+            {
+                return BadRequest();
+            }
+        }
+
+        /// <summary>
+        /// 短網址換長網址
+        /// </summary>       
+        [HttpPost("get-long-url")]
+        public IActionResult GetLongUrl(JsonElement request)
+        {
+            if (!request.TryGetProperty("url", out JsonElement url)) return BadRequest();
+            try
+            {
+                var uri = new Uri(url.GetString());
+
+                var table = _azureStorage.GetCloudTableClient().GetTableReference("ShortUrl");
+
+                var shortUrl = table.Get<ShortUrl>(uri.Host, uri.AbsolutePath.Replace("/", string.Empty));
+                if (shortUrl is not null)
+                {                   
+                    return Ok(new { result=shortUrl.Url });
+                }
+                else
+                {
+                    return BadRequest();
+                }
+            }
+            catch
+            {
+                return BadRequest();
+            }
+        }
     }