diff --git a/Inotify/Common/Extensions.cs b/Inotify/Common/Extensions.cs index 5c9d4d4..445a413 100644 --- a/Inotify/Common/Extensions.cs +++ b/Inotify/Common/Extensions.cs @@ -1,21 +1,13 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; namespace Inotify.Common { public static class Extensions { - static int rep = 0; + private static int rep = 0; - /// - /// MD5加密字符串(32位大写) - /// - /// 源字符串 - /// 加密后的字符串 public static string ToMd5(this string source) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); @@ -32,7 +24,11 @@ namespace Inotify.Common public static string Base64Encode(this string source) { - if (string.IsNullOrEmpty(source)) return ""; + if (string.IsNullOrEmpty(source)) + { + return ""; + } + byte[] bytes = (Encoding.UTF8.GetBytes(source)); return Convert.ToBase64String(bytes); @@ -40,7 +36,11 @@ namespace Inotify.Common public static string Base64Decode(this string source) { - if (string.IsNullOrEmpty(source)) return ""; + if (string.IsNullOrEmpty(source)) + { + return ""; + } + var bytes = Convert.FromBase64String(source); return System.Text.Encoding.Default.GetString(bytes); } @@ -67,5 +67,17 @@ namespace Inotify.Common } return str; } + + public static long ToUTC(this DateTime time) + { + TimeSpan ts = time - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + return Convert.ToInt64(ts.TotalMilliseconds); + } + + public static long ToUnix(this DateTime time) + { + var expiration = time.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + return (long)expiration.TotalSeconds; + } } } diff --git a/Inotify/Controllers/BarkControlor.cs b/Inotify/Controllers/BarkControlor.cs index b9df48b..f3fc0ec 100644 --- a/Inotify/Controllers/BarkControlor.cs +++ b/Inotify/Controllers/BarkControlor.cs @@ -6,123 +6,128 @@ using Inotify.Sends.Products; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; -using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; -using System.Threading.Tasks; namespace Inotify.Controllers { - [ApiController] - [Route("/")] - public class BarkControlor : BaseControlor - { - [HttpGet, Route("Ping")] - public JsonResult Ping() - { - return Me("pong"); - } + [ApiController] + [Route("/")] + public class BarkControlor : BaseControlor + { + [HttpGet, Route("Ping")] + public JsonResult Ping() + { + return Me("pong"); + } - [HttpGet, Route("Info")] - public JsonResult Info() - { - var dateTime = System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location); - var devices = DBManager.Instance.DBase.Query().Count(); - return Json(new - { - version = "v2.0.1", - build = dateTime.ToString("yyyy-MM-dd HH:mm:ss"), - arch = RuntimeInformation.OSDescription, - commit = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), - devices - }); - } + [HttpGet, Route("Info")] + public JsonResult Info() + { + var dateTime = System.IO.File.GetLastWriteTime(GetType().Assembly.Location); + var devices = DBManager.Instance.DBase.Query().Count(); + return Json(new + { + version = "v2.0.1", + build = dateTime.ToString("yyyy-MM-dd HH:mm:ss"), + arch = RuntimeInformation.OSDescription, + commit = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), + devices + }); + } - [HttpGet, Route("Healthz")] + [HttpGet, Route("Healthz")] - public string Healthz() - { - return "ok"; - } + public string Healthz() + { + return "ok"; + } - [HttpGet, Route("Register")] - public JsonResult Register(string? act, string? key, string? devicetoken, string? device_key) => !string.IsNullOrEmpty(device_key) ? - Register(device_key) : Register(act, key, devicetoken); + [HttpGet, Route("Register")] + public JsonResult Register(string? act, string? key, string? devicetoken, string? device_key) + { + return !string.IsNullOrEmpty(device_key) ? +Register(device_key) : Register(act, key, devicetoken); + } - [HttpPost, Route("Register")] - public JsonResult Register(string? act, string? device_key, string? device_token) - { - if (string.IsNullOrEmpty(act)) - return Fail(400, "request bind failed : act is empty"); + [HttpPost, Route("Register")] + public JsonResult Register(string? act, string? device_key, string? device_token) + { + if (string.IsNullOrEmpty(act)) + { + return Fail(400, "request bind failed : act is empty"); + } - if (string.IsNullOrEmpty(device_token)) - return Fail(400, "request bind failed : device_token is empty"); + if (string.IsNullOrEmpty(device_token)) + { + return Fail(400, "request bind failed : device_token is empty"); + } - var userInfo = DBManager.Instance.DBase.Query().FirstOrDefault(e => e.Token == act); - if (userInfo == null) - { - return Fail(400, "request bind failed : act is not registered"); - } - else - { - BarkAuth barkAuth = null; - SendAuthInfo barkSendAuthInfo = null; - var barkTemplateAttribute = typeof(BarkSendTemplate).GetCustomAttributes(typeof(SendMethodKeyAttribute), false).OfType().First(); + var userInfo = DBManager.Instance.DBase.Query().FirstOrDefault(e => e.Token == act); + if (userInfo == null) + { + return Fail(400, "request bind failed : act is not registered"); + } + else + { + BarkAuth barkAuth = null; + SendAuthInfo barkSendAuthInfo = null; + var barkTemplateAttribute = typeof(BarkSendTemplate).GetCustomAttributes(typeof(SendMethodKeyAttribute), false).OfType().First(); - if (!string.IsNullOrEmpty(device_key)) - { - barkSendAuthInfo = DBManager.Instance.DBase.Query().FirstOrDefault(e => e.Key == device_key); - if (barkSendAuthInfo != null) - { - barkAuth = JsonConvert.DeserializeObject(barkSendAuthInfo.AuthData); - barkAuth.DeviceToken = device_token; - barkSendAuthInfo.AuthData = JsonConvert.SerializeObject(barkAuth); - barkSendAuthInfo.ModifyTime = DateTime.Now; - DBManager.Instance.DBase.Update(barkSendAuthInfo); - } - } + if (!string.IsNullOrEmpty(device_key)) + { + barkSendAuthInfo = DBManager.Instance.DBase.Query().FirstOrDefault(e => e.Key == device_key); + if (barkSendAuthInfo != null) + { + barkAuth = JsonConvert.DeserializeObject(barkSendAuthInfo.AuthData); + barkAuth.DeviceToken = device_token; + barkSendAuthInfo.AuthData = JsonConvert.SerializeObject(barkAuth); + barkSendAuthInfo.ModifyTime = DateTime.Now; + DBManager.Instance.DBase.Update(barkSendAuthInfo); + } + } - if (barkSendAuthInfo == null) - { - device_key = 16.GenerateCheckCode(); - barkAuth = new BarkAuth() { DeviceKey = device_key, DeviceToken = device_token, IsArchive = "1", AutoMaticallyCopy = "1", Sound = "1107" }; - barkSendAuthInfo = new SendAuthInfo() - { - Name = barkTemplateAttribute.Name, - SendMethodTemplate = barkTemplateAttribute.Key, - Key = device_key, - AuthData = JsonConvert.SerializeObject(barkAuth), - UserId = userInfo.Id, - CreateTime = DateTime.Now, - ModifyTime = DateTime.Now, - Active = true, - }; - DBManager.Instance.DBase.Insert(barkSendAuthInfo); - } + if (barkSendAuthInfo == null) + { + device_key = 16.GenerateCheckCode(); + barkAuth = new BarkAuth() { DeviceKey = device_key, DeviceToken = device_token, IsArchive = "1", AutoMaticallyCopy = "1", Sound = "1107" }; + barkSendAuthInfo = new SendAuthInfo() + { + Name = barkTemplateAttribute.Name, + SendMethodTemplate = barkTemplateAttribute.Key, + Key = device_key, + AuthData = JsonConvert.SerializeObject(barkAuth), + UserId = userInfo.Id, + CreateTime = DateTime.Now, + ModifyTime = DateTime.Now, + Active = true, + }; + DBManager.Instance.DBase.Insert(barkSendAuthInfo); + } - return Json(new - { - key = device_key, - device_key = device_key, - device_token = device_token - }); - } - } + return Json(new + { + key = device_key, + device_key = device_key, + device_token = device_token + }); + } + } - [HttpGet, Route("RegisterCheck")] - public JsonResult Register(string device_key) - { - if (string.IsNullOrEmpty(device_key)) - { - return Fail(400, "device key is empty"); - } - if (!DBManager.Instance.DBase.Query().Any(e => e.Key == device_key)) - { - return Fail(400, "device not registered"); - } + [HttpGet, Route("RegisterCheck")] + public JsonResult Register(string device_key) + { + if (string.IsNullOrEmpty(device_key)) + { + return Fail(400, "device key is empty"); + } + if (!DBManager.Instance.DBase.Query().Any(e => e.Key == device_key)) + { + return Fail(400, "device not registered"); + } - return OK(); - } - } + return OK(); + } + } } diff --git a/Inotify/Controllers/BaseControlor.cs b/Inotify/Controllers/BaseControlor.cs index 7463749..6de3884 100644 --- a/Inotify/Controllers/BaseControlor.cs +++ b/Inotify/Controllers/BaseControlor.cs @@ -1,9 +1,8 @@ -using Microsoft.AspNetCore.Mvc; +using Inotify.Common; +using Microsoft.AspNetCore.Mvc; using System; -using System.Collections.Generic; using System.Linq; using System.Security.Claims; -using System.Threading.Tasks; namespace Inotify.Controllers { @@ -70,18 +69,18 @@ namespace Inotify.Controllers { code = 200, message = "sucess", - timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + timestamp = DateTime.Now.ToUnix() }); } - protected JsonResult OK(object obj ) + protected JsonResult OK(object obj) { return Json(new { code = 200, message = "sucess", data = obj ?? "", - timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + timestamp = DateTime.Now.ToUnix() }); } @@ -91,7 +90,7 @@ namespace Inotify.Controllers { code = 200, message = message, - timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + timestamp = DateTime.Now.ToUnix() }); } @@ -101,7 +100,7 @@ namespace Inotify.Controllers { code = 404, message = "failed", - timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + timestamp = DateTime.Now.ToUnix() }); } @@ -109,9 +108,9 @@ namespace Inotify.Controllers { return Json(new { - code= code, + code = code, message = "failed", - timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + timestamp = DateTime.Now.ToUnix() }); } @@ -119,9 +118,9 @@ namespace Inotify.Controllers { return new JsonResult(new { - code=code, - message=message, - timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + code = code, + message = message, + timestamp = DateTime.Now.ToUnix() }); } diff --git a/Inotify/Controllers/OAuthControlor.cs b/Inotify/Controllers/OAuthControlor.cs index bb2c5bd..b0128e6 100644 --- a/Inotify/Controllers/OAuthControlor.cs +++ b/Inotify/Controllers/OAuthControlor.cs @@ -5,22 +5,16 @@ using Inotify.Sends; using Inotify.ThridOauth.Common; using Inotify.ThridOauth.IService; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Linq; -using NPoco; using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; -using System.Threading.Tasks; namespace Inotify.Controllers { @@ -47,7 +41,10 @@ namespace Inotify.Controllers if (userInfo != null) { if (!userInfo.Active) + { return Fail(401, "用户被禁用"); + } + if (userInfo.Password == password.ToMd5()) { var token = GenToken(username); @@ -97,13 +94,19 @@ namespace Inotify.Controllers string? avtar = null; string email = ""; if (res.Result.TryGetValue("login", out JToken? jToken)) + { githubUserName = jToken.ToString(); + } if (res.Result.TryGetValue("avatar_url", out jToken)) + { avtar = jToken.ToString(); + } if (res.Result.TryGetValue("email", out jToken)) + { email = jToken.ToString(); + } if (githubUserName != null && avtar != null) { @@ -114,7 +117,9 @@ namespace Inotify.Controllers user.Avatar = avtar; DBManager.Instance.DBase.Update(user); if (!user.Active) + { return Fail(401, "用户被禁用"); + } } else { diff --git a/Inotify/Controllers/SendControlor.cs b/Inotify/Controllers/SendControlor.cs index 5464ccc..edaf3ab 100644 --- a/Inotify/Controllers/SendControlor.cs +++ b/Inotify/Controllers/SendControlor.cs @@ -2,8 +2,6 @@ using Inotify.Data; using Inotify.Sends; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Caching.Memory; -using System; namespace Inotify.Controllers { @@ -16,7 +14,10 @@ namespace Inotify.Controllers { if (DBManager.Instance.IsToken(token, out bool hasActive)) { - if (!hasActive) return Fail(400, "you have no tunnel is acitve"); + if (!hasActive) + { + return Fail(400, "you have no tunnel is acitve"); + } if (!string.IsNullOrEmpty(key)) { @@ -41,7 +42,10 @@ namespace Inotify.Controllers Key = key, }; - if (SendTaskManager.Instance.SendMessage(message)) return OK(); + if (SendTaskManager.Instance.SendMessage(message)) + { + return OK(); + } } return Fail(400, $"token:{token} is not registered"); diff --git a/Inotify/Controllers/SettingControlor.cs b/Inotify/Controllers/SettingControlor.cs index 2cd1f18..483b7d1 100644 --- a/Inotify/Controllers/SettingControlor.cs +++ b/Inotify/Controllers/SettingControlor.cs @@ -2,17 +2,11 @@ using Inotify.Data.Models; using Inotify.Sends; using Inotify.Sends.Products; -using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; -using System.Security.Claims; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading.Tasks; namespace Inotify.Controllers { @@ -154,7 +148,10 @@ namespace Inotify.Controllers { var userInfo = DBManager.Instance.GetUser(UserName); if (userInfo != null) + { return OK(userInfo.Token); + } + return Fail(); } diff --git a/Inotify/Controllers/SetttingSysControlor.cs b/Inotify/Controllers/SetttingSysControlor.cs index 9a6d861..9d9338e 100644 --- a/Inotify/Controllers/SetttingSysControlor.cs +++ b/Inotify/Controllers/SetttingSysControlor.cs @@ -4,11 +4,7 @@ using Inotify.Data.Models.System; using Inotify.Sends; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using NPoco; -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; namespace Inotify.Controllers { @@ -30,7 +26,7 @@ namespace Inotify.Controllers githubClientID = SendCacheStore.GetSystemValue("githubClientID"), githubClientSecret = SendCacheStore.GetSystemValue("githubClientSecret"), githubEnable = githubEnable != "" && bool.Parse(githubEnable), - barkKeyId= SendCacheStore.GetSystemValue("barkKeyId"), + barkKeyId = SendCacheStore.GetSystemValue("barkKeyId"), barkTeamId = SendCacheStore.GetSystemValue("barkTeamId"), barkPrivateKey = SendCacheStore.GetSystemValue("barkPrivateKey"), }); @@ -111,9 +107,13 @@ namespace Inotify.Controllers public IActionResult GetUsers(string? query, int page, int pageSize) { if (query == null) + { return OK(DBManager.Instance.DBase.Query().ToPage(page, pageSize)); - else return OK(DBManager.Instance.DBase.Query().Where(e => e.UserName.Contains(query) || e.Email.Contains(query)).ToPage(page, pageSize)); - + } + else + { + return OK(DBManager.Instance.DBase.Query().Where(e => e.UserName.Contains(query) || e.Email.Contains(query)).ToPage(page, pageSize)); + } } [HttpGet, Route("GetSendInfos"), Authorize(Policys.Systems)] diff --git a/Inotify/Data/DBManager.cs b/Inotify/Data/DBManager.cs index 11a83dc..9632c9d 100644 --- a/Inotify/Data/DBManager.cs +++ b/Inotify/Data/DBManager.cs @@ -1,9 +1,6 @@ -using Inotify.Common; -using Inotify.Data.Models; +using Inotify.Data.Models; using Inotify.Data.Models.System; -using Inotify.Sends.Products; using Microsoft.Data.Sqlite; -using Microsoft.IdentityModel; using Newtonsoft.Json; using NPoco; using NPoco.Migrations; @@ -11,9 +8,7 @@ using NPoco.Migrations.CurrentVersion; using System; using System.Data; using System.IO; -using System.Net.Mail; using System.Runtime.InteropServices; -using System.Security.Cryptography; namespace Inotify.Data { @@ -35,7 +30,7 @@ namespace Inotify.Data public JwtInfo JWT { - get { return m_JWT; } + get => m_JWT; set { m_JWT = value; @@ -53,7 +48,11 @@ namespace Inotify.Data { get { - if (m_Instance == null) m_Instance = new DBManager(); + if (m_Instance == null) + { + m_Instance = new DBManager(); + } + return m_Instance; } } @@ -64,7 +63,10 @@ namespace Inotify.Data if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Inotify_Data = Path.Combine(Directory.GetCurrentDirectory(), m_dataPath); - if (!Directory.Exists(Inotify_Data)) Directory.CreateDirectory(Inotify_Data); + if (!Directory.Exists(Inotify_Data)) + { + Directory.CreateDirectory(Inotify_Data); + } m_jwtPath = Path.Combine(Directory.GetCurrentDirectory(), "/" + m_dataPath + "/jwt.json"); m_dbPath = Path.Combine(Directory.GetCurrentDirectory(), "/" + m_dataPath + "/data.db"); @@ -74,7 +76,10 @@ namespace Inotify.Data if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Inotify_Data = Path.Combine(Directory.GetCurrentDirectory(), m_dataPath); - if (!Directory.Exists(Inotify_Data)) Directory.CreateDirectory(Inotify_Data); + if (!Directory.Exists(Inotify_Data)) + { + Directory.CreateDirectory(Inotify_Data); + } m_jwtPath = Path.Combine(Directory.GetCurrentDirectory(), m_dataPath + "/jwt.json"); m_dbPath = Path.Combine(Directory.GetCurrentDirectory(), m_dataPath + "/data.db"); @@ -107,20 +112,24 @@ namespace Inotify.Data m_dbConnection = new SqliteConnection(string.Format("Data Source={0}", m_dbPath)); if (m_dbConnection.State == ConnectionState.Closed) + { m_dbConnection.Open(); + } - DBase = new Database(m_dbConnection, DatabaseType.SQLite); - DBase.KeepConnectionAlive = true; + DBase = new Database(m_dbConnection, DatabaseType.SQLite) + { + KeepConnectionAlive = true + }; m_migrator = new Migrator(DBase); } - public bool IsToken(string token,out bool hasActive) + public bool IsToken(string token, out bool hasActive) { hasActive = false; - var userInfo= DBase.Query().FirstOrDefault(e => e.Token == token); + var userInfo = DBase.Query().FirstOrDefault(e => e.Token == token); if (userInfo != null) { - hasActive= DBase.Query().Any(e => e.UserId== userInfo.Id && e.Active); + hasActive = DBase.Query().Any(e => e.UserId == userInfo.Id && e.Active); return true; } @@ -154,11 +163,16 @@ namespace Inotify.Data guid = string.Empty; var upToekn = token.ToUpper(); var userInfo = DBManager.Instance.DBase.Query().FirstOrDefault(e => e.Token == upToekn && e.Active); - if (userInfo == null) return null; + if (userInfo == null) + { + return null; + } var authInfo = DBManager.Instance.DBase.Query().FirstOrDefault(e => e.Id == userInfo.SendAuthId && e.UserId == userInfo.Id); if (authInfo == null) + { return null; + } guid = authInfo.SendMethodTemplate; return authInfo.AuthData; @@ -177,7 +191,7 @@ namespace Inotify.Data } else { - sendAuthInfos = DBManager.Instance.DBase.Query().Where(e => e.UserId == userInfo.Id && e.Active &&e.Key==key).ToArray(); + sendAuthInfos = DBManager.Instance.DBase.Query().Where(e => e.UserId == userInfo.Id && e.Active && e.Key == key).ToArray(); } } diff --git a/Inotify/Data/DBMigrations.cs b/Inotify/Data/DBMigrations.cs index 3cea911..b05b041 100644 --- a/Inotify/Data/DBMigrations.cs +++ b/Inotify/Data/DBMigrations.cs @@ -2,9 +2,6 @@ using Inotify.Data.Models; using NPoco.Migrations; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Inotify.Data { @@ -31,7 +28,9 @@ namespace Inotify.Data } if (!Migrator.TableExists()) + { Migrator.CreateTable(true).Execute(); + } if (!Migrator.TableExists()) { @@ -80,7 +79,7 @@ namespace Inotify.Data { protected override void execute() { - + //对AuthInfo的AuthDate字段进行加密 var sendAuthInfos = Migrator.Database.Query().ToList(); sendAuthInfos.ForEach(sendAuthInfo => diff --git a/Inotify/Data/Models/SendAuthInfo.cs b/Inotify/Data/Models/SendAuthInfo.cs index 13dcd0a..156953b 100644 --- a/Inotify/Data/Models/SendAuthInfo.cs +++ b/Inotify/Data/Models/SendAuthInfo.cs @@ -1,5 +1,5 @@ -using System; -using Inotify.Common; +using Inotify.Common; +using System; namespace Inotify.Data.Models { [NPoco.TableName("sendAuthInfo")] @@ -24,14 +24,8 @@ namespace Inotify.Data.Models [NPoco.Ignore] public string AuthData { - get - { - return AuthDataSave.Base64Decode(); - } - set - { - AuthDataSave = value.Base64Encode(); - } + get => AuthDataSave.Base64Decode(); + set => AuthDataSave = value.Base64Encode(); } [NPoco.Column("modifyTime")] diff --git a/Inotify/Data/Models/SendInfo.cs b/Inotify/Data/Models/SendInfo.cs index b05bce4..ef48501 100644 --- a/Inotify/Data/Models/SendInfo.cs +++ b/Inotify/Data/Models/SendInfo.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Inotify.Data.Models +namespace Inotify.Data.Models { [NPoco.TableName("sendInfo")] [NPoco.PrimaryKey(new string[] { "templateID", "date" }, AutoIncrement = false)] diff --git a/Inotify/Data/Models/SendUserInfo.cs b/Inotify/Data/Models/SendUserInfo.cs index 082fc29..40a121b 100644 --- a/Inotify/Data/Models/SendUserInfo.cs +++ b/Inotify/Data/Models/SendUserInfo.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Inotify.Data.Models +namespace Inotify.Data.Models { [NPoco.TableName("userInfo")] [NPoco.PrimaryKey("id")] diff --git a/Inotify/Data/Models/System/JwtInfo.cs b/Inotify/Data/Models/System/JwtInfo.cs index 77191c5..6366262 100644 --- a/Inotify/Data/Models/System/JwtInfo.cs +++ b/Inotify/Data/Models/System/JwtInfo.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Inotify.Data.Models.System +namespace Inotify.Data.Models.System { public class JwtInfo { diff --git a/Inotify/Data/Models/System/SystemInfo.cs b/Inotify/Data/Models/System/SystemInfo.cs index f285334..a2c5362 100644 --- a/Inotify/Data/Models/System/SystemInfo.cs +++ b/Inotify/Data/Models/System/SystemInfo.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Inotify.Data.Models +namespace Inotify.Data.Models { [NPoco.TableName("systemInfo")] diff --git a/Inotify/Inotify.csproj b/Inotify/Inotify.csproj index 77c8727..2ab67df 100644 --- a/Inotify/Inotify.csproj +++ b/Inotify/Inotify.csproj @@ -6,8 +6,8 @@ Linux Inotify.Program enable - 2.0.0.1 - 2.0.0.1 + 2.0.0.2 + 2.0.0.2 diff --git a/Inotify/Program.cs b/Inotify/Program.cs index 2235cae..c38eda3 100644 --- a/Inotify/Program.cs +++ b/Inotify/Program.cs @@ -1,16 +1,7 @@ using Inotify.Data; using Inotify.Sends; - -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; namespace Inotify { diff --git a/Inotify/Sends/Products/BarkSendTemplate.cs b/Inotify/Sends/Products/BarkSendTemplate.cs index 516341b..c0facee 100644 --- a/Inotify/Sends/Products/BarkSendTemplate.cs +++ b/Inotify/Sends/Products/BarkSendTemplate.cs @@ -1,19 +1,10 @@ -using Inotify.Common; -using Inotify.Data; -using Microsoft.IdentityModel.Tokens; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.IO; using System.Linq; using System.Net.Http; -using System.Runtime.InteropServices; using System.Security.Cryptography; -using System.Security.Policy; using System.Text; -using System.Threading.Tasks; namespace Inotify.Sends.Products { @@ -41,7 +32,7 @@ namespace Inotify.Sends.Products } - [SendMethodKey("3B6DE04D-A9EF-4C91-A151-60B7425C5AB2", "Bark", Order = 6, Waring = "BARK通道勿手动添加,请使用APP添加BARK地址绑定")] + [SendMethodKey("3B6DE04D-A9EF-4C91-A151-60B7425C5AB2", "Bark", Order = 2999, Waring = "BARK通道勿手动添加,请使用APP添加BARK地址绑定")] public class BarkSendTemplate : SendTemplate { private static string KeyID; @@ -50,8 +41,6 @@ namespace Inotify.Sends.Products private static CngKey SecretKey; - public override BarkAuth Auth { get; set; } - public override bool SendMessage(SendMessage message) { if (SecretKey == null) @@ -65,7 +54,9 @@ namespace Inotify.Sends.Products } if (Auth.DeviceToken == null) + { return false; + } var payload = CreatePayload(message); var accessToken = CreateAccessToken(payload); @@ -82,9 +73,14 @@ namespace Inotify.Sends.Products var alert = new Dictionary(); if (!string.IsNullOrEmpty(message.Data)) + { alert.Add("body", message.Data); + } + if (!string.IsNullOrEmpty(message.Title)) + { alert.Add("title", message.Title); + } var aps = new Dictionary { @@ -105,7 +101,9 @@ namespace Inotify.Sends.Products }; if (!string.IsNullOrEmpty(message.Title)) + { payload.Add("copy", message.Title); + } var payloadString = JObject.FromObject(payload).ToString(); @@ -164,7 +162,9 @@ namespace Inotify.Sends.Products return true; } else + { return false; + } } else { diff --git a/Inotify/Sends/Products/DingtalkSendTemplate.cs b/Inotify/Sends/Products/DingtalkSendTemplate.cs new file mode 100644 index 0000000..5608983 --- /dev/null +++ b/Inotify/Sends/Products/DingtalkSendTemplate.cs @@ -0,0 +1,88 @@ +using Inotify.Common; +using Newtonsoft.Json; +using System; +using System.IO; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace Inotify.Sends.Products +{ + + public class DingtalkAuth + { + [InputTypeAttribte(0, "WebHook", "WebHook", "https://oapi.dingtalk.com/robot/send?access_token=xxxxx")] + public string WebHook { get; set; } + + + [InputTypeAttribte(0, "Secret", "签名校验", "SEC77xxxx")] + public string Secret { get; set; } + } + + + [SendMethodKey("048297D4-D975-48F6-9A91-8B4EF75805C1", "钉钉群机器人", Order = 21)] + public class DingtalkSendTemplate : SendTemplate + { + public override bool SendMessage(SendMessage message) + { + var bodyObject = new + { + markdown = new + { + title = $"{message.Title}", + text = $"#### {message.Title}\n{message.Data}", + }, + msgtype = "markdown", + + }; + + var timestamp = DateTime.UtcNow.ToUTC(); + var sign = GetHmac(timestamp, Auth.Secret); + var url = $"{Auth.WebHook}×tamp={timestamp}&sign={sign}"; + var webRequest = WebRequest.Create(url); + + var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); + + webRequest.Method = "POST"; + webRequest.ContentType = "application/json;charset=utf-8"; + webRequest.ContentLength = 0; + + using (var postStream = webRequest.GetRequestStream()) + { + var requestStream = webRequest.GetRequestStream(); + webRequest.ContentLength = bytes.Length; + requestStream.Write(bytes, 0, bytes.Length); + } + + try + { + var response = webRequest.GetResponse(); + using (Stream stream = response.GetResponseStream()) + { + using StreamReader reader = new StreamReader(stream, Encoding.UTF8); + var resuleJson = reader.ReadToEnd(); + if (resuleJson.Contains("errcode")) + { + return false; + } + } + return true; + } + catch + { + return false; + } + } + + + private string GetHmac(long timestamp, string secret) + { + var stringToSign = $"{timestamp}\n{secret}"; + using var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); + byte[] hashmessage = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)); + return HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage), Encoding.UTF8); + + } + } +} diff --git a/Inotify/Sends/Products/EmailSendTemplate.cs b/Inotify/Sends/Products/EmailSendTemplate.cs index 150249e..1de9551 100644 --- a/Inotify/Sends/Products/EmailSendTemplate.cs +++ b/Inotify/Sends/Products/EmailSendTemplate.cs @@ -1,11 +1,7 @@ using FluentEmail.Core; -using FluentEmail.Liquid; using FluentEmail.Smtp; -using System; -using System.Collections.Generic; using System.Net; using System.Net.Mail; -using System.Text; namespace Inotify.Sends.Products { @@ -38,8 +34,6 @@ namespace Inotify.Sends.Products [SendMethodKey("EA2B43F7-956C-4C01-B583-0C943ABB36C3", "邮件推送", Order = 1)] public class EmailSendTemplate : SendTemplate { - public override EmailAuth Auth { get; set; } - public override bool SendMessage(SendMessage message) { var smtpSender = new SmtpSender(new SmtpClient() @@ -52,8 +46,7 @@ namespace Inotify.Sends.Products Credentials = new NetworkCredential(Auth.From, Auth.Password), }); - var email = - Email.From(Auth.From, Auth.FromName) + var email = Email.From(Auth.From, Auth.FromName) .Subject(message.Title) .Body(message.Data ?? "") .To(Auth.To); diff --git a/Inotify/Sends/Products/FeishuSendTemplate.cs b/Inotify/Sends/Products/FeishuSendTemplate.cs new file mode 100644 index 0000000..5824b40 --- /dev/null +++ b/Inotify/Sends/Products/FeishuSendTemplate.cs @@ -0,0 +1,96 @@ +using Inotify.Common; +using Newtonsoft.Json; +using System; +using System.IO; +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace Inotify.Sends.Products +{ + public class FeishuAuth + { + [InputTypeAttribte(0, "WebHook", "WebHook", "https://open.feishu.cn/open-apis/bot/v2/hook/5d7b917e-bfb8-4c7e-ba8c-337xxxx")] + public string WebHook { get; set; } + + + [InputTypeAttribte(0, "Secret", "签名校验", "VcgAbeuZOhTZPSP0zxxxx")] + public string Secret { get; set; } + } + + + [SendMethodKey("C01A08B4-3A71-452B-9D4B-D8EC7EF1D68F", "飞书群机器人", Order = 22)] + public class FeishuASendTemplate : SendTemplate + { + public override bool SendMessage(SendMessage message) + { + var timestamp = DateTime.Now.ToUnix() - 10; + var sign = GetHmac(timestamp, Auth.Secret); + + var bodyObject = new + { + content = new + { + text = $"{message.Title}\n{message.Data}", + }, + msg_type = "text", + sign = sign, + timestamp = timestamp, + }; + Console.WriteLine(bodyObject); + + var webRequest = WebRequest.Create(Auth.WebHook); + var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); + + webRequest.Method = "POST"; + webRequest.ContentType = "application/json"; + webRequest.ContentLength = 0; + + using (var postStream = webRequest.GetRequestStream()) + { + var requestStream = webRequest.GetRequestStream(); + webRequest.ContentLength = bytes.Length; + requestStream.Write(bytes, 0, bytes.Length); + } + + try + { + var response = webRequest.GetResponse(); + using (Stream stream = response.GetResponseStream()) + { + using StreamReader reader = new StreamReader(stream, Encoding.UTF8); + var resuleJson = reader.ReadToEnd(); + if (resuleJson.Contains("code")) + { + return false; + } + } + return true; + } + catch + { + return false; + } + } + + private string GetHmac(long timestamp, string secret) + { + var stringToSign = $"{timestamp}\n{secret}"; + using var hmacsha256 = new HMACSHA256Final(Encoding.UTF8.GetBytes(stringToSign)); + return Convert.ToBase64String(hmacsha256.GetHashFinal()); + } + } + + public class HMACSHA256Final : HMACSHA256 + { + public HMACSHA256Final(byte[] bytes) : base(bytes) + { + + } + public byte[] GetHashFinal() + { + + return base.HashFinal(); + } + } +} diff --git a/Inotify/Sends/Products/HttpGetTemplate.cs b/Inotify/Sends/Products/HttpGetTemplate.cs index cc3d096..67d95e6 100644 --- a/Inotify/Sends/Products/HttpGetTemplate.cs +++ b/Inotify/Sends/Products/HttpGetTemplate.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading.Tasks; +using System.Net; namespace Inotify.Sends.Products { @@ -16,7 +12,6 @@ namespace Inotify.Sends.Products [SendMethodKey("ADB11045-F2C8-457E-BF7E-1698AD37ED53", "自定义GET", Order = 4)] public class HttpGetTemplate : SendTemplate { - public override HttpGetAuth Auth { get; set; } public override bool SendMessage(SendMessage message) { diff --git a/Inotify/Sends/Products/HttpPostTemplate.cs b/Inotify/Sends/Products/HttpPostTemplate.cs index 68b82de..361780c 100644 --- a/Inotify/Sends/Products/HttpPostTemplate.cs +++ b/Inotify/Sends/Products/HttpPostTemplate.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; +using System.Net; using System.Text; -using System.Threading.Tasks; namespace Inotify.Sends.Products { @@ -29,19 +24,23 @@ namespace Inotify.Sends.Products [SendMethodKey("A3C1E614-717E-4CF1-BA9B-7242717FC037", "自定义POST", Order = 5)] public class HttpPostTemplate : SendTemplate { - public override HttpPostAuth Auth { get; set; } public override bool SendMessage(SendMessage message) { if (Auth.Data == null) + { Auth.Data = ""; + } if (string.IsNullOrEmpty(Auth.ContentType)) + { Auth.ContentType = "application/json"; - + } if (string.IsNullOrEmpty(Auth.Encoding)) + { Auth.Encoding = "utf-8"; + } var url = Auth.URL.Replace("{title}", message.Title).Replace("{data}", message.Data); var webRequest = WebRequest.Create(url); diff --git a/Inotify/Sends/Products/TelegramBotSendTemplate.cs b/Inotify/Sends/Products/TelegramBotSendTemplate.cs index dbf7e14..79a5c5f 100644 --- a/Inotify/Sends/Products/TelegramBotSendTemplate.cs +++ b/Inotify/Sends/Products/TelegramBotSendTemplate.cs @@ -1,10 +1,5 @@  using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types.InputFiles; @@ -26,7 +21,6 @@ namespace Inotify.Sends.Products public class TelegramBotSendTemplate : SendTemplate { - public override TelegramBotAuth Auth { get; set; } public override bool SendMessage(SendMessage message) { @@ -34,7 +28,7 @@ namespace Inotify.Sends.Products var proxy = GetProxy(); var client = proxy == null ? new TelegramBotClient(Auth.BotToken) : new TelegramBotClient(Auth.BotToken, proxy); var content = string.IsNullOrEmpty(message.Title) ? message.Title : message.Title + "\n" + message.Data; - var isIMG = !String.IsNullOrEmpty(message.Title) && IsUrl(message.Title) && IsImage(message.Title) && String.IsNullOrEmpty(message.Data); + var isIMG = !string.IsNullOrEmpty(message.Title) && IsUrl(message.Title) && IsImage(message.Title) && string.IsNullOrEmpty(message.Data); if (isIMG) { client.SendPhotoAsync(Auth.Chat_id, new InputOnlineFile(new Uri(message.Title))); diff --git a/Inotify/Sends/Products/WeixiSendTemplate.cs b/Inotify/Sends/Products/WeixiSendTemplate.cs index ccc47a1..fc00f78 100644 --- a/Inotify/Sends/Products/WeixiSendTemplate.cs +++ b/Inotify/Sends/Products/WeixiSendTemplate.cs @@ -1,9 +1,6 @@ -using Inotify.Common; -using Inotify.Sends; -using Newtonsoft.Json; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; -using System.Collections.Generic; using System.IO; using System.Net; using System.Text; @@ -30,64 +27,34 @@ namespace Inotify.Sends.Products [SendMethodKey("409A30D5-ABE8-4A28-BADD-D04B9908D763", "企业微信", Order = 0)] public class WeixiSendTemplate : SendTemplate { - public override WeixiAuth Auth { get; set; } - public override bool SendMessage(SendMessage message) { - if (Auth == null) return false; - - var token = GetAccessToken(); - if (token == null) return false; - - return PostMail(token, message.Title, message.Data); - } - - /// 获取AccessToken - /// - /// - private string GetAccessToken() - { - var key = Auth.Corpid + Auth.AgentID + Auth.Corpsecret; - var toekn = SendCacheStore.Get(key); - if (toekn == null) + if (Auth == null) { - var url = string.Format(@"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", Auth.Corpid, Auth.Corpsecret); - - WebRequest request = WebRequest.Create(url); - request.Credentials = CredentialCache.DefaultCredentials; - using WebResponse response = request.GetResponse(); - using Stream streamResponse = response.GetResponseStream(); - StreamReader reader = new StreamReader(streamResponse); - string responseFromServer = reader.ReadToEnd(); - if (!string.IsNullOrEmpty(responseFromServer)) - { - if (JsonConvert.DeserializeObject(responseFromServer) is JObject res) - { - if (res.TryGetValue("access_token", out JToken? jtoken)) - { - toekn = jtoken.ToString(); - } - } - } - reader.Close(); + return false; } - if (toekn != null) - SendCacheStore.Set(key, toekn, DateTimeOffset.Now.AddHours(2)); + var token = CreateAcessToken(); + if (token == null) + { + return false; + } - return toekn; + return CreatePush(token, message.Title, message.Data); } - private bool PostMail(string accessToken, string title, string? data) + private bool CreatePush(string accessToken, string title, string? data) { var uri = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken; var content = string.IsNullOrEmpty(data) ? title : title + "\n" + data; - var isImage = !String.IsNullOrEmpty(title) && IsUrl(title) && IsImage(title) && String.IsNullOrEmpty(data); + var isImage = !string.IsNullOrEmpty(title) && IsUrl(title) && IsImage(title) && string.IsNullOrEmpty(data); var imageData = isImage ? GetImage(title) : null; string mediaId = string.Empty; if (imageData != null) - mediaId = UpLoadIMage(accessToken, imageData); + { + mediaId = CreateImage(accessToken, imageData); + } //创建请求 WebRequest myWebRequest = WebRequest.Create(uri); @@ -148,7 +115,42 @@ namespace Inotify.Sends.Products return true; } - private string UpLoadIMage(string accessToken, byte[] bytes) + private string CreateAcessToken() + { + var key = Auth.Corpid + Auth.AgentID + Auth.Corpsecret; + var toekn = SendCacheStore.Get(key); + if (toekn == null) + { + var url = string.Format(@"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", Auth.Corpid, Auth.Corpsecret); + + WebRequest request = WebRequest.Create(url); + request.Credentials = CredentialCache.DefaultCredentials; + using WebResponse response = request.GetResponse(); + using Stream streamResponse = response.GetResponseStream(); + StreamReader reader = new StreamReader(streamResponse); + string responseFromServer = reader.ReadToEnd(); + if (!string.IsNullOrEmpty(responseFromServer)) + { + if (JsonConvert.DeserializeObject(responseFromServer) is JObject res) + { + if (res.TryGetValue("access_token", out JToken? jtoken)) + { + toekn = jtoken.ToString(); + } + } + } + reader.Close(); + } + + if (toekn != null) + { + SendCacheStore.Set(key, toekn, DateTimeOffset.Now.AddHours(2)); + } + + return toekn; + } + + private string CreateImage(string accessToken, byte[] bytes) { try { @@ -182,7 +184,7 @@ namespace Inotify.Sends.Products } catch { - + } return null; diff --git a/Inotify/Sends/SendCacheStore.cs b/Inotify/Sends/SendCacheStore.cs index 4b9d5d9..e63fd7e 100644 --- a/Inotify/Sends/SendCacheStore.cs +++ b/Inotify/Sends/SendCacheStore.cs @@ -1,13 +1,9 @@ -using Inotify; -using Inotify.Data; +using Inotify.Data; using Inotify.Data.Models; -using Inotify.Sends; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; -using System.Text; -using System.Web; namespace Inotify.Sends { @@ -27,7 +23,10 @@ namespace Inotify.Sends { object obj = m_cache.Get(key); if (obj != null && obj is string) + { return obj as string; + } + return null; } @@ -40,7 +39,10 @@ namespace Inotify.Sends public static string GetSystemValue(string key) { if (m_systemInfos.ContainsKey(key)) + { return m_systemInfos[key]; + } + return ""; } diff --git a/Inotify/Sends/SendMessage.cs b/Inotify/Sends/SendMessage.cs index c943b47..a6d2398 100644 --- a/Inotify/Sends/SendMessage.cs +++ b/Inotify/Sends/SendMessage.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Inotify.Sends +namespace Inotify.Sends { public class SendMessage { diff --git a/Inotify/Sends/SendTaskManager.cs b/Inotify/Sends/SendTaskManager.cs index b4c1160..e56a28b 100644 --- a/Inotify/Sends/SendTaskManager.cs +++ b/Inotify/Sends/SendTaskManager.cs @@ -1,15 +1,10 @@ -using Inotify; -using Inotify.Data; +using Inotify.Data; using Inotify.Data.Models; -using Inotify.Sends; -using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Reflection; -using System.Text; using System.Threading; @@ -22,7 +17,11 @@ namespace Inotify.Sends { get { - if (m_Instance == null) m_Instance = new SendTaskManager(); + if (m_Instance == null) + { + m_Instance = new SendTaskManager(); + } + return m_Instance; } } @@ -47,7 +46,7 @@ namespace Inotify.Sends var sendMethodTemplates = Assembly.GetExecutingAssembly() .GetTypes() .Where(e => e.GetCustomAttribute() != null) - .OrderBy(e => e.GetCustomAttribute().Order) + .OrderBy(e => e.GetCustomAttribute().Order.ToString()) .ToList(); sendMethodTemplates.ForEach(sendMethodTemplate => @@ -105,7 +104,9 @@ namespace Inotify.Sends public bool SendMessage(SendMessage message) { if (m_sendMessages.Count > 10000) + { return false; + } m_sendMessages.Add(message); @@ -124,7 +125,9 @@ namespace Inotify.Sends if (getTemeplateMethod != null) { if (getTemeplateMethod.Invoke(obj, null) is InputTemeplate temeplate && temeplate.Key != null) + { sendTemplates.Add(temeplate.Key, temeplate); + } } } return sendTemplates; diff --git a/Inotify/Sends/SendTemplate.cs b/Inotify/Sends/SendTemplate.cs index 2e5f041..ad67c1f 100644 --- a/Inotify/Sends/SendTemplate.cs +++ b/Inotify/Sends/SendTemplate.cs @@ -1,14 +1,10 @@ -using Inotify.Sends; -using Newtonsoft.Json; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Net; -using System.Net.Mail; using System.Reflection; -using System.Text; using System.Text.RegularExpressions; namespace Inotify.Sends @@ -86,8 +82,13 @@ namespace Inotify.Sends if (item.Name != null && item.Value != null) { if (item.Type == InputType.CHECK) + { jObject.Add(item.Name, item.Value.ToLower() == "true"); - else jObject.Add(item.Name, item.Value); + } + else + { + jObject.Add(item.Name, item.Value); + } } } } @@ -125,8 +126,8 @@ namespace Inotify.Sends { public InputTypeValue InputTypeData { get; set; } - - private InputTypeAttribte(int order, string name, string description, string defaultValue, InputType type,bool show=true,bool readOnly=false) + + private InputTypeAttribte(int order, string name, string description, string defaultValue, InputType type, bool show = true, bool readOnly = false) { InputTypeData = new InputTypeValue { @@ -156,8 +157,7 @@ namespace Inotify.Sends public abstract class SendTemplate { - - public abstract T Auth { get; set; } + public T Auth { get; set; } public void Composition(string authInfo) { @@ -173,7 +173,7 @@ namespace Inotify.Sends .Select(e => e.InputTypeData) .ToList(); - var sendMethodKeyAttribute = this.GetType().GetCustomAttribute(); + var sendMethodKeyAttribute = GetType().GetCustomAttribute(); if (sendMethodKeyAttribute != null) { @@ -190,10 +190,8 @@ namespace Inotify.Sends return null; } - public virtual bool SendMessage(SendMessage message) - { - return false; - } + public abstract bool SendMessage(SendMessage message); + protected WebProxy GetProxy() { diff --git a/Inotify/Startup.cs b/Inotify/Startup.cs index 6e98bab..fb7479b 100644 --- a/Inotify/Startup.cs +++ b/Inotify/Startup.cs @@ -2,7 +2,6 @@ using Inotify.Controllers; using Inotify.Data; using Inotify.Sends; using Inotify.ThridOauth; -using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -13,11 +12,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; -using NPoco; using System; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; using System.Text; using System.Text.Encodings.Web; using System.Text.RegularExpressions; @@ -132,7 +127,7 @@ namespace Inotify rewriteContext.HttpContext.Request.Path = @"/api/send"; rewriteContext.HttpContext.Request.QueryString = new QueryString($"?token={groups[1]}&key={groups[2]}"); } - else if(rewriteContext.HttpContext.Request.QueryString.Value.StartsWith("?")) + else if (rewriteContext.HttpContext.Request.QueryString.Value.StartsWith("?")) { rewriteContext.HttpContext.Request.Path = @"/info"; rewriteContext.HttpContext.Request.QueryString = new QueryString(); diff --git a/Inotify/StartupManager.cs b/Inotify/StartupManager.cs index 45ff7c6..87ff1a5 100644 --- a/Inotify/StartupManager.cs +++ b/Inotify/StartupManager.cs @@ -1,10 +1,6 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; -using System; -using System.Collections.Generic; -using System.Linq; using System.Threading; -using System.Threading.Tasks; namespace Inotify { @@ -27,7 +23,9 @@ namespace Inotify public static StartUpManager Load() { if (_appManager == null) + { _appManager = new StartUpManager(); + } return _appManager; } @@ -35,10 +33,14 @@ namespace Inotify public void Start(string[] args) { if (_running) + { return; + } if (_tokenSource != null && _tokenSource.IsCancellationRequested) + { return; + } _tokenSource = new CancellationTokenSource(); _tokenSource.Token.ThrowIfCancellationRequested(); @@ -56,7 +58,9 @@ namespace Inotify public void Stop() { if (!_running) + { return; + } _tokenSource.Cancel(); _running = false; diff --git a/Inotify/ThridOauth/Common/AuthorizeResult.cs b/Inotify/ThridOauth/Common/AuthorizeResult.cs index f58d3d3..b29686b 100644 --- a/Inotify/ThridOauth/Common/AuthorizeResult.cs +++ b/Inotify/ThridOauth/Common/AuthorizeResult.cs @@ -1,5 +1,4 @@ -using Inotify.ThridOauth.Common; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; diff --git a/Inotify/ThridOauth/Common/JsonCommon.cs b/Inotify/ThridOauth/Common/JsonCommon.cs index 2cd9899..28c1e4d 100644 --- a/Inotify/ThridOauth/Common/JsonCommon.cs +++ b/Inotify/ThridOauth/Common/JsonCommon.cs @@ -1,5 +1,4 @@ -using Inotify.ThridOauth.Common; -using Newtonsoft.Json; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Inotify/ThridOauth/Entity/CredentialSetting.cs b/Inotify/ThridOauth/Entity/CredentialSetting.cs index eb9de9f..3d5f693 100644 --- a/Inotify/ThridOauth/Entity/CredentialSetting.cs +++ b/Inotify/ThridOauth/Entity/CredentialSetting.cs @@ -1,8 +1,4 @@ -using Inotify.ThridOauth.Entity; - - - -namespace Inotify.ThridOauth.Entity +namespace Inotify.ThridOauth.Entity { public class CredentialSetting { diff --git a/Inotify/ThridOauth/Entity/FaceBookCredential.cs b/Inotify/ThridOauth/Entity/FaceBookCredential.cs index 857eefb..d5640ce 100644 --- a/Inotify/ThridOauth/Entity/FaceBookCredential.cs +++ b/Inotify/ThridOauth/Entity/FaceBookCredential.cs @@ -1,7 +1,3 @@ -using Inotify.ThridOauth.Entity; - - - namespace Inotify.ThridOauth.Entity { public class FaceBookCredential : CredentialSetting diff --git a/Inotify/ThridOauth/Entity/GitHubCredential.cs b/Inotify/ThridOauth/Entity/GitHubCredential.cs index 1f593e0..ad5801b 100644 --- a/Inotify/ThridOauth/Entity/GitHubCredential.cs +++ b/Inotify/ThridOauth/Entity/GitHubCredential.cs @@ -1,7 +1,3 @@ -using Inotify.ThridOauth.Entity; - - - namespace Inotify.ThridOauth.Entity { public class GitHubCredential : CredentialSetting diff --git a/Inotify/ThridOauth/Entity/QQCredential.cs b/Inotify/ThridOauth/Entity/QQCredential.cs index d345fc7..21d6de3 100644 --- a/Inotify/ThridOauth/Entity/QQCredential.cs +++ b/Inotify/ThridOauth/Entity/QQCredential.cs @@ -1,7 +1,3 @@ -using Inotify.ThridOauth.Entity; - - - namespace Inotify.ThridOauth.Entity { public class QQCredential : CredentialSetting diff --git a/Inotify/ThridOauth/Entity/WechatCredential.cs b/Inotify/ThridOauth/Entity/WechatCredential.cs index f0255ce..4daa9d3 100644 --- a/Inotify/ThridOauth/Entity/WechatCredential.cs +++ b/Inotify/ThridOauth/Entity/WechatCredential.cs @@ -1,7 +1,3 @@ -using Inotify.ThridOauth.Entity; - - - namespace Inotify.ThridOauth.Entity { public class WechatCredential : CredentialSetting diff --git a/Inotify/ThridOauth/Entity/WeiBoCredential.cs b/Inotify/ThridOauth/Entity/WeiBoCredential.cs index 3d05977..8b7984b 100644 --- a/Inotify/ThridOauth/Entity/WeiBoCredential.cs +++ b/Inotify/ThridOauth/Entity/WeiBoCredential.cs @@ -1,7 +1,3 @@ -using Inotify.ThridOauth.Entity; - - - namespace Inotify.ThridOauth.Entity { public class WeiBoCredential : CredentialSetting diff --git a/Inotify/ThridOauth/IService/IFacebookLogin.cs b/Inotify/ThridOauth/IService/IFacebookLogin.cs index c797fae..d836db5 100644 --- a/Inotify/ThridOauth/IService/IFacebookLogin.cs +++ b/Inotify/ThridOauth/IService/IFacebookLogin.cs @@ -1,8 +1,4 @@ -using Inotify.ThridOauth.IService; - - - -namespace Inotify.ThridOauth.IService +namespace Inotify.ThridOauth.IService { public interface IFacebookLogin : ILogin { diff --git a/Inotify/ThridOauth/IService/IGitHubLogin.cs b/Inotify/ThridOauth/IService/IGitHubLogin.cs index 5b55157..80100b9 100644 --- a/Inotify/ThridOauth/IService/IGitHubLogin.cs +++ b/Inotify/ThridOauth/IService/IGitHubLogin.cs @@ -1,7 +1,3 @@ -using Inotify.ThridOauth.IService; - - - namespace Inotify.ThridOauth.IService { public interface IGitHubLogin : ILogin diff --git a/Inotify/ThridOauth/IService/ILogin.cs b/Inotify/ThridOauth/IService/ILogin.cs index 743bcd5..825fb43 100644 --- a/Inotify/ThridOauth/IService/ILogin.cs +++ b/Inotify/ThridOauth/IService/ILogin.cs @@ -1,5 +1,4 @@ using Inotify.ThridOauth.Common; -using Inotify.ThridOauth.IService; diff --git a/Inotify/ThridOauth/IService/IQqLogin.cs b/Inotify/ThridOauth/IService/IQqLogin.cs index c467c8a..377a495 100644 --- a/Inotify/ThridOauth/IService/IQqLogin.cs +++ b/Inotify/ThridOauth/IService/IQqLogin.cs @@ -1,8 +1,4 @@ -using Inotify.ThridOauth.IService; - - - -namespace Inotify.ThridOauth.IService +namespace Inotify.ThridOauth.IService { public interface IQqLogin : ILogin { diff --git a/Inotify/ThridOauth/IService/ISinaLogin.cs b/Inotify/ThridOauth/IService/ISinaLogin.cs index fbe999a..166c1e0 100644 --- a/Inotify/ThridOauth/IService/ISinaLogin.cs +++ b/Inotify/ThridOauth/IService/ISinaLogin.cs @@ -1,8 +1,4 @@ -using Inotify.ThridOauth.IService; - - - -namespace Inotify.ThridOauth.IService +namespace Inotify.ThridOauth.IService { public interface ISinaLogin : ILogin { diff --git a/Inotify/ThridOauth/IService/IWeChatLogin.cs b/Inotify/ThridOauth/IService/IWeChatLogin.cs index 7b9abcf..933568b 100644 --- a/Inotify/ThridOauth/IService/IWeChatLogin.cs +++ b/Inotify/ThridOauth/IService/IWeChatLogin.cs @@ -1,8 +1,4 @@ -using Inotify.ThridOauth.IService; - - - -namespace Inotify.ThridOauth.IService +namespace Inotify.ThridOauth.IService { public interface IWeChatLogin : ILogin { diff --git a/Inotify/ThridOauth/Service/FacebookLogin.cs b/Inotify/ThridOauth/Service/FacebookLogin.cs index e039b44..4abc757 100644 --- a/Inotify/ThridOauth/Service/FacebookLogin.cs +++ b/Inotify/ThridOauth/Service/FacebookLogin.cs @@ -1,7 +1,6 @@ using Inotify.ThridOauth.Common; using Inotify.ThridOauth.Entity; using Inotify.ThridOauth.IService; -using Inotify.ThridOauth.Service; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; @@ -47,7 +46,10 @@ namespace Inotify.ThridOauth.Service var token = GetAccessToken(code, ref errMsg); if (!string.IsNullOrEmpty(errMsg)) + { return new AuthorizeResult { Code = Code.UserInfoErrorMsg, Error = errMsg }; + } + var accessToken = token.Value("access_token"); var user = UserInfo(accessToken, ref errMsg); diff --git a/Inotify/ThridOauth/Service/GitHubLogin.cs b/Inotify/ThridOauth/Service/GitHubLogin.cs index f8080bc..e39c773 100644 --- a/Inotify/ThridOauth/Service/GitHubLogin.cs +++ b/Inotify/ThridOauth/Service/GitHubLogin.cs @@ -2,14 +2,10 @@ using Inotify.Sends; using Inotify.ThridOauth.Common; using Inotify.ThridOauth.Entity; using Inotify.ThridOauth.IService; -using Inotify.ThridOauth.Service; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; -using System.Linq; -using System.Net; using System.Net.Http; @@ -56,11 +52,14 @@ namespace Inotify.ThridOauth.Service var token = GetAccessToken(code, ref errorMsg); if (!string.IsNullOrEmpty(errorMsg)) + { return new AuthorizeResult { Code = Code.UserInfoErrorMsg, Error = errorMsg }; + } + var accessToken = token.Value("access_token"); var user = UserInfo(accessToken, ref errorMsg); @@ -140,11 +139,17 @@ namespace Inotify.ThridOauth.Service { startindex = sourse.IndexOf(startstr, StringComparison.Ordinal); if (startindex == -1) + { return result; + } + string tmpstr = sourse[(startindex + startstr.Length)..]; endindex = tmpstr.IndexOf(endstr, StringComparison.Ordinal); if (endindex == -1) + { return result; + } + result = tmpstr.Remove(endindex); } catch (Exception ex) diff --git a/Inotify/ThridOauth/Service/LoginBase.cs b/Inotify/ThridOauth/Service/LoginBase.cs index fc6c862..7e950f1 100644 --- a/Inotify/ThridOauth/Service/LoginBase.cs +++ b/Inotify/ThridOauth/Service/LoginBase.cs @@ -1,6 +1,5 @@ using Inotify.Sends; using Inotify.ThridOauth.Entity; -using Inotify.ThridOauth.Service; using Microsoft.AspNetCore.Http; using System; using System.Net; diff --git a/Inotify/ThridOauth/Service/QQLogin.cs b/Inotify/ThridOauth/Service/QQLogin.cs index e9431f0..135a007 100644 --- a/Inotify/ThridOauth/Service/QQLogin.cs +++ b/Inotify/ThridOauth/Service/QQLogin.cs @@ -1,7 +1,6 @@ using Inotify.ThridOauth.Common; using Inotify.ThridOauth.Entity; using Inotify.ThridOauth.IService; -using Inotify.ThridOauth.Service; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; @@ -58,7 +57,10 @@ namespace Inotify.ThridOauth.Service var token = GetAccessToken(code, ref errorMsg); if (!string.IsNullOrEmpty(errorMsg)) + { return new AuthorizeResult { Code = Code.UserInfoErrorMsg, Error = errorMsg }; + } + var accessToken = token["access_token"]; var user = UserInfo(accessToken, ref errorMsg); diff --git a/Inotify/ThridOauth/Service/WeChatLogin.cs b/Inotify/ThridOauth/Service/WeChatLogin.cs index 932a600..3e3da85 100644 --- a/Inotify/ThridOauth/Service/WeChatLogin.cs +++ b/Inotify/ThridOauth/Service/WeChatLogin.cs @@ -1,7 +1,6 @@ using Inotify.ThridOauth.Common; using Inotify.ThridOauth.Entity; using Inotify.ThridOauth.IService; -using Inotify.ThridOauth.Service; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; @@ -55,7 +54,11 @@ namespace Inotify.ThridOauth.Service var token = GetAccessToken(code, ref errorMsg); - if (!string.IsNullOrEmpty(errorMsg)) return new AuthorizeResult { Code = Code.UserInfoErrorMsg, Error = errorMsg }; + if (!string.IsNullOrEmpty(errorMsg)) + { + return new AuthorizeResult { Code = Code.UserInfoErrorMsg, Error = errorMsg }; + } + var accessToken = token.Value("access_token"); var uid = token.Value("openid"); diff --git a/Inotify/ThridOauth/Service/WeiBoLogin.cs b/Inotify/ThridOauth/Service/WeiBoLogin.cs index e3c2d0c..352c2b8 100644 --- a/Inotify/ThridOauth/Service/WeiBoLogin.cs +++ b/Inotify/ThridOauth/Service/WeiBoLogin.cs @@ -1,7 +1,6 @@ using Inotify.ThridOauth.Common; using Inotify.ThridOauth.Entity; using Inotify.ThridOauth.IService; -using Inotify.ThridOauth.Service; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; @@ -53,7 +52,10 @@ namespace Inotify.ThridOauth.Service var token = GetAccessToken(code, ref errorMsg); if (!string.IsNullOrEmpty(errorMsg)) + { return new AuthorizeResult { Code = Code.UserInfoErrorMsg, Error = errorMsg }; + } + var accessToken = token.Value("access_token"); var uid = token.Value("uid"); diff --git a/Inotify/ThridOauth/ThridPartyLoginExtensions.cs b/Inotify/ThridOauth/ThridPartyLoginExtensions.cs index 69947c8..4e6b802 100644 --- a/Inotify/ThridOauth/ThridPartyLoginExtensions.cs +++ b/Inotify/ThridOauth/ThridPartyLoginExtensions.cs @@ -1,5 +1,4 @@ -using Inotify.ThridOauth; -using Inotify.ThridOauth.Entity; +using Inotify.ThridOauth.Entity; using Inotify.ThridOauth.IService; using Inotify.ThridOauth.Service; using Microsoft.Extensions.DependencyInjection; @@ -16,7 +15,11 @@ namespace Inotify.ThridOauth public static IServiceCollection AddWeChatLogin(this IServiceCollection services, Action credential) { - if (services == null) throw new ArgumentNullException(nameof(services)); + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + services.Configure(credential); services.AddScoped(); return services; @@ -25,7 +28,11 @@ namespace Inotify.ThridOauth public static IServiceCollection AddQqLogin(this IServiceCollection services, Action credential) { - if (services == null) throw new ArgumentNullException(nameof(services)); + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + services.Configure(credential); services.AddScoped(); return services; @@ -34,7 +41,11 @@ namespace Inotify.ThridOauth public static IServiceCollection AddSinaLogin(this IServiceCollection services, Action credential) { - if (services == null) throw new ArgumentNullException(nameof(services)); + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + services.Configure(credential); services.AddScoped(); return services; @@ -43,7 +54,11 @@ namespace Inotify.ThridOauth public static IServiceCollection AddFackbookLogin(this IServiceCollection services, Action credential) { - if (services == null) throw new ArgumentNullException(nameof(services)); + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + services.Configure(credential); services.AddScoped(); return services; @@ -52,7 +67,11 @@ namespace Inotify.ThridOauth public static IServiceCollection AddGitHubLogin(this IServiceCollection services, Action credential) { - if (services == null) throw new ArgumentNullException(nameof(services)); + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + services.Configure(credential); services.AddScoped(); return services; diff --git a/README.md b/README.md index 7daedf3..fb91358 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,8 @@ - [x] 电报机器人消息 - [x] SMTP邮箱消息 - [x] BARK -- [ ] 钉钉群机器人 -- [ ] 飞书群机器人 +- [x] 钉钉群机器人 +- [x] 飞书群机器人 - [x] 自定义 ## 更新日志 @@ -35,31 +35,34 @@ * 支持自定义Get、POST * V2.0.0.2 * 支持BARK + * V2.0.0.3 + * 支持钉钉群消息 + * 支持飞书群消息 ## 使用方法 1. Docker安装 * 稳定版V1.0 - ``` - docker run --name=inotify -d -p 8000:80 -v inotify_data:/inotify_data --restart=always xpnas/inotify:latest - ``` - * 开发版V2.0.0.2 - ``` - docker run --name=inotify -d -p 8000:80 -v inotify_data:/inotify_data --restart=always xpnas/inotify:master - ``` + ``` + docker run --name=inotify -d -p 8000:80 -v inotify_data:/inotify_data --restart=always xpnas/inotify:latest + ``` + * 开发版V2.0.0.3 + ``` + docker run --name=inotify -d -p 8000:80 -v inotify_data:/inotify_data --restart=always xpnas/inotify:master + ``` 2. 配置Nginx代理 - ``` - server - { - location / { proxy_pass http://127.0.0.1:8000; } - } - ``` + ``` + server + { + location / { proxy_pass http://127.0.0.1:8000; } + } + ``` 3. 进入`Github/Settings/Developer settings/OAuth Apps`创建应用 * 记录`Client ID`,创建`Client secrets` * `Authorization callback URL`回调地址填写https://{您的域名}/api/oauth/githubLogin 4. 使用`默认用户名admin,密码123456`登陆后台/全局参数,修改Github登陆的`应用ID`、`应用密钥`并启动登陆 5. 建议将`管理权限`的用户名设置成自己的github用户名,再使用Github登陆后,在用户管理页面`删除默认账号admin` - + ## BARK设置 1. 本项目依据Bark-Server接口规范实现了内置BARK服务端 2. 复制或扫码`消息验证\BARK授权`中的地址,填入BARK应用的服务器地址中,如`https://inotify.cf?act=6D474C0DB1474F19BD8F7342D570C0FC`