diff --git a/aspnet-core/LINGYUN.MicroService.All.slnx b/aspnet-core/LINGYUN.MicroService.All.slnx index b242203d3..1bfd020fb 100644 --- a/aspnet-core/LINGYUN.MicroService.All.slnx +++ b/aspnet-core/LINGYUN.MicroService.All.slnx @@ -596,7 +596,10 @@ + + + diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MediaMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MediaMessage.cs index 97e6254c1..8e1c124f5 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MediaMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MediaMessage.cs @@ -15,6 +15,9 @@ public class MediaMessage [JsonProperty("media_id")] [JsonPropertyName("media_id")] public string MediaId { get; set; } + + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public MediaMessage(string mediaId) { MediaId = mediaId; diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MiniProgramMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MiniProgramMessage.cs index 15d509872..5a3070cfd 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MiniProgramMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MiniProgramMessage.cs @@ -51,10 +51,9 @@ public class MiniProgramMessage [JsonProperty("content_item")] [JsonPropertyName("content_item")] public List? ContentItems { get; set; } - public MiniProgramMessage() - { - } + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public MiniProgramMessage( string appId, string title, @@ -86,4 +85,12 @@ public class MiniProgramContent [JsonProperty("value")] [JsonPropertyName("value")] public string Value { get; set; } = default!; + + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] + public MiniProgramContent(string key, string value) + { + Key = key; + Value = value; + } } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MpNewMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MpNewMessage.cs index 165f1e7d4..0ac2e26d7 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MpNewMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MpNewMessage.cs @@ -16,6 +16,9 @@ public class MpNewMessagePayload [JsonProperty("articles")] [JsonPropertyName("articles")] public List Articles { get; set; } + + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public MpNewMessagePayload(List articles) { Articles = articles; @@ -26,6 +29,8 @@ public class MpNewMessagePayload /// public class MpNewMessage { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public MpNewMessage( string title, string thumbMediaId, @@ -48,40 +53,40 @@ public class MpNewMessage [NotNull] [JsonProperty("title")] [JsonPropertyName("title")] - public string Title { get; set; } + public string Title { get; set; } = default!; /// /// 图文消息缩略图的media_id, 可以通过素材管理接口获得。此处thumb_media_id即上传接口返回的media_id /// [NotNull] [JsonProperty("thumb_media_id")] [JsonPropertyName("thumb_media_id")] - public string ThumbMediaId { get; set; } + public string ThumbMediaId { get; set; } = default!; /// /// 图文消息的作者,不超过64个字节 /// [CanBeNull] [JsonProperty("author")] [JsonPropertyName("author")] - public string Author { get; set; } + public string? Author { get; set; } /// /// 图文消息点击“阅读原文”之后的页面链接 /// [CanBeNull] [JsonProperty("content_source_url")] [JsonPropertyName("content_source_url")] - public string ContentSourceUrl { get; set; } + public string? ContentSourceUrl { get; set; } /// /// 图文消息的内容,支持html标签,不超过666 K个字节(支持id转译) /// [NotNull] [JsonProperty("content")] [JsonPropertyName("content")] - public string Content { get; set; } + public string Content { get; set; } = default!; /// /// 图文消息的描述,不超过512个字节,超过会自动截断(支持id转译) /// [CanBeNull] [JsonProperty("digest")] [JsonPropertyName("digest")] - public string Description { get; set; } + public string? Description { get; set; } } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardActionMenu.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardActionMenu.cs index ea44e33dc..f864fa27e 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardActionMenu.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardActionMenu.cs @@ -15,7 +15,7 @@ public class TemplateCardActionMenu [CanBeNull] [JsonProperty("desc")] [JsonPropertyName("desc")] - public string Description { get; set; } + public string? Description { get; set; } /// /// 操作列表,列表长度取值范围为 [1, 3] /// @@ -23,6 +23,9 @@ public class TemplateCardActionMenu [JsonProperty("action_list")] [JsonPropertyName("action_list")] public List Actions { get; set;} + + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardActionMenu(List actions, string description = "") { Actions = actions; diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardCardAction.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardCardAction.cs index 91a6b360e..8eb5353e0 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardCardAction.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardCardAction.cs @@ -8,11 +8,14 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TemplateCardCardAction { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardCardAction(string url) { Type = 1; Url = url; } + public TemplateCardCardAction(string appid, string pagePath) { Type = 2; diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardEmphasisContent.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardEmphasisContent.cs index d93d74973..71ee5b2fc 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardEmphasisContent.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardEmphasisContent.cs @@ -8,6 +8,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TemplateCardEmphasisContent { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardEmphasisContent( string title = "", string description = "") @@ -22,12 +24,12 @@ public class TemplateCardEmphasisContent [CanBeNull] [JsonProperty("title")] [JsonPropertyName("title")] - public string Title { get; set; } + public string? Title { get; set; } /// /// 关键数据样式的数据描述内容,建议不超过22个字 /// [CanBeNull] [JsonProperty("desc")] [JsonPropertyName("desc")] - public string Description { get; set; } + public string? Description { get; set; } } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardHorizontalContent.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardHorizontalContent.cs index 55dc5fc6e..9ba58f980 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardHorizontalContent.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardHorizontalContent.cs @@ -32,6 +32,8 @@ public class TemplateCardHorizontalContent keyName, 3, value, userId: userId); } + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardHorizontalContent( string keyName, byte type = 0, @@ -61,7 +63,7 @@ public class TemplateCardHorizontalContent [NotNull] [JsonProperty("keyname")] [JsonPropertyName("keyname")] - public string KeyName { get; set; } + public string KeyName { get; set; } = default!; /// /// 二级文本,如果horizontal_content_list.type是2,该字段代表文件名称(要包含文件类型),建议不超过30个字,(支持id转译) /// diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardJump.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardJump.cs index 9a2819869..1886c001d 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardJump.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardJump.cs @@ -11,6 +11,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TemplateCardJump { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardJump(string title, string url) { Type = 1; diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardMainTitle.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardMainTitle.cs index b8a0f78cc..ac656ac2e 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardMainTitle.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardMainTitle.cs @@ -8,6 +8,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TemplateCardMainTitle { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardMainTitle( string title = "", string description = "") @@ -22,12 +24,12 @@ public class TemplateCardMainTitle [CanBeNull] [JsonProperty("title")] [JsonPropertyName("title")] - public string Title { get; set; } + public string? Title { get; set; } /// /// 标题辅助信息,建议不超过44个字,(支持id转译) /// [CanBeNull] [JsonProperty("desc")] [JsonPropertyName("desc")] - public string Description { get; set; } + public string? Description { get; set; } } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardQuoteArea.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardQuoteArea.cs index 58d23c49e..63a1150bd 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardQuoteArea.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardQuoteArea.cs @@ -8,6 +8,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TemplateCardQuoteArea { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardQuoteArea(string url, string title = "", string text = "") { Type = 1; @@ -29,7 +31,7 @@ public class TemplateCardQuoteArea [CanBeNull] [JsonProperty("type")] [JsonPropertyName("type")] - public byte Type { get; } + public byte? Type { get; } /// /// 点击跳转的url,quote_area.type是1时必填 /// @@ -57,12 +59,12 @@ public class TemplateCardQuoteArea [CanBeNull] [JsonProperty("title")] [JsonPropertyName("title")] - public string Title { get; set; } + public string? Title { get; set; } /// /// 引用文献样式的引用文案 /// [CanBeNull] [JsonProperty("quote_text")] [JsonPropertyName("quote_text")] - public string Text { get; set; } + public string? Text { get; set; } } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardSource.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardSource.cs index 7000f010e..40cf27394 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardSource.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardSource.cs @@ -18,6 +18,8 @@ public enum DescriptionColor /// public class TemplateCardSource { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TemplateCardSource( string iconUrl = "", string description = "", diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextCardMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextCardMessage.cs index 28e22e09b..589bf58a5 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextCardMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextCardMessage.cs @@ -8,6 +8,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TextCardMessage { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TextCardMessage( string title, string description, diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextTemplateCard.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextTemplateCard.cs index c73eed500..bda3288c7 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextTemplateCard.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextTemplateCard.cs @@ -9,6 +9,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class TextTemplateCard : TemplateCard { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public TextTemplateCard(TemplateCardCardAction cardAction, string taskId = "") : base("template_card", taskId) { @@ -77,5 +79,5 @@ public class TextTemplateCard : TemplateCard [NotNull] [JsonProperty("TemplateCardCardAction")] [JsonPropertyName("TemplateCardCardAction")] - public TemplateCardCardAction CardAction { get; set; } + public TemplateCardCardAction CardAction { get; set; } = default!; } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/VideoMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/VideoMessage.cs index 3b0aed5db..ae0c55995 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/VideoMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/VideoMessage.cs @@ -8,6 +8,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// public class VideoMessage { + [Newtonsoft.Json.JsonConstructor] + [System.Text.Json.Serialization.JsonConstructor] public VideoMessage( string mediaId, string title = "", diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkMiniProgramMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkMiniProgramMessage.cs index e23d0fb38..d676eb416 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkMiniProgramMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkMiniProgramMessage.cs @@ -6,36 +6,8 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// /// 企业微信小程序通知消息 /// -public class WeChatWorkMiniProgramMessage +public class WeChatWorkMiniProgramMessage : WeChatWorkMessage { - /// - /// 指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)。 - /// 特殊情况:指定为"@all",则向该企业应用的全部成员发送 - /// - [JsonProperty("touser")] - [JsonPropertyName("touser")] - public virtual string? ToUser { get; set; } - /// - /// 指定接收消息的部门,部门ID列表,多个接收者用‘|’分隔,最多支持100个。 - /// 当touser为"@all"时忽略本参数 - /// - [JsonProperty("toparty")] - [JsonPropertyName("toparty")] - public virtual string? ToParty { get; set; } - /// - /// 指定接收消息的标签,标签ID列表,多个接收者用‘|’分隔,最多支持100个。 - /// 当touser为"@all"时忽略本参数 - /// - [JsonProperty("totag")] - [JsonPropertyName("totag")] - public virtual string? ToTag { get; set; } - /// - /// 消息类型 - /// - [NotNull] - [JsonProperty("msgtype")] - [JsonPropertyName("msgtype")] - public virtual string MsgType { get; } /// /// 表示是否开启id转译,0表示否,1表示是,默认0。 /// 仅第三方应用需要用到 @@ -71,14 +43,11 @@ public class WeChatWorkMiniProgramMessage byte enableIdTrans = 0, byte enableDuplicateCheck = 0, int duplicateCheckInterval = 1800) + : base("", "miniprogram_notice", toUser, toParty, toTag) { - ToUser = toUser; - ToParty = toParty; - ToTag = toTag; + MiniProgram = miniProgram; EnableIdTrans = enableIdTrans; EnableDuplicateCheck = enableDuplicateCheck; DuplicateCheckInterval = duplicateCheckInterval; - MiniProgram = miniProgram; - MsgType = "miniprogram_notice"; } } diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkWebhookNewsMessage.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkWebhookNewsMessage.cs index 56e065431..b4cd2b769 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkWebhookNewsMessage.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkWebhookNewsMessage.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; @@ -6,7 +6,7 @@ namespace LINGYUN.Abp.WeChat.Work.Messages.Models; /// /// 企业微信Webhook图文消息 /// -internal class WeChatWorkWebhookNewsMessage : WeChatWorkWebhookMessage +public class WeChatWorkWebhookNewsMessage : WeChatWorkWebhookMessage { /// /// 图文消息体 diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardAction.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardAction.cs index d4fea6930..66584779f 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardAction.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardAction.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; using Volo.Abp; @@ -37,7 +37,8 @@ public class WebhookTemplateCardAction [JsonProperty("pagepath")] [JsonPropertyName("pagepath")] public string? PagePath { get; set; } - private WebhookTemplateCardAction( + [System.Text.Json.Serialization.JsonConstructor] + public WebhookTemplateCardAction( int type, string? url = null, string? appId = null, diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardHorizontalContent.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardHorizontalContent.cs index a1dd4d056..99b126dd5 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardHorizontalContent.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardHorizontalContent.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; using Volo.Abp; @@ -51,7 +51,8 @@ public class WebhookTemplateCardHorizontalContent [JsonProperty("userid")] [JsonPropertyName("userid")] public string? UserId { get; set; } - private WebhookTemplateCardHorizontalContent( + [System.Text.Json.Serialization.JsonConstructor] + public WebhookTemplateCardHorizontalContent( string keyName, int? type = null, string? value = null, diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardImageTextArea.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardImageTextArea.cs index a75fa0d59..5fca26ae3 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardImageTextArea.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardImageTextArea.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; using Volo.Abp; @@ -58,7 +58,8 @@ public class WebhookTemplateCardImageTextArea [JsonProperty("desc")] [JsonPropertyName("desc")] public string? Description { get; set; } - private WebhookTemplateCardImageTextArea( + [System.Text.Json.Serialization.JsonConstructor] + public WebhookTemplateCardImageTextArea( string imageUrl, int? type = null, string? url = null, diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardJump.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardJump.cs index 72445dadd..807b29928 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardJump.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardJump.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; using Volo.Abp; @@ -44,7 +44,8 @@ public class WebhookTemplateCardJump [JsonProperty("pagepath")] [JsonPropertyName("pagepath")] public string? PagePath { get; set; } - private WebhookTemplateCardJump( + [System.Text.Json.Serialization.JsonConstructor] + public WebhookTemplateCardJump( string title, int? type = null, string? url = null, diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardQuoteArea.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardQuoteArea.cs index d423088a9..2ab8ce587 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardQuoteArea.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardQuoteArea.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; using Volo.Abp; @@ -51,7 +51,8 @@ public class WebhookTemplateCardQuoteArea [JsonProperty("quote_text")] [JsonPropertyName("quote_text")] public string? QuoteText { get; set; } - private WebhookTemplateCardQuoteArea( + [System.Text.Json.Serialization.JsonConstructor] + public WebhookTemplateCardQuoteArea( string title, int? type = null, string? url = null, diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSource.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSource.cs index b424df8f1..e8c4a5506 100644 --- a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSource.cs +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSource.cs @@ -1,4 +1,4 @@ -using JetBrains.Annotations; +using JetBrains.Annotations; using Newtonsoft.Json; using System.Text.Json.Serialization; @@ -29,7 +29,8 @@ public class WebhookTemplateCardSource [JsonProperty("desc_color")] [JsonPropertyName("desc_color")] public int? DescriptionColor { get; set; } - private WebhookTemplateCardSource( + [System.Text.Json.Serialization.JsonConstructor] + public WebhookTemplateCardSource( string? iconUrl = null, string? description = null, int? descriptionColor = 0) diff --git a/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSystemTextJsonConverter.cs b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSystemTextJsonConverter.cs new file mode 100644 index 000000000..4f4b8e1f9 --- /dev/null +++ b/aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSystemTextJsonConverter.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace LINGYUN.Abp.WeChat.Work.Messages.Models; + +/// +/// Webhook 模板卡片消息 System.Text.Json 序列化 +/// +/// +/// +/// 是抽象类型, 且具体类型的构造函数带必填参数 +/// (例如 的 cardImage / action / mainTitle), +/// 因此无法通过无参构造还原 —— 模板卡片一旦作为通知数据持久化就再也无法反序列化。 +/// +/// +/// 这里按 card_type 判别符还原具体类型。判别符由构造函数传递给基类, 通过读取构造函数 +/// IL 中的字符串常量获得, 因此新增卡片类型无需修改本转换器。 +/// +/// +/// 项目使用的 JSON 集成是 Volo.Abp.Json.SystemTextJson, +/// 因此由渠道模块在启动时自动注册到全局选项。 +/// +/// +public class WebhookTemplateCardSystemTextJsonConverter : JsonConverter +{ + private const byte LdstrOpCode = 0x72; + + private const string CardTypePropertyName = "card_type"; + + private static readonly Dictionary CardTypes = new(StringComparer.OrdinalIgnoreCase); + + private static readonly object SyncLock = new(); + + private static bool _initialized; + + public override WebhookTemplateCardMessage? Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + + using var jsonDocument = JsonDocument.ParseValue(ref reader); + var jsonElement = jsonDocument.RootElement; + + if (jsonElement.ValueKind != JsonValueKind.Object) + { + throw new JsonException( + $"Unable to resolve a webhook template card from a JSON token of kind '{jsonElement.ValueKind}'."); + } + + var cardType = jsonElement.TryGetProperty(CardTypePropertyName, out var cardTypeElement) + ? cardTypeElement.GetString() + : null; + + var concreteType = ResolveCardType(cardType, typeToConvert); + if (concreteType == null) + { + throw new JsonException( + $"Unable to resolve a webhook template card type for card_type: '{cardType}'."); + } + + // 指定具体类型反序列化, 从而避开本转换器(否则会递归) + return (WebhookTemplateCardMessage?)JsonSerializer.Deserialize( + jsonElement.GetRawText(), + concreteType, + options); + } + + public override void Write( + Utf8JsonWriter writer, + WebhookTemplateCardMessage value, + JsonSerializerOptions options) + { + // 按运行时类型写出, 避免只输出基类成员 + JsonSerializer.Serialize(writer, value, value.GetType(), options); + } + + /// + /// 按 card_type 获取具体的卡片类型 + /// + public static Type? GetCardType(string cardType) + { + EnsureInitialized(); + + return CardTypes.TryGetValue(cardType, out var type) ? type : null; + } + + private static Type? ResolveCardType(string? cardType, Type targetType) + { + EnsureInitialized(); + + if (!cardType.IsNullOrWhiteSpace()) + { + if (!CardTypes.TryGetValue(cardType!, out var mappedType)) + { + throw new JsonException($"Unknown webhook template card type: '{cardType}'."); + } + + if (!targetType.IsAssignableFrom(mappedType)) + { + throw new JsonException( + $"The webhook template card data of card_type: '{cardType}' can not be deserialized as '{targetType.FullName}'."); + } + + return mappedType; + } + + // 缺少判别符时: 目标是具体类型则直接使用 + if (!targetType.IsAbstract) + { + return targetType; + } + + // 抽象目标且判别符缺失: 回退到文本通知模版卡片 + return CardTypes.TryGetValue(nameof(WebhookTextNoticeCardMessage), out var fallbackType) + ? fallbackType + : null; + } + + private static void EnsureInitialized() + { + if (_initialized) + { + return; + } + + lock (SyncLock) + { + if (_initialized) + { + return; + } + + foreach (var type in typeof(WebhookTemplateCardSystemTextJsonConverter).Assembly.GetTypes()) + { + if (type.IsAbstract || !typeof(WebhookTemplateCardMessage).IsAssignableFrom(type)) + { + continue; + } + + foreach (var discriminator in GetDiscriminators(type)) + { + CardTypes[discriminator] = type; + } + } + + _initialized = true; + } + } + + /// + /// 获取卡片类型的判别符 + /// + /// + /// 判别符由构造函数传递给基类, 因此读取构造函数 IL 中的字符串常量。 + /// 同时以类型名作为兜底键。 + /// + private static IEnumerable GetDiscriminators(Type cardType) + { + var discriminators = new List(); + + foreach (var constructor in cardType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) + { + try + { + var body = constructor.GetMethodBody(); + if (body == null) + { + continue; + } + + var discriminator = ReadFirstStringConstant(body.GetILAsByteArray(), constructor.Module); + if (!discriminator.IsNullOrWhiteSpace() && !discriminators.Contains(discriminator!)) + { + discriminators.Add(discriminator!); + } + } + catch + { + // 读取 IL 失败不影响兜底判别符 + } + } + + discriminators.Add(cardType.Name); + + return discriminators; + } + + private static string? ReadFirstStringConstant(byte[]? il, Module module) + { + if (il == null) + { + return null; + } + + for (var index = 0; index < il.Length; index++) + { + if (il[index] != LdstrOpCode || index + 4 >= il.Length) + { + continue; + } + + var token = BitConverter.ToInt32(il, index + 1); + + try + { + return module.ResolveString(token); + } + catch + { + // 不是字符串元数据标记, 继续扫描 + } + } + + return null; + } +} diff --git a/aspnet-core/modules/realtime-notifications/CHANNEL-DATA-USAGE.md b/aspnet-core/modules/realtime-notifications/CHANNEL-DATA-USAGE.md new file mode 100644 index 000000000..7db4a4ecf --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/CHANNEL-DATA-USAGE.md @@ -0,0 +1,737 @@ +# 通知渠道数据 — 使用指南 + +> 框架设计说明见 [CHANNEL-DATA.md](./CHANNEL-DATA.md) + +--- + +## 0. 三个接入点 + +| 角色 | 用哪个 API | 典型位置 | +|---|---|---| +| 生产者(业务代码) | `INotificationChannelDataSerializer.Write` 或渠道扩展方法 | 发送通知的 AppService / DomainService | +| 通知定义 | `NotificationDefinition.WithProviders(...)` | `NotificationDefinitionProvider` | +| 渠道实现 | `INotificationChannelDataResolver` | 各 `*NotificationPublishProvider` | + +渠道数据是"生产者 → 渠道"的**单向约定**;通知定义负责决定**哪些渠道会收到**。 +两者是独立的:定义里没声明该渠道,渠道根本不会被调用。 + +--- + +## 1. 场景一:企业微信渠道 + +### 1.1 最简单——只用标准数据 + +不写任何渠道数据,企业微信渠道会按通知定义的 `ContentType` 自动推导载体: + +| 定义的内容类型 | 自动生成的载体 | +|---|---| +| `Text` | 文本消息(取 `message`) | +| `Html` | 文本卡片消息(取 `title`/`description`/`message`) | +| `Markdown` | markdown消息(取 `message`) | + +```csharp +public class MyAppService : ApplicationService +{ + private readonly INotificationSender _notificationSender; + + public MyAppService(INotificationSender notificationSender) + { + _notificationSender = notificationSender; + } + + public async Task NotifyAsync(Guid userId) + { + var data = new NotificationData(); + data.WriteStandardData( + title: "构建完成", + message: "**v1.2.0** 已部署到生产环境", + createTime: Clock.Now, + formUser: CurrentUser.UserName ?? "system"); + + await _notificationSender.SendNofiterAsync( + name: "BuildFinished", + data: data, + user: new UserIdentifier(userId, "admin")); + } +} +``` + +### 1.2 指定接收人 / 保密 / 去重 + +写入"投递选项"。这些选项在**持久化与失败重试后依然生效**: + +```csharp +var data = new NotificationData(); +data.WriteStandardData("标题", "内容", Clock.Now, "system"); + +data.TrySetData(WeChatWorkNotificationDataKeys.ToParty, "1|2"); // 指定部门 +data.TrySetData(WeChatWorkNotificationDataKeys.ToTag, "3"); // 指定标签 +data.TrySetData(WeChatWorkNotificationDataKeys.Safe, true); // 保密消息 +data.TrySetData(WeChatWorkNotificationDataKeys.EnableIdTrans, true); // 开启 id 转译 +data.TrySetData(WeChatWorkNotificationDataKeys.EnableDuplicateCheck, true); +data.TrySetData(WeChatWorkNotificationDataKeys.DuplicateCheckInterval, 600); // 秒 + +await _notificationSender.SendNofiterAsync("BuildFinished", data, user); +``` + +> 键名带本渠道前缀(`wx-work:`);读取大小写不敏感。 +> 成员(`touser`)由企业微信身份绑定关系自动解析,**不由通知数据指定**。 +> `touser` / `toparty` / `totag` 三者不能同时为空。 + +### 1.3 文本卡片 + +```csharp +channelDataSerializer.Write(data, new WeChatWorkTextCardChannelData +{ + TextCard = new TextCardMessage( + title: "审批通过", + description: "您的请假申请已通过,请前往查看", + url: "https://example.com/leave/123", + buttonText: "去查看") +}); +``` + +> `channelDataSerializer` 是注入的 `INotificationChannelDataSerializer`。 +> 它按载荷类型上标注的 写入对应键, +> 生产侧与渠道侧共用同一份契约定义。 + +### 1.4 模板卡片(推荐用于审批/告警类) + +```csharp +var card = new TextTemplateCard( + new TemplateCardCardAction("https://example.com/approval/123")) +{ + MainTitle = new TemplateCardMainTitle("请假通过通知", "您的请假申请已通过"), + SubTitle = "请及时处理后续交接事项", + HorizontalContents = new List + { + TemplateCardHorizontalContent.None("审批单号", "QJ20251000000136"), + TemplateCardHorizontalContent.None("请假日期", "2025/10/01-2025/10/10"), + TemplateCardHorizontalContent.None("通过时间", "2025-10-01 15:30:00"), + // 也可以带跳转/素材/人员 + TemplateCardHorizontalContent.FromUrl("详情", "https://example.com/oa/123", "点击查看"), + }, + Jumps = new List + { + new TemplateCardJump("去OA查看", "https://example.com/oa/123"), + } +}; + +channelDataSerializer.Write(data, new WeChatWorkTemplateCardChannelData { TemplateCard = card }); +``` + +> 可用的 `TemplateCardHorizontalContent` 工厂: +> `None(keyName, value)`、`FromUrl(keyName, url, value)`、 +> `FromMedia(keyName, mediaId, value)`、`FromUser(keyName, userId, value)`。 +> `TemplateCardJump` 支持"跳转链接"与"跳转小程序"两个构造函数。 +> 完整可运行示例见你仓库中的 +> `tests/LINGYUN.Abp.WeChat.Work.Tests/.../WeChatWorkMessageSender_Tests.cs`。 + +### 1.5 小程序通知 + +```csharp +channelDataSerializer.Write(data, new WeChatWorkMiniProgramNoticeChannelData +{ + MiniProgram = new MiniProgramMessage( + appId: "wx1234567890", + title: "订单已发货", + page: "pages/order/detail?id=123", + description: "点击查看物流详情") + { + EmphasisFirstItem = true, + ContentItems = new List + { + new MiniProgramContent("订单号", "SO20251001001"), + new MiniProgramContent("物流公司", "顺丰速运"), + } + } +}); +``` + +### 1.6 图文 / 视频 / 语音 / 文件 + +```csharp +channelDataSerializer.Write(data, new WeChatWorkMpNewChannelData +{ + MpNewMessage = new MpNewMessagePayload(new List + { + new MpNewMessage( + title: "月度报告", + thumbMediaId: "MEDIA_ID", + content: "

报告正文

", + author: "运营部", + contentSourceUrl: "https://example.com/report", + description: "2025年10月经营月报") + }) +}); + +channelDataSerializer.Write(data, new WeChatWorkVideoChannelData +{ + Video = new VideoMessage("MEDIA_ID", "培训视频", "新人入职培训") +}); + +channelDataSerializer.Write(data, new WeChatWorkVoiceChannelData +{ + Voice = new MediaMessage("MEDIA_ID") +}); + +channelDataSerializer.Write(data, new WeChatWorkFileChannelData +{ + File = new MediaMessage("MEDIA_ID") +}); +``` + +### 1.7 可用的载荷类型与选项支持 + +生产者只需选择合适的载荷类型;选项由渠道按载体能力自动取舍(不支持的字段**不会被设置**)。 + +| 载荷类型 | 载体 | `safe` | `enable_id_trans` | `enable_duplicate_check` | +|---|---|---|---|---| +| `WeChatWorkTextCardChannelData` | 文本卡片 | ❌ | ✅ | ✅ | +| `WeChatWorkTemplateCardChannelData` | 模板卡片 | ❌ | ✅ | ✅ | +| `WeChatWorkMiniProgramNoticeChannelData` | 小程序通知 | ❌ | ✅ | ✅ | +| `WeChatWorkMpNewChannelData` | 图文(mpnews) | ✅ | ✅ | ✅ | +| `WeChatWorkVideoChannelData` | 视频 | ✅ | ❌ | ✅ | +| `WeChatWorkFileChannelData` | 文件 | ✅ | ❌ | ✅ | +| `WeChatWorkVoiceChannelData` | 语音 | ❌ | ❌ | ✅ | +| (无,按 `ContentType=Markdown` 推导) | markdown | ❌ | ❌ | ✅ | +| (无,按 `ContentType=Text` 推导) | 文本 | ✅ | ✅ | ✅ | + +### 1.8 多个载荷同时存在怎么处理 + +**全部都会发送**,顺序由载荷的 `Priority` 决定(固定值,见下表): + +| 载荷 | Priority | +|---|---| +| 小程序通知 | 100 | +| 图文(mpnews) | 200 | +| 模板卡片 | 300 | +| 文本卡片 | 400 | +| 视频 | 500 | +| 语音 | 600 | +| 文件 | 700 | + +即"同时设置文本卡片与小程序通知"会**发两条消息**。如果只想发一条,只写一个载荷。 +只有当**没有任何显式载荷**时,才回退到按 `ContentType` 推导的默认载体。 + +--- + +## 2. 场景二:其他内置渠道 + +### 2.1 微信小程序订阅消息 + +> 注意:`TemplateId` 等键沿用历史命名(**无前缀**),读取已改为**大小写不敏感**。 + +```csharp +var data = new NotificationData(); +data.WriteStandardData("订单发货", "您的订单已发货", Clock.Now, "system"); + +// 键带本渠道前缀 wx-mp:; 不写则用 AbpNotificationsWeChatMiniProgramOptions 的默认值 +data.TrySetData(WeChatMiniProgramNotificationDataKeys.TemplateId, "TEMPLATE_ID"); +data.TrySetData(WeChatMiniProgramNotificationDataKeys.RedirectPage, "pages/order/detail?id=123"); +data.TrySetData(WeChatMiniProgramNotificationDataKeys.WeAppState, "developer"); +data.TrySetData(WeChatMiniProgramNotificationDataKeys.WeAppLanguage, "zh_CN"); + +// 模板数据本身就取自属性包,按微信模板字段名写入 +data.TrySetData("character_string1", "SO20251001001"); +data.TrySetData("thing2", "顺丰速运"); + +await _notificationSender.SendNofiterAsync("OrderShipped", data, user); +``` + +> 模板数据键(`character_string1`、`thing2` …)由**微信模板定义**决定, +> 不属于渠道自有键, 因此不加前缀。 +> +> 早期版本使用的无前缀键(`TemplateId` 等)由渠道只读回退兼容 +> (见 `WeChatMiniProgramNotificationDataKeys.Legacy`), 新代码请使用带前缀的常量。 + +### 2.2 WxPusher + +```csharp +// 方式一: 用序列化器(推荐) +channelDataSerializer.Write(data, new WxPusherChannelData +{ + Url = "https://example.com/detail/123" +}); + +// 方式二: 直接写键 +data.TrySetData(WxPusherNotificationDataKeys.Url, "https://example.com/detail/123"); +``` + +### 2.3 PushPlus + +```csharp +channelDataSerializer.Write(data, new PushPlusChannelData +{ + Webhook = "https://example.com/hook", + CallbackUrl = "https://example.com/callback" +}); +``` + +> PushPlus 的 `Presence` 是 `AnyDeclaredProperty`: 写入其中任意一个键即视为声明了载荷。 + +### 2.4 短信 / 邮件 / SignalR + +**无渠道专属键**,只需要标准数据: + +```csharp +var data = new NotificationData(); +data.WriteStandardData("告警", "CPU 使用率超过 90%", Clock.Now, "monitor"); + +await _notificationSender.SendNofiterAsync(NotifyNames.SystemAlarm, data, user); +``` + +- 短信:只取 `message` +- 邮件:`title` 作为主题,`message` 作为正文(`ContentType=Markdown` 时自动转 HTML) +- SignalR:直接推送整个 `NotificationData`,由客户端解释 + +--- + +## 3. 场景三:企业微信 Webhook(群机器人) + +项目:`LINGYUN.Abp.Notifications.Webhook.WeChat.Work` + +### 3.1 与企业微信应用消息的区别 + +| | 应用消息 | Webhook(群机器人)| +|---|---|---| +| 渠道名(通知定义里声明) | `WeChat.Work` | `Webhook` | +| 载荷注册表键 | `WeChat.Work` | `WeChat.Work.Webhook` | +| 数据键前缀 | `wx-work:` | `wx-work-hook:` | +| 收件人 | 由身份绑定解析(`touser`) | 由 Webhook 定义决定(群)| + +> **为什么要分成两个渠道**:两者是不同传输方式、不同载体模型。 +> 若共用注册表键与键前缀,同一个通知被两个渠道同时订阅时, +> 载荷会被两边都解析并各发一条消息。 + +### 3.2 定义侧 + +```csharp +context.AddGroup("Monitor", L("Monitor")) + .AddNotification("SystemAlarm", L("SystemAlarm")) + .WithProviders( + "Webhook"); // WebhookNotificationPublishProvider.ProviderName +``` + +Webhook 的投递目标由**订阅关系**决定(`IWebhookPublisher`), +通知数据只负责"发什么"。 + +### 3.3 生产者侧 + +```csharp +var data = new NotificationData(); +data.WriteStandardData("构建失败", "构建 #1234 失败", Clock.Now, "ci"); + +// 用序列化器写载荷(推荐) +channelDataSerializer.Write(data, new WeChatWorkWebhookTextChannelData +{ + Content = "构建 #1234 失败,请查看日志" +}); + +// 也可以直接写键 +data.TrySetData(WeChatWorkWebhookNotificationDataKeys.Markdown, "**构建失败**"); +``` + +### 3.4 可用的载荷类型 + +| 载荷类型 | `msgtype` | 用途 | +|---|---|---| +| `WeChatWorkWebhookTextChannelData` | `text` | 纯文本 | +| `WeChatWorkWebhookMarkdownChannelData` | `markdown` | markdown | +| `WeChatWorkWebhookMarkdownV2ChannelData` | `markdown_v2` | markdown_v2(支持表格、代码块)| +| `WeChatWorkWebhookImageChannelData` | `image` | 图片(base64 + md5)| +| `WeChatWorkWebhookNewsChannelData` | `news` | 图文 | +| `WeChatWorkWebhookFileChannelData` | `file` | 文件(素材 ID)| +| `WeChatWorkWebhookVoiceChannelData` | `voice` | 语音(素材 ID)| +| `WeChatWorkWebhookTemplateCardChannelData` | `template_card` | 模板卡片 | + +**每种载荷 1:1 映射到自己的 `msgtype`,不做隐式降级。** +(改造前只支持 `text` / `markdown` / `markdown_v2` 三种,其余内容类型被静默丢弃。) + +模板卡片示例: + +```csharp +channelDataSerializer.Write(data, new WeChatWorkWebhookTemplateCardChannelData +{ + TemplateCard = new WebhookTextNoticeCardMessage( + action: WebhookTemplateCardAction.Link("https://example.com/build/1234"), + mainTitle: new WebhookTemplateCardMainTitle("构建失败", "请及时处理"), + subTitleText: "构建 #1234 于 15:30 失败", + horizontalContents: new List + { + WebhookTemplateCardHorizontalContent.Default("分支", "main"), + WebhookTemplateCardHorizontalContent.Default("提交", "a1b2c3d"), + }) +}); +``` + +图文消息示例: + +```csharp +channelDataSerializer.Write(data, new WeChatWorkWebhookNewsChannelData +{ + News = new WebhookNewsMessage(new List + { + new WebhookArticleMessage( + title: "月度经营报告", + url: "https://example.com/report", + description: "2025年10月", + pictureUrl: "https://example.com/cover.png") + }) +}); +``` + +### 3.5 向后兼容 + +**载荷缺失时**回退到按 `ContentType` 推导(即改造前的行为): + +| `ContentType` | 推导出的载体 | +|---|---| +| `Text` | `text` | +| `Html` | HTML → markdown,再按 `UseMarkdownV2` 决定 `markdown_v2` 或 `markdown` | +| `Markdown` | 按 `UseMarkdownV2` 决定 `markdown_v2` 或 `markdown` | + +因此只写标准数据的历史生产者**无需改动**。 + +`UseMarkdownV2` 默认 `true`,可在模块的 `PreConfigure` 中覆盖: + +```csharp +[DependsOn(typeof(AbpNotificationsWebhookWeChatWorkModule))] +public class MyModule : AbpModule +{ + public override void PreConfigureServices(ServiceConfigurationContext context) + { + PreConfigure(options => + { + options.UseMarkdownV2 = false; + }); + } +} +``` + +### 3.6 一个 Webhook 只承载一条消息 + +声明多个载荷时取 `Priority` 最小的那个: + +| 载荷 | Priority | +|---|---| +| 文本 | 100 | +| markdown | 200 | +| markdown_v2 | 300 | +| 图片 | 400 | +| 图文 | 500 | +| 文件 | 600 | +| 语音 | 700 | +| 模板卡片 | 800 | + +> 这与企业微信**应用消息**渠道不同——后者多个载荷会**发多条**消息。 +> Webhook 一次发布对应一个订阅回调,因此只能承载一条。 + +--- + +## 4. 场景四:自定义渠道 + +以一个"钉钉机器人"渠道为例。 + +### 4.1 定义载荷 + +```csharp +using LINGYUN.Abp.Notifications; + +namespace MyProject.Notifications.DingTalk; + +public static class DingTalkNotificationDataKeys +{ + public const string Prefix = "dingtalk:"; + public const string Webhook = Prefix + "webhook"; + public const string AtMobiles = Prefix + "at_mobiles"; +} + +[NotificationChannelData(DingTalkNotificationPublishProvider.ProviderName, Priority = 100)] +public class DingTalkChannelData : NotificationChannelData +{ + [NotificationChannelProperty(DingTalkNotificationDataKeys.Webhook)] + public virtual string? Webhook { get; set; } + + [NotificationChannelProperty(DingTalkNotificationDataKeys.AtMobiles)] + public virtual string? AtMobiles { get; set; } +} +``` + +> ✅ **不需要实现 `IsSet`**。 +> 存在性由 `Presence` 声明式推导(默认"参与匹配的属性全部存在")。 +> 若希望"只写 atMobiles 也算声明", 改为: +> `[NotificationChannelData(..., Presence = NotificationChannelDataPresenceMode.AnyDeclaredProperty)]`。 +> +> 若某属性只是可选读取项(不参与存在性判定), 给它加 `IgnoreWhenMatching = true`。 +> +> 若既未声明 `Presence`、又没有任何可匹配属性, **注册时会抛 +> `AbpNotificationChannelDataConfigurationException`**。这是刻意设计: +> 把"忘了定义存在性"从生产环境静默丢消息变成启动即失败。 +> +> 为什么不用"抽象静态方法强制实现"? C# 不允许 `static` 成员标记为 `abstract`(CS0112), +> 基类无法强制派生类实现静态成员; 而提供"默认返回 false"的兜底实现会导致 +> **忘记实现者静默失效**。详见 [CHANNEL-DATA.md §3](./CHANNEL-DATA.md)。 + +### 4.2 注册 + +渠道模块在自己的 `AbpModule` 中用 `Configure<>` 声明载荷: + +```csharp +using LINGYUN.Abp.Notifications; +using Volo.Abp.Modularity; + +namespace MyProject.Notifications.DingTalk; + +[DependsOn(typeof(AbpNotificationsModule))] +public class AbpNotificationsDingTalkModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.PublishProviders.Add(); + }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + }); + } +} +``` + +> `AbpNotificationChannelDataOptions` 是纯数据对象, 注册期的存在性校验只依赖声明元数据、 +> 不依赖任何服务, 因此 `Add()` 不要求任何初始化顺序, 也不需要额外的配置器类。 + +### 4.3 在渠道实现中解析 + +```csharp +public class DingTalkNotificationPublishProvider : NotificationPublishProvider +{ + public const string ProviderName = "DingTalk"; + public override string Name => ProviderName; + + protected INotificationChannelDataResolver ChannelDataResolver + => ServiceProvider.LazyGetRequiredService(); + + protected async override Task PublishAsync( + NotificationPublishContext context, + CancellationToken cancellationToken = default) + { + var data = context.Notification.Data; + + // ① 载荷已声明但解析失败 => 生产者数据非法,明确报错而不是静默回退 + if (ChannelDataResolver.IsDeclared(data, typeof(DingTalkChannelData)) + && ChannelDataResolver.Resolve(data) is not { } payload) + { + context.Cancel("The dingtalk payload can not be parsed, please check the notification data."); + Logger.LogWarning(context.Reason); + return; + } + + // ② 未声明则走默认行为 + var webhook = ChannelDataResolver.Resolve(data)?.Webhook; + if (webhook.IsNullOrWhiteSpace()) + { + context.Cancel("Unable to send dingtalk messages because the webhook is not set."); + return; + } + + // ③ 需要标量选项时用类型化读取(不要用 as) + var timeout = ChannelDataResolver.GetValue(data, "dingtalk:timeout") ?? 30; + + await SendAsync(webhook, context, cancellationToken); + } +} +``` + +### 4.4 定义侧(必须声明渠道,否则渠道不会被调用) + +```csharp +public class MyNotificationDefinitionProvider : NotificationDefinitionProvider +{ + public override void Define(INotificationDefinitionContext context) + { + context.AddGroup("MyGroup", L("MyGroup")) + .AddNotification("OrderShipped", L("OrderShipped")) + .WithProviders( + DingTalkNotificationPublishProvider.ProviderName, + NotificationProviderNames.SignalR); + } +} +``` + +### 4.5 生产者侧 + +```csharp +var data = new NotificationData(); +data.WriteStandardData("订单发货", "您的订单已发货", Clock.Now, "system"); + +// 载荷由类型声明驱动(推荐) +channelDataSerializer.Write(data, new DingTalkChannelData +{ + Webhook = "https://oapi.dingtalk.com/robot/send?access_token=xxx", + AtMobiles = "13800000000" +}); + +await _notificationSender.SendNofiterAsync("OrderShipped", data, user); +``` + +> **不要为渠道添加扩展方法**(如 `WithDingTalkRobot`)。 +> 本框架已移除所有渠道专属的写入扩展方法: 载荷类型 + 序列化器 +> 已经提供了带前缀、可校验、可发现的统一入口, +> 再叠一层扩展方法只会造成两套并行的写入约定。 + +--- + +## 5. 场景五:从旧写法迁移 + +### 5.1 渠道专属扩展方法已全部移除 + +早期版本在渠道模块中提供了一组写入/读取扩展方法: + +| 已移除 | 取代方式 | +|---|---| +| `data.WithTextCardMessage(...)`、`WithTemplateCardMessage`、`WithMiniProgramMessage`、`WithMpNewMessage`、`WithVideoMessage`、`WithVoiceMessage`、`WithFileMessage` | `channelDataSerializer.Write(data, new WeChatWorkXxxChannelData { ... })` | +| `data.SetSafe(...)`、`SetEnableIdTrans`、`SetEnableDuplicateCheck`、`SetDuplicateCheckInterval` | `data.TrySetData(WeChatWorkNotificationDataKeys.Xxx, value)` | +| `data.SetParty(...)`、`SetTag(...)` | `data.TrySetData(WeChatWorkNotificationDataKeys.ToParty / ToTag, value)` | +| `data.SetUrl(...)` (WxPusher) | `data.TrySetData(WxPusherNotificationDataKeys.Url, value)` 或 `channelDataSerializer.Write(data, new WxPusherChannelData { ... })` | +| `data.SetWebhook(...)`、`SetCallbackUrl(...)` (PushPlus) | `data.TrySetData(PushPlusNotificationDataKeys.Webhook / CallbackUrl, value)` | +| `GetSafe()`、`GetUrlOrNull()`、`TryGetMessagePayload()` 等读取方法 | `INotificationChannelDataResolver` | + +**键常量(`XxxNotificationDataKeys`)全部保留** —— 它们定义的是数据契约, +不是便捷 API。渠道的 `NotificationDefinition` 扩展方法(如 +`WithAgentId`、`WithTag`)是**定义侧** API, 与数据键无关, 同样保留。 + +### 5.2 渠道实现:替换裸转换 + +```csharp +// ❌ 旧写法 —— 持久化后必然失效,且无日志 +var safe = data.TryGetData("wx-work:safe") as byte? ?? 0; +var url = data.TryGetData("wx-pusher:url")?.ToString(); + +// ✅ 新写法(注入 INotificationChannelDataResolver) +var safe = channelDataResolver.GetValue(data, WeChatWorkNotificationDataKeys.Safe); +var payload = channelDataResolver.Resolve(data); +var url = payload?.Url; +``` + +### 5.3 破坏性变更清单 + +| 变更 | 影响 | +|---|---| +| **渠道专属扩展方法已全部删除** | `NotificationDataWeChatWorkExtensions`、WxPusher / PushPlus 的 `NotificationDataExtensions` 均已移除。传递方式见 §4.1 对照表 | +| **`NotificationChannelValues` 静态类已删除** | 全部能力改为实例服务: `INotificationChannelDataAccessor`(转换) 与 `INotificationChannelDataResolver`(渠道读取)。静态 API 无处可查即编译失败 | +| 载荷不再需要(也不应再写) `IsSet` | 存在性改为 `Presence` 声明式; 旧 `IsSet` 不会被调用 | +| `NotificationChannelDataSerializer.AddJsonConverter` 已移除 | 改为 `INotificationChannelDataJsonSerializer`; 抽象载荷的转换器注册到 JSON 选项 | +| 企业微信 `agentId` 数据键 | 键常量保留(`WeChatWorkNotificationDataKeys.AgentId`); 仅写入扩展方法被移除 | + +> **保留**: `XxxNotificationDataKeys`(数据契约)、 +> `NotificationDefinition` 的渠道扩展方法(定义侧 API, 如 `WithAgentId`、`WithTag`)、 +> 各渠道的 `NotificationDefinitionProvider`。 + +### 5.4 读取迁移对照表 + +| 旧扩展方法 | 新写法 | +|---|---| +| `data.GetSafe()` | `resolver.GetValue(data, WeChatWorkNotificationDataKeys.Safe, false)` | +| `data.GetEnableIdTrans()` / `GetEnableDuplicateCheck()` | `resolver.GetValue(data, WeChatWorkNotificationDataKeys.EnableIdTrans / EnableDuplicateCheck, false)` | +| `data.GetDuplicateCheckInterval()` | `resolver.GetValue(data, WeChatWorkNotificationDataKeys.DuplicateCheckInterval, 1800)` | +| `data.GetAgentIdOrNull()` / `GetTagOrNull()` / `GetPartyOrNull()` | `resolver.GetOrNull(data, WeChatWorkNotificationDataKeys.AgentId / ToTag / ToParty)` | +| `data.GetUrlOrNull()` (WxPusher) | `resolver.Resolve(data)?.Url` | +| `data.GetWebhookOrNull()` (PushPlus) | `resolver.Resolve(data)?.Webhook` | +| `data.GetCallbackUrlOrNull()` (PushPlus) | `resolver.Resolve(data)?.CallbackUrl` | +| `data.TryGetMessagePayload(key, out var m)` | `resolver.Resolve(data)` | + +--- + +## 6. 常见问题 + +| 现象 | 原因 | 处理 | +|---|---|---| +| 渠道没被调用 | 通知定义没声明该渠道名 | `WithProviders(...)` 或发送时传 `useProviders` | +| 载荷"写了但没生效" | 存在性判定把该键排除了(标了 `IgnoreWhenMatching`,或 `Presence` 与预期不符) | 检查 `Presence` 与 `IgnoreWhenMatching` 标注 | +| 启动即抛 `AbpNotificationChannelDataConfigurationException` | 未声明 `Presence` 且没有可匹配属性;或同渠道 `Priority` 重复;或缺 `[NotificationChannelData]` | 按异常信息修正 | +| 同时收到两条企业微信消息 | 写了多个载荷,每个都会发送 | 只保留一个载荷 | +| 模板卡片报 `abstract class and cannot be instantiated` | 抽象类型缺少 JSON 转换器 | 由 `AbpNotificationsWeChatWorkModule` 自动注册到 `AbpSystemTextJsonSerializerOptions`;手工构建容器时需自行注册 | +| 生产环境静默丢消息 | 载荷数据非法(解析失败) | 渠道侧用 `IsDeclared` + `Resolve` 组合明确报错;日志中会输出失败键名 | + +--- + +## 7. 单元测试 + +### 7.1 按模块拆分 + +测试项目与模块一一对应。**框架契约**与**具体渠道**分开测: + +| 测试项目 | 覆盖范围 | +|---|---| +| `tests/LINGYUN.Abp.Notifications.ChannelData.Tests` | **框架契约**: 弱类型转换、存在性判定(三种模式)、注册期校验、优先级排序、JSON 往返。用本文件内的 stub 载荷 | +| `tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests` | 企业微信**应用消息**渠道 | +| `tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests` | 企业微信 **Webhook** 渠道 | +| `tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests` | 微信小程序订阅消息渠道 | +| `tests/LINGYUN.Abp.Notifications.WxPusher.Tests` | WxPusher 渠道 | +| `tests/LINGYUN.Abp.Notifications.PushPlus.Tests` | PushPlus 渠道 | + +### 7.2 统一的测试写法 + +每个渠道测试都走同一条路径:**先 new 消息对象 → 通过 `IJsonSerializer` 序列化写入通知数据 → 渠道侧验证**。 + +```csharp +public class WeChatWorkChannelData_Tests : AbpNotificationsWeChatWorkTestsBase +{ + [Fact] + public void Should_Resolve_TextCard_Message() + { + // 1. 先 new 消息对象 + var message = new TextCardMessage( + title: "审批通过", + description: "您的请假申请已通过", + url: "https://example.com/leave/123", + buttonText: "去查看"); + + // 2. 经 IJsonSerializer 序列化写入通知数据的载荷键 + var data = WriteChannelData(new WeChatWorkTextCardChannelData { TextCard = message }); + + // 3. 渠道侧验证还原结果 + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.TextCard!.Title.ShouldBe(message.Title); + payload.TextCard.Url.ShouldBe(message.Url); + } +} +``` + +公共基类 `NotificationChannelDataTestsBase`(位于 +`tests/LINGYUN.Abp.Notifications.Tests`)提供: + +| 成员 | 说明 | +|---|---| +| `JsonSerializer` | ABP 的 `IJsonSerializer`,用于断言 JSON 契约 | +| `ChannelDataAccessor` | 生产侧写入(序列化) | +| `ChannelDataResolver` | 渠道侧解析 | +| `ChannelDataSerializer` | 生产者侧序列化器 | +| `Serialize(payload)` | 仅序列化,用于断言字段名契约 | +| `WriteChannelData(channelData)` | new → 序列化 → 写入,返回 `NotificationData` | +| `MergeChannelData(data, channelData)` | 合并多个载荷到同一份通知数据 | + +> 测试基座是真实的 ABP 集成测试(`AbpIntegratedTest`),因此 `IJsonSerializer` +> 就是生产环境那一份 —— 包含全局 JSON 策略与渠道注册的转换器。 +> 渠道的**真实发送**被替换为捕获式假实现(`FakeSubscribeMessager` / +> `FakeWxPusherMessageSender` / `FakePushPlusMessageSender`), +> 从而能断言"渠道最终发出的消息内容",而不真正调用第三方接口。 + +### 7.3 运行 + +```bash +# 全部 +dotnet test aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests +dotnet test aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests +dotnet test aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests +dotnet test aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests +dotnet test aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests +dotnet test aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests +``` diff --git a/aspnet-core/modules/realtime-notifications/CHANNEL-DATA.md b/aspnet-core/modules/realtime-notifications/CHANNEL-DATA.md new file mode 100644 index 000000000..bdc58606e --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/CHANNEL-DATA.md @@ -0,0 +1,375 @@ +# 通知渠道数据结构解析 + +面向 **发布渠道** 的强类型载荷(渠道数据)框架。 + +解决的核心问题: 生产者用弱类型属性包表达渠道专属语义时, +"写了键但渠道永远读不到"、"经持久化后配置静默失效"、"载荷类型靠字段探测顺序猜测"。 + +--- + +## 1. 问题背景 + +通知数据 `NotificationData` 底层是 `ExtraPropertyDictionary`(弱类型属性包), +在以下链路中必然经历 JSON 往返: + +| 链路 | 位置 | +|---|---| +| 持久化后回读 | `NotificationStore.InsertNotificationAsync` → `Notification.SetData` | +| 失败重试 | `NotificationPublishJob` 从存储读取后重新发布 | +| 跨进程投递 | `NotificationEto` 经 EventBus | + +JSON 往返后值的运行时类型会改变: + +``` +byte 1 -> long 1 / JsonElement(Number) +int 1 -> long 1 / JsonElement(Number) +``` + +因此旧实现中的裸转换会**永远失败且没有任何日志**: + +```csharp +// 写入 int, 读取 byte? —— as 操作符对 boxed int 恒返回 null +notificationData.TrySetData(Safe, safe ? 1 : 0); +var safe = notificationData.TryGetData(Safe) as byte?; // 永远是 null +``` + +受影响的选项: 企业微信 `safe`、`enable_id_trans`、`enable_duplicate_check`。 + +--- + +## 2. 设计原则 + +1. **全部通过依赖注入获取, 不提供静态 API** + —— 转换依赖 JSON 配置与日志, 静态入口会迫使框架维护一套"静态可用的降级实现", + 增加状态与初始化顺序的隐性耦合。 +2. **JSON 通过专用接口抽象**, 默认复用 ABP 全局配置。 +3. **存在性声明式表达 + 注册期强制校验**, 让配置错误在启动阶段暴露。 +4. **转换逻辑在读写两侧共用同一份实现**(`INotificationChannelDataAccessor`), + 避免"写入方与读取方规则不一致"。 + +--- + +## 3. 框架组成 + +### 3.1 契约 (`LINGYUN.Abp.Notifications.Core`, `ChannelData/` 子目录) + +| 文件 | 类型 | 作用 | +|---|---|---| +| `NotificationChannelData.cs` | `NotificationChannelData` | 载荷基类(空标记, 见 §4) | +| `NotificationChannelDataAttribute.cs` | `NotificationChannelDataAttribute` | 声明渠道、匹配顺序 `Priority`、存在性模式 `Presence` | +| `NotificationChannelDataPresenceMode.cs` | `NotificationChannelDataPresenceMode` | 存在性判定模式 (None / DeclaredProperties / AnyDeclaredProperty) | +| `NotificationChannelPropertyAttribute.cs` | `NotificationChannelPropertyAttribute` | 声明参与读写的属性; `Name` 兼容历史键; `IgnoreWhenMatching` 排除可选读取项 | +| `NotificationChannelDataFormat.cs` | `NotificationChannelDataFormat` | 属性存储格式 (Auto / Json) | +| `NotificationChannelDataDescriptor.cs` | `NotificationChannelDataDescriptor` | 载荷描述符 (只读元数据) | + +### 3.2 实现 (`LINGYUN.Abp.Notifications`, `ChannelData/` 子目录) + +每个类型单独一个文件(接口与实现分文件)。 + +| 接口 | 默认实现 | 作用 | +|---|---|---| +| `INotificationChannelDataJsonSerializer` | `AbpNotificationChannelDataJsonSerializer` | JSON 抽象, 默认委托 ABP `IJsonSerializer` | +| `INotificationChannelDataAccessor` | `NotificationChannelDataAccessor` | **弱类型转换 + JSON 的唯一实现**, 读写共用 | +| `INotificationChannelDataPresenceProvider` | `NotificationChannelDataPresenceProvider` | 存在性判定委托的创建与缓存(含注册期校验) | +| `INotificationChannelDataSerializer` | `NotificationChannelDataSerializer` | 生产者侧写入入口 | +| `INotificationChannelDataResolver` | `NotificationChannelDataResolver` | 渠道侧解析入口 | + +辅助类型: `AbpNotificationChannelDataOptions`(载荷注册)、 +`NotificationChannelDataDescriptorList`、`AbpNotificationChannelDataConfigurationException`、 +`NotificationChannelDataPresence`(存在性判定, 纯静态)、 +`NotificationChannelDataProperty` / `NotificationChannelDataPropertyCache`(属性元数据)、 +`NotificationChannelDataValueTypes`(值类型判定)。 + +### 3.3 注册方式: 模块 `PostConfigure<>` + +渠道模块在自己的 `AbpModule.ConfigureServices` 中声明载荷: + +```csharp +[DependsOn(typeof(AbpNotificationsModule))] +public class AbpNotificationsMyChannelModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.PublishProviders.Add(); + }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + }); + } +} +``` + +**为什么不需要额外的配置器类、也不存在顺序问题**: +`AbpNotificationChannelDataOptions` 是**纯数据**对象 —— 注册期的存在性校验只依赖 +载荷类型上的声明元数据(`[NotificationChannelData]` / `[NotificationChannelProperty]`), +不依赖任何服务。判定逻辑位于静态的 `NotificationChannelDataPresence`, +因此 `options.Add(...)` 在容器构建之前、以任意模块顺序调用都能正常工作。 + +对应地, 之前为"解析存在性提供者"而引入的 +`NotificationChannelDataPresenceConfigurer` 已删除, 选项对象上的 +`PresenceProvider` 属性也已移除。`INotificationChannelDataPresenceProvider` +保留为依赖注入形态的薄封装(委托给静态实现), 供解析器与序列化器使用。 + +--- + +## 4. 数据键命名约定 + +### 4.1 必须带本渠道前缀 + +所有渠道自有键统一使用 `<渠道前缀><键名>` 形式, 避免不同渠道的键在同一个 +通知数据属性包中相互冲突: + +| 渠道 | 前缀 | 键 | +|---|---|---| +| 企业微信 | `wx-work:` | `wx-work:text_card_message`、`wx-work:template_card_message`、`wx-work:safe` … | +| 企业微信 Webhook | `wx-work-hook:` | `wx-work-hook:text`、`wx-work-hook:markdown_v2`、`wx-work-hook:template_card` … | +| 微信小程序 | `wx-mp:` | `wx-mp:template_id`、`wx-mp:redirect_page`、`wx-mp:weapp_state`、`wx-mp:weapp_language` | +| WxPusher | `wx-pusher:` | `wx-pusher:url` | +| PushPlus | `push-plus:` | `push-plus:webhook`、`push-plus:callback` | + +> **渠道注册表键与键前缀都是独立命名空间**。企业微信应用消息与 Webhook 是两种传输方式、 +> 两套载体模型, 因此注册表键(`WeChat.Work` / `WeChat.Work.Webhook`)与键前缀 +> (`wx-work:` / `wx-work-hook:`)都必须分开 —— +> 否则同一个通知被两个渠道同时订阅时, 载荷会被两边都解析并各发一条。 + +每个渠道都以 `XxxNotificationDataKeys` 暴露常量, 并给出 `Prefix`: + +```csharp +public static class MyChannelNotificationDataKeys +{ + public const string Prefix = "my-channel:"; + + public const string TemplateId = Prefix + "template_id"; + public const string RedirectPage = Prefix + "redirect_page"; +} +``` + +> 唯一例外是**通知标准数据**的键(`title` / `message` / `description` / +> `formUser` / `createTime`), 它们由 `NotificationData.WriteStandardData` 定义, +> 属于所有渠道共用的通用约定, 不加前缀。 + +### 4.2 读取大小写不敏感 + +键匹配规则是**精确匹配优先, 未命中再忽略大小写**, +因此生产者使用 `wx-work:text_card_message`、`WX-WORK:TEXT_CARD_MESSAGE` +或 `Wx-Work:Text_Card_Message` 都能命中。 + +该规则在 `INotificationChannelDataAccessor.TryGetRawValue` 中统一实现, +`NotificationChannelDataPresence.ContainsKey` 使用同一规则, +保证"存在性判定"与"实际读取"不会出现规则不一致。 + +### 4.3 历史遗留的无前缀键 + +微信小程序渠道在早期版本使用了无前缀键(`TemplateId` 等)。 +为让已安装的生产者平滑升级, 这些键保留在 +`WeChatMiniProgramNotificationDataKeys.Legacy` 中, 由渠道在解析时**只读回退** +(带前缀的键优先), 并在命中遗留键时记录警告以推动迁移。 + +新代码请一律使用带前缀的常量。 + +### 4.4 一个数据对象中可共存多个渠道的键 + +不同前缀互不冲突, 因此同一个通知可以同时驱动多个渠道: + +```csharp +data.TrySetData(WeChatWorkNotificationDataKeys.ToParty, "1|2"); // 应用消息 +data.TrySetData(WeChatWorkWebhookNotificationDataKeys.Markdown, "# 告警"); // Webhook +``` + +各渠道只解析自己前缀的载荷, 不会互相干扰(见 §9)。 + +--- + +## 5. 存在性判定 + +**声明式存在性 + 注册期强制校验**: + +```csharp +public enum NotificationChannelDataPresenceMode +{ + None = 0, // 始终存在(不依赖通知数据) + DeclaredProperties = 1, // 参与匹配的属性全部存在(默认) + AnyDeclaredProperty = 2 // 参与匹配的属性存在任意一个 +} +``` + +校验规则(注册时执行, 即启动阶段): + +| 情况 | 结果 | +|---|---| +| 声明了按键判定, 却没有任何可匹配属性 | 抛 `AbpNotificationChannelDataConfigurationException` | +| 显式声明 `Presence = None` | 合法, 载荷始终存在 | +| 缺少 `[NotificationChannelData]` | 抛 `AbpNotificationChannelDataConfigurationException` | +| 同渠道 `Priority` 重复 | 抛 `AbpNotificationChannelDataConfigurationException` | + +这样"忘了定义存在性"从**静默丢消息**变成**启动即失败**。 + +--- + +## 6. JSON 序列化抽象 + +```csharp +public interface INotificationChannelDataJsonSerializer +{ + string Serialize(object value, Type valueType); + object? Deserialize(string json, Type targetType); +} + +[Dependency(TryRegister = true)] +public class AbpNotificationChannelDataJsonSerializer + : INotificationChannelDataJsonSerializer, ISingletonDependency +{ + protected IJsonSerializer JsonSerializer { get; } + + public string Serialize(object value, Type valueType) => JsonSerializer.Serialize(value); + + public object? Deserialize(string json, Type targetType) + => json.IsNullOrWhiteSpace() ? null : JsonSerializer.Deserialize(targetType, json); +} +``` + +复用到的全局能力: 驼峰策略、时间格式、枚举转换、 +`AbpSystemTextJsonSerializerModifiersOptions` 修饰器、自定义 Converter。 + +需要加密/压缩/私有格式时替换该接口实现即可。 + +> **注意**: 项目使用的 JSON 集成是 `Volo.Abp.Json.SystemTextJson`, +> 因此复杂载荷的 `JsonConverter` 必须实现 System.Text.Json 版本 +> (参见 `TemplateCardSystemTextJsonConverter`)。 + +--- + +## 7. 与 JSON 实现解耦 + +`NotificationChannelDataAccessor` 在转换前会**还原 JSON 中间表示**: + +| JSON 实现 | 属性包中的值 | +|---|---| +| System.Text.Json | `JsonElement` | +| Newtonsoft.Json | `JValue` / 原始 CLR 值 | + +两者都会先还原为 CLR 原始值(数字还原为最小可用数值类型), 再做弱类型转换。 +因此同一份逻辑在两种 JSON 实现下行为一致。 + +--- + +## 8. 生产者用法 + +### 8.1 声明载荷 + +```csharp +[NotificationChannelData(MyProvider.ProviderName, Priority = 100)] +public class MyChannelData : NotificationChannelData +{ + [NotificationChannelProperty("my:template_id")] + public string? TemplateId { get; set; } + + // 可选读取项: 不参与存在性判定 + [NotificationChannelProperty("my:page", IgnoreWhenMatching = true)] + public string? Page { get; set; } +} +``` + +### 8.2 在模块中注册 + +```csharp +[DependsOn(typeof(AbpNotificationsModule))] +public class AbpNotificationsMyChannelModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.PublishProviders.Add(); + }); + + Configure(options => + { + options.Add(); + }); + } +} +``` + +### 8.3 写入通知数据 + +```csharp +public class MyProducer +{ + private readonly INotificationChannelDataSerializer _channelDataSerializer; + + public MyProducer(INotificationChannelDataSerializer channelDataSerializer) + { + _channelDataSerializer = channelDataSerializer; + } + + public void Build(NotificationData data) + { + _channelDataSerializer.Write(data, new MyChannelData { TemplateId = "tpl-1" }); + } +} +``` + +--- + +## 9. 渠道用法 + +```csharp +public class MyProvider : NotificationPublishProvider +{ + protected INotificationChannelDataResolver ChannelDataResolver + => ServiceProvider.LazyGetRequiredService(); + + protected override Task PublishAsync(NotificationPublishContext context, CancellationToken ct) + { + var data = context.Notification.Data; + + // 按类型解析 + var payload = ChannelDataResolver.Resolve(data); + + // 区分"未写入"与"写入了但数据非法" + if (ChannelDataResolver.IsDeclared(data, typeof(MyChannelData)) && payload == null) + { + context.Cancel("The payload can not be parsed."); + return Task.CompletedTask; + } + + // 标量选项 + var safe = ChannelDataResolver.GetValue(data, "my:safe", false); + + return Task.CompletedTask; + } +} +``` + +--- + +## 10. 行为保证 + +| 场景 | 行为 | +|---|---| +| 未设置的值 | 返回 `null`(而不是被默认值吞掉), 可区分"未设置"与"显式 false/0" | +| JSON 往返后 | `byte`/`int`/`long`/`string`/`bool`/`JsonElement` 均可正确转换 | +| 键大小写不一致 | 大小写不敏感匹配, 兼容历史遗留键(如 `TemplateId`) | +| 数据非法 | 不抛异常; `Resolve` 返回 `null` 并记录警告日志, `IsDeclared` 仍为 `true` | +| 未声明存在性规则 | 注册期抛 `AbpNotificationChannelDataConfigurationException` | +| 缺少渠道特性 | 注册期抛 `AbpNotificationChannelDataConfigurationException` | +| 同渠道优先级冲突 | 注册期抛 `AbpNotificationChannelDataConfigurationException` | +| 载荷类型未映射消息载体 | 构造时抛 `AbpNotificationChannelDataConfigurationException`(快速失败) | + +--- + +## 11. 扩展新渠道的检查清单 + +1. 定义载荷类型并标注 `[NotificationChannelData]`; +2. 至少给一个"标识属性"标注 `[NotificationChannelProperty]`(可选读取项加 `IgnoreWhenMatching = true`); +3. 需要"任意一个键即可"时把 `Presence` 设为 `AnyDeclaredProperty`; 需要"始终存在"时设为 `None`; +4. 在本模块的 `Configure` 中注册载荷; +5. 渠道实现中**不要**出现 `as byte?` / `as int?` 这类裸转换, 改用 `INotificationChannelDataResolver`; +6. 需要区分"未声明"与"数据非法"时, 组合使用 `IsDeclared` 与 `Resolve`; +7. 抽象类型载荷需要注册 JSON 类型转换器(注意 JSON 实现: STJ 或 Newtonsoft)。 diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/AbpNotificationChannelDataConfigurationException.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/AbpNotificationChannelDataConfigurationException.cs new file mode 100644 index 000000000..9af1e842d --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/AbpNotificationChannelDataConfigurationException.cs @@ -0,0 +1,23 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据配置异常 +/// +/// +/// 注册期契约校验失败时抛出, 目的: 让配置错误在启动阶段暴露, +/// 而不是在生产环境静默丢弃通知。 +/// +public class AbpNotificationChannelDataConfigurationException : Exception +{ + public AbpNotificationChannelDataConfigurationException(string message) + : base(message) + { + } + + public AbpNotificationChannelDataConfigurationException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelData.cs new file mode 100644 index 000000000..41de9e5d2 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelData.cs @@ -0,0 +1,26 @@ +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)基类 +/// +/// +/// +/// 渠道数据是"发布渠道能理解的强类型数据结构", 生产者用它表达渠道专属语义, +/// 渠道实现用它解析出具体的消息载体。 +/// +/// +/// 派生类需要做两件事: +/// +/// +/// 用 声明渠道、匹配顺序与 +/// 存在性判定模式; +/// +/// +/// 用 标注参与读写的属性。 +/// +/// +/// +/// +public abstract class NotificationChannelData +{ +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAttribute.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAttribute.cs new file mode 100644 index 000000000..c2a771760 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAttribute.cs @@ -0,0 +1,56 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据契约 +/// +/// +/// +/// 渠道数据(载荷)是发布渠道与生产者之间约定的数据结构。 +/// 生产者通过 写入载荷, +/// 渠道通过 解析载荷。 +/// +/// +/// 载荷的存在性由 声明式表达, 结合 +/// 的键定义自动推导, +/// 无需在载荷类型中实现判定方法。 +/// +/// +/// 若既未声明 、又没有可参与匹配的属性, +/// 注册时会抛出 : +/// 让"忘了定义存在性"在启动阶段暴露, 而不是在生产环境静默丢弃通知。 +/// +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class NotificationChannelDataAttribute : Attribute +{ + /// + /// 渠道名称, 对应 + /// + public string ProviderName { get; } + + /// + /// 载荷在同一个渠道内的匹配顺序, 数值越小越先匹配 + /// + /// + /// 用于表达渠道内的显式规则, 匹配顺序必须声明, + /// 不允许依赖注册顺序或字段探测顺序。 + /// + public int Priority { get; set; } + + /// + /// 存在性判定模式, 默认按"参与匹配的属性全部存在"判定 + /// + public NotificationChannelDataPresenceMode Presence { get; set; } = NotificationChannelDataPresenceMode.DeclaredProperties; + + public NotificationChannelDataAttribute(string providerName) + { + if (providerName.IsNullOrWhiteSpace()) + { + throw new ArgumentException("The provider name of the channel data can not be null or whitespace.", nameof(providerName)); + } + + ProviderName = providerName; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptor.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptor.cs new file mode 100644 index 000000000..fbe70dc6e --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptor.cs @@ -0,0 +1,53 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)描述符 +/// +public sealed class NotificationChannelDataDescriptor +{ + /// + /// 渠道名称 + /// + public string ProviderName { get; } + + /// + /// 载荷类型 + /// + public Type PayloadType { get; } + + /// + /// 匹配顺序, 数值越小越先匹配 + /// + public int Priority { get; } + + /// + /// 存在性判定模式 + /// + public NotificationChannelDataPresenceMode Presence { get; } + + /// + /// 判断通知数据中是否存在本载荷 + /// + public Func IsPresent { get; } + + public NotificationChannelDataDescriptor( + string providerName, + Type payloadType, + int priority, + NotificationChannelDataPresenceMode presence, + Func isPresent) + { + ProviderName = providerName; + PayloadType = payloadType; + Priority = priority; + Presence = presence; + IsPresent = isPresent; + } + + public override string ToString() + { + return $"{ProviderName}:{PayloadType.Name}(Priority={Priority}, Presence={Presence})"; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataFormat.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataFormat.cs new file mode 100644 index 000000000..7df1a0e34 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataFormat.cs @@ -0,0 +1,20 @@ +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)属性的存储格式 +/// +public enum NotificationChannelDataFormat +{ + /// + /// 自动识别(默认) + /// + /// + /// 简单类型直接转换, 复杂类型序列化为 JSON 字符串, + /// 读取时同样兼容"对象实例"与"JSON 字符串"两种形态。 + /// + Auto = 0, + /// + /// 始终以 JSON 字符串存储 + /// + Json = 1 +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceMode.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceMode.cs new file mode 100644 index 000000000..2db910e6b --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceMode.cs @@ -0,0 +1,32 @@ +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据(载荷)存在性判定模式 +/// +public enum NotificationChannelDataPresenceMode +{ + /// + /// 载荷始终被视为存在 + /// + /// + /// 适用于不依赖通知数据的载荷(由渠道在运行时构造)。 + /// + None = 0, + + /// + /// 参与匹配的属性全部存在时, 载荷被视为存在(默认) + /// + /// + /// 适用于"某个键就是载荷标识"的场景, 例如企业微信的各消息类型。 + /// + DeclaredProperties = 1, + + /// + /// 参与匹配的属性存在任意一个时, 载荷被视为存在 + /// + /// + /// 适用于"多个可选键中任意一个即可"的场景, + /// 例如 PushPlus 的 webhook 与 callback 二者其一。 + /// + AnyDeclaredProperty = 2 +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelPropertyAttribute.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelPropertyAttribute.cs new file mode 100644 index 000000000..1a01369f4 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelPropertyAttribute.cs @@ -0,0 +1,44 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 标记通知渠道数据(载荷)的属性参与类型化读写 +/// +/// +/// +/// 参与读写的属性名称默认取属性名, 也可以通过 显式指定, +/// 以便兼容历史遗留的通知数据键(例如 TemplateId 这类未加前缀的键)。 +/// +/// +/// 读写过程会做弱类型转换, 因此数据无论经历过多少次 +/// JSON 序列化/反序列化(持久化、失败重试、跨进程投递)都不会丢失。 +/// +/// +[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] +public sealed class NotificationChannelPropertyAttribute : Attribute +{ + /// + /// 通知数据中的键名, 为空时取属性名 + /// + public string? Name { get; } + + /// + /// 匹配载荷时是否忽略本属性 + /// + /// + /// 适用于"投递选项"这类不决定载荷形态的属性, + /// 例如企业微信的接收人(to_user/toparty/totag)。 + /// 投递选项单独存在时不代表某个消息载荷存在。 + /// + public bool IgnoreWhenMatching { get; set; } + + public NotificationChannelPropertyAttribute() + { + } + + public NotificationChannelPropertyAttribute(string name) + { + Name = name; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusModule.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusModule.cs index aa1c2e6ff..0de385610 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusModule.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusModule.cs @@ -1,4 +1,4 @@ -using LINGYUN.Abp.PushPlus; +using LINGYUN.Abp.PushPlus; using Volo.Abp.Modularity; namespace LINGYUN.Abp.Notifications.PushPlus; @@ -14,5 +14,11 @@ public class AbpNotificationsPushPlusModule : AbpModule { options.PublishProviders.Add(); }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + }); } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData.cs new file mode 100644 index 000000000..67e82a927 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData.cs @@ -0,0 +1,30 @@ +using LINGYUN.Abp.Notifications; + +namespace LINGYUN.Abp.Notifications.PushPlus; + +/// +/// PushPlus 渠道数据(载荷) +/// +/// +/// webhook 与 callback 是"可选参数"而非互斥的"载荷标识": +/// 写入其中任意一个即表示生产者要使用 PushPlus 渠道, +/// 因此存在性判定模式声明为 。 +/// +[NotificationChannelData( + PushPlusNotificationPublishProvider.ProviderName, + Priority = 100, + Presence = NotificationChannelDataPresenceMode.AnyDeclaredProperty)] +public class PushPlusChannelData : NotificationChannelData +{ + /// + /// webhook 地址 + /// + [NotificationChannelProperty(PushPlusNotificationDataKeys.Webhook)] + public virtual string? Webhook { get; set; } + + /// + /// 回调地址 + /// + [NotificationChannelProperty(PushPlusNotificationDataKeys.CallbackUrl)] + public virtual string? CallbackUrl { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationDataKeys.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationDataKeys.cs new file mode 100644 index 000000000..a28153702 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationDataKeys.cs @@ -0,0 +1,18 @@ +namespace LINGYUN.Abp.Notifications.PushPlus; + +/// +/// PushPlus 通知数据键 +/// +public static class PushPlusNotificationDataKeys +{ + public const string Prefix = "push-plus:"; + + /// + /// webhook 地址 + /// + public const string Webhook = Prefix + "webhook"; + /// + /// 回调地址 + /// + public const string CallbackUrl = Prefix + "callback"; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationPublishProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationPublishProvider.cs index 4b5c417b1..489ee0f2e 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationPublishProvider.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationPublishProvider.cs @@ -1,4 +1,4 @@ -using LINGYUN.Abp.PushPlus.Channel; +using LINGYUN.Abp.PushPlus.Channel; using LINGYUN.Abp.PushPlus.Features; using LINGYUN.Abp.PushPlus.Message; using Microsoft.Extensions.Logging; @@ -20,6 +20,7 @@ public class PushPlusNotificationPublishProvider : NotificationPublishProvider protected IPushPlusMessageSender PushPlusMessageSender => ServiceProvider.LazyGetRequiredService(); protected INotificationDataSerializer NotificationDataSerializer => ServiceProvider.LazyGetRequiredService(); protected INotificationDefinitionManager NotificationDefinitionManager => ServiceProvider.LazyGetRequiredService(); + protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService(); protected async override Task CanPublishAsync(NotificationInfo notification, CancellationToken cancellationToken = default) { @@ -50,8 +51,9 @@ public class PushPlusNotificationPublishProvider : NotificationPublishProvider ?? PushPlusChannelType.Email; var template = notificationDefine?.GetTemplateOrDefault(PushPlusMessageTemplate.Text) ?? PushPlusMessageTemplate.Text; - var webhook = context.Notification.Data.GetWebhookOrNull() ?? ""; - var callbackUrl = context.Notification.Data.GetCallbackUrlOrNull() ?? ""; + var channelData = ChannelDataResolver.Resolve(context.Notification.Data); + var webhook = channelData?.Webhook ?? ""; + var callbackUrl = channelData?.CallbackUrl ?? ""; var notificationData = await NotificationDataSerializer.ToStandard(context.Notification.Data); await PushPlusMessageSender.SendWithChannelAsync( diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramModule.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramModule.cs index bf6da3bde..9bf570bdf 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramModule.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramModule.cs @@ -1,4 +1,4 @@ -using LINGYUN.Abp.WeChat.MiniProgram; +using LINGYUN.Abp.WeChat.MiniProgram; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; @@ -22,5 +22,11 @@ public class AbpNotificationsWeChatMiniProgramModule : AbpModule { options.PublishProviders.Add(); }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + }); } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationDataKeys.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationDataKeys.cs new file mode 100644 index 000000000..228abbedb --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationDataKeys.cs @@ -0,0 +1,100 @@ +using System; + +namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram; + +/// +/// 微信小程序通知数据键 +/// +/// +/// +/// 键名统一带本渠道前缀(), 与其它渠道保持一致, +/// 避免不同渠道的键在同一个通知数据属性包中相互冲突。 +/// +/// +/// 读取过程大小写不敏感(精确匹配优先), 因此生产者使用任意大小写都能命中。 +/// +/// +public static class WeChatMiniProgramNotificationDataKeys +{ + /// + /// 本渠道的数据键前缀 + /// + public const string Prefix = "wx-mp:"; + + /// + /// 小程序模板标识(载荷标识键) + /// + public const string TemplateId = Prefix + "template_id"; + + /// + /// 点击跳转的小程序页面 + /// + public const string RedirectPage = Prefix + "redirect_page"; + + /// + /// 跳转小程序类型 + /// + public const string WeAppState = Prefix + "weapp_state"; + + /// + /// 小程序语言 + /// + public const string WeAppLanguage = Prefix + "weapp_language"; + + /// + /// 历史遗留的无前缀键 + /// + /// + /// + /// 早期版本使用无前缀键, 已安装的生产者可能仍在写入, 因此保留**只读兼容**。 + /// + /// + /// 已弃用: 新代码请使用带前缀的常量( 等)。 + /// 唯一允许的读取点是渠道侧的历史回退 + /// (WeChatMiniProgramNotificationPublishProvider.ApplyLegacyKeys), + /// 它命中遗留键时会记录告警以推动生产者迁移。 + /// + /// + [Obsolete("The legacy non-prefixed keys are deprecated. Use the prefixed constants instead, for example WeChatMiniProgramNotificationDataKeys.TemplateId. They are kept for read-only fallback to remain compatible with already deployed producers.")] + public static class Legacy + { +#pragma warning disable CS0618 // Type or member is obsolete: the nested class references its own members + + /// + /// 历史: 小程序模板标识 + /// + [Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.TemplateId instead.")] + public const string TemplateId = "TemplateId"; + + /// + /// 历史: 点击跳转的小程序页面 + /// + [Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.RedirectPage instead.")] + public const string RedirectPage = "RedirectPage"; + + /// + /// 历史: 跳转小程序类型 + /// + [Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.WeAppState instead.")] + public const string WeAppState = "WeAppState"; + + /// + /// 历史: 小程序语言 + /// + [Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.WeAppLanguage instead.")] + public const string WeAppLanguage = "WeAppLanguage"; + + /// + /// 全部历史键 + /// + public static readonly string[] All = + { + TemplateId, + RedirectPage, + WeAppState, + WeAppLanguage + }; + +#pragma warning restore CS0618 + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationPublishProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationPublishProvider.cs index 3bbbefc6d..22d39827b 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationPublishProvider.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationPublishProvider.cs @@ -1,4 +1,4 @@ -using LINGYUN.Abp.WeChat.Common.Security.Claims; +using LINGYUN.Abp.WeChat.Common.Security.Claims; using LINGYUN.Abp.WeChat.MiniProgram.Features; using LINGYUN.Abp.WeChat.MiniProgram.Messages; using Microsoft.Extensions.Logging; @@ -14,6 +14,10 @@ namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram; /// /// 微信小程序消息推送提供者 /// +/// +/// 小程序订阅消息的模板数据本身就是动态键值对, 因此载荷只声明标量字段, +/// 模板数据仍然直接取自通知数据的属性包。 +/// public class WeChatMiniProgramNotificationPublishProvider : NotificationPublishProvider { public const string ProviderName = NotificationProviderNames.WechatMiniProgram; @@ -21,6 +25,7 @@ public class WeChatMiniProgramNotificationPublishProvider : NotificationPublishP protected IFeatureChecker FeatureChecker => ServiceProvider.LazyGetRequiredService(); protected ISubscribeMessager SubscribeMessager => ServiceProvider.LazyGetRequiredService(); protected IOptions Options => ServiceProvider.LazyGetRequiredService>(); + protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService(); protected async override Task CanPublishAsync(NotificationInfo notification, CancellationToken cancellationToken = default) { @@ -39,53 +44,50 @@ public class WeChatMiniProgramNotificationPublishProvider : NotificationPublishP protected async override Task PublishAsync(NotificationPublishContext context, CancellationToken cancellationToken = default) { - // step1 默认微信openid绑定的就是username, - // 如果不是,需要自行处理openid获取逻辑 - - // step2 调用微信消息推送接口 - // 微信不支持推送到所有用户 // 在小程序里用户订阅消息后通过 api/subscribes/subscribe 接口订阅对应模板消息 + var channelData = ResolveChannelData(context.Notification.Data); + foreach (var identifier in context.Users) { - var templateId = GetOrDefaultTemplateId(context.Notification.Data); - if (templateId.IsNullOrWhiteSpace()) + if (channelData.TemplateId.IsNullOrWhiteSpace()) { context.Cancel("Wechat weapp template id be empty, can not send notification!"); Logger.LogWarning(context.Reason); continue; } - Logger.LogDebug($"Get wechat weapp template id: {templateId}"); - - var redirect = GetOrDefault(context.Notification.Data, "RedirectPage", ""); - Logger.LogDebug($"Get wechat weapp redirect page: {redirect ?? "null"}"); + Logger.LogDebug($"Get wechat weapp template id: {channelData.TemplateId}"); - var weAppState = GetOrDefault(context.Notification.Data, "WeAppState", Options.Value.DefaultState); - Logger.LogDebug($"Get wechat weapp state: {weAppState ?? null}"); - - var weAppLang = GetOrDefault(context.Notification.Data, "WeAppLanguage", Options.Value.DefaultLanguage); - Logger.LogDebug($"Get wechat weapp language: {weAppLang ?? null}"); + Logger.LogDebug($"Get wechat weapp redirect page: {channelData.RedirectPage ?? "null"}"); + Logger.LogDebug($"Get wechat weapp state: {channelData.WeAppState ?? null}"); + Logger.LogDebug($"Get wechat weapp language: {channelData.WeAppLanguage ?? null}"); // TODO: 如果微信端发布通知,请组装好 openid 字段在通知数据内容里面 - var openId = GetOrDefault(context.Notification.Data, AbpWeChatClaimTypes.OpenId, ""); + var openId = ChannelDataResolver.GetOrNull(context.Notification.Data, AbpWeChatClaimTypes.OpenId); if (openId.IsNullOrWhiteSpace()) { // 发送小程序订阅消息 await SubscribeMessager .SendAsync( - identifier.UserId, - templateId, - redirect, - weAppLang, - weAppState, - context.Notification.Data.ExtraProperties, + identifier.UserId, + channelData.TemplateId!, + channelData.RedirectPage, + channelData.WeAppLanguage, + channelData.WeAppState, + context.Notification.Data.ExtraProperties, cancellationToken); } else { - var weChatWeAppNotificationData = new SubscribeMessage(openId, templateId, redirect, weAppState, weAppLang); + var weChatWeAppNotificationData = new SubscribeMessage( + openId, + channelData.TemplateId!, + channelData.RedirectPage, + channelData.WeAppState, + channelData.WeAppLanguage); + // 写入模板数据 weChatWeAppNotificationData.WriteData(context.Notification.Data.ExtraProperties); @@ -99,19 +101,83 @@ public class WeChatMiniProgramNotificationPublishProvider : NotificationPublishP } } - protected string GetOrDefaultTemplateId(NotificationData data) + /// + /// 解析小程序渠道数据 + /// + /// + /// 键名带本渠道前缀, 读取大小写不敏感; + /// 为了让已安装的生产者平滑升级, 这里对历史遗留的**无前缀键**做只读回退; + /// 缺省值来自渠道配置。 + /// + protected virtual WeChatMiniProgramSubscribeChannelData ResolveChannelData(NotificationData notificationData) + { + var channelData = ChannelDataResolver.Resolve(notificationData) + ?? new WeChatMiniProgramSubscribeChannelData(); + + // 历史遗留的无前缀键只读回退 + ApplyLegacyKeys(channelData, notificationData); + + if (channelData.TemplateId.IsNullOrWhiteSpace()) + { + channelData.TemplateId = Options.Value.DefaultTemplateId; + } + if (channelData.WeAppState.IsNullOrWhiteSpace()) + { + channelData.WeAppState = Options.Value.DefaultState; + } + if (channelData.WeAppLanguage.IsNullOrWhiteSpace()) + { + channelData.WeAppLanguage = Options.Value.DefaultLanguage; + } + + return channelData; + } + + /// + /// 回退读取历史遗留的无前缀键 + /// + /// + /// + /// 早期版本使用 TemplateId 这类无前缀键, 已安装的生产者可能仍在写入。 + /// 带前缀的键优先; 命中遗留键时记录一次警告以便推动迁移。 + /// + /// +#pragma warning disable CS0618 // Type or member is obsolete: the only sanctioned read site for legacy keys + protected virtual void ApplyLegacyKeys( + WeChatMiniProgramSubscribeChannelData channelData, + NotificationData notificationData) { - return GetOrDefault(data, "TemplateId", Options.Value.DefaultTemplateId); + if (channelData.TemplateId.IsNullOrWhiteSpace()) + { + channelData.TemplateId = ReadLegacy(notificationData, WeChatMiniProgramNotificationDataKeys.Legacy.TemplateId); + } + if (channelData.RedirectPage.IsNullOrWhiteSpace()) + { + channelData.RedirectPage = ReadLegacy(notificationData, WeChatMiniProgramNotificationDataKeys.Legacy.RedirectPage); + } + if (channelData.WeAppState.IsNullOrWhiteSpace()) + { + channelData.WeAppState = ReadLegacy(notificationData, WeChatMiniProgramNotificationDataKeys.Legacy.WeAppState); + } + if (channelData.WeAppLanguage.IsNullOrWhiteSpace()) + { + channelData.WeAppLanguage = ReadLegacy(notificationData, WeChatMiniProgramNotificationDataKeys.Legacy.WeAppLanguage); + } } +#pragma warning restore CS0618 - protected string GetOrDefault(NotificationData data, string key, string defaultValue) + private string? ReadLegacy(NotificationData notificationData, string legacyKey) { - if (data.ExtraProperties.TryGetValue(key, out var value) && value != null) + var value = ChannelDataResolver.GetOrNull(notificationData, legacyKey); + if (!value.IsNullOrWhiteSpace()) { - // 取得了数据就删除对应键值 - // data.Properties.Remove(key); - return value.ToString()!; + Logger.LogWarning( + "The wechat mini program notification data is using the legacy key '{LegacyKey}' without channel prefix. " + + "Please migrate to the prefixed key '{Prefix}...'.", + legacyKey, + WeChatMiniProgramNotificationDataKeys.Prefix); } - return defaultValue; + + return value; } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramSubscribeChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramSubscribeChannelData.cs new file mode 100644 index 000000000..7ed73aa56 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramSubscribeChannelData.cs @@ -0,0 +1,50 @@ +using LINGYUN.Abp.Notifications; + +namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram; + +/// +/// 微信小程序渠道数据(载荷) +/// +/// +/// +/// 小程序订阅消息的载荷是"广播式"的: 除模板标识与跳转参数外, +/// 模板数据(data)直接来自通知数据的属性包, 因此这里只声明 +/// 需要类型化读取的标量字段。 +/// +/// +/// 键名带本渠道前缀(), +/// 读取大小写不敏感; 存在性由模板标识键推导, 因此把跳转参数声明为 +/// "仅读取、不参与匹配" —— 生产者可能只写模板标识。 +/// +/// +/// 历史遗留的无前缀键由渠道在解析时回退读取(见 +/// WeChatMiniProgramNotificationPublishProvider.ResolveChannelData)。 +/// +/// +[NotificationChannelData(WeChatMiniProgramNotificationPublishProvider.ProviderName, Priority = 100)] +public class WeChatMiniProgramSubscribeChannelData : NotificationChannelData +{ + /// + /// 小程序模板标识(载荷标识键) + /// + [NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.TemplateId)] + public virtual string? TemplateId { get; set; } + + /// + /// 点击跳转的小程序页面 + /// + [NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.RedirectPage, IgnoreWhenMatching = true)] + public virtual string? RedirectPage { get; set; } + + /// + /// 跳转小程序类型 + /// + [NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.WeAppState, IgnoreWhenMatching = true)] + public virtual string? WeAppState { get; set; } + + /// + /// 小程序语言 + /// + [NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.WeAppLanguage, IgnoreWhenMatching = true)] + public virtual string? WeAppLanguage { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkModule.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkModule.cs index b40f9b578..9a364280b 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkModule.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkModule.cs @@ -1,5 +1,7 @@ -using LINGYUN.Abp.WeChat.Work; +using LINGYUN.Abp.WeChat.Work; using LINGYUN.Abp.WeChat.Work.Localization; +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Volo.Abp.Json.SystemTextJson; using Volo.Abp.Localization; using Volo.Abp.Modularity; using Volo.Abp.VirtualFileSystem; @@ -29,5 +31,29 @@ public class AbpNotificationsWeChatWorkModule : AbpModule { options.PublishProviders.Add(); }); + + // 模板卡片是抽象类型: 注册类型转换器, 使其能在渠道数据(JSON)中往返 + Configure(options => + { + options.JsonSerializerOptions.Converters.Add(new TemplateCardSystemTextJsonConverter()); + }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + }); + + // 消息载体工厂分派 + Configure(options => + { + options.MapDefaultMessageFactories(); + }); } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/AbpWeChatWorkNotificationMessageOptions.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/AbpWeChatWorkNotificationMessageOptions.cs new file mode 100644 index 000000000..95173f755 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/AbpWeChatWorkNotificationMessageOptions.cs @@ -0,0 +1,79 @@ +using LINGYUN.Abp.WeChat.Work.Messages; +using System; +using System.Collections.Generic; +using Volo.Abp; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信消息构造选项 +/// +/// +/// +/// 渠道数据的形态到消息载体的转换集中注册在这里, 新增一种消息类型只需要 +/// options.Map(kind, factory), 不需要修改 Provider 的发布逻辑。 +/// +/// +/// 相比旧的 if/else 探测链, 这里的分派是 O(1) 且显式的: +/// 载荷类型与工厂键不一致时会直接抛出异常, 而不是静默发出错误的消息。 +/// +/// +public class AbpWeChatWorkNotificationMessageOptions +{ + private readonly Dictionary> _factories + = new Dictionary>(); + + /// + /// 已注册的消息类型 + /// + public IReadOnlyCollection MessageKinds => _factories.Keys; + + /// + /// 注册消息构造工厂 + /// + public AbpWeChatWorkNotificationMessageOptions Map( + WeChatWorkMessageKind kind, + Func factory) + { + Check.NotNull(factory, nameof(factory)); + + _factories[kind] = factory; + + return this; + } + + /// + /// 构造消息载体 + /// + public WeChatWorkMessageFactoryResult Create(WeChatWorkMessageFactoryContext context) + { + Check.NotNull(context, nameof(context)); + + var kind = context.ChannelData.Kind; + + if (!_factories.TryGetValue(kind, out var factory)) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work message kind '{kind}' has not been mapped, please call '{nameof(Map)}' when configuring '{nameof(AbpWeChatWorkNotificationMessageOptions)}'."); + } + + var result = factory(context); + if (result == null || result.Message == null) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The factory of the WeChat Work message kind '{kind}' returned an empty message."); + } + + return result; + } + + /// + /// 获取已注册的工厂 + /// + public bool TryGetFactory( + WeChatWorkMessageKind kind, + out Func? factory) + { + return _factories.TryGetValue(kind, out factory); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkChannelData.cs new file mode 100644 index 000000000..e59810f9f --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkChannelData.cs @@ -0,0 +1,21 @@ +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信渠道数据(载荷)基类 +/// +/// +/// 每个载荷对应一种企业微信消息载体, 通过 显式声明形态, +/// 渠道侧使用工厂字典做 O(1) 分派, 不再依赖 if/else 探测顺序。 +/// +/// 存在性由 声明式推导: +/// 每个载荷都只有一个"标识键", 因此默认的"参与匹配的属性全部存在"即为正确语义, +/// 无需在载荷类型中实现判定方法。 +/// +/// +public abstract class WeChatWorkChannelData : NotificationChannelData +{ + /// + /// 消息载体类型 + /// + public abstract WeChatWorkMessageKind Kind { get; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkFileChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkFileChannelData.cs new file mode 100644 index 000000000..dad94b361 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkFileChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 文件消息载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 700)] +public class WeChatWorkFileChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.File; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.FileMessage)] + public virtual MediaMessage? File { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMarkdownChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMarkdownChannelData.cs new file mode 100644 index 000000000..2880f0b2c --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMarkdownChannelData.cs @@ -0,0 +1,18 @@ +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// markdown消息载荷 +/// +/// +/// 不参与渠道解析: 由通知定义的 ContentType 推导, +/// 生产者不需要为它准备任何渠道专属数据。 +/// +public class WeChatWorkMarkdownChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Markdown; + + /// + /// 消息内容, 为空时使用通知标准数据 + /// + public virtual string? Content { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactory.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactory.cs new file mode 100644 index 000000000..0b4df8caf --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactory.cs @@ -0,0 +1,326 @@ +using LINGYUN.Abp.WeChat.Work.Messages; +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using System; +using Volo.Abp; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信默认消息构造工厂 +/// +/// +/// +/// 每一种渠道数据(载荷)与消息载体的映射都是显式的, 新增消息类型只需追加一个 +/// Map 调用, 不需要修改 Provider 的发布逻辑。 +/// +/// +/// 企业微信各消息载体支持的选项并不一致, 因此按具体载体类型分别重载, +/// 由编译器保证只设置载体真正支持的字段, 而不是像旧实现那样无差别赋值。 +/// +/// +public static class WeChatWorkMessageFactoryExtensions +{ + /// + /// 注册内置的消息构造工厂 + /// + public static AbpWeChatWorkNotificationMessageOptions MapDefaultMessageFactories( + this AbpWeChatWorkNotificationMessageOptions options) + { + Check.NotNull(options, nameof(options)); + + options.Map(WeChatWorkMessageKind.MiniProgramNotice, context => + { + var channelData = Cast(context); + var miniProgram = channelData.MiniProgram + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work mini program notice of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply( + new WeChatWorkMiniProgramMessage( + miniProgram, + context.Contact.ToUser ?? string.Empty, + context.Contact.ToParty ?? string.Empty, + context.Contact.ToTag ?? string.Empty), + context), + WeChatWorkMessageKind.MiniProgramNotice); + }); + + options.Map(WeChatWorkMessageKind.MpNews, context => + { + var channelData = Cast(context); + var mpNewMessage = channelData.MpNewMessage + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work mp news of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkMpNewMessage(context.Options.AgentId, mpNewMessage), context), + WeChatWorkMessageKind.MpNews); + }); + + options.Map(WeChatWorkMessageKind.TemplateCard, context => + { + var channelData = Cast(context); + var templateCard = channelData.TemplateCard + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work template card of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkTemplateCardMessage(context.Options.AgentId, templateCard), context), + WeChatWorkMessageKind.TemplateCard); + }); + + options.Map(WeChatWorkMessageKind.TextCard, context => + { + var channelData = Cast(context); + var textCard = channelData.TextCard + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work text card of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkTextCardMessage(context.Options.AgentId, textCard), context), + WeChatWorkMessageKind.TextCard); + }); + + options.Map(WeChatWorkMessageKind.Video, context => + { + var channelData = Cast(context); + var video = channelData.Video + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work video of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkVideoMessage(context.Options.AgentId, video), context), + WeChatWorkMessageKind.Video); + }); + + options.Map(WeChatWorkMessageKind.Voice, context => + { + var channelData = Cast(context); + var voice = channelData.Voice + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work voice of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkVoiceMessage(context.Options.AgentId, voice), context), + WeChatWorkMessageKind.Voice); + }); + + options.Map(WeChatWorkMessageKind.File, context => + { + var channelData = Cast(context); + var file = channelData.File + ?? throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work file of notification '{context.Notification.Name}' is empty."); + + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkFileMessage(context.Options.AgentId, file), context), + WeChatWorkMessageKind.File); + }); + + options.Map(WeChatWorkMessageKind.Text, context => + { + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkTextMessage(context.Options.AgentId, new TextMessage(GetContent(context))), context), + WeChatWorkMessageKind.Text); + }); + + options.Map(WeChatWorkMessageKind.Markdown, context => + { + return WeChatWorkMessageFactoryResult.Create( + Apply(new WeChatWorkMarkdownMessage(context.Options.AgentId, new MarkdownMessage(GetContent(context))), context), + WeChatWorkMessageKind.Markdown); + }); + + return options; + } + + private static TChannelData Cast(WeChatWorkMessageFactoryContext context) + where TChannelData : WeChatWorkChannelData + { + if (context.ChannelData is not TChannelData channelData) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The channel data '{context.ChannelData.GetType().FullName}' of notification '{context.Notification.Name}' does not match the registered factory '{typeof(TChannelData).FullName}'."); + } + + return channelData; + } + + private static string GetContent(WeChatWorkMessageFactoryContext context) + { + if (context.ChannelData is WeChatWorkTextChannelData textChannelData && + !textChannelData.Content.IsNullOrWhiteSpace()) + { + return textChannelData.Content!; + } + + if (context.ChannelData is WeChatWorkMarkdownChannelData markdownChannelData && + !markdownChannelData.Content.IsNullOrWhiteSpace()) + { + return markdownChannelData.Content!; + } + + return context.StandardData.Message; + } + + /// + /// 应用接收者 + /// + private static TMessage ApplyContact(TMessage message, WeChatWorkMessageFactoryContext context) + where TMessage : WeChatWorkMessage + { + if (!context.Contact.IsEmpty()) + { + message.ToUser = context.Contact.ToUser; + message.ToParty = context.Contact.ToParty; + message.ToTag = context.Contact.ToTag; + } + + return message; + } + + /// + /// 文本消息: 支持 safe、enable_id_trans、enable_duplicate_check + /// + private static WeChatWorkTextMessage Apply( + WeChatWorkTextMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.Safe = context.Options.SafeValue; + message.EnableIdTrans = context.Options.EnableIdTransValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 图文消息: 支持 safe、enable_id_trans、enable_duplicate_check + /// + private static WeChatWorkMpNewMessage Apply( + WeChatWorkMpNewMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.Safe = context.Options.SafeValue; + message.EnableIdTrans = context.Options.EnableIdTransValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 文件消息: 支持 safe、enable_duplicate_check, 不支持 enable_id_trans + /// + private static WeChatWorkFileMessage Apply( + WeChatWorkFileMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.Safe = context.Options.SafeValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 视频消息: 支持 safe、enable_duplicate_check, 不支持 enable_id_trans + /// + private static WeChatWorkVideoMessage Apply( + WeChatWorkVideoMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.Safe = context.Options.SafeValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 语音消息: 不支持 safe, 也不支持 enable_id_trans + /// + private static WeChatWorkVoiceMessage Apply( + WeChatWorkVoiceMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// markdown消息: 支持 enable_duplicate_check, 不支持 safe + /// + private static WeChatWorkMarkdownMessage Apply( + WeChatWorkMarkdownMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 文本卡片消息: 不支持 safe + /// + private static WeChatWorkTextCardMessage Apply( + WeChatWorkTextCardMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.EnableIdTrans = context.Options.EnableIdTransValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 模板卡片消息: 不支持 safe + /// + private static WeChatWorkTemplateCardMessage Apply( + WeChatWorkTemplateCardMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.EnableIdTrans = context.Options.EnableIdTransValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } + + /// + /// 小程序通知消息: 不支持 safe + /// + private static WeChatWorkMiniProgramMessage Apply( + WeChatWorkMiniProgramMessage message, + WeChatWorkMessageFactoryContext context) + { + ApplyContact(message, context); + + message.EnableIdTrans = context.Options.EnableIdTransValue; + message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue; + message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue; + + return message; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryContext.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryContext.cs new file mode 100644 index 000000000..8e681b58e --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryContext.cs @@ -0,0 +1,48 @@ +using LINGYUN.Abp.WeChat.Work.Messages; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信消息构造上下文 +/// +public class WeChatWorkMessageFactoryContext +{ + /// + /// 通知消息 + /// + public NotificationInfo Notification { get; } + + /// + /// 通知标准数据(已完成本地化与模板渲染) + /// + public NotificationStandardData StandardData { get; } + + /// + /// 渠道数据(载荷) + /// + public WeChatWorkChannelData ChannelData { get; } + + /// + /// 消息接收者 + /// + public WeChatWorkNotificationContact Contact { get; } + + /// + /// 消息公共选项 + /// + public WeChatWorkMessageOptions Options { get; } + + public WeChatWorkMessageFactoryContext( + NotificationInfo notification, + NotificationStandardData standardData, + WeChatWorkChannelData channelData, + WeChatWorkNotificationContact contact, + WeChatWorkMessageOptions options) + { + Notification = notification; + StandardData = standardData; + ChannelData = channelData; + Contact = contact; + Options = options; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryResult.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryResult.cs new file mode 100644 index 000000000..fe24511d3 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryResult.cs @@ -0,0 +1,30 @@ +using LINGYUN.Abp.WeChat.Work.Messages; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信消息构造结果 +/// +public class WeChatWorkMessageFactoryResult +{ + /// + /// 消息载体 + /// + public WeChatWorkMessage Message { get; } + + /// + /// 消息载体类型, 用于日志与排障 + /// + public WeChatWorkMessageKind Kind { get; } + + public WeChatWorkMessageFactoryResult(WeChatWorkMessage message, WeChatWorkMessageKind kind) + { + Message = message; + Kind = kind; + } + + public static WeChatWorkMessageFactoryResult Create(WeChatWorkMessage message, WeChatWorkMessageKind kind) + { + return new WeChatWorkMessageFactoryResult(message, kind); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageKind.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageKind.cs new file mode 100644 index 000000000..9cc0d464b --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageKind.cs @@ -0,0 +1,52 @@ +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信消息载体类型 +/// +/// +/// 显式声明渠道数据的形态, 替代旧实现中"按字段逐个探测"的隐式优先级, +/// 生产者也因此可以明确表达自己的意图。 +/// +public enum WeChatWorkMessageKind +{ + /// + /// 未指定, 由渠道按内容类型推导 + /// + None = 0, + /// + /// 小程序通知消息 + /// + MiniProgramNotice = 1, + /// + /// 图文消息(mpnews) + /// + MpNews = 2, + /// + /// 模板卡片消息 + /// + TemplateCard = 3, + /// + /// 文本卡片消息 + /// + TextCard = 4, + /// + /// 视频消息 + /// + Video = 5, + /// + /// 语音消息 + /// + Voice = 6, + /// + /// 文件消息 + /// + File = 7, + /// + /// 文本消息 + /// + Text = 8, + /// + /// markdown消息 + /// + Markdown = 9 +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageOptions.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageOptions.cs new file mode 100644 index 000000000..fc92d725e --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageOptions.cs @@ -0,0 +1,74 @@ +using System; +using Volo.Abp; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信消息公共选项 +/// +public class WeChatWorkMessageOptions +{ + /// + /// 消息应用标识, 由渠道在发布时填充 + /// + public string AgentId { get; set; } = default!; + + /// + /// 是否是保密消息 + /// + public bool? Safe { get; set; } + + /// + /// 是否开启id转译 + /// + public bool? EnableIdTrans { get; set; } + + /// + /// 是否开启重复消息检查 + /// + public bool? EnableDuplicateCheck { get; set; } + + /// + /// 重复消息检查的时间间隔(秒) + /// + public int? DuplicateCheckInterval { get; set; } + + /// + /// 从通知数据中解析公共选项 + /// + public static WeChatWorkMessageOptions From( + INotificationChannelDataResolver resolver, + NotificationData notificationData) + { + Check.NotNull(resolver, nameof(resolver)); + Check.NotNull(notificationData, nameof(notificationData)); + + return new WeChatWorkMessageOptions + { + Safe = resolver.GetValue(notificationData, WeChatWorkNotificationDataKeys.Safe), + EnableIdTrans = resolver.GetValue(notificationData, WeChatWorkNotificationDataKeys.EnableIdTrans), + EnableDuplicateCheck = resolver.GetValue(notificationData, WeChatWorkNotificationDataKeys.EnableDuplicateCheck), + DuplicateCheckInterval = resolver.GetValue(notificationData, WeChatWorkNotificationDataKeys.DuplicateCheckInterval) + }; + } + + /// + /// 保密消息标记 + /// + public byte SafeValue => Safe == true ? (byte)1 : (byte)0; + + /// + /// id转译标记 + /// + public byte EnableIdTransValue => EnableIdTrans == true ? (byte)1 : (byte)0; + + /// + /// 重复消息检查标记 + /// + public byte EnableDuplicateCheckValue => EnableDuplicateCheck == true ? (byte)1 : (byte)0; + + /// + /// 重复消息检查间隔, 未设置时使用企业微信默认值 + /// + public int DuplicateCheckIntervalValue => DuplicateCheckInterval ?? 1800; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMiniProgramNoticeChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMiniProgramNoticeChannelData.cs new file mode 100644 index 000000000..09cfc7235 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMiniProgramNoticeChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 小程序通知消息载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 100)] +public class WeChatWorkMiniProgramNoticeChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.MiniProgramNotice; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.MiniProgramMessage)] + public virtual MiniProgramMessage? MiniProgram { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMpNewChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMpNewChannelData.cs new file mode 100644 index 000000000..ae9c8938f --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMpNewChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 图文消息(mpnews)载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 200)] +public class WeChatWorkMpNewChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.MpNews; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.MpNewMessage)] + public virtual MpNewMessagePayload? MpNewMessage { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationContact.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationContact.cs new file mode 100644 index 000000000..ff98d9b8c --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationContact.cs @@ -0,0 +1,48 @@ +using System; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信消息接收者 +/// +/// +/// 企业微信要求 touser / toparty / totag 不能同时为空, +/// 因此接收者必须作为整体传递给消息构造过程。 +/// +public class WeChatWorkNotificationContact +{ + /// + /// 成员ID列表, 多个接收者使用"|"分隔 + /// + public string? ToUser { get; set; } + + /// + /// 部门ID列表, 多个接收者使用"|"分隔 + /// + public string? ToParty { get; set; } + + /// + /// 标签ID列表, 多个接收者使用"|"分隔 + /// + public string? ToTag { get; set; } + + public bool IsEmpty() + { + return ToUser.IsNullOrWhiteSpace() + && ToParty.IsNullOrWhiteSpace() + && ToTag.IsNullOrWhiteSpace(); + } + + public static WeChatWorkNotificationContact From( + string? toUser = null, + string? toParty = null, + string? toTag = null) + { + return new WeChatWorkNotificationContact + { + ToUser = toUser, + ToParty = toParty, + ToTag = toTag + }; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationDataKeys.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationDataKeys.cs new file mode 100644 index 000000000..c70c9b7fc --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationDataKeys.cs @@ -0,0 +1,55 @@ +using System; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信通知数据键 +/// +/// +/// 键名与历史实现保持一致(wx-work: 前缀), 保证已上线的生产者不受影响。 +/// +public static class WeChatWorkNotificationDataKeys +{ + public const string Prefix = "wx-work:"; + + /// + /// 指定接收消息的成员 + /// + public const string ToUser = Prefix + "to_user"; + /// + /// 指定接收消息的部门 + /// + public const string ToParty = Prefix + "to_party"; + /// + /// 指定接收消息的标签 + /// + public const string ToTag = Prefix + "to_tag"; + /// + /// 应用标识 + /// + public const string AgentId = Prefix + "agent_id"; + /// + /// 是否是保密消息 + /// + public const string Safe = Prefix + "safe"; + /// + /// 是否开启id转译 + /// + public const string EnableIdTrans = Prefix + "enable_id_trans"; + /// + /// 是否开启重复消息检查 + /// + public const string EnableDuplicateCheck = Prefix + "enable_duplicate_check"; + /// + /// 重复消息检查的时间间隔 + /// + public const string DuplicateCheckInterval = Prefix + "duplicate_check_interval"; + + public const string MiniProgramMessage = Prefix + "mini_program_message"; + public const string MpNewMessage = Prefix + "mp_new_message"; + public const string TemplateCardMessage = Prefix + "template_card_message"; + public const string TextCardMessage = Prefix + "text_card_message"; + public const string VideoMessage = Prefix + "video_message"; + public const string VoiceMessage = Prefix + "voice_message"; + public const string FileMessage = Prefix + "file_message"; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTemplateCardChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTemplateCardChannelData.cs new file mode 100644 index 000000000..b46f535f5 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTemplateCardChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 模板卡片消息载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 300)] +public class WeChatWorkTemplateCardChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.TemplateCard; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.TemplateCardMessage)] + public virtual TemplateCard? TemplateCard { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextCardChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextCardChannelData.cs new file mode 100644 index 000000000..0a2548cdf --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextCardChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 文本卡片消息载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 400)] +public class WeChatWorkTextCardChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.TextCard; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.TextCardMessage)] + public virtual TextCardMessage? TextCard { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextChannelData.cs new file mode 100644 index 000000000..42e5c5a4b --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextChannelData.cs @@ -0,0 +1,18 @@ +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 文本消息载荷 +/// +/// +/// 不参与渠道解析: 文本消息由通知标准数据(title/message)推导, +/// 生产者不需要为它准备任何渠道专属数据。 +/// +public class WeChatWorkTextChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Text; + + /// + /// 消息内容, 为空时使用通知标准数据 + /// + public virtual string? Content { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVideoChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVideoChannelData.cs new file mode 100644 index 000000000..cf4a7e4cf --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVideoChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 视频消息载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 500)] +public class WeChatWorkVideoChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Video; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.VideoMessage)] + public virtual VideoMessage? Video { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVoiceChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVoiceChannelData.cs new file mode 100644 index 000000000..f4d3a8807 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVoiceChannelData.cs @@ -0,0 +1,16 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 语音消息载荷 +/// +[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 600)] +public class WeChatWorkVoiceChannelData : WeChatWorkChannelData +{ + public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Voice; + + [NotificationChannelProperty(WeChatWorkNotificationDataKeys.VoiceMessage)] + public virtual MediaMessage? Voice { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkNotificationPublishProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkNotificationPublishProvider.cs index c1ab47ac7..1a034e433 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkNotificationPublishProvider.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkNotificationPublishProvider.cs @@ -1,9 +1,10 @@ -using LINGYUN.Abp.WeChat.Work.Authorize; +using LINGYUN.Abp.WeChat.Work.Authorize; using LINGYUN.Abp.WeChat.Work.Features; using LINGYUN.Abp.WeChat.Work.Messages; using LINGYUN.Abp.WeChat.Work.Messages.Models; using LINGYUN.Abp.WeChat.Work.Settings; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; @@ -13,17 +14,24 @@ using Volo.Abp.Features; using Volo.Abp.Settings; namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信通知发布渠道 +/// public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider { - public const string ProviderName = NotificationProviderNames.WechatWork; + public override string Name => ProviderName; + protected IFeatureChecker FeatureChecker => ServiceProvider.LazyGetRequiredService(); protected ISettingProvider SettingProvider => ServiceProvider.LazyGetRequiredService(); protected IWeChatWorkMessageSender WeChatWorkMessageSender => ServiceProvider.LazyGetRequiredService(); protected INotificationDataSerializer NotificationDataSerializer => ServiceProvider.LazyGetRequiredService(); protected IWeChatWorkUserClaimProvider WeChatWorkInternalUserFinder => ServiceProvider.LazyGetRequiredService(); protected INotificationDefinitionManager NotificationDefinitionManager => ServiceProvider.LazyGetRequiredService(); + protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService(); + protected IOptions MessageOptions => ServiceProvider.LazyGetRequiredService>(); protected async override Task CanPublishAsync(NotificationInfo notification, CancellationToken cancellationToken = default) { @@ -44,8 +52,6 @@ public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider NotificationPublishContext context, CancellationToken cancellationToken = default) { - var sendToAgentIds = new List(); - var notificationDefine = await NotificationDefinitionManager.GetOrNullAsync(context.Notification.Name); var agentId = await SettingProvider.GetOrNullAsync(WeChatWorkSettingNames.Connection.AgentId); if (agentId.IsNullOrWhiteSpace()) { @@ -53,6 +59,7 @@ public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider Logger.LogWarning(context.Reason); return; } + var notificationData = await NotificationDataSerializer.ToStandard(context.Notification.Data); if (notificationData.Title.IsNullOrWhiteSpace() && notificationData.Message.IsNullOrWhiteSpace()) { @@ -61,11 +68,10 @@ public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider return; } - var toTag = context.Notification.Data.GetTagOrNull() ?? notificationDefine?.GetTagOrNull(); - var toParty = context.Notification.Data.GetPartyOrNull() ?? notificationDefine?.GetPartyOrNull(); - var toUsers = await WeChatWorkInternalUserFinder.FindUserIdentifierListAsync(context.Users.Select(id => id.UserId)); + var notificationDefine = await NotificationDefinitionManager.GetOrNullAsync(context.Notification.Name); - if (toUsers.IsNullOrEmpty() && toTag.IsNullOrWhiteSpace() && toParty.IsNullOrWhiteSpace()) + var contact = await ResolveContactAsync(context, notificationDefine, cancellationToken); + if (contact.IsEmpty()) { // touser、toparty、totag不能同时为空:https://developer.work.weixin.qq.com/document/path/90236 context.Cancel("Unable to send work weixin messages because The recipient/department/label cannot be empty simultaneously."); @@ -73,60 +79,224 @@ public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider return; } - // 发送到个人 - await PublishToAgentAsync( - context, - agentId, - notificationData.Title, - notificationData.Message, - notificationData.Description, - toTag: toTag, - toParty: toParty, - toUser: toUsers.JoinAsString("|"), - cancellationToken: cancellationToken); + var options = WeChatWorkMessageOptions.From(ChannelDataResolver, context.Notification.Data); + options.AgentId = agentId; + + var messages = ResolveMessages(context, notificationData, contact, options); + if (messages.Count == 0) + { + context.Cancel("Unable to send work weixin messages because WeChatWorkMessage is null."); + Logger.LogWarning(context.Reason); + return; + } + var failures = new List(); + + foreach (var message in messages) + { + try + { + var response = await WeChatWorkMessageSender.SendAsync(message.Message, cancellationToken); + + if (!response.IsSuccessed) + { + // 企业微信以业务错误码返回失败, 必须让上层感知, 否则失败会被记录为成功 + context.Cancel( + $"Unable to send work weixin messages, error code: {response.ErrorCode}, error message: {response.ErrorMessage}"); + + Logger.LogWarning( + "The notification: {Notification} with provider: {Provider} and message kind: {Kind} failed, error code: {ErrorCode}, error message: {ErrorMessage}", + context.Notification.Name, Name, message.Kind, response.ErrorCode, response.ErrorMessage); + continue; + } + + Logger.LogDebug( + "The notification: {Notification} with provider: {Provider} and message kind: {Kind} has successfully published!", + context.Notification.Name, Name, message.Kind); + } + catch (Exception ex) + { + Logger.LogWarning(ex, + "Send notification {Notification} with provider {Provider} and message kind {Kind} failed", + context.Notification.Name, Name, message.Kind); + failures.Add(ex); + } + } + + if (failures.Count > 0) + { + context.Cancel( + $"Failed to send work weixin messages of notification '{context.Notification.Name}'.", + new AggregateException( + $"Failed to send work weixin messages of notification '{context.Notification.Name}'.", + failures)); + } } - protected async virtual Task PublishToAgentAsync( + /// + /// 解析消息接收者 + /// + /// + /// 成员标识由企业微信身份绑定关系解析, 部门与标签优先取通知数据, 其次取通知定义。 + /// + protected async virtual Task ResolveContactAsync( NotificationPublishContext context, - string agentId, - string title, - string content, - string? description = "", - string? toUser = null, - string? toParty = null, - string? toTag = null, + NotificationDefinition? notificationDefine, CancellationToken cancellationToken = default) { - WeChatWorkMessage? message = null; + var toUser = await WeChatWorkInternalUserFinder.FindUserIdentifierListAsync( + context.Users.Select(id => id.UserId), + cancellationToken); + + var toTag = ChannelDataResolver.GetOrNull(context.Notification.Data, WeChatWorkNotificationDataKeys.ToTag) + ?? notificationDefine?.GetTagOrNull(); + + var toParty = ChannelDataResolver.GetOrNull(context.Notification.Data, WeChatWorkNotificationDataKeys.ToParty) + ?? notificationDefine?.GetPartyOrNull(); + + return WeChatWorkNotificationContact.From( + toUser: toUser.JoinAsString("|"), + toParty: toParty, + toTag: toTag); + } + + /// + /// 解析待发送的消息载体集合 + /// + /// + /// 优先使用生产者显式声明的渠道数据(载荷); + /// 未声明时按通知内容类型推导默认载体, 保证既有生产者的行为不变。 + /// + protected virtual List ResolveMessages( + NotificationPublishContext context, + NotificationStandardData standardData, + WeChatWorkNotificationContact contact, + WeChatWorkMessageOptions options) + { + var messages = new List(); + if (TryResolveChannelData(context, out var invalidPayload, out var resolvedPayloads)) + { + foreach (var channelData in resolvedPayloads) + { + messages.Add(CreateMessage(channelData, context.Notification, standardData, contact, options)); + } + } + else + { + context.Cancel( + $"Unable to send work weixin messages because the work weixin payload '{invalidPayload}' can not be parsed, please check the notification data written by the producer."); + Logger.LogWarning(context.Reason); + return messages; + } + + if (messages.Count == 0) + { + var defaultChannelData = CreateDefaultChannelData(context, standardData); + if (defaultChannelData != null) + { + messages.Add(CreateMessage(defaultChannelData, context.Notification, standardData, contact, options)); + } + } + + return messages; + } + + /// + /// 解析渠道数据(载荷) + /// + /// + /// 区分"生产者未写入载荷"与"载荷已写入但无法解析": + /// 后者是生产者错误, 必须明确报错, 而不是静默回退到默认载体。 + /// + protected virtual bool TryResolveChannelData( + NotificationPublishContext context, + out string? invalidPayloadKey, + out List resolvedPayloads) + { + invalidPayloadKey = null; + resolvedPayloads = new List(); + + foreach (var payloadType in ChannelDataResolver.GetPayloadTypes(ProviderName)) + { + if (!ChannelDataResolver.IsDeclared(context.Notification.Data, payloadType)) + { + continue; + } + + var payload = ChannelDataResolver.Resolve(payloadType, context.Notification.Data); + + if (payload == null) + { + invalidPayloadKey = ChannelDataResolver.GetKey(context.Notification.Data, payloadType); + return false; + } + + resolvedPayloads.Add(payload); + } + + return true; + } + + /// + /// 按通知内容类型推导默认的消息载体 + /// + protected virtual WeChatWorkChannelData? CreateDefaultChannelData( + NotificationPublishContext context, + NotificationStandardData standardData) + { switch (context.Notification.ContentType) { case NotificationContentType.Text: - message = new WeChatWorkTextMessage(agentId, new TextMessage(content)); - break; + return new WeChatWorkTextChannelData + { + Content = standardData.Message + }; + case NotificationContentType.Html: - message = new WeChatWorkTextCardMessage(agentId, new TextCardMessage(title, content, "javascript(0);")); - break; + return new WeChatWorkTextCardChannelData + { + TextCard = new TextCardMessage( + standardData.Title ?? string.Empty, + // 旧实现丢弃了 description, 这里补全文本卡片的描述 + standardData.Description.IsNullOrWhiteSpace() ? standardData.Message : standardData.Description!, + // 跳转地址应由生产者通过载荷显式指定, 默认不可点击 + "javascript:;") + }; + case NotificationContentType.Markdown: - message = new WeChatWorkMarkdownMessage(agentId, new MarkdownMessage(content)); - break; + return new WeChatWorkMarkdownChannelData + { + Content = standardData.Message + }; + default: - break; + Logger.LogWarning( + "The notification: {Notification} with provider: {Provider} can not resolve a work weixin message for content type: {ContentType}.", + context.Notification.Name, Name, context.Notification.ContentType); + return null; } + } - if (message == null) + protected virtual WeChatWorkMessageFactoryResult CreateMessage( + NotificationChannelData channelData, + NotificationInfo notification, + NotificationStandardData standardData, + WeChatWorkNotificationContact contact, + WeChatWorkMessageOptions options) + { + if (channelData is not WeChatWorkChannelData weChatWorkChannelData) { - context.Cancel("Unable to send work weixin messages because WeChatWorkMessage is null."); - Logger.LogWarning(context.Reason); - return; + throw new AbpNotificationChannelDataConfigurationException( + $"The channel data '{channelData.GetType().FullName}' is not a work weixin channel data."); } - message.ToUser = toUser; - message.ToTag = toTag; - message.ToParty = toParty; - - await WeChatWorkMessageSender.SendAsync(message, cancellationToken); + var factoryContext = new WeChatWorkMessageFactoryContext( + notification, + standardData, + weChatWorkChannelData, + contact, + options); - Logger.LogDebug("The notification: {0} with provider: {1} has successfully published!", context.Notification.Name, Name); + return MessageOptions.Value.Create(factoryContext); } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkModule.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkModule.cs index a9fd1580d..b3518f389 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkModule.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkModule.cs @@ -1,4 +1,7 @@ -using LINGYUN.Abp.WeChat.Work; +using LINGYUN.Abp.WeChat.Work; +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Json.SystemTextJson; using Volo.Abp.Modularity; namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; @@ -10,14 +13,44 @@ public class AbpNotificationsWebhookWeChatWorkModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { + // 允许使用方在 PreConfigure 中覆盖(例如关闭 markdown v2) + var preActions = context.Services.GetPreConfigureActions(); + Configure(options => { options.UseMarkdownV2 = true; + + preActions.Configure(options); }); Configure(options => { options.Contributors.Add(new WeChatWorkWebhookNotificationContributor()); }); + + // 模板卡片是抽象类型: 注册类型转换器, 使其能在渠道数据(JSON)中往返 + Configure(options => + { + options.JsonSerializerOptions.Converters.Add(new WebhookTemplateCardSystemTextJsonConverter()); + }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + }); + + // 消息载体工厂分派 + Configure(options => + { + options.MapDefaultMessageFactories(); + }); } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/AbpNotificationsWebhookWeChatWorkMessageOptions.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/AbpNotificationsWebhookWeChatWorkMessageOptions.cs new file mode 100644 index 000000000..c7aff486f --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/AbpNotificationsWebhookWeChatWorkMessageOptions.cs @@ -0,0 +1,75 @@ +using LINGYUN.Abp.WeChat.Work.Messages; +using System; +using System.Collections.Generic; +using Volo.Abp; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 消息构造选项 +/// +/// +/// +/// 渠道数据的形态到消息载体的转换集中注册在这里, 新增一种消息类型只需要 +/// options.Map(kind, factory), 不需要修改贡献者的发布逻辑。 +/// +/// +public class AbpNotificationsWebhookWeChatWorkMessageOptions +{ + private readonly Dictionary> _factories + = new Dictionary>(); + + /// + /// 已注册的消息类型 + /// + public IReadOnlyCollection MessageKinds => _factories.Keys; + + /// + /// 注册消息构造工厂 + /// + public AbpNotificationsWebhookWeChatWorkMessageOptions Map( + WeChatWorkWebhookMessageKind kind, + Func factory) + { + Check.NotNull(factory, nameof(factory)); + + _factories[kind] = factory; + + return this; + } + + /// + /// 构造消息载体 + /// + public WeChatWorkWebhookMessageFactoryResult Create(WeChatWorkWebhookMessageFactoryContext context) + { + Check.NotNull(context, nameof(context)); + + var kind = context.ChannelData.Kind; + + if (!_factories.TryGetValue(kind, out var factory)) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The WeChat Work webhook message kind '{kind}' has not been mapped, please call '{nameof(Map)}' when configuring '{nameof(AbpNotificationsWebhookWeChatWorkMessageOptions)}'."); + } + + var result = factory(context); + if (result == null || result.Message == null) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The factory of the WeChat Work webhook message kind '{kind}' returned an empty message."); + } + + return result; + } + + /// + /// 获取已注册的工厂 + /// + public bool TryGetFactory( + WeChatWorkWebhookMessageKind kind, + out Func? factory) + { + return _factories.TryGetValue(kind, out factory); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookChannelData.cs new file mode 100644 index 000000000..3b04a57ee --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookChannelData.cs @@ -0,0 +1,16 @@ +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 渠道数据(载荷)基类 +/// +/// +/// 每个载荷对应一种 Webhook 消息载体, 通过 显式声明形态, +/// 渠道侧使用工厂字典做 O(1) 分派。 +/// +public abstract class WeChatWorkWebhookChannelData : NotificationChannelData +{ + /// + /// 消息载体类型 + /// + public abstract WeChatWorkWebhookMessageKind Kind { get; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookFileChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookFileChannelData.cs new file mode 100644 index 000000000..5896b22dd --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookFileChannelData.cs @@ -0,0 +1,19 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 文件消息载荷 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 600)] +public class WeChatWorkWebhookFileChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.File; + + /// + /// 文件消息体(素材 ID) + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.File)] + public virtual WebhookFileMessage? File { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookImageChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookImageChannelData.cs new file mode 100644 index 000000000..8c78477dc --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookImageChannelData.cs @@ -0,0 +1,19 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 图片消息载荷 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 400)] +public class WeChatWorkWebhookImageChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Image; + + /// + /// 图片内容(base64 编码, 不超过 2MB) + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Image)] + public virtual WebhookImageMessage? Image { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownChannelData.cs new file mode 100644 index 000000000..e36bed1dd --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownChannelData.cs @@ -0,0 +1,18 @@ +using LINGYUN.Abp.Notifications; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// markdown 消息载荷 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 200)] +public class WeChatWorkWebhookMarkdownChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Markdown; + + /// + /// markdown 内容 + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Markdown)] + public virtual string? Content { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownV2ChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownV2ChannelData.cs new file mode 100644 index 000000000..f4b27c86a --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownV2ChannelData.cs @@ -0,0 +1,22 @@ +using LINGYUN.Abp.Notifications; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// markdown_v2 消息载荷 +/// +/// +/// markdown_v2 支持表格、代码块等更丰富的语法, +/// 详见 https://developer.work.weixin.qq.com/document/path/99110#markdown-v2%E7%B1%BB%E5%9E%8B +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 300)] +public class WeChatWorkWebhookMarkdownV2ChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.MarkdownV2; + + /// + /// markdown_v2 内容 + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.MarkdownV2)] + public virtual string? Content { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactory.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactory.cs new file mode 100644 index 000000000..4f29725e6 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactory.cs @@ -0,0 +1,92 @@ +using LINGYUN.Abp.WeChat.Work.Messages; +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Volo.Abp; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 消息工厂 +/// +public static class WeChatWorkWebhookMessageFactory +{ + /// + /// 注册内置消息工厂 + /// + /// + /// 每种载荷对应一种 msgtype, 一一映射, 不做隐式降级: + /// 生产者选择了模板卡片, 就一定发模板卡片, 而不是静默发成文本。 + /// 唯一的例外是 markdown 与 markdown_v2 的取舍, 由渠道选项 + /// 决定。 + /// + public static AbpNotificationsWebhookWeChatWorkMessageOptions MapDefaultMessageFactories( + this AbpNotificationsWebhookWeChatWorkMessageOptions options) + { + Check.NotNull(options, nameof(options)); + + return options + .Map(WeChatWorkWebhookMessageKind.Text, context => + { + var payload = (WeChatWorkWebhookTextChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookTextMessage(new WebhookTextMessage(payload.Content!)), + WeChatWorkWebhookMessageKind.Text); + }) + .Map(WeChatWorkWebhookMessageKind.Markdown, context => + { + var payload = (WeChatWorkWebhookMarkdownChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookMarkdownMessage(new WebhookMarkdownMessage(payload.Content!)), + WeChatWorkWebhookMessageKind.Markdown); + }) + .Map(WeChatWorkWebhookMessageKind.MarkdownV2, context => + { + var payload = (WeChatWorkWebhookMarkdownV2ChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookMarkdownV2Message(new WebhookMarkdownV2Message(payload.Content!)), + WeChatWorkWebhookMessageKind.MarkdownV2); + }) + .Map(WeChatWorkWebhookMessageKind.Image, context => + { + var payload = (WeChatWorkWebhookImageChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookImageMessage(payload.Image!), + WeChatWorkWebhookMessageKind.Image); + }) + .Map(WeChatWorkWebhookMessageKind.News, context => + { + var payload = (WeChatWorkWebhookNewsChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookNewsMessage(payload.News!), + WeChatWorkWebhookMessageKind.News); + }) + .Map(WeChatWorkWebhookMessageKind.File, context => + { + var payload = (WeChatWorkWebhookFileChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookFileMessage(payload.File!), + WeChatWorkWebhookMessageKind.File); + }) + .Map(WeChatWorkWebhookMessageKind.Voice, context => + { + var payload = (WeChatWorkWebhookVoiceChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookVoiceMessage(payload.Voice!), + WeChatWorkWebhookMessageKind.Voice); + }) + .Map(WeChatWorkWebhookMessageKind.TemplateCard, context => + { + var payload = (WeChatWorkWebhookTemplateCardChannelData)context.ChannelData; + + return WeChatWorkWebhookMessageFactoryResult.Create( + new WeChatWorkWebhookTemplateCardMessage(payload.TemplateCard!), + WeChatWorkWebhookMessageKind.TemplateCard); + }); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryContext.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryContext.cs new file mode 100644 index 000000000..8a617e87f --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryContext.cs @@ -0,0 +1,41 @@ +using LINGYUN.Abp.WeChat.Work.Messages; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 消息构造上下文 +/// +public class WeChatWorkWebhookMessageFactoryContext +{ + /// + /// 通知消息 + /// + public NotificationInfo Notification { get; } + + /// + /// 通知标准数据(已完成本地化与模板渲染) + /// + public NotificationStandardData StandardData { get; } + + /// + /// 渠道数据(载荷) + /// + public WeChatWorkWebhookChannelData ChannelData { get; } + + /// + /// 渠道选项 + /// + public AbpNotificationsWebhookWeChatWorkOptions Options { get; } + + public WeChatWorkWebhookMessageFactoryContext( + NotificationInfo notification, + NotificationStandardData standardData, + WeChatWorkWebhookChannelData channelData, + AbpNotificationsWebhookWeChatWorkOptions options) + { + Notification = notification; + StandardData = standardData; + ChannelData = channelData; + Options = options; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryResult.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryResult.cs new file mode 100644 index 000000000..57a4820fd --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryResult.cs @@ -0,0 +1,34 @@ +using LINGYUN.Abp.WeChat.Work.Messages; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 消息构造结果 +/// +public class WeChatWorkWebhookMessageFactoryResult +{ + /// + /// 消息载体 + /// + public WeChatWorkWebhookMessage Message { get; } + + /// + /// 消息载体类型, 用于日志与排障 + /// + public WeChatWorkWebhookMessageKind Kind { get; } + + public WeChatWorkWebhookMessageFactoryResult( + WeChatWorkWebhookMessage message, + WeChatWorkWebhookMessageKind kind) + { + Message = message; + Kind = kind; + } + + public static WeChatWorkWebhookMessageFactoryResult Create( + WeChatWorkWebhookMessage message, + WeChatWorkWebhookMessageKind kind) + { + return new WeChatWorkWebhookMessageFactoryResult(message, kind); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageKind.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageKind.cs new file mode 100644 index 000000000..fc0934f68 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageKind.cs @@ -0,0 +1,47 @@ +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 消息载体类型 +/// +/// +/// 取值与框架 WeChatWorkWebhookMessage.MsgType 一致。 +/// +public enum WeChatWorkWebhookMessageKind +{ + /// + /// 未指定 + /// + None = 0, + /// + /// 文本 + /// + Text = 1, + /// + /// markdown + /// + Markdown = 2, + /// + /// markdown_v2 + /// + MarkdownV2 = 3, + /// + /// 图片 + /// + Image = 4, + /// + /// 图文 + /// + News = 5, + /// + /// 文件 + /// + File = 6, + /// + /// 语音 + /// + Voice = 7, + /// + /// 模板卡片 + /// + TemplateCard = 8 +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNewsChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNewsChannelData.cs new file mode 100644 index 000000000..6a6738061 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNewsChannelData.cs @@ -0,0 +1,19 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 图文消息载荷 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 500)] +public class WeChatWorkWebhookNewsChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.News; + + /// + /// 图文消息体 + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.News)] + public virtual WebhookNewsMessage? News { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationDataKeys.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationDataKeys.cs new file mode 100644 index 000000000..ba29050b6 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationDataKeys.cs @@ -0,0 +1,56 @@ +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 通知数据键 +/// +/// +/// +/// 前缀 wx-work-hook: 归属 Webhook 渠道自身。 +/// 企业微信**应用消息**渠道使用 wx-work: 前缀 —— 两者是不同传输方式, +/// 键空间必须分开, 否则同一个通知被两个渠道同时订阅时, +/// 载荷会被两边都解析并各发一条。 +/// +/// +/// 读取过程大小写不敏感(精确匹配优先)。 +/// +/// +public static class WeChatWorkWebhookNotificationDataKeys +{ + /// + /// 本渠道的数据键前缀 + /// + public const string Prefix = "wx-work-hook:"; + + /// + /// 文本消息 + /// + public const string Text = Prefix + "text"; + /// + /// markdown 消息 + /// + public const string Markdown = Prefix + "markdown"; + /// + /// markdown_v2 消息 + /// + public const string MarkdownV2 = Prefix + "markdown_v2"; + /// + /// 图片消息(base64 + md5) + /// + public const string Image = Prefix + "image"; + /// + /// 图文消息 + /// + public const string News = Prefix + "news"; + /// + /// 文件消息 + /// + public const string File = Prefix + "file"; + /// + /// 语音消息 + /// + public const string Voice = Prefix + "voice"; + /// + /// 模板卡片消息 + /// + public const string TemplateCard = Prefix + "template_card"; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationProvider.cs new file mode 100644 index 000000000..1a33367dc --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationProvider.cs @@ -0,0 +1,26 @@ +using Volo.Abp.Modularity; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 通知渠道名 +/// +/// +/// +/// Webhook 的**发布**仍走 WebhookNotificationPublishProvider(渠道名 Webhook), +/// 本常量只作为**载荷注册表的键**使用: +/// 企业微信应用消息(渠道名 WeChat.Work)与 Webhook 是两种传输方式、 +/// 两套载体模型, 因此必须使用不同的注册表键, 避免载荷被对方误解析。 +/// +/// +/// 生产者侧: 通知定义中仍声明 ProviderName 为 "Webhook" 才会被发布, +/// 载荷用本渠道的数据键(前缀 wx-work-hook:)写入。 +/// +/// +public static class WeChatWorkWebhookNotificationProvider +{ + /// + /// 本渠道的载荷注册表键 + /// + public const string ProviderName = "WeChat.Work.Webhook"; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTemplateCardChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTemplateCardChannelData.cs new file mode 100644 index 000000000..f529c02e6 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTemplateCardChannelData.cs @@ -0,0 +1,24 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 模板卡片消息载荷 +/// +/// +/// 抽象类型 的两个具体实现 +/// ( / ) +/// 都需要 JSON 多态转换器才能在通知数据中往返, 由渠道模块注册。 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 800)] +public class WeChatWorkWebhookTemplateCardChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.TemplateCard; + + /// + /// 模板卡片消息体 + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.TemplateCard)] + public virtual WebhookTemplateCardMessage? TemplateCard { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTextChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTextChannelData.cs new file mode 100644 index 000000000..afab217a9 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTextChannelData.cs @@ -0,0 +1,18 @@ +using LINGYUN.Abp.Notifications; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 文本消息载荷 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 100)] +public class WeChatWorkWebhookTextChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Text; + + /// + /// 文本内容 + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Text)] + public virtual string? Content { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookVoiceChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookVoiceChannelData.cs new file mode 100644 index 000000000..fe6c6d766 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookVoiceChannelData.cs @@ -0,0 +1,19 @@ +using LINGYUN.Abp.Notifications; +using LINGYUN.Abp.WeChat.Work.Messages.Models; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 语音消息载荷 +/// +[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 700)] +public class WeChatWorkWebhookVoiceChannelData : WeChatWorkWebhookChannelData +{ + public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Voice; + + /// + /// 语音消息体(素材 ID) + /// + [NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Voice)] + public virtual WebhookVoiceMessage? Voice { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookNotificationContributor.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookNotificationContributor.cs index a3d702b23..757cc2525 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookNotificationContributor.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookNotificationContributor.cs @@ -1,74 +1,185 @@ -using LINGYUN.Abp.WeChat.Work.Messages; +using LINGYUN.Abp.Notifications.Webhook.WeChat.Work; using LINGYUN.Abp.WeChat.Work.Messages.Models; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using System; +using System.Collections.Generic; using System.Threading.Tasks; +using Volo.Abp; namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 通知贡献者 +/// +/// +/// +/// 优先解析生产者写入的**渠道数据(载荷)**, 载荷缺失时才回退到按 +/// 推导, +/// 因此历史用法(只写标准数据)行为不变。 +/// +/// +/// 一个 Webhook 只能承载一条消息, 因此声明多个载荷时取 +/// 最小的那个, +/// 并按 1:1 映射构造载体 —— 不再像旧实现那样把未知内容类型静默丢弃。 +/// +/// public class WeChatWorkWebhookNotificationContributor : IWebhookNotificationContributor { - public string Name => "WeChat.Work"; + /// + /// 贡献者名称(仅用于日志) + /// + public string Name => WeChatWorkWebhookNotificationProvider.ProviderName; public async virtual Task ContributeAsync(IWebhookNotificationContext context) { - var options = context.ServiceProvider.GetRequiredService>().Value; - var notificationDataSerializer = context.ServiceProvider.GetRequiredService(); + Check.NotNull(context, nameof(context)); + + var options = context.ServiceProvider + .GetRequiredService>().Value; + var messageOptions = context.ServiceProvider + .GetRequiredService>().Value; + var resolver = context.ServiceProvider + .GetRequiredService(); + var notificationDataSerializer = context.ServiceProvider + .GetRequiredService(); - var data = await notificationDataSerializer.ToStandard(context.Notification.Data); - var notificationContent = data.Message; + var standardData = await notificationDataSerializer.ToStandard(context.Notification.Data); try { - if (context.Notification.ContentType == NotificationContentType.Html) - { - notificationContent = CommonMark.CommonMarkConverter.Convert(notificationContent); - } - - WeChatWorkWebhookMessage message; + var payloads = resolver.Resolve( + WeChatWorkWebhookNotificationProvider.ProviderName, + context.Notification.Data); - switch (context.Notification.ContentType) + if (payloads.Count == 0) { - case NotificationContentType.Text: - message = new WeChatWorkWebhookTextMessage( - new WebhookTextMessage(notificationContent)); - break; - case NotificationContentType.Html: - case NotificationContentType.Markdown: - if (options.UseMarkdownV2) - { - message = new WeChatWorkWebhookMarkdownV2Message( - new WebhookMarkdownV2Message(notificationContent)); - } - else - { - message = new WeChatWorkWebhookMarkdownMessage( - new WebhookMarkdownMessage(notificationContent)); - } - break; - default: - return; + // 回退: 生产者未写入载荷, 按内容类型推导(保持历史行为) + payloads = ResolveContentTypePayloads( + context.Notification.ContentType, + standardData.Message, + options); } - if (message == null) + if (payloads.Count == 0) { - context.ServiceProvider - .GetService>() - ?.LogWarning("Unable to send work weixin messages because WeChatWorkMessage is null."); + Logger(context).LogDebug( + "No wechat work webhook channel data was resolved for the notification: {name}, skip it.", + context.Notification.Name); + return; } + // 一个 Webhook 只能承载一条消息: 按 Priority 取第一个(解析结果已排序) + var channelData = (WeChatWorkWebhookChannelData)payloads[0]; + + ApplyStandardDataFallback(channelData, standardData); + + var message = messageOptions.Create( + new WeChatWorkWebhookMessageFactoryContext( + context.Notification, + standardData, + channelData, + options)); + context.Webhook = new WebhookNotificationData( context.Notification.Name, - message); + message.Message); context.Handled = true; } catch (Exception ex) { - context.ServiceProvider - .GetService>() - ?.LogWarning("Failed to parse the content of the Webhook message: {message}", ex.Message); + Logger(context).LogWarning( + "Failed to parse the content of the wechat work webhook message: {message}", + ex.Message); + } + } + + /// + /// 按通知内容类型推导载荷(兼容未写入渠道数据的历史生产者) + /// + protected virtual IReadOnlyList ResolveContentTypePayloads( + NotificationContentType contentType, + string? message, + AbpNotificationsWebhookWeChatWorkOptions options) + { + var content = message ?? string.Empty; + + switch (contentType) + { + case NotificationContentType.Text: + return new NotificationChannelData[] + { + new WeChatWorkWebhookTextChannelData { Content = content } + }; + + case NotificationContentType.Markdown: + return options.UseMarkdownV2 + ? new NotificationChannelData[] + { + new WeChatWorkWebhookMarkdownV2ChannelData { Content = content } + } + : new NotificationChannelData[] + { + new WeChatWorkWebhookMarkdownChannelData { Content = content } + }; + + case NotificationContentType.Html: + // HTML 先转为 markdown 再投递 + var markdown = CommonMark.CommonMarkConverter.Convert(content); + + return options.UseMarkdownV2 + ? new NotificationChannelData[] + { + new WeChatWorkWebhookMarkdownV2ChannelData { Content = markdown } + } + : new NotificationChannelData[] + { + new WeChatWorkWebhookMarkdownChannelData { Content = markdown } + }; + + default: + return Array.Empty(); + } + } + + /// + /// 用标准数据补全载荷中未指定的内容 + /// + /// + /// 生产者只声明"用哪种载体"而不写内容时(例如只写 wx-work-hook:markdown), + /// 使用已本地化/渲染完成的通知正文, 避免发出空内容。 + /// + protected virtual void ApplyStandardDataFallback( + WeChatWorkWebhookChannelData channelData, + NotificationStandardData standardData) + { + if (standardData.Message.IsNullOrWhiteSpace()) + { + return; + } + + switch (channelData) + { + case WeChatWorkWebhookTextChannelData text when text.Content.IsNullOrWhiteSpace(): + text.Content = standardData.Message; + break; + + case WeChatWorkWebhookMarkdownChannelData markdown when markdown.Content.IsNullOrWhiteSpace(): + markdown.Content = standardData.Message; + break; + + case WeChatWorkWebhookMarkdownV2ChannelData markdownV2 when markdownV2.Content.IsNullOrWhiteSpace(): + markdownV2.Content = standardData.Message; + break; } } + + private static ILogger Logger(IWebhookNotificationContext context) + { + return context.ServiceProvider.GetService>() + ?? NullLogger.Instance; + } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/NotificationDataExtensions.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/NotificationDataExtensions.cs deleted file mode 100644 index dfc74c973..000000000 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/NotificationDataExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace LINGYUN.Abp.Notifications; -public static class NotificationDataExtensions -{ - private const string Prefix = "wx-pusher:"; - private const string UrlKey = Prefix + "url"; - - public static void SetUrl( - this NotificationData notificationData, - string url) - { - notificationData.TrySetData(UrlKey, url); - } - - public static string? GetUrlOrNull( - this NotificationData notificationData) - { - return notificationData.TryGetData(UrlKey)?.ToString(); - } -} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherModule.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherModule.cs index a4c230893..d30caa970 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherModule.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherModule.cs @@ -1,4 +1,4 @@ -using LINGYUN.Abp.WxPusher; +using LINGYUN.Abp.WxPusher; using Volo.Abp.Modularity; namespace LINGYUN.Abp.Notifications.WxPusher; @@ -14,5 +14,11 @@ public class AbpNotificationsWxPusherModule : AbpModule { options.PublishProviders.Add(); }); + + // 声明本渠道支持的载荷形态(注册期即校验存在性契约) + Configure(options => + { + options.Add(); + }); } } diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData.cs new file mode 100644 index 000000000..104177066 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData.cs @@ -0,0 +1,19 @@ +using LINGYUN.Abp.Notifications; + +namespace LINGYUN.Abp.Notifications.WxPusher; + +/// +/// WxPusher 渠道数据(载荷) +/// +/// +/// 存在性由 url 键推导(默认 Presence = DeclaredProperties), 无需实现判定方法。 +/// +[NotificationChannelData(WxPusherNotificationPublishProvider.ProviderName, Priority = 100)] +public class WxPusherChannelData : NotificationChannelData +{ + /// + /// 消息点击后的跳转地址 + /// + [NotificationChannelProperty(WxPusherNotificationDataKeys.Url)] + public virtual string? Url { get; set; } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationDataKeys.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationDataKeys.cs new file mode 100644 index 000000000..44cbf0b46 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationDataKeys.cs @@ -0,0 +1,14 @@ +namespace LINGYUN.Abp.Notifications.WxPusher; + +/// +/// WxPusher 通知数据键 +/// +public static class WxPusherNotificationDataKeys +{ + public const string Prefix = "wx-pusher:"; + + /// + /// 消息点击后的跳转地址 + /// + public const string Url = Prefix + "url"; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationPublishProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationPublishProvider.cs index af6dffe59..9af690b4b 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationPublishProvider.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationPublishProvider.cs @@ -1,4 +1,4 @@ -using LINGYUN.Abp.WxPusher.Features; +using LINGYUN.Abp.WxPusher.Features; using LINGYUN.Abp.WxPusher.Messages; using LINGYUN.Abp.WxPusher.User; using Microsoft.Extensions.Logging; @@ -18,6 +18,7 @@ public class WxPusherNotificationPublishProvider : NotificationPublishProvider protected IWxPusherMessageSender WxPusherMessageSender => ServiceProvider.LazyGetRequiredService(); protected INotificationDataSerializer NotificationDataSerializer => ServiceProvider.LazyGetRequiredService(); protected INotificationDefinitionManager NotificationDefinitionManager => ServiceProvider.LazyGetRequiredService(); + protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService(); protected async override Task CanPublishAsync(NotificationInfo notification, CancellationToken cancellationToken = default) { @@ -44,7 +45,8 @@ public class WxPusherNotificationPublishProvider : NotificationPublishProvider var uids = await WxPusherUserStore.GetBindUidsAsync(subscribeUserIds, cancellationToken); var notificationDefine = await NotificationDefinitionManager.GetOrNullAsync(context.Notification.Name); - var url = context.Notification.Data.GetUrlOrNull() ?? notificationDefine?.GetUrlOrNull(); + var channelData = ChannelDataResolver.Resolve(context.Notification.Data); + var url = channelData?.Url ?? notificationDefine?.GetUrlOrNull(); topics ??= notificationDefine?.GetTopics(); var contentType = notificationDefine?.GetContentTypeOrDefault(MessageContentType.Text) ?? MessageContentType.Text; diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN.Abp.Notifications.csproj b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN.Abp.Notifications.csproj index 8a2d62060..b48d75309 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN.Abp.Notifications.csproj +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN.Abp.Notifications.csproj @@ -1,4 +1,4 @@ - + @@ -24,6 +24,7 @@ + diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/AbpNotificationsModule.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/AbpNotificationsModule.cs index c8a015343..567e31915 100644 --- a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/AbpNotificationsModule.cs +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/AbpNotificationsModule.cs @@ -3,6 +3,7 @@ using LINGYUN.Abp.Notifications.Localization; using Volo.Abp.BackgroundJobs; using Volo.Abp.BackgroundWorkers; using Volo.Abp.EventBus; +using Volo.Abp.Json; using Volo.Abp.Localization; using Volo.Abp.Modularity; using Volo.Abp.TextTemplating; @@ -17,6 +18,7 @@ namespace LINGYUN.Abp.Notifications; typeof(AbpIdGeneratorModule), typeof(AbpLocalizationModule), typeof(AbpEventBusModule), + typeof(AbpJsonModule), typeof(AbpTextTemplatingCoreModule))] public class AbpNotificationsModule : AbpModule { diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataJsonSerializer.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataJsonSerializer.cs new file mode 100644 index 000000000..6c5ac3794 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataJsonSerializer.cs @@ -0,0 +1,31 @@ +using System; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Json; + +namespace LINGYUN.Abp.Notifications; + +[Dependency(TryRegister = true)] +public class AbpNotificationChannelDataJsonSerializer : INotificationChannelDataJsonSerializer, ISingletonDependency +{ + protected IJsonSerializer JsonSerializer { get; } + + public AbpNotificationChannelDataJsonSerializer(IJsonSerializer jsonSerializer) + { + JsonSerializer = jsonSerializer; + } + + public virtual string Serialize(object value, Type valueType) + { + return JsonSerializer.Serialize(value); + } + + public virtual object? Deserialize(string json, Type targetType) + { + if (json.IsNullOrWhiteSpace()) + { + return null; + } + + return JsonSerializer.Deserialize(targetType, json); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataOptions.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataOptions.cs new file mode 100644 index 000000000..525cec12d --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataOptions.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Volo.Abp; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)选项 +/// +public class AbpNotificationChannelDataOptions +{ + private readonly Dictionary _providers + = new(StringComparer.OrdinalIgnoreCase); + + private readonly List _payloadTypes = new(); + + /// + /// 已注册的载荷类型 + /// + public IReadOnlyList PayloadTypes => _payloadTypes; + + /// + /// 获取指定渠道的载荷集合(按匹配顺序排列) + /// + public NotificationChannelDataDescriptorList GetProviderData(string providerName) + { + if (!_providers.TryGetValue(providerName, out var list)) + { + list = new NotificationChannelDataDescriptorList(); + _providers[providerName] = list; + } + + return list; + } + + /// + /// 注册渠道数据(载荷) + /// + /// + /// 渠道名称、匹配顺序与存在性判定模式来自 + /// 。 + /// + public AbpNotificationChannelDataOptions Add() + where TChannelData : NotificationChannelData + { + return Add(typeof(TChannelData)); + } + + /// + /// 注册渠道数据(载荷) + /// + /// + /// 缺少 、 + /// 未声明存在性规则, 或同渠道优先级冲突 + /// + public AbpNotificationChannelDataOptions Add(Type channelDataType) + { + Check.NotNull(channelDataType, nameof(channelDataType)); + + if (_payloadTypes.Contains(channelDataType)) + { + return this; + } + + var attribute = channelDataType.GetCustomAttribute(inherit: false); + if (attribute == null) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The channel data type '{channelDataType.FullName}' must be annotated with '{nameof(NotificationChannelDataAttribute)}'."); + } + + // 注册期即校验存在性声明, 让配置错误在启动阶段暴露。 + // 校验只依赖声明元数据, 因此不需要解析任何服务。 + NotificationChannelDataPresence.Validate(channelDataType); + + var descriptors = GetProviderData(attribute.ProviderName); + + if (descriptors.Any(x => x.Priority == attribute.Priority)) + { + var conflict = descriptors.First(x => x.Priority == attribute.Priority); + throw new AbpNotificationChannelDataConfigurationException( + $"The channel data '{channelDataType.FullName}' and '{conflict.PayloadType.FullName}' of provider '{attribute.ProviderName}' declare the same priority '{attribute.Priority}', the matching order would be ambiguous."); + } + + descriptors.Add(new NotificationChannelDataDescriptor( + attribute.ProviderName, + channelDataType, + attribute.Priority, + attribute.Presence, + NotificationChannelDataPresence.Create(channelDataType))); + + descriptors.Sort((left, right) => left.Priority.CompareTo(right.Priority)); + + _payloadTypes.Add(channelDataType); + + return this; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataAccessor.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataAccessor.cs new file mode 100644 index 000000000..4d3a13065 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataAccessor.cs @@ -0,0 +1,71 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)存取器 +/// +/// +/// +/// 通知数据在持久化、失败重试、跨进程投递等链路中必然经历 JSON 往返, +/// 往返之后 ExtraPropertyDictionary 中的值是 JSON 节点而不是原始 CLR 实例: +/// byte 1 会变成 long 1 / JsonElement(Number), +/// 原有的 x as byte? 将永远返回 null。 +/// +/// +/// 本服务是渠道数据"弱类型属性包 ↔ 强类型值"转换的唯一实现, +/// 由 与 +/// 共用, +/// 并保证与所用 JSON 实现无关。 +/// +/// +public interface INotificationChannelDataAccessor +{ + /// + /// 获取载荷的数据类型键 + /// + /// 键名, 类型无全名时返回 null + string? GetDataTypeKey(Type payloadType); + + /// + /// 是否存在键(大小写不敏感) + /// + bool IsPresent(NotificationData notificationData, string key); + + /// + /// 读取原始值(大小写不敏感) + /// + /// 通知数据 + /// 键名 + /// 原始值 + /// 实际命中的键名(可能与入参大小写不同) + bool TryGetRawValue(NotificationData notificationData, string key, out object? value, out string? matchedKey); + + /// + /// 读取并转换为目标类型 + /// + /// 转换后的值; 键不存在或无法转换时返回 null + object? Get(NotificationData notificationData, string key, Type targetType); + + /// + /// 类型化读取(未设置时返回 null, 以便区分"未设置"与"显式 false/0") + /// + TValue? GetValue(NotificationData notificationData, string key) + where TValue : struct; + + /// + /// 类型化读取, 未设置时返回默认值 + /// + TValue GetValue(NotificationData notificationData, string key, TValue defaultValue) + where TValue : struct; + + /// + /// 按顺序读取第一个非空字符串值(大小写不敏感) + /// + string? GetOrNull(NotificationData notificationData, params string[] keys); + + /// + /// 写入值, 复杂类型以 JSON 形式存储 + /// + void Set(NotificationData notificationData, string key, Type valueType, object? value, NotificationChannelDataFormat format); +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataJsonSerializer.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataJsonSerializer.cs new file mode 100644 index 000000000..525b88554 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataJsonSerializer.cs @@ -0,0 +1,22 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)的 JSON 序列化抽象 +/// +public interface INotificationChannelDataJsonSerializer +{ + /// + /// 序列化 + /// + string Serialize(object value, Type valueType); + + /// + /// 反序列化 + /// + /// JSON 字符串 + /// 目标类型 + /// 实例, 类型不支持时返回 null + object? Deserialize(string json, Type targetType); +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataPresenceProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataPresenceProvider.cs new file mode 100644 index 000000000..6ac3cd4d3 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataPresenceProvider.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据存在性判定提供者 +/// +public interface INotificationChannelDataPresenceProvider +{ + /// + /// 获取载荷声明的存在性判定模式 + /// + NotificationChannelDataPresenceMode GetPresenceMode(Type channelDataType); + + /// + /// 获取参与匹配的属性键 + /// + IReadOnlyList GetMatchingKeys(Type channelDataType); + + /// + /// 创建存在性判定委托 + /// + /// + /// 声明了按键判定, 却没有任何可参与匹配的属性 + /// + Func Create(Type channelDataType); +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataResolver.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataResolver.cs new file mode 100644 index 000000000..bd7da5a33 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataResolver.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)解析器 +/// +public interface INotificationChannelDataResolver +{ + /// + /// 按匹配顺序解析指定渠道的载荷 + /// + /// + /// 仅返回"已写入且可解析"的载荷; 传入非法数据时会被跳过并记录日志, + /// 渠道如果需要区分该情况, 应配合 使用。 + /// + IReadOnlyList Resolve(string providerName, NotificationData notificationData); + + /// + /// 解析指定类型的渠道数据 + /// + /// 载荷实例, 未写入或无法解析时返回 null + TChannelData? Resolve(NotificationData notificationData) + where TChannelData : NotificationChannelData; + + /// + /// 解析指定类型的渠道数据 + /// + NotificationChannelData? Resolve(Type payloadType, NotificationData notificationData); + + /// + /// 判断生产者是否声明了指定类型的渠道数据 + /// + /// + /// 与解析结果配合使用, 可以区分 + /// "生产者未写入载荷" 与 "载荷已写入但无法解析(数据非法)"。 + /// 后者属于生产者错误, 渠道应当明确报错而不是静默回退。 + /// + bool IsDeclared(NotificationData notificationData, Type payloadType); + + /// + /// 获取指定渠道的载荷类型集合 + /// + IReadOnlyList GetPayloadTypes(string providerName); + + /// + /// 获取载荷的标识键 + /// + /// + /// 返回该载荷第一个"参与存在性判定"的属性键(数据中的实际键名), + /// 用于诊断信息(例如"哪个键解析失败")。未声明可匹配属性时返回 null。 + /// + string? GetKey(NotificationData notificationData, Type payloadType); + + /// + /// 弱类型读取, 并转换为目标类型 + /// + object? Get(NotificationData notificationData, string key, Type targetType); + + /// + /// 类型化读取渠道数据键 + /// + /// + /// 用于读取"散落的标量选项"(如企业微信的 safe、enable_id_trans), + /// 这类值不需要独立载荷类型, 但同样必须经过弱类型转换。 + /// + TValue? GetValue(NotificationData notificationData, string key) + where TValue : struct; + + /// + /// 类型化读取渠道数据键, 未设置时返回默认值 + /// + TValue GetValue(NotificationData notificationData, string key, TValue defaultValue) + where TValue : struct; + + /// + /// 大小写不敏感地读取渠道数据键 + /// + /// + /// 用于兼容历史渠道实现中大小写敏感的遗留键(如 TemplateId), + /// 避免生产者因为大小写差异而静默失效。 + /// + string? GetOrNull(NotificationData notificationData, params string[] keys); +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataSerializer.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataSerializer.cs new file mode 100644 index 000000000..2f3a3c3b8 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataSerializer.cs @@ -0,0 +1,40 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)序列化器 +/// +/// +/// 生产者侧的统一入口, 负责把强类型载荷写入 。 +/// +public interface INotificationChannelDataSerializer +{ + /// + /// 写入渠道数据(载荷) + /// + /// 载荷类型 + /// 通知数据 + /// 载荷实例 + NotificationData Write(NotificationData notificationData, TChannelData channelData) + where TChannelData : class; + + /// + /// 写入渠道数据(载荷) + /// + /// 通知数据 + /// 载荷实例 + NotificationData Write(NotificationData notificationData, NotificationChannelData channelData); + + /// + /// 按载荷类型清除渠道数据 + /// + NotificationData Clear(NotificationData notificationData) + where TChannelData : class; + + /// + /// 判断通知数据中是否存在指定载荷 + /// + bool Has(NotificationData notificationData) + where TPayload : class; +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAccessor.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAccessor.cs new file mode 100644 index 000000000..a440b966d --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAccessor.cs @@ -0,0 +1,381 @@ +using System; +using System.Collections; +using System.Globalization; +using System.Text.Json; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Newtonsoft.Json.Linq; +using Volo.Abp.DependencyInjection; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)存取器 +/// +/// +/// 渠道数据"弱类型属性包 ↔ 强类型值"转换的唯一实现, +/// 由 与 +/// 共用, 并保证与所用 JSON 实现无关。 +/// +public class NotificationChannelDataAccessor : INotificationChannelDataAccessor, ISingletonDependency +{ + protected ILogger Logger { get; } + protected INotificationChannelDataJsonSerializer JsonSerializer { get; } + + public NotificationChannelDataAccessor( + INotificationChannelDataJsonSerializer jsonSerializer, + ILogger? logger = null) + { + JsonSerializer = jsonSerializer; + Logger = logger ?? NullLogger.Instance; + } + + public virtual string? GetDataTypeKey(Type payloadType) + { + return payloadType.FullName; + } + + public virtual bool IsPresent(NotificationData notificationData, string key) + { + return TryGetRawValue(notificationData, key, out _, out _); + } + + public virtual bool TryGetRawValue( + NotificationData notificationData, + string key, + out object? value, + out string? matchedKey) + { + value = null; + matchedKey = null; + + if (notificationData == null || key.IsNullOrWhiteSpace()) + { + return false; + } + + if (notificationData.ExtraProperties.TryGetValue(key, out var exactValue)) + { + value = exactValue; + matchedKey = key; + + return true; + } + + // 精确匹配未命中时按大小写不敏感匹配, 兼容历史遗留键(如 TemplateId) + foreach (var property in notificationData.ExtraProperties) + { + if (string.Equals(property.Key, key, StringComparison.OrdinalIgnoreCase)) + { + value = property.Value; + matchedKey = property.Key; + + return true; + } + } + + return false; + } + + public virtual object? Get(NotificationData notificationData, string key, Type targetType) + { + return TryGetRawValue(notificationData, key, out var rawValue, out var matchedKey) + ? ConvertValue(rawValue!, targetType, matchedKey ?? key) + : null; + } + + public virtual TValue? GetValue(NotificationData notificationData, string key) + where TValue : struct + { + var value = Get(notificationData, key, typeof(TValue)); + + return value is TValue typedValue ? typedValue : null; + } + + public virtual TValue GetValue(NotificationData notificationData, string key, TValue defaultValue) + where TValue : struct + { + return GetValue(notificationData, key) ?? defaultValue; + } + + public virtual string? GetOrNull(NotificationData notificationData, params string[] keys) + { + if (notificationData == null || keys == null) + { + return null; + } + + foreach (var key in keys) + { + if (TryGetRawValue(notificationData, key, out var value, out _) && value != null) + { + return value.ToString(); + } + } + + return null; + } + + public virtual void Set( + NotificationData notificationData, + string key, + Type valueType, + object? value, + NotificationChannelDataFormat format) + { + if (value == null) + { + notificationData.TrySetData(key, null); + return; + } + + var underlyingType = Nullable.GetUnderlyingType(valueType) ?? valueType; + + if (format == NotificationChannelDataFormat.Json || !NotificationChannelDataValueTypes.IsPrimitive(underlyingType)) + { + notificationData.TrySetData(key, JsonSerializer.Serialize(value, underlyingType)); + return; + } + + notificationData.TrySetData(key, value); + } + + protected virtual object? ConvertValue(object rawValue, Type targetType, string key) + { + var underlyingType = Nullable.GetUnderlyingType(targetType) ?? targetType; + + if (underlyingType.IsInstanceOfType(rawValue)) + { + return rawValue; + } + + // 不同 JSON 实现留下的中间表示(JsonElement / JValue)先还原为 CLR 原始值 + var unwrapped = UnwrapJsonValue(rawValue); + if (unwrapped == null) + { + return null; + } + + if (underlyingType.IsInstanceOfType(unwrapped)) + { + return unwrapped; + } + + if (underlyingType == typeof(string)) + { + return unwrapped.ToString(); + } + + if (underlyingType.IsEnum) + { + return ConvertEnumValue(unwrapped, underlyingType, key); + } + + if (NotificationChannelDataValueTypes.IsPrimitive(underlyingType)) + { + return ConvertPrimitiveValue(unwrapped, underlyingType, key); + } + + return ConvertComplexValue(unwrapped, underlyingType, key); + } + + /// + /// 还原 JSON 中间表示 + /// + /// + /// System.Text.Json 产生 JsonElement, Newtonsoft 产生 JValue; + /// 两者都还原为 CLR 原始值, 使转换逻辑与 JSON 实现无关。 + /// + protected virtual object? UnwrapJsonValue(object rawValue) + { + if (rawValue is JsonElement jsonElement) + { + return UnwrapJsonElement(jsonElement); + } + + if (rawValue is JValue jValue) + { + return jValue.Value; + } + + return rawValue; + } + + protected virtual object? UnwrapJsonElement(JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.Null: + case JsonValueKind.Undefined: + return null; + + case JsonValueKind.String: + return element.GetString(); + + case JsonValueKind.True: + return true; + + case JsonValueKind.False: + return false; + + case JsonValueKind.Number: + if (element.TryGetInt32(out var intValue)) + { + return intValue; + } + if (element.TryGetInt64(out var longValue)) + { + return longValue; + } + if (element.TryGetDecimal(out var decimalValue)) + { + return decimalValue; + } + return element.GetDouble(); + + default: + // 数组/对象: 以原始 JSON 文本参与后续反序列化 + return element.GetRawText(); + } + } + + protected virtual object? ConvertEnumValue(object rawValue, Type underlyingType, string key) + { + if (rawValue is string enumName) + { + try + { + return Enum.Parse(underlyingType, enumName, ignoreCase: true); + } + catch (Exception ex) + { + Logger.LogWarning(ex, + "Failed to parse the channel data '{Key}' as enum '{Type}', the value will be ignored.", + key, underlyingType.FullName); + return null; + } + } + + try + { + return Enum.ToObject( + underlyingType, + Convert.ChangeType(rawValue, Enum.GetUnderlyingType(underlyingType), CultureInfo.InvariantCulture)!); + } + catch (Exception ex) + { + Logger.LogWarning(ex, + "Failed to convert the channel data '{Key}' to enum '{Type}', the value will be ignored.", + key, underlyingType.FullName); + return null; + } + } + + protected virtual object? ConvertPrimitiveValue(object rawValue, Type underlyingType, string key) + { + // JSON 往返后布尔值可能以数字或字符串形式出现, 而 Convert 只认 "True"/"False" + if (underlyingType == typeof(bool) && TryConvertBoolean(rawValue, out var booleanValue)) + { + return booleanValue; + } + + try + { + return Convert.ChangeType(rawValue, underlyingType, CultureInfo.InvariantCulture); + } + catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException) + { + // JSON 往返后字符串可能包裹了引号, 例如 "\"1\"", 再尝试一次去引号转换 + if (rawValue is string text) + { + var trimmed = text.Trim().Trim('"'); + if (!ReferenceEquals(trimmed, text) && trimmed.Length > 0) + { + try + { + return Convert.ChangeType(trimmed, underlyingType, CultureInfo.InvariantCulture); + } + catch (Exception inner) when (inner is FormatException || inner is InvalidCastException || inner is OverflowException) + { + // 忽略, 统一在下方记录日志 + } + } + } + + Logger.LogWarning(ex, + "Failed to convert the channel data '{Key}' of '{ValueType}' to '{TargetType}', the value will be ignored.", + key, rawValue.GetType().FullName, underlyingType.FullName); + return null; + } + } + + protected virtual object? ConvertComplexValue(object rawValue, Type underlyingType, string key) + { + if (rawValue is not string json) + { + Logger.LogWarning( + "The channel data '{Key}' is stored as '{ValueType}', but '{TargetType}' was expected, the value will be ignored.", + key, rawValue.GetType().FullName, underlyingType.FullName); + return null; + } + + try + { + return JsonSerializer.Deserialize(json, underlyingType); + } + catch (Exception ex) + { + // 载荷非法时只记录日志并返回 null, + // 由调用方通过"已声明但解析失败"来明确报错 + Logger.LogWarning(ex, + "Failed to deserialize the channel data '{Key}' to '{TargetType}', the value will be ignored.", + key, underlyingType.FullName); + return null; + } + } + + /// + /// 尝试把各种表示形式转换为布尔值 + /// + /// + /// 数值型 0/1 与字符串 "0"/"1" / "true"/"false" 都会被识别, + /// Convert.ChangeType 只接受 "True"/"False", 因此需要单独处理。 + /// + protected virtual bool TryConvertBoolean(object rawValue, out bool result) + { + switch (rawValue) + { + case bool booleanValue: + result = booleanValue; + return true; + + case string text: + var trimmed = text.Trim().Trim('"'); + if (bool.TryParse(trimmed, out var parsed)) + { + result = parsed; + return true; + } + if (double.TryParse(trimmed, NumberStyles.Any, CultureInfo.InvariantCulture, out var number)) + { + result = number != 0; + return true; + } + break; + + default: + try + { + result = Convert.ToDouble(rawValue, CultureInfo.InvariantCulture) != 0; + return true; + } + catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException) + { + break; + } + } + + result = false; + return false; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptorList.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptorList.cs new file mode 100644 index 000000000..57f9ad50d --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptorList.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)类型集合 +/// +/// +/// 同一个渠道内的载荷按 排序, +/// 匹配顺序必须显式声明, 不允许依赖注册顺序或字段探测顺序。 +/// +public sealed class NotificationChannelDataDescriptorList : List +{ +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresence.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresence.cs new file mode 100644 index 000000000..2501868ae --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresence.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据存在性判定 +/// +/// +public static class NotificationChannelDataPresence +{ + private static readonly Dictionary> Delegates = new(); + private static readonly object SyncLock = new(); + + /// + /// 获取载荷声明的存在性判定模式 + /// + public static NotificationChannelDataPresenceMode GetPresenceMode(Type channelDataType) + { + var attribute = channelDataType.GetCustomAttribute(inherit: false); + + return attribute?.Presence ?? NotificationChannelDataPresenceMode.DeclaredProperties; + } + + /// + /// 获取参与匹配的属性键 + /// + public static IReadOnlyList GetMatchingKeys(Type channelDataType) + { + return channelDataType + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Select(property => new + { + Property = property, + Attribute = property.GetCustomAttribute(inherit: true) + }) + .Where(x => x.Attribute != null && !x.Attribute.IgnoreWhenMatching) + .Select(x => x.Attribute!.Name.IsNullOrWhiteSpace() ? x.Property.Name : x.Attribute!.Name!) + .Distinct() + .ToArray(); + } + + /// + /// 校验载荷的存在性声明 + /// + /// + /// 声明了按键判定, 却没有任何可参与匹配的属性 + /// + public static void Validate(Type channelDataType) + { + var mode = GetPresenceMode(channelDataType); + + if (mode != NotificationChannelDataPresenceMode.None && GetMatchingKeys(channelDataType).Count == 0) + { + throw new AbpNotificationChannelDataConfigurationException( + $"The channel data type '{channelDataType.FullName}' declares the presence mode '{mode}' " + + $"but has no matchable property. Annotate at least one property with " + + $"'{nameof(NotificationChannelPropertyAttribute)}' (and do not set " + + $"'{nameof(NotificationChannelPropertyAttribute.IgnoreWhenMatching)}' to true), " + + $"or set '{nameof(NotificationChannelDataAttribute.Presence)}' to " + + $"'{NotificationChannelDataPresenceMode.None}' if the payload always exists."); + } + } + + /// + /// 创建存在性判定委托 + /// + public static Func Create(Type channelDataType) + { + Validate(channelDataType); + + var mode = GetPresenceMode(channelDataType); + var keys = GetMatchingKeys(channelDataType); + + var cacheKey = $"{channelDataType.AssemblyQualifiedName}|{mode}|{string.Join(",", keys)}"; + + lock (SyncLock) + { + if (Delegates.TryGetValue(cacheKey, out var cached)) + { + return cached; + } + + var presence = Build(mode, keys); + + Delegates[cacheKey] = presence; + + return presence; + } + } + + /// + /// 判断通知数据中是否存在该键(大小写不敏感) + /// + /// + /// 精确匹配优先, 未命中时按大小写不敏感匹配, + /// 与 的规则保持一致。 + /// + public static bool ContainsKey(NotificationData notificationData, string key) + { + if (notificationData == null || key.IsNullOrWhiteSpace()) + { + return false; + } + + if (notificationData.ExtraProperties.ContainsKey(key)) + { + return true; + } + + foreach (var property in notificationData.ExtraProperties) + { + if (string.Equals(property.Key, key, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } + + private static Func Build( + NotificationChannelDataPresenceMode mode, + IReadOnlyList keys) + { + if (mode == NotificationChannelDataPresenceMode.None) + { + return _ => true; + } + + var notificationData = Expression.Parameter(typeof(NotificationData), "notificationData"); + var containsKeyMethod = typeof(NotificationChannelDataPresence) + .GetMethod(nameof(ContainsKey), BindingFlags.Public | BindingFlags.Static)!; + + Expression? body = null; + + foreach (var key in keys) + { + var containsKey = Expression.Call( + containsKeyMethod, + notificationData, + Expression.Constant(key)); + + body = body == null + ? containsKey + : mode == NotificationChannelDataPresenceMode.AnyDeclaredProperty + ? Expression.OrElse(body, containsKey) + : Expression.AndAlso(body, containsKey); + } + + return Expression + .Lambda>(body!, notificationData) + .Compile(); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceProvider.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceProvider.cs new file mode 100644 index 000000000..18208c113 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceProvider.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using Volo.Abp.DependencyInjection; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据存在性判定提供者 +/// +public class NotificationChannelDataPresenceProvider : INotificationChannelDataPresenceProvider, ISingletonDependency +{ + public virtual NotificationChannelDataPresenceMode GetPresenceMode(Type channelDataType) + { + return NotificationChannelDataPresence.GetPresenceMode(channelDataType); + } + + public virtual IReadOnlyList GetMatchingKeys(Type channelDataType) + { + return NotificationChannelDataPresence.GetMatchingKeys(channelDataType); + } + + public virtual Func Create(Type channelDataType) + { + return NotificationChannelDataPresence.Create(channelDataType); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataProperty.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataProperty.cs new file mode 100644 index 000000000..b70789ef7 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataProperty.cs @@ -0,0 +1,59 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据属性元数据 +/// +/// +/// 由 推导而来, +/// 描述"写入/读取哪个键、类型是什么、是否参与存在性判定"。 +/// +public sealed class NotificationChannelDataProperty +{ + /// + /// 数据键名 + /// + public string Key { get; } + + /// + /// 属性声明类型 + /// + public Type PropertyType { get; } + + /// + /// 存储格式 + /// + public NotificationChannelDataFormat Format { get; } + + /// + /// 是否在存在性判定时忽略本属性 + /// + public bool IgnoreWhenMatching { get; } + + /// + /// 读取委托 + /// + public Func GetValue { get; } + + /// + /// 写入委托 + /// + public Action SetValue { get; } + + public NotificationChannelDataProperty( + string key, + Type propertyType, + NotificationChannelDataFormat format, + bool ignoreWhenMatching, + Func getValue, + Action setValue) + { + Key = key; + PropertyType = propertyType; + Format = format; + IgnoreWhenMatching = ignoreWhenMatching; + GetValue = getValue; + SetValue = setValue; + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPropertyCache.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPropertyCache.cs new file mode 100644 index 000000000..5bcbbabfd --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPropertyCache.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据属性元数据缓存 +/// +/// +/// 纯反射元数据缓存(无 JSON、无日志、无配置依赖), 因此保持静态以避免 +/// 在序列化器、解析器、存在性提供者之间重复注入。 +/// +public static class NotificationChannelDataPropertyCache +{ + private static readonly Dictionary PropertiesCache = new(); + private static readonly object SyncLock = new(); + + /// + /// 获取载荷类型的属性元数据 + /// + public static NotificationChannelDataProperty[] GetProperties(Type channelDataType) + { + lock (SyncLock) + { + if (PropertiesCache.TryGetValue(channelDataType, out var properties)) + { + return properties; + } + + properties = channelDataType + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Select(TryCreateProperty) + .Where(x => x != null) + .Select(x => x!) + .ToArray(); + + PropertiesCache[channelDataType] = properties; + + return properties; + } + } + + private static NotificationChannelDataProperty? TryCreateProperty(PropertyInfo property) + { + var attribute = property.GetCustomAttribute(inherit: true); + if (attribute == null || !property.CanRead) + { + return null; + } + + var key = attribute.Name.IsNullOrWhiteSpace() ? property.Name : attribute.Name!; + + return new NotificationChannelDataProperty( + key, + property.PropertyType, + NotificationChannelDataFormat.Auto, + attribute.IgnoreWhenMatching, + CreateGetter(property), + property.CanWrite ? CreateSetter(property) : null!); + } + + private static Func CreateGetter(PropertyInfo property) + { + var instance = Expression.Parameter(typeof(object), "instance"); + var typedInstance = Expression.Convert(instance, property.DeclaringType!); + var propertyAccess = Expression.Property(typedInstance, property); + + return Expression + .Lambda>(Expression.Convert(propertyAccess, typeof(object)), instance) + .Compile(); + } + + private static Action CreateSetter(PropertyInfo property) + { + var instance = Expression.Parameter(typeof(object), "instance"); + var value = Expression.Parameter(typeof(object), "value"); + var typedInstance = Expression.Convert(instance, property.DeclaringType!); + + var assign = Expression.Assign( + Expression.Property(typedInstance, property), + Expression.Convert(value, property.PropertyType)); + + return Expression + .Lambda>(assign, instance, value) + .Compile(); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataResolver.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataResolver.cs new file mode 100644 index 000000000..f39aa76a6 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataResolver.cs @@ -0,0 +1,279 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Volo.Abp; +using Volo.Abp.DependencyInjection; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)解析器 +/// +public class NotificationChannelDataResolver : INotificationChannelDataResolver, ISingletonDependency +{ + protected IServiceProvider ServiceProvider { get; } + protected INotificationChannelDataAccessor Accessor { get; } + protected INotificationChannelDataPresenceProvider PresenceProvider { get; } + protected ILogger Logger { get; } + + private readonly IOptions _options; + private readonly Dictionary> _registrations; + private readonly Dictionary _registrationsByType; + private readonly object _syncLock = new(); + + public NotificationChannelDataResolver( + IServiceProvider serviceProvider, + IOptions options, + INotificationChannelDataAccessor accessor, + INotificationChannelDataPresenceProvider presenceProvider, + ILogger? logger = null) + { + ServiceProvider = serviceProvider; + _options = options; + Accessor = accessor; + PresenceProvider = presenceProvider; + Logger = logger ?? NullLogger.Instance; + _registrations = new Dictionary>(StringComparer.OrdinalIgnoreCase); + _registrationsByType = new Dictionary(); + } + + public virtual IReadOnlyList Resolve(string providerName, NotificationData notificationData) + { + Check.NotNull(providerName, nameof(providerName)); + Check.NotNull(notificationData, nameof(notificationData)); + + var result = new List(); + + foreach (var registration in GetRegistrations(providerName)) + { + if (!registration.IsPresent(notificationData)) + { + continue; + } + + var channelData = CreateChannelData(registration, notificationData); + if (channelData != null) + { + result.Add(channelData); + } + } + + return result; + } + + public virtual TChannelData? Resolve(NotificationData notificationData) + where TChannelData : NotificationChannelData + { + return Resolve(typeof(TChannelData), notificationData) as TChannelData; + } + + public virtual NotificationChannelData? Resolve(Type payloadType, NotificationData notificationData) + { + Check.NotNull(payloadType, nameof(payloadType)); + Check.NotNull(notificationData, nameof(notificationData)); + + var registration = GetRegistration(payloadType); + + return registration.IsPresent(notificationData) + ? CreateChannelData(registration, notificationData) + : null; + } + + public virtual bool IsDeclared(NotificationData notificationData, Type payloadType) + { + Check.NotNull(notificationData, nameof(notificationData)); + Check.NotNull(payloadType, nameof(payloadType)); + + return GetRegistration(payloadType).IsPresent(notificationData); + } + + public virtual IReadOnlyList GetPayloadTypes(string providerName) + { + return GetRegistrations(providerName) + .Select(x => x.Descriptor.PayloadType) + .ToArray(); + } + + public virtual string? GetKey(NotificationData notificationData, Type payloadType) + { + Check.NotNull(payloadType, nameof(payloadType)); + + // 返回数据中实际命中的载荷标识键(大小写可能与声明不同), 用于诊断信息 + foreach (var key in PresenceProvider.GetMatchingKeys(payloadType)) + { + if (Accessor.TryGetRawValue(notificationData, key, out _, out var matchedKey)) + { + return matchedKey ?? key; + } + } + + // 数据中不存在时返回声明的标识键 + return PresenceProvider.GetMatchingKeys(payloadType).FirstOrDefault(); + } + + public virtual object? Get(NotificationData notificationData, string key, Type targetType) + { + return Accessor.Get(notificationData, key, targetType); + } + + public virtual TValue? GetValue(NotificationData notificationData, string key) + where TValue : struct + { + return Accessor.GetValue(notificationData, key); + } + + public virtual TValue GetValue(NotificationData notificationData, string key, TValue defaultValue) + where TValue : struct + { + return Accessor.GetValue(notificationData, key, defaultValue); + } + + public virtual string? GetOrNull(NotificationData notificationData, params string[] keys) + { + return Accessor.GetOrNull(notificationData, keys); + } + + protected virtual ChannelDataRegistration GetRegistration(Type payloadType) + { + if (_registrationsByType.TryGetValue(payloadType, out var registration)) + { + return registration; + } + + // 未注册的类型按约定直接读取, 避免生产者与渠道耦合到注册顺序 + return new ChannelDataRegistration( + new NotificationChannelDataDescriptor( + string.Empty, + payloadType, + 0, + PresenceProvider.GetPresenceMode(payloadType), + PresenceProvider.Create(payloadType)), + serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, payloadType)); + } + + protected virtual NotificationChannelData? CreateChannelData( + ChannelDataRegistration registration, + NotificationData notificationData) + { + object? instance; + try + { + instance = registration.Factory(ServiceProvider); + } + catch (Exception ex) + { + Logger.LogError(ex, + "Failed to create the channel data '{ChannelData}' for provider '{Provider}'.", + registration.Descriptor.PayloadType.FullName, registration.Descriptor.ProviderName); + return null; + } + + if (instance is not NotificationChannelData channelData) + { + Logger.LogError( + "The channel data '{ChannelData}' for provider '{Provider}' is not assignable to '{BaseType}'.", + registration.Descriptor.PayloadType.FullName, registration.Descriptor.ProviderName, typeof(NotificationChannelData).FullName); + return null; + } + + foreach (var property in NotificationChannelDataPropertyCache.GetProperties(registration.Descriptor.PayloadType)) + { + // 按大小写不敏感的方式定位实际键名, 兼容生产者使用不同大小写写入的数据 + if (!Accessor.TryGetRawValue(notificationData, property.Key, out var rawValue, out var matchedKey)) + { + continue; + } + + if (rawValue == null) + { + continue; + } + + var value = ConvertPropertyValue(notificationData, property, matchedKey); + + if (value == null) + { + // 值存在但无法解析/类型不符, 说明生产者写入的载荷非法 + Logger.LogWarning( + "The channel data '{ChannelData}' property '{Property}' of provider '{Provider}' can not be resolved from the key '{Key}'.", + registration.Descriptor.PayloadType.FullName, property.Key, registration.Descriptor.ProviderName, matchedKey ?? property.Key); + return null; + } + + property.SetValue(channelData, value); + } + + return channelData; + } + + /// + /// 转换载荷属性值 + /// + /// 转换结果; 无法转换或类型不符时返回 null + protected virtual object? ConvertPropertyValue( + NotificationData notificationData, + NotificationChannelDataProperty property, + string? matchedKey) + { + var value = Accessor.Get(notificationData, matchedKey ?? property.Key, property.PropertyType); + + if (value == null) + { + return null; + } + + // 值的运行时类型必须与属性声明类型兼容 + var underlyingType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; + + return underlyingType.IsInstanceOfType(value) ? value : null; + } + + protected virtual IReadOnlyList GetRegistrations(string providerName) + { + lock (_syncLock) + { + if (_registrations.TryGetValue(providerName, out var registrations)) + { + return registrations; + } + + registrations = _options.Value + .GetProviderData(providerName) + .Select(CreateRegistration) + .ToList(); + + _registrations[providerName] = registrations; + + return registrations; + } + } + + protected virtual ChannelDataRegistration CreateRegistration(NotificationChannelDataDescriptor descriptor) + { + return new ChannelDataRegistration( + descriptor, + serviceProvider => ActivatorUtilities.CreateInstance(serviceProvider, descriptor.PayloadType)); + } + + /// + /// 渠道数据注册项 + /// + protected sealed class ChannelDataRegistration + { + public NotificationChannelDataDescriptor Descriptor { get; } + public Func Factory { get; } + public Func IsPresent => Descriptor.IsPresent; + + public ChannelDataRegistration( + NotificationChannelDataDescriptor descriptor, + Func factory) + { + Descriptor = descriptor; + Factory = factory; + } + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataSerializer.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataSerializer.cs new file mode 100644 index 000000000..6f1110176 --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataSerializer.cs @@ -0,0 +1,89 @@ +using System; +using Volo.Abp; +using Volo.Abp.DependencyInjection; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 通知渠道数据(载荷)序列化器 +/// +/// +/// +/// 生产者侧的统一入口, 负责把强类型载荷写入 。 +/// +/// +/// 载荷的写入是"声明式"的: 载荷类型上的 +/// 决定写入哪些键以及如何转换, 因此生产者与渠道实现共用同一份契约定义, +/// 不会出现"一方写了键、另一方永远读不到"的情况。 +/// +/// +public class NotificationChannelDataSerializer : INotificationChannelDataSerializer, ISingletonDependency +{ + protected INotificationChannelDataAccessor Accessor { get; } + protected INotificationChannelDataPresenceProvider PresenceProvider { get; } + + public NotificationChannelDataSerializer( + INotificationChannelDataAccessor accessor, + INotificationChannelDataPresenceProvider presenceProvider) + { + Accessor = accessor; + PresenceProvider = presenceProvider; + } + + public virtual NotificationData Write(NotificationData notificationData, TChannelData channelData) + where TChannelData : class + { + Check.NotNull(notificationData, nameof(notificationData)); + Check.NotNull(channelData, nameof(channelData)); + + return Write(notificationData, (NotificationChannelData)(object)channelData); + } + + public virtual NotificationData Write(NotificationData notificationData, NotificationChannelData channelData) + { + Check.NotNull(notificationData, nameof(notificationData)); + Check.NotNull(channelData, nameof(channelData)); + + foreach (var property in NotificationChannelDataPropertyCache.GetProperties(channelData.GetType())) + { + var value = property.GetValue(channelData); + if (value == null) + { + continue; + } + + Accessor.Set(notificationData, property.Key, property.PropertyType, value, property.Format); + } + + return notificationData; + } + + public virtual NotificationData Clear(NotificationData notificationData) + where TChannelData : class + { + Check.NotNull(notificationData, nameof(notificationData)); + + return Clear(notificationData, typeof(TChannelData)); + } + + public virtual NotificationData Clear(NotificationData notificationData, Type channelDataType) + { + Check.NotNull(notificationData, nameof(notificationData)); + Check.NotNull(channelDataType, nameof(channelDataType)); + + foreach (var property in NotificationChannelDataPropertyCache.GetProperties(channelDataType)) + { + notificationData.ExtraProperties.Remove(property.Key); + } + + return notificationData; + } + + public virtual bool Has(NotificationData notificationData) + where TPayload : class + { + Check.NotNull(notificationData, nameof(notificationData)); + + return PresenceProvider.Create(typeof(TPayload))(notificationData); + } +} diff --git a/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataValueTypes.cs b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataValueTypes.cs new file mode 100644 index 000000000..ee7fbdb8a --- /dev/null +++ b/aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataValueTypes.cs @@ -0,0 +1,27 @@ +using System; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据的值类型判定 +/// +/// +/// 用于区分"可直接存入属性包"的简单类型与"需要序列化"的复杂类型。 +/// +public static class NotificationChannelDataValueTypes +{ + /// + /// 判断是否为可直接存储的简单类型 + /// + public static bool IsPrimitive(Type type) + { + return type.IsPrimitive + || type.IsEnum + || type == typeof(string) + || type == typeof(decimal) + || type == typeof(DateTime) + || type == typeof(DateTimeOffset) + || type == typeof(TimeSpan) + || type == typeof(Guid); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/LINGYUN.Abp.Notifications.ChannelData.Tests.csproj b/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/LINGYUN.Abp.Notifications.ChannelData.Tests.csproj new file mode 100644 index 000000000..3bedb9364 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/LINGYUN.Abp.Notifications.ChannelData.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + + false + enable + Debug;Release;PostgreSQL + AnyCPU + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/NotificationChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/NotificationChannelData_Tests.cs new file mode 100644 index 000000000..63c00b51c --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/NotificationChannelData_Tests.cs @@ -0,0 +1,390 @@ +using LINGYUN.Abp.Notifications; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using System; +using System.Linq; +using System.Text.Json; +using Xunit; + +namespace LINGYUN.Abp.Notifications.ChannelData.Tests; + +/// +/// 渠道数据(载荷)框架契约测试 +/// +/// +/// +/// 本文件只测试**框架契约**本身: 弱类型转换、存在性判定、注册期校验、 +/// 优先级排序、JSON 往返。测试用载荷是本文件内定义的 stub 类型。 +/// +/// +/// **具体渠道**的数据测试在各自的测试项目中(先 new 消息对象 → +/// IJsonSerializer 序列化 → 渠道侧验证): +/// +/// LINGYUN.Abp.Notifications.WeChat.Work.Tests +/// LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests +/// LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests +/// LINGYUN.Abp.Notifications.WxPusher.Tests +/// LINGYUN.Abp.Notifications.PushPlus.Tests +/// +/// +/// +public class NotificationChannelData_Tests +{ + // ---------- 1. 弱类型转换 ---------- + + [Theory] + [InlineData((byte)1)] + [InlineData(1)] + [InlineData(1L)] + [InlineData("1")] + [InlineData("\"1\"")] + [InlineData(true)] + [InlineData("true")] + public void Should_Coerce_All_Representations_To_Bool(object stored) + { + var data = new NotificationData(); + data.TrySetData("key", stored); + + CreateResolver().GetValue(data, "key", false).ShouldBeTrue(); + } + + [Fact] + public void Should_Distinguish_Unset_From_Explicit_False() + { + var unset = new NotificationData(); + CreateResolver().GetValue(unset, "key").ShouldBeNull(); + + var explicitFalse = new NotificationData(); + explicitFalse.TrySetData("key", 0); + CreateResolver().GetValue(explicitFalse, "key").ShouldBe(false); + } + + [Fact] + public void Should_Read_Values_After_Json_RoundTrip() + { + // 通知数据在持久化/失败重试/跨进程投递后必然经历 JSON 往返 + var data = new NotificationData(); + data.TrySetData("key", (byte)1); + + var roundTripped = RoundTrip(data); + roundTripped.ExtraProperties["key"].ShouldNotBeOfType(); + + CreateResolver().GetValue(roundTripped, "key", false).ShouldBeTrue(); + } + + [Fact] + public void Should_Match_Keys_Case_Insensitively() + { + var data = new NotificationData(); + data.TrySetData("my-stub:key", "value-1"); + + var resolver = CreateResolver(); + + // 精确命中 + resolver.GetOrNull(data, "my-stub:key").ShouldBe("value-1"); + // 任意大小写都应命中 + resolver.GetOrNull(data, "MY-STUB:KEY").ShouldBe("value-1"); + resolver.GetOrNull(data, "My-Stub:Key").ShouldBe("value-1"); + } + + // ---------- 2. 存在性判定(声明式) ---------- + + [Fact] + public void Should_Detect_Explicit_Payload() + { + var data = new NotificationData(); + ChannelData().Write(data, new PriorityStubA { A = "a" }); + + CreateResolver().IsDeclared(data, typeof(PriorityStubA)).ShouldBeTrue(); + CreateResolver().IsDeclared(data, typeof(PriorityStubB)).ShouldBeFalse(); + } + + [Fact] + public void Should_Not_Treat_Ignored_Properties_As_Payload() + { + var data = new NotificationData(); + // 只写被标记为"仅读取"的属性: 不得视为声明了载荷 + data.TrySetData("stubB:optional", "value"); + + CreateResolver().IsDeclared(data, typeof(PriorityStubB)).ShouldBeFalse(); + } + + [Fact] + public void Should_Apply_AnyDeclaredProperty_Presence_Mode() + { + var resolver = CreateResolver(); + + var first = new NotificationData(); + first.TrySetData("stub-many:first", "v"); + resolver.IsDeclared(first, typeof(AnyDeclaredPropertyStub)).ShouldBeTrue(); + + var second = new NotificationData(); + second.TrySetData("stub-many:second", "v"); + resolver.IsDeclared(second, typeof(AnyDeclaredPropertyStub)).ShouldBeTrue(); + + // 声明了按键判定, 但一个键都没写 -> 不存在 + resolver.IsDeclared(new NotificationData(), typeof(AnyDeclaredPropertyStub)).ShouldBeFalse(); + } + + [Fact] + public void Should_Ignore_Matching_For_Optional_Properties() + { + var data = new NotificationData(); + // 只写"仅读取"的属性 -> 不算载荷 + data.TrySetData("stubB:optional", "value"); + CreateResolver().IsDeclared(data, typeof(PriorityStubB)).ShouldBeFalse(); + + // 写标识键 -> 算载荷 + var withIdentity = new NotificationData(); + withIdentity.TrySetData("stub:b", "value"); + CreateResolver().IsDeclared(withIdentity, typeof(PriorityStubB)).ShouldBeTrue(); + } + + [Fact] + public void Should_Allow_Always_Present_Payload() + { + var resolver = CreateResolver(); + + // Presence = None: 无条件存在 + resolver.IsDeclared(new NotificationData(), typeof(AlwaysPresentStub)).ShouldBeTrue(); + + var payload = resolver.Resolve(new NotificationData()); + payload.ShouldNotBeNull(); + } + + // ---------- 3. 注册期校验 ---------- + + [Fact] + public void Should_Throw_When_Presence_Declared_Without_Matchable_Property() + { + var exception = Should.Throw( + () => CreateOptions().Add()); + + exception.Message.ShouldContain("matchable property"); + } + + [Fact] + public void Should_Reject_Missing_Channel_Data_Attribute() + { + var exception = Should.Throw( + () => CreateOptions().Add()); + + exception.Message.ShouldContain("NotificationChannelDataAttribute"); + } + + [Fact] + public void Should_Reject_Duplicate_Priority_In_Same_Provider() + { + var options = CreateOptions(); + options.Add(); + + var exception = Should.Throw( + () => options.Add()); + + exception.Message.ShouldContain("same priority"); + } + + // ---------- 4. 解析与排序 ---------- + + [Fact] + public void Should_Resolve_Payloads_In_Declared_Priority_Order() + { + var data = new NotificationData(); + ChannelData().Write(data, new PriorityStubB { B = "b" }); + ChannelData().Write(data, new PriorityStubA { A = "a" }); + + var resolved = CreateResolver().Resolve(TestProvider, data); + + // 只声明了 A 与 B; AnyDeclaredPropertyStub 未写入, AlwaysPresentStub(Presence=None) + // 无条件存在, 因此共 3 个 + resolved.Count.ShouldBe(3); + // Priority: AlwaysPresentStub=400, A=100, B=200 -> 排序后 A, B, Always + resolved[0].ShouldBeOfType(); + resolved[1].ShouldBeOfType(); + resolved[2].ShouldBeOfType(); + } + + [Fact] + public void Should_Resolve_Payload_After_Json_RoundTrip() + { + var data = new NotificationData(); + ChannelData().Write(data, new PriorityStubA { A = "卡片标题" }); + + // 复杂载荷以 JSON 字符串形式存储, 往返后仍必须能还原为强类型 + data.ExtraProperties["stub:a"].ShouldBeOfType(); + + var payload = CreateResolver().Resolve(RoundTrip(data)); + + payload.ShouldNotBeNull(); + payload!.A.ShouldBe("卡片标题"); + } + + [Fact] + public void Should_Not_Throw_For_Invalid_Payload_But_Report_Declared() + { + var data = new NotificationData(); + // 复杂载荷以 JSON 字符串存储; 这里写入非法 JSON + data.TrySetData("stub:json", "{ this is not json }"); + + var resolver = CreateResolver(); + + // IsDeclared 仍为 true(生产者确实写了), Resolve 返回 null(解析失败, 仅记日志) + resolver.IsDeclared(data, typeof(JsonPayloadStub)).ShouldBeTrue(); + resolver.Resolve(data).ShouldBeNull(); + // 诊断信息给出实际命中的键名 + resolver.GetKey(data, typeof(JsonPayloadStub)).ShouldBe("stub:json"); + } + + [Fact] + public void Should_Resolve_Complex_Payload_After_Json_RoundTrip() + { + var data = new NotificationData(); + ChannelData().Write(data, new JsonPayloadStub + { + Payload = new StubPayload { Name = "标题", Count = 3 } + }); + + // 复杂类型以 JSON 字符串形式存储 + data.ExtraProperties["stub:json"].ShouldBeOfType(); + + var payload = CreateResolver().Resolve(RoundTrip(data)); + + payload.ShouldNotBeNull(); + payload!.Payload.ShouldNotBeNull(); + payload.Payload!.Name.ShouldBe("标题"); + payload.Payload.Count.ShouldBe(3); + } + + // ---------- 5. 测试用载荷 ---------- + + private const string TestProvider = "stub"; + + [NotificationChannelData(TestProvider, Priority = 100)] + private class PriorityStubA : NotificationChannelData + { + [NotificationChannelProperty("stub:a")] + public string? A { get; set; } + } + + [NotificationChannelData(TestProvider, Priority = 200)] + private class PriorityStubB : NotificationChannelData + { + [NotificationChannelProperty("stub:b")] + public string? B { get; set; } + + [NotificationChannelProperty("stubB:optional", IgnoreWhenMatching = true)] + public string? Optional { get; set; } + } + + [NotificationChannelData(TestProvider, Priority = 100)] + private class DuplicatePriorityStub : NotificationChannelData + { + [NotificationChannelProperty("stub:dup")] + public string? Value { get; set; } + } + + [NotificationChannelData(TestProvider, Priority = 300, + Presence = NotificationChannelDataPresenceMode.AnyDeclaredProperty)] + private class AnyDeclaredPropertyStub : NotificationChannelData + { + [NotificationChannelProperty("stub-many:first")] + public string? First { get; set; } + + [NotificationChannelProperty("stub-many:second")] + public string? Second { get; set; } + } + + [NotificationChannelData(TestProvider, Priority = 400, + Presence = NotificationChannelDataPresenceMode.None)] + private class AlwaysPresentStub : NotificationChannelData + { + [NotificationChannelProperty("stub-always:value")] + public string? Value { get; set; } + } + + [NotificationChannelData(TestProvider, Priority = 500, + Presence = NotificationChannelDataPresenceMode.DeclaredProperties)] + private class MissingMatchablePropertyStub : NotificationChannelData + { + // 没有任何带 [NotificationChannelProperty] 的属性 + public string? Value { get; set; } + } + + /// + /// 复杂载荷(以 JSON 字符串存储) + /// + [NotificationChannelData(TestProvider, Priority = 600)] + private class JsonPayloadStub : NotificationChannelData + { + [NotificationChannelProperty("stub:json")] + public StubPayload? Payload { get; set; } + } + + private class StubPayload + { + public string? Name { get; set; } + + public int Count { get; set; } + } + + private class NoAttributeStub : NotificationChannelData + { + public string? Value { get; set; } + } + + // ---------- 辅助 ---------- + + private static AbpNotificationChannelDataOptions CreateOptions() + { + // 选项是纯数据: 存在性判定为纯静态, 注册时无需解析任何服务 + return new AbpNotificationChannelDataOptions(); + } + + private static NotificationChannelDataResolver CreateResolver() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.PostConfigure(options => + { + options.Add(); + options.Add(); + options.Add(); + options.Add(); + options.Add(); + }); + + var provider = services.BuildServiceProvider(); + + return (NotificationChannelDataResolver)provider.GetRequiredService(); + } + + private static INotificationChannelDataSerializer ChannelData() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + return services.BuildServiceProvider().GetRequiredService(); + } + + private static NotificationData RoundTrip(NotificationData data) + { + var json = JsonSerializer.Serialize(data.ExtraProperties); + + return new NotificationData + { + ExtraProperties = JsonSerializer.Deserialize(json)! + }; + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/TestNotificationChannelDataJsonSerializer.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/TestNotificationChannelDataJsonSerializer.cs new file mode 100644 index 000000000..cb99a3311 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.ChannelData.Tests/TestNotificationChannelDataJsonSerializer.cs @@ -0,0 +1,30 @@ +using System; +using System.Text.Json; + +namespace LINGYUN.Abp.Notifications.ChannelData.Tests; + +/// +/// 测试用 JSON 实现 +/// +/// +/// 与 AbpNotificationChannelDataJsonSerializer 的职责一致(委托给 JSON 库), +/// 这里直接使用 , +/// 以避免框架契约测试依赖 ABP 的完整模块装载。 +/// +/// 渠道特有的多态转换器(模板卡片等)在各自渠道的测试项目中断言。 +/// +/// +public class TestNotificationChannelDataJsonSerializer : INotificationChannelDataJsonSerializer +{ + private static readonly JsonSerializerOptions Options = new(); + + public string Serialize(object value, Type valueType) + { + return JsonSerializer.Serialize(value, valueType, Options); + } + + public object? Deserialize(string json, Type targetType) + { + return JsonSerializer.Deserialize(json, targetType, Options); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN.Abp.Notifications.PushPlus.Tests.csproj b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN.Abp.Notifications.PushPlus.Tests.csproj new file mode 100644 index 000000000..c2636e1b1 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN.Abp.Notifications.PushPlus.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + + false + Debug;Release;PostgreSQL + AnyCPU + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusTestsBase.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusTestsBase.cs new file mode 100644 index 000000000..3d39c240a --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusTestsBase.cs @@ -0,0 +1,6 @@ +namespace LINGYUN.Abp.Notifications.PushPlus; + +public abstract class AbpNotificationsPushPlusTestsBase + : NotificationChannelDataTestsBase +{ +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusTestsModule.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusTestsModule.cs new file mode 100644 index 000000000..7584b4512 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusTestsModule.cs @@ -0,0 +1,21 @@ +using LINGYUN.Abp.PushPlus.Message; +using LINGYUN.Abp.Tests; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Volo.Abp.Modularity; + +namespace LINGYUN.Abp.Notifications.PushPlus; + +[DependsOn( + typeof(AbpNotificationsPushPlusModule), + typeof(AbpNotificationsTestsModule), + typeof(AbpTestsBaseModule))] +public class AbpNotificationsPushPlusTestsModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + // 用捕获式假实现替换真实发送, 避免真正调用 PushPlus 接口 + context.Services.Replace( + ServiceDescriptor.Singleton()); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/FakePushPlusMessageSender.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/FakePushPlusMessageSender.cs new file mode 100644 index 000000000..2f7a5228f --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/FakePushPlusMessageSender.cs @@ -0,0 +1,54 @@ +using LINGYUN.Abp.PushPlus.Message; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace LINGYUN.Abp.Notifications.PushPlus; + +/// +/// 捕获式 假实现 +/// +public class FakePushPlusMessageSender : IPushPlusMessageSender +{ + public List SentMessages { get; } = new(); + + public Task SendWeChatAsync(string title, string content, string topic = "", PushPlusMessageTemplate template = PushPlusMessageTemplate.Html, string webhook = "", string callbackUrl = "", CancellationToken cancellationToken = default) + => Capture("WeChat", title, content, topic, template, webhook, callbackUrl); + + public Task SendEmailAsync(string title, string content, string topic = "", PushPlusMessageTemplate template = PushPlusMessageTemplate.Html, string webhook = "", string callbackUrl = "", CancellationToken cancellationToken = default) + => Capture("Email", title, content, topic, template, webhook, callbackUrl); + + public Task SendWeWorkAsync(string title, string content, string topic = "", PushPlusMessageTemplate template = PushPlusMessageTemplate.Html, string webhook = "", string callbackUrl = "", CancellationToken cancellationToken = default) + => Capture("WeWork", title, content, topic, template, webhook, callbackUrl); + + public Task SendWebhookAsync(string title, string content, string topic = "", PushPlusMessageTemplate template = PushPlusMessageTemplate.Html, string webhook = "", string callbackUrl = "", CancellationToken cancellationToken = default) + => Capture("Webhook", title, content, topic, template, webhook, callbackUrl); + + public Task SendSmsAsync(string title, string content, string topic = "", PushPlusMessageTemplate template = PushPlusMessageTemplate.Html, string webhook = "", string callbackUrl = "", CancellationToken cancellationToken = default) + => Capture("Sms", title, content, topic, template, webhook, callbackUrl); + + public void Clear() => SentMessages.Clear(); + + private Task Capture( + string channel, + string title, + string content, + string topic, + PushPlusMessageTemplate template, + string webhook, + string callbackUrl) + { + SentMessages.Add(new SentArgs(channel, title, content, topic, template, webhook, callbackUrl)); + + return Task.FromResult(string.Empty); + } + + public record SentArgs( + string Channel, + string Title, + string Content, + string Topic, + PushPlusMessageTemplate Template, + string Webhook, + string CallbackUrl); +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData_Tests.cs new file mode 100644 index 000000000..550f695f9 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.PushPlus.Tests/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData_Tests.cs @@ -0,0 +1,136 @@ +using Shouldly; +using System; +using System.Threading.Tasks; +using Xunit; + +namespace LINGYUN.Abp.Notifications.PushPlus; + +/// +/// PushPlus 渠道数据测试 +/// +/// +/// 统一写法: 先 new 渠道数据 → 通过 IJsonSerializer 序列化写入通知数据 → +/// 再让渠道实际发布, 断言捕获到的消息参数。 +/// +public class PushPlusChannelData_Tests : AbpNotificationsPushPlusTestsBase +{ + private const string Provider = PushPlusNotificationPublishProvider.ProviderName; + + private FakePushPlusMessageSender Sender + => (FakePushPlusMessageSender)GetRequiredService(); + + // ---------- 1. 解析渠道数据 ---------- + + [Fact] + public void Should_Resolve_Both_Optional_Keys() + { + var data = WriteChannelData(new PushPlusChannelData + { + Webhook = "https://example.com/hook", + CallbackUrl = "https://example.com/callback" + }); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.Webhook.ShouldBe("https://example.com/hook"); + payload.CallbackUrl.ShouldBe("https://example.com/callback"); + } + + [Fact] + public void Should_Declare_Payload_When_Only_One_Key_Written() + { + // Presence = AnyDeclaredProperty: 写入任意一个即视为声明 + var webhookOnly = WriteChannelData(new PushPlusChannelData + { + Webhook = "https://example.com/hook" + }); + ChannelDataResolver.IsDeclared(webhookOnly, typeof(PushPlusChannelData)).ShouldBeTrue(); + + var callbackOnly = WriteChannelData(new PushPlusChannelData + { + CallbackUrl = "https://example.com/callback" + }); + ChannelDataResolver.IsDeclared(callbackOnly, typeof(PushPlusChannelData)).ShouldBeTrue(); + } + + [Fact] + public void Should_Not_Declare_Payload_When_Nothing_Written() + { + ChannelDataResolver.IsDeclared(new NotificationData(), typeof(PushPlusChannelData)) + .ShouldBeFalse(); + } + + [Fact] + public void Should_Match_Keys_Case_Insensitively() + { + var data = new NotificationData(); + data.TrySetData(PushPlusNotificationDataKeys.Webhook, "https://example.com/hook"); + + ChannelDataResolver.Resolve(data)!.Webhook + .ShouldBe("https://example.com/hook"); + + var upper = new NotificationData(); + upper.TrySetData("PUSH-PLUS:WEBHOOK", "https://example.com/HOOK"); + + ChannelDataResolver.Resolve(upper)!.Webhook + .ShouldBe("https://example.com/HOOK"); + } + + // ---------- 2. 渠道实际发布(端到端) ---------- + + [Fact] + public async Task Should_Send_With_Resolved_Webhook_And_CallbackUrl() + { + Sender.Clear(); + + var data = WriteChannelData(new PushPlusChannelData + { + Webhook = "https://example.com/from-channel-data", + CallbackUrl = "https://example.com/callback" + }); + data.WriteStandardData("标题", "内容", DateTime.Now, "system"); + + await PublishAsync(data); + + Sender.SentMessages.Count.ShouldBe(1); + Sender.SentMessages[0].Webhook.ShouldBe("https://example.com/from-channel-data"); + Sender.SentMessages[0].CallbackUrl.ShouldBe("https://example.com/callback"); + Sender.SentMessages[0].Title.ShouldBe("标题"); + Sender.SentMessages[0].Content.ShouldBe("内容"); + } + + [Fact] + public async Task Should_Send_With_Empty_Options_When_Nothing_Written() + { + Sender.Clear(); + + var data = new NotificationData(); + data.WriteStandardData("标题", "内容", DateTime.Now, "system"); + + await PublishAsync(data); + + Sender.SentMessages.Count.ShouldBe(1); + Sender.SentMessages[0].Webhook.ShouldBeEmpty(); + Sender.SentMessages[0].CallbackUrl.ShouldBeEmpty(); + } + + private async Task PublishAsync(NotificationData data) + { + var provider = GetRequiredService(); + + var notification = new NotificationInfo + { + Name = "Test", + ContentType = NotificationContentType.Text, + Data = data + }; + notification.SetId(1); + + var context = new NotificationPublishContext( + notification, + new[] { new UserIdentifier(Guid.NewGuid(), "tester") }); + + await provider.PublishAsync(context); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.Tests/LINGYUN/Abp/Notifications/NotificationChannelDataTestsBase.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.Tests/LINGYUN/Abp/Notifications/NotificationChannelDataTestsBase.cs new file mode 100644 index 000000000..b176e9cc5 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.Tests/LINGYUN/Abp/Notifications/NotificationChannelDataTestsBase.cs @@ -0,0 +1,92 @@ +using LINGYUN.Abp.Tests; +using System.Reflection; +using Volo.Abp.Json; +using Volo.Abp.Modularity; + +namespace LINGYUN.Abp.Notifications; + +/// +/// 渠道数据测试基类 +/// +/// +/// 各渠道的测试项目继承本类并指定自己的测试模块(该模块依赖真实渠道模块), +/// 从而共用同一套"new 消息对象 → IJsonSerializer 序列化 → 渠道侧验证"的写法。 +/// +public abstract class NotificationChannelDataTestsBase : AbpTestsBase + where TStartupModule : IAbpModule +{ + /// + /// 渠道侧解析器 + /// + protected INotificationChannelDataResolver ChannelDataResolver + => GetRequiredService(); + + /// + /// 渠道数据存取器(生产侧写入用) + /// + protected INotificationChannelDataAccessor ChannelDataAccessor + => GetRequiredService(); + + /// + /// 生产者侧序列化器 + /// + protected INotificationChannelDataSerializer ChannelDataSerializer + => GetRequiredService(); + + /// + /// ABP 全局 JSON 序列化器 + /// + protected IJsonSerializer JsonSerializer + => GetRequiredService(); + + /// + /// 仅序列化消息对象, 便于断言 JSON 契约 + /// + protected string Serialize(TPayload payload) + where TPayload : class + { + return JsonSerializer.Serialize(payload); + } + + /// + /// 把消息对象序列化后写入通知数据的载荷键 + /// + /// + /// 走生产路径: 对复杂类型 + /// 调用 序列化, 与生产者写入的结果完全一致。 + /// + protected NotificationData WriteChannelData(TChannelData channelData) + where TChannelData : NotificationChannelData + { + return MergeChannelData(new NotificationData(), channelData); + } + + /// + /// 把消息对象序列化后合并写入已有的通知数据 + /// + protected NotificationData MergeChannelData( + NotificationData notificationData, + TChannelData channelData) + where TChannelData : NotificationChannelData + { + foreach (var property in typeof(TChannelData).GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + var attribute = property.GetCustomAttribute(); + if (attribute == null) + { + continue; + } + + var key = string.IsNullOrWhiteSpace(attribute.Name) ? property.Name : attribute.Name!; + + ChannelDataAccessor.Set( + notificationData, + key, + property.PropertyType, + property.GetValue(channelData), + NotificationChannelDataFormat.Auto); + } + + return notificationData; + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsBase.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsBase.cs index abde857bb..212f50fac 100644 --- a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsBase.cs +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsBase.cs @@ -1,8 +1,7 @@ -using LINGYUN.Abp.Tests; - namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram { - public class AbpNotificationsWeChatMiniProgramTestsBase : AbpTestsBase + public abstract class AbpNotificationsWeChatMiniProgramTestsBase + : NotificationChannelDataTestsBase { } } diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsModule.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsModule.cs index 292394526..d08dd8512 100644 --- a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsModule.cs +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramTestsModule.cs @@ -1,4 +1,7 @@ using LINGYUN.Abp.Tests; +using LINGYUN.Abp.WeChat.MiniProgram.Messages; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Volo.Abp.Modularity; namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram @@ -13,15 +16,18 @@ namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram { PreConfigure(options => { - // options.DefaultMsgPrefix = "[wmp-override]"; + // 默认值, 便于断言"未写入渠道数据时的兜底" + options.DefaultTemplateId = "DEFAULT_TEMPLATE_ID"; + options.DefaultState = "formal"; + options.DefaultLanguage = "zh_CN"; }); } public override void ConfigureServices(ServiceConfigurationContext context) { - Configure(options => - { - }); + // 用捕获式假实现替换真实发送, 避免真正调用微信接口 + context.Services.Replace( + ServiceDescriptor.Singleton()); } } } diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/FakeSubscribeMessager.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/FakeSubscribeMessager.cs new file mode 100644 index 000000000..a861843be --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/FakeSubscribeMessager.cs @@ -0,0 +1,62 @@ +using LINGYUN.Abp.WeChat.MiniProgram.Messages; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +// 本测试项目未全局启用可空上下文, 而本文件需要表达"可空参数"语义 +#nullable enable + +namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram; + +/// +/// 捕获式 假实现 +/// +/// +/// 用于在不真正调用微信接口的前提下, 断言渠道最终发出的模板消息内容。 +/// +public class FakeSubscribeMessager : ISubscribeMessager +{ + /// + /// 已发送的模板消息(按顺序) + /// + public List SentMessages { get; } = new(); + + /// + /// 已发送的"按模板参数"形式的调用 + /// + public List SentTemplates { get; } = new(); + + public Task SendAsync(SubscribeMessage message, CancellationToken cancellation = default) + { + SentMessages.Add(message); + return Task.CompletedTask; + } + + public Task SendAsync( + Guid toUser, + string templateId, + string? page = "", + string? lang = "zh_CN", + string? state = "formal", + Dictionary? data = null, + CancellationToken cancellation = default) + { + SentTemplates.Add(new SentTemplateArgs(toUser, templateId, page, lang, state, data)); + return Task.CompletedTask; + } + + public void Clear() + { + SentMessages.Clear(); + SentTemplates.Clear(); + } + + public record SentTemplateArgs( + Guid ToUser, + string TemplateId, + string? Page, + string? Lang, + string? State, + Dictionary? Data); +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramChannelData_Tests.cs new file mode 100644 index 000000000..3d82a894e --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramChannelData_Tests.cs @@ -0,0 +1,227 @@ +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; + +namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram +{ + /// + /// 微信小程序订阅消息渠道数据测试 + /// + /// + /// 统一写法: 先 new 渠道数据 → 通过 IJsonSerializer 序列化写入通知数据 → + /// 再让渠道实际发布, 断言捕获到的模板消息。 + /// + public class WeChatMiniProgramChannelData_Tests : AbpNotificationsWeChatMiniProgramTestsBase + { + private const string Provider = WeChatMiniProgramNotificationPublishProvider.ProviderName; + + private FakeSubscribeMessager Messager + => (FakeSubscribeMessager)GetRequiredService(); + + // ---------- 1. 解析渠道数据 ---------- + + [Fact] + public void Should_Resolve_New_Prefixed_Keys() + { + var data = WriteChannelData(new WeChatMiniProgramSubscribeChannelData + { + TemplateId = "TPL_FROM_PREFIXED_KEY", + RedirectPage = "pages/order/detail?id=123", + WeAppState = "developer", + WeAppLanguage = "zh_CN" + }); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.TemplateId.ShouldBe("TPL_FROM_PREFIXED_KEY"); + payload.RedirectPage.ShouldBe("pages/order/detail?id=123"); + payload.WeAppState.ShouldBe("developer"); + payload.WeAppLanguage.ShouldBe("zh_CN"); + } + + [Fact] + public void Should_Declare_Payload_When_Only_TemplateId_Is_Written() + { + // 跳转参数是"可选读取项", 不得参与存在性判定 + var data = WriteChannelData(new WeChatMiniProgramSubscribeChannelData + { + TemplateId = "TPL_ONLY" + }); + + ChannelDataResolver.IsDeclared(data, typeof(WeChatMiniProgramSubscribeChannelData)) + .ShouldBeTrue(); + ChannelDataResolver.Resolve(data)! + .RedirectPage.ShouldBeNull(); + } + + [Fact] + public void Should_Match_Prefixed_Key_Case_Insensitively() + { + var data = new NotificationData(); + data.TrySetData(WeChatMiniProgramNotificationDataKeys.TemplateId, "TPL_CASE"); + + ChannelDataResolver.IsDeclared(data, typeof(WeChatMiniProgramSubscribeChannelData)) + .ShouldBeTrue(); + ChannelDataResolver.Resolve(data)! + .TemplateId.ShouldBe("TPL_CASE"); + + // 换一种大小写写入也应命中 + var upper = new NotificationData(); + upper.TrySetData("WX-MP:TEMPLATE_ID", "TPL_UPPER"); + + ChannelDataResolver.Resolve(upper)! + .TemplateId.ShouldBe("TPL_UPPER"); + } + + // ---------- 2. 渠道实际发布(端到端) ---------- + + [Fact] + public async Task Should_Send_With_Resolved_Channel_Data() + { + Messager.Clear(); + + var data = WriteChannelData(new WeChatMiniProgramSubscribeChannelData + { + TemplateId = "TPL_SEND", + RedirectPage = "pages/a/b", + WeAppState = "developer", + WeAppLanguage = "en_US" + }); + + await PublishAsync(data, NewUser()); + + Messager.SentTemplates.Count.ShouldBe(1); + + var sent = Messager.SentTemplates[0]; + sent.TemplateId.ShouldBe("TPL_SEND"); + sent.Page.ShouldBe("pages/a/b"); + sent.State.ShouldBe("developer"); + sent.Lang.ShouldBe("en_US"); + } + + [Fact] + public async Task Should_Fall_Back_To_Default_TemplateId_When_Nothing_Written() + { + Messager.Clear(); + + await PublishAsync(new NotificationData(), NewUser()); + + Messager.SentTemplates.Count.ShouldBe(1); + Messager.SentTemplates[0].TemplateId.ShouldBe("DEFAULT_TEMPLATE_ID"); + } + + [Fact] + public async Task Should_Read_Legacy_Bare_Keys_As_Fallback() + { + Messager.Clear(); + + // 历史遗留的无前缀键, 已安装的生产者可能仍在写入 + // (测试历史兼容路径, 因此显式压制弃用告警) + var data = new NotificationData(); +#pragma warning disable CS0618 // Type or member is obsolete: this test verifies the legacy compatibility fallback + data.TrySetData(WeChatMiniProgramNotificationDataKeys.Legacy.TemplateId, "TPL_LEGACY"); + data.TrySetData(WeChatMiniProgramNotificationDataKeys.Legacy.RedirectPage, "pages/legacy"); +#pragma warning restore CS0618 + + await PublishAsync(data, NewUser()); + + Messager.SentTemplates.Count.ShouldBe(1); + Messager.SentTemplates[0].TemplateId.ShouldBe("TPL_LEGACY"); + Messager.SentTemplates[0].Page.ShouldBe("pages/legacy"); + } + + [Fact] + public async Task Should_Prefer_Prefixed_Key_Over_Legacy_Key() + { + Messager.Clear(); + + var data = WriteChannelData(new WeChatMiniProgramSubscribeChannelData + { + TemplateId = "TPL_NEW" + }); + // 同时写入遗留键, 带前缀的必须优先 +#pragma warning disable CS0618 // Type or member is obsolete: this test verifies the prefixed key wins over the legacy key + data.TrySetData(WeChatMiniProgramNotificationDataKeys.Legacy.TemplateId, "TPL_LEGACY"); +#pragma warning restore CS0618 + + await PublishAsync(data, NewUser()); + + Messager.SentTemplates[0].TemplateId.ShouldBe("TPL_NEW"); + } + + [Fact] + public async Task Should_Not_Send_When_TemplateId_Missing_And_No_Default() + { + Messager.Clear(); + + // 覆盖默认模板为空 + var options = GetRequiredService>().Value; + var original = options.DefaultTemplateId; + options.DefaultTemplateId = string.Empty; + + try + { + var context = await PublishAsync(new NotificationData(), NewUser()); + + Messager.SentTemplates.Count.ShouldBe(0); + context.Reason.ShouldNotBeNullOrWhiteSpace(); + } + finally + { + options.DefaultTemplateId = original; + } + } + + // ---------- 3. 模板数据取自属性包 ---------- + + [Fact] + public async Task Should_Pass_Extra_Properties_As_Template_Data() + { + Messager.Clear(); + + var data = WriteChannelData(new WeChatMiniProgramSubscribeChannelData + { + TemplateId = "TPL_DATA" + }); + data.TrySetData("character_string1", "SO20251001001"); + data.TrySetData("thing2", "顺丰速运"); + + await PublishAsync(data, NewUser()); + + var templateData = Messager.SentTemplates[0].Data; + templateData.ShouldNotBeNull(); + templateData!.ShouldContainKey("character_string1"); + templateData["character_string1"].ShouldBe("SO20251001001"); + templateData.ShouldContainKey("thing2"); + } + + // ---------- 辅助 ---------- + + private static UserIdentifier NewUser() => new(Guid.NewGuid(), "tester"); + + private async Task PublishAsync( + NotificationData data, + UserIdentifier user) + { + var provider = GetRequiredService(); + + var notification = new NotificationInfo + { + Name = "Test", + ContentType = NotificationContentType.Text, + Data = data + }; + notification.SetId(1); + + var context = new NotificationPublishContext(notification, new[] { user }); + + await provider.PublishAsync(context); + + return context; + } + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramDbJsonChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramDbJsonChannelData_Tests.cs new file mode 100644 index 000000000..5fecefb7b --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramDbJsonChannelData_Tests.cs @@ -0,0 +1,166 @@ +using LINGYUN.Abp.WeChat.MiniProgram.Messages; +using Shouldly; +using System; +using System.Threading.Tasks; +using Volo.Abp.Data; +using Volo.Abp.Json; +using Xunit; + +namespace LINGYUN.Abp.Notifications.WeChat.MiniProgram; + +/// +/// 从数据库 JSON 字符串解析渠道数据测试 +/// +/// +/// +/// 前面的测试是"内存中写入 → 读取"的同进程路径, 验证不到持久化往返。 +/// 本组测试补上**真实链路**: 直接给出数据库里存的 JSON 字符串, +/// 还原为 后, 再走渠道侧解析与真实发布, +/// 回答"从数据库取到数据后能否正常解析为渠道消息格式"。 +/// +/// +/// 小程序渠道数据都是标量, 因此库中值为原始类型(而非 JSON 字符串)。 +/// +/// +public class WeChatMiniProgramDbJsonChannelData_Tests + : AbpNotificationsWeChatMiniProgramTestsBase +{ + private const string Provider = WeChatMiniProgramNotificationPublishProvider.ProviderName; + + private FakeSubscribeMessager Messager + => (FakeSubscribeMessager)GetRequiredService(); + + // ---------- 1. 带前缀键 ---------- + + [Fact] + public void Should_Restore_Channel_Data_From_Db_Json() + { + var data = RestoreFromDbJson( + "{\"title\":\"订单状态\",\"message\":\"您的订单已发货\"," + + "\"wx-mp:template_id\":\"TPL_DB\"," + + "\"wx-mp:redirect_page\":\"pages/order/detail\"," + + "\"wx-mp:weapp_state\":\"developer\"," + + "\"wx-mp:weapp_language\":\"en_US\"}"); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.TemplateId.ShouldBe("TPL_DB"); + payload.RedirectPage.ShouldBe("pages/order/detail"); + payload.WeAppState.ShouldBe("developer"); + payload.WeAppLanguage.ShouldBe("en_US"); + } + + // ---------- 2. 从数据库 JSON 一路发到渠道(端到端) ---------- + + [Fact] + public async Task Should_Send_With_Data_Restored_From_Db_Json() + { + Messager.Clear(); + + var data = RestoreFromDbJson( + "{\"wx-mp:template_id\":\"TPL_DB_SEND\"," + + "\"wx-mp:redirect_page\":\"pages/a/b\"," + + "\"wx-mp:weapp_state\":\"formal\"}"); + + await PublishAsync(data, NewUser()); + + // 从库中还原的数据必须能真正发出去 + Messager.SentTemplates.Count.ShouldBe(1); + + var sent = Messager.SentTemplates[0]; + sent.TemplateId.ShouldBe("TPL_DB_SEND"); + sent.Page.ShouldBe("pages/a/b"); + sent.State.ShouldBe("formal"); + } + + // ---------- 3. 历史遗留无前缀键 ---------- + + /// + /// + /// 历史键不在渠道数据解析器的匹配范围内, 而是由渠道 Provider 在解析时回退读取, + /// 因此这里必须走真实发布路径验证。 + /// + /// + /// 键名以 JSON 字面量书写(而非引用已弃用的 + /// WeChatMiniProgramNotificationDataKeys.Legacy): + /// 既避免引用弃用成员, 也更贴近"数据库里存的就是这些字符串"的事实。 + /// + /// + [Fact] + public async Task Should_Restore_Legacy_Keys_From_Db_Json() + { + Messager.Clear(); + + // 早期版本写入的无前缀键, 已安装的生产者可能仍在写 + var data = RestoreFromDbJson( + "{\"TemplateId\":\"TPL_LEGACY\",\"RedirectPage\":\"pages/legacy\"}"); + + await PublishAsync(data, NewUser()); + + Messager.SentTemplates.Count.ShouldBe(1); + Messager.SentTemplates[0].TemplateId.ShouldBe("TPL_LEGACY"); + Messager.SentTemplates[0].Page.ShouldBe("pages/legacy"); + } + + [Fact] + public async Task Should_Prefer_Prefixed_Key_Over_Legacy_Key_From_Db_Json() + { + Messager.Clear(); + + var data = RestoreFromDbJson( + "{\"TemplateId\":\"TPL_LEGACY\",\"wx-mp:template_id\":\"TPL_NEW\"}"); + + // 渠道数据解析器只认带前缀的键 + ChannelDataResolver.Resolve(data)! + .TemplateId.ShouldBe("TPL_NEW"); + + // 真实发布时带前缀的键必须优先 + await PublishAsync(data, NewUser()); + + Messager.SentTemplates[0].TemplateId.ShouldBe("TPL_NEW"); + } + + // ---------- 4. 无渠道数据时不误解析 ---------- + + [Fact] + public void Should_Resolve_Nothing_When_Db_Json_Has_No_Channel_Data() + { + var data = RestoreFromDbJson( + "{\"title\":\"订单状态\",\"message\":\"您的订单已发货\"}"); + + ChannelDataResolver.Resolve(Provider, data).ShouldBeEmpty(); + } + + // ---------- 辅助 ---------- + + /// + /// 模拟"从数据库取出 JSON 字符串"后还原通知数据 + /// + /// + /// 与 EF 的属性包值转换器一致: 属性包整体是一个扁平 JSON 对象。 + /// + private NotificationData RestoreFromDbJson(string dbJson) + { + var extraProperties = JsonSerializer.Deserialize(dbJson); + + return new NotificationData { ExtraProperties = extraProperties }; + } + + private static UserIdentifier NewUser() => new(Guid.NewGuid(), "tester"); + + private async Task PublishAsync(NotificationData data, UserIdentifier user) + { + var provider = GetRequiredService(); + + var notification = new NotificationInfo + { + Name = "Test", + ContentType = NotificationContentType.Text, + Data = data + }; + notification.SetId(1); + + await provider.PublishAsync(new NotificationPublishContext(notification, new[] { user })); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests.csproj b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests.csproj new file mode 100644 index 000000000..e1b3aff68 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + + false + Debug;Release;PostgreSQL + AnyCPU + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkTestsBase.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkTestsBase.cs new file mode 100644 index 000000000..90f5654b8 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkTestsBase.cs @@ -0,0 +1,6 @@ +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +public abstract class AbpNotificationsWeChatWorkTestsBase + : NotificationChannelDataTestsBase +{ +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkTestsModule.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkTestsModule.cs new file mode 100644 index 000000000..6620473e0 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkTestsModule.cs @@ -0,0 +1,12 @@ +using LINGYUN.Abp.Tests; +using Volo.Abp.Modularity; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +[DependsOn( + typeof(AbpNotificationsWeChatWorkModule), + typeof(AbpNotificationsTestsModule), + typeof(AbpTestsBaseModule))] +public class AbpNotificationsWeChatWorkTestsModule : AbpModule +{ +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkChannelData_Tests.cs new file mode 100644 index 000000000..c0a386bbf --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkChannelData_Tests.cs @@ -0,0 +1,265 @@ +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Shouldly; +using System.Collections.Generic; +using Xunit; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 企业微信应用消息渠道数据测试 +/// +/// +/// 统一写法: 先 new 消息对象 → 通过 IJsonSerializer 序列化写入通知数据 → +/// 再用渠道侧解析器验证还原结果。 +/// +public class WeChatWorkChannelData_Tests : AbpNotificationsWeChatWorkTestsBase +{ + // ---------- 文本卡片 ---------- + + [Fact] + public void Should_Resolve_TextCard_Message() + { + var message = new TextCardMessage( + title: "审批通过", + description: "您的请假申请已通过", + url: "https://example.com/leave/123", + buttonText: "去查看"); + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkTextCardChannelData { TextCard = message })); + + payload.ShouldNotBeNull(); + payload!.TextCard.ShouldNotBeNull(); + + // 渠道侧还原出的消息必须与生产者 new 出来的对象逐字段一致 + payload.TextCard!.Title.ShouldBe(message.Title); + payload.TextCard.Description.ShouldBe(message.Description); + payload.TextCard.Url.ShouldBe(message.Url); + payload.TextCard.ButtonText.ShouldBe(message.ButtonText); + } + + [Fact] + public void Should_Serialize_TextCard_By_Json_Contract() + { + var json = Serialize(new TextCardMessage("标题", "描述", "https://example.com")); + + // 序列化契约: 字段名必须是企业微信要求的 snake_case + json.ShouldContain("\"title\""); + json.ShouldContain("\"description\""); + json.ShouldContain("\"url\""); + } + + // ---------- 小程序通知 ---------- + + [Fact] + public void Should_Resolve_MiniProgram_Message() + { + var message = new MiniProgramMessage( + appId: "wx1234567890", + title: "订单已发货", + page: "pages/order/detail?id=123", + description: "点击查看物流详情") + { + EmphasisFirstItem = true, + ContentItems = new List + { + new MiniProgramContent("订单号", "SO20251001001") + } + }; + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkMiniProgramNoticeChannelData { MiniProgram = message })); + + payload.ShouldNotBeNull(); + payload!.MiniProgram.ShouldNotBeNull(); + payload.MiniProgram!.AppId.ShouldBe("wx1234567890"); + payload.MiniProgram.Title.ShouldBe("订单已发货"); + payload.MiniProgram.Page.ShouldBe("pages/order/detail?id=123"); + payload.MiniProgram.EmphasisFirstItem.ShouldBe(true); + payload.MiniProgram.ContentItems.ShouldNotBeNull(); + payload.MiniProgram.ContentItems!.Count.ShouldBe(1); + payload.MiniProgram.ContentItems[0].Key.ShouldBe("订单号"); + payload.MiniProgram.ContentItems[0].Value.ShouldBe("SO20251001001"); + } + + // ---------- 图文消息 ---------- + + [Fact] + public void Should_Resolve_MpNew_Message() + { + var message = new MpNewMessagePayload(new List + { + new MpNewMessage( + title: "月度报告", + thumbMediaId: "MEDIA_ID", + content: "

报告正文

", + author: "运营部", + contentSourceUrl: "https://example.com/report", + description: "2025年10月经营月报") + }); + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkMpNewChannelData { MpNewMessage = message })); + + payload.ShouldNotBeNull(); + payload!.MpNewMessage.ShouldNotBeNull(); + payload.MpNewMessage!.Articles.Count.ShouldBe(1); + + var article = payload.MpNewMessage.Articles[0]; + article.Title.ShouldBe("月度报告"); + article.ThumbMediaId.ShouldBe("MEDIA_ID"); + article.Content.ShouldBe("

报告正文

"); + article.Author.ShouldBe("运营部"); + article.ContentSourceUrl.ShouldBe("https://example.com/report"); + article.Description.ShouldBe("2025年10月经营月报"); + } + + // ---------- 视频 / 语音 / 文件 ---------- + + [Fact] + public void Should_Resolve_Video_Message() + { + var message = new VideoMessage("MEDIA_ID", "培训视频", "新人入职培训"); + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkVideoChannelData { Video = message })); + + payload.ShouldNotBeNull(); + payload!.Video.ShouldNotBeNull(); + payload.Video!.MediaId.ShouldBe("MEDIA_ID"); + payload.Video.Title.ShouldBe("培训视频"); + payload.Video.Description.ShouldBe("新人入职培训"); + } + + [Fact] + public void Should_Resolve_Voice_Message() + { + var message = new MediaMessage("VOICE_MEDIA_ID"); + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkVoiceChannelData { Voice = message })); + + payload.ShouldNotBeNull(); + payload!.Voice.ShouldNotBeNull(); + payload.Voice!.MediaId.ShouldBe("VOICE_MEDIA_ID"); + } + + [Fact] + public void Should_Resolve_File_Message() + { + var message = new MediaMessage("FILE_MEDIA_ID"); + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkFileChannelData { File = message })); + + payload.ShouldNotBeNull(); + payload!.File.ShouldNotBeNull(); + payload.File!.MediaId.ShouldBe("FILE_MEDIA_ID"); + } + + // ---------- 模板卡片(抽象类型多态) ---------- + + [Fact] + public void Should_Resolve_TemplateCard_Message() + { + var message = new TextTemplateCard( + new TemplateCardCardAction("https://example.com/approval/123")) + { + MainTitle = new TemplateCardMainTitle("请假通过通知", "您的请假申请已通过"), + SubTitle = "请及时处理后续交接事项" + }; + + var payload = ChannelDataResolver.Resolve( + WriteChannelData(new WeChatWorkTemplateCardChannelData { TemplateCard = message })); + + payload.ShouldNotBeNull(); + payload!.TemplateCard.ShouldNotBeNull(); + + // 抽象基类必须能还原为具体卡片类型 + payload.TemplateCard.ShouldBeOfType(); + + var card = (TextTemplateCard)payload.TemplateCard!; + card.MainTitle!.Title.ShouldBe("请假通过通知"); + card.SubTitle.ShouldBe("请及时处理后续交接事项"); + card.CardAction.Url.ShouldBe("https://example.com/approval/123"); + } + + // ---------- 投递选项与载荷共存 ---------- + + [Fact] + public void Should_Resolve_Payload_Along_With_Delivery_Options() + { + var data = WriteChannelData(new WeChatWorkTextCardChannelData + { + TextCard = new TextCardMessage("标题", "描述", "https://example.com") + }); + + data.TrySetData(WeChatWorkNotificationDataKeys.Safe, true); + data.TrySetData(WeChatWorkNotificationDataKeys.ToParty, "1|2"); + data.TrySetData(WeChatWorkNotificationDataKeys.DuplicateCheckInterval, 600); + + // 载荷 + ChannelDataResolver.Resolve(data).ShouldNotBeNull(); + + // 标量选项 + ChannelDataResolver.GetValue(data, WeChatWorkNotificationDataKeys.Safe, false).ShouldBeTrue(); + ChannelDataResolver.GetValue(data, WeChatWorkNotificationDataKeys.DuplicateCheckInterval, 1800) + .ShouldBe(600); + ChannelDataResolver.GetOrNull(data, WeChatWorkNotificationDataKeys.ToParty).ShouldBe("1|2"); + } + + [Fact] + public void Should_Require_Only_Its_Own_Key_To_Be_Declared() + { + // 只写一个载荷键, 不得误命中其它载荷类型 + var data = WriteChannelData(new WeChatWorkVideoChannelData + { + Video = new VideoMessage("MEDIA_ID") + }); + + ChannelDataResolver.IsDeclared(data, typeof(WeChatWorkVideoChannelData)).ShouldBeTrue(); + ChannelDataResolver.IsDeclared(data, typeof(WeChatWorkTextCardChannelData)).ShouldBeFalse(); + ChannelDataResolver.IsDeclared(data, typeof(WeChatWorkFileChannelData)).ShouldBeFalse(); + ChannelDataResolver.IsDeclared(data, typeof(WeChatWorkTemplateCardChannelData)).ShouldBeFalse(); + } + + // ---------- 多个载荷共存: 按 Priority 排序 ---------- + + [Fact] + public void Should_Resolve_All_Payloads_In_Priority_Order() + { + var data = WriteChannelData(new WeChatWorkTextCardChannelData + { + TextCard = new TextCardMessage("标题", "描述", "https://example.com") + }); + // 合并另一个载荷(不同键, 互不冲突) + MergeChannelData(data, new WeChatWorkMiniProgramNoticeChannelData + { + MiniProgram = new MiniProgramMessage("appid", "标题") + }); + + var payloads = ChannelDataResolver.Resolve( + WeChatWorkNotificationPublishProvider.ProviderName, + data); + + payloads.Count.ShouldBe(2); + // Priority: 小程序通知 100 < 文本卡片 400 + payloads[0].ShouldBeOfType(); + payloads[1].ShouldBeOfType(); + } + + [Fact] + public void Should_Declare_Every_Registered_Payload_Kind() + { + var types = ChannelDataResolver.GetPayloadTypes(WeChatWorkNotificationPublishProvider.ProviderName); + + types.Count.ShouldBe(7); + types.ShouldContain(typeof(WeChatWorkMiniProgramNoticeChannelData)); + types.ShouldContain(typeof(WeChatWorkMpNewChannelData)); + types.ShouldContain(typeof(WeChatWorkTemplateCardChannelData)); + types.ShouldContain(typeof(WeChatWorkTextCardChannelData)); + types.ShouldContain(typeof(WeChatWorkVideoChannelData)); + types.ShouldContain(typeof(WeChatWorkVoiceChannelData)); + types.ShouldContain(typeof(WeChatWorkFileChannelData)); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkDbJsonChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkDbJsonChannelData_Tests.cs new file mode 100644 index 000000000..8b43ee3f2 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkDbJsonChannelData_Tests.cs @@ -0,0 +1,146 @@ +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Shouldly; +using Volo.Abp.Data; +using Volo.Abp.Json; +using Xunit; + +namespace LINGYUN.Abp.Notifications.WeChat.Work; + +/// +/// 从数据库 JSON 字符串解析渠道数据测试 +/// +/// +/// +/// 前面的测试是"内存中写入 → 读取"的同进程路径, 验证不到持久化往返。 +/// 本组测试补上**真实链路**: 直接给出数据库里存的 JSON 字符串, +/// 还原为 后, 再走渠道侧解析与消息工厂, +/// 回答"从数据库取到数据后能否正常解析为渠道消息格式"。 +/// +/// +/// 关键点: 属性包里的复杂值为 **JSON 字符串**(而非嵌套对象), +/// 且模板卡片的判别符 card_type 必须保留, 否则抽象类型无法还原。 +/// +/// +public class WeChatWorkDbJsonChannelData_Tests + : AbpNotificationsWeChatWorkTestsBase +{ + private const string Provider = NotificationProviderNames.WechatWork; + + // ---------- 1. 模板卡片(抽象类型 + 判别符) ---------- + + /// + /// 数据库中的模板卡片 JSON(转义形式, 与 EF 存的一致) + /// + private const string TemplateCardDbJson = + "{\"wx-work:template_card_message\":\"{" + + "\\\"main_title\\\":{\\\"title\\\":\\\"请假通过通知\\\",\\\"desc\\\":\\\"您的请假申请已通过\\\"}," + + "\\\"sub_title_text\\\":\\\"请及时处理后继交接事项\\\"," + + "\\\"horizontal_content_list\\\":[{\\\"keyname\\\":\\\"单号\\\",\\\"value\\\":\\\"LV20251001\\\"}]," + + "\\\"TemplateCardCardAction\\\":{\\\"type\\\":1,\\\"url\\\":\\\"https://example.com/approval/123\\\"}," + + "\\\"card_type\\\":\\\"template_card\\\"}\"}"; + + [Fact] + public void Should_Restore_TemplateCard_From_Db_Json() + { + var data = RestoreFromDbJson(TemplateCardDbJson); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.TemplateCard.ShouldNotBeNull(); + + // 抽象基类必须能还原为具体卡片类型 + var card = payload.TemplateCard.ShouldBeOfType(); + card.MainTitle!.Title.ShouldBe("请假通过通知"); + card.MainTitle!.Description.ShouldBe("您的请假申请已通过"); + card.SubTitle.ShouldBe("请及时处理后继交接事项"); + card.CardAction.Url.ShouldBe("https://example.com/approval/123"); + + // 嵌套列表也要完整还原 + card.HorizontalContents.ShouldNotBeNull(); + card.HorizontalContents!.Count.ShouldBe(1); + card.HorizontalContents[0].KeyName.ShouldBe("单号"); + card.HorizontalContents[0].Value.ShouldBe("LV20251001"); + } + + // ---------- 2. 文本卡片(基础类型) ---------- + + [Fact] + public void Should_Restore_TextCard_From_Db_Json() + { + var data = RestoreFromDbJson( + "{\"wx-work:text_card_message\":\"{" + + "\\\"title\\\":\\\"标题\\\",\\\"description\\\":\\\"描述\\\"," + + "\\\"url\\\":\\\"https://example.com\\\",\\\"btntxt\\\":\\\"详情\\\"}\"}"); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.TextCard.ShouldNotBeNull(); + payload.TextCard!.Title.ShouldBe("标题"); + payload.TextCard!.Url.ShouldBe("https://example.com"); + } + + // ---------- 3. 投递选项与渠道数据共存 ---------- + + [Fact] + public void Should_Restore_Delivery_Options_Alongside_Channel_Data() + { + // 真实库中既有渠道数据, 也有投递选项(safe / 重复检查间隔等) + var data = RestoreFromDbJson( + "{\"wx-work:safe\":true,\"wx-work:duplicate_check_interval\":600," + + "\"wx-work:text_card_message\":\"{" + + "\\\"title\\\":\\\"标题\\\",\\\"description\\\":\\\"描述\\\",\\\"url\\\":\\\"https://example.com\\\"}\"}"); + + ChannelDataResolver.Resolve(data).ShouldNotBeNull(); + + // 投递选项为原始类型, 需按声明类型正确还原 + ChannelDataResolver.GetValue(data, WeChatWorkNotificationDataKeys.Safe, false).ShouldBeTrue(); + ChannelDataResolver.GetValue(data, WeChatWorkNotificationDataKeys.DuplicateCheckInterval, 0).ShouldBe(600); + } + + // ---------- 4. 无渠道数据时不误解析 ---------- + + [Fact] + public void Should_Resolve_Nothing_When_Db_Json_Has_No_Channel_Data() + { + var data = RestoreFromDbJson( + "{\"title\":\"标题\",\"message\":\"内容\",\"formUser\":\"ci\"}"); + + ChannelDataResolver.Resolve(Provider, data).ShouldBeEmpty(); + } + + // ---------- 5. 载荷非法时的行为 ---------- + + [Fact] + public void Should_Report_Declared_But_Resolve_Nothing_When_Db_Json_Payload_Is_Invalid() + { + // 复杂渠道数据以 JSON 字符串存放, 这里写入无法反序列化的内容 + var data = RestoreFromDbJson( + "{\"wx-work:template_card_message\":\"{ this is not json }\"}"); + + // 契约: 键确实存在 → IsDeclared 为 true; 解析失败 → Resolve 返回空, 不抛异常 + ChannelDataResolver.IsDeclared(data, typeof(WeChatWorkTemplateCardChannelData)).ShouldBeTrue(); + ChannelDataResolver.Resolve(Provider, data).ShouldBeEmpty(); + + // 诊断信息仍能给出实际命中的键, 便于排查 + ChannelDataResolver.GetKey(data, typeof(WeChatWorkTemplateCardChannelData)) + .ShouldBe(WeChatWorkNotificationDataKeys.TemplateCardMessage); + } + + // ---------- 辅助 ---------- + + /// + /// 模拟"从数据库取出 JSON 字符串"后还原通知数据 + /// + /// + /// 与 EF 的属性包值转换器一致: 属性包整体是一个扁平 JSON 对象, + /// 复杂渠道数据在其中以 转义后的 JSON 字符串 存放。 + /// + private NotificationData RestoreFromDbJson(string dbJson) + { + var extraProperties = JsonSerializer.Deserialize(dbJson); + + return new NotificationData { ExtraProperties = extraProperties }; + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests.csproj b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests.csproj new file mode 100644 index 000000000..f7f41a6d6 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + + false + Debug;Release;PostgreSQL + AnyCPU + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkTestsBase.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkTestsBase.cs new file mode 100644 index 000000000..7e63942b5 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkTestsBase.cs @@ -0,0 +1,6 @@ +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +public abstract class AbpNotificationsWebhookWeChatWorkTestsBase + : NotificationChannelDataTestsBase +{ +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkTestsModule.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkTestsModule.cs new file mode 100644 index 000000000..c08db5ae9 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkTestsModule.cs @@ -0,0 +1,12 @@ +using LINGYUN.Abp.Tests; +using Volo.Abp.Modularity; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +[DependsOn( + typeof(AbpNotificationsWebhookWeChatWorkModule), + typeof(AbpNotificationsTestsModule), + typeof(AbpTestsBaseModule))] +public class AbpNotificationsWebhookWeChatWorkTestsModule : AbpModule +{ +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookChannelData_Tests.cs new file mode 100644 index 000000000..47d7246ea --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookChannelData_Tests.cs @@ -0,0 +1,343 @@ +using LINGYUN.Abp.WeChat.Work.Messages; +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; +using System.Collections.Generic; +using Xunit; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 企业微信 Webhook 渠道数据测试 +/// +/// +/// 统一写法: 先 new 消息对象 → 通过 IJsonSerializer 序列化写入通知数据 → +/// 再用渠道侧解析器 + 消息工厂验证最终载体。 +/// +public class WeChatWorkWebhookChannelData_Tests : AbpNotificationsWebhookWeChatWorkTestsBase +{ + private const string Provider = WeChatWorkWebhookNotificationProvider.ProviderName; + + private AbpNotificationsWebhookWeChatWorkMessageOptions MessageOptions + => GetRequiredService>().Value; + + private AbpNotificationsWebhookWeChatWorkOptions ChannelOptions + => GetRequiredService>().Value; + + // ---------- 1. 解析 + 载体构造(端到端) ---------- + + [Fact] + public void Should_Resolve_Text_Payload_And_Build_Text_Message() + { + var data = WriteChannelData(new WeChatWorkWebhookTextChannelData + { + Content = "构建 #1234 失败" + }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + payload!.Content.ShouldBe("构建 #1234 失败"); + + var message = BuildMessage(payload); + message.MsgType.ShouldBe("text"); + + var text = message.ShouldBeOfType(); + text.Text.Content.ShouldBe("构建 #1234 失败"); + } + + [Fact] + public void Should_Resolve_Markdown_Payload_And_Build_Markdown_Message() + { + var data = WriteChannelData(new WeChatWorkWebhookMarkdownChannelData + { + Content = "**构建失败**" + }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + + var message = BuildMessage(payload!); + message.MsgType.ShouldBe("markdown"); + message.ShouldBeOfType() + .Markdown.Content.ShouldBe("**构建失败**"); + } + + [Fact] + public void Should_Resolve_MarkdownV2_Payload_And_Build_MarkdownV2_Message() + { + var data = WriteChannelData(new WeChatWorkWebhookMarkdownV2ChannelData + { + Content = "| a | b |\n|---|---|\n| 1 | 2 |" + }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + + var message = BuildMessage(payload!); + message.MsgType.ShouldBe("markdown_v2"); + message.ShouldBeOfType() + .Markdown.Content.ShouldContain("| a | b |"); + } + + [Fact] + public void Should_Resolve_Image_Payload_And_Build_Image_Message() + { + var image = new WebhookImageMessage("BASE64_DATA", "MD5_HASH"); + + var data = WriteChannelData(new WeChatWorkWebhookImageChannelData { Image = image }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + payload!.Image.ShouldNotBeNull(); + payload.Image!.Base64.ShouldBe("BASE64_DATA"); + payload.Image.Md5.ShouldBe("MD5_HASH"); + + var message = BuildMessage(payload); + message.MsgType.ShouldBe("image"); + message.ShouldBeOfType() + .Image.Base64.ShouldBe("BASE64_DATA"); + } + + [Fact] + public void Should_Resolve_News_Payload_And_Build_News_Message() + { + var news = new WebhookNewsMessage(new List + { + new WebhookArticleMessage( + title: "月度报告", + url: "https://example.com/report", + description: "2025年10月", + pictureUrl: "https://example.com/cover.png") + }); + + var data = WriteChannelData(new WeChatWorkWebhookNewsChannelData { News = news }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + payload!.News.ShouldNotBeNull(); + payload.News!.Articles.Count.ShouldBe(1); + payload.News.Articles[0].Title.ShouldBe("月度报告"); + payload.News.Articles[0].Url.ShouldBe("https://example.com/report"); + payload.News.Articles[0].PictureUrl.ShouldBe("https://example.com/cover.png"); + + var message = BuildMessage(payload); + message.MsgType.ShouldBe("news"); + + // 该载体原先因 WeChatWorkWebhookNewsMessage 为 internal 而无法使用 + var newsMessage = message.ShouldBeOfType(); + newsMessage.News.Articles[0].Title.ShouldBe("月度报告"); + } + + [Fact] + public void Should_Resolve_File_Payload_And_Build_File_Message() + { + var data = WriteChannelData(new WeChatWorkWebhookFileChannelData + { + File = new WebhookFileMessage("FILE_MEDIA_ID") + }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + + var message = BuildMessage(payload!); + message.MsgType.ShouldBe("file"); + message.ShouldBeOfType() + .File.MediaId.ShouldBe("FILE_MEDIA_ID"); + } + + [Fact] + public void Should_Resolve_Voice_Payload_And_Build_Voice_Message() + { + var data = WriteChannelData(new WeChatWorkWebhookVoiceChannelData + { + Voice = new WebhookVoiceMessage("VOICE_MEDIA_ID") + }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + + var message = BuildMessage(payload!); + message.MsgType.ShouldBe("voice"); + message.ShouldBeOfType() + .Voice.MediaId.ShouldBe("VOICE_MEDIA_ID"); + } + + // ---------- 2. 模板卡片(抽象类型多态) ---------- + + [Fact] + public void Should_Resolve_TextNoticeCard_And_Build_TemplateCard_Message() + { + var card = new WebhookTextNoticeCardMessage( + action: WebhookTemplateCardAction.Link("https://example.com/build/1234"), + mainTitle: new WebhookTemplateCardMainTitle("构建失败", "请及时处理"), + subTitleText: "构建 #1234 于 15:30 失败", + horizontalContents: new List + { + WebhookTemplateCardHorizontalContent.Default("分支", "main") + }); + + var data = WriteChannelData(new WeChatWorkWebhookTemplateCardChannelData { TemplateCard = card }); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + payload!.TemplateCard.ShouldNotBeNull(); + + // 抽象基类必须还原为具体卡片类型 + var restored = payload.TemplateCard.ShouldBeOfType(); + restored.CardType.ShouldBe("text_notice"); + restored.SubTitleText.ShouldBe("构建 #1234 于 15:30 失败"); + restored.Action!.Url.ShouldBe("https://example.com/build/1234"); + restored.MainTitle!.Title.ShouldBe("构建失败"); + restored.HorizontalContents!.Count.ShouldBe(1); + + var message = BuildMessage(payload); + message.MsgType.ShouldBe("template_card"); + message.ShouldBeOfType() + .TemplateCard.ShouldBeOfType(); + } + + [Fact] + public void Should_Resolve_NewsNoticeCard() + { + var card = new WebhookNewsNoticeCardMessage( + cardImage: new WebhookTemplateCardImage("https://example.com/pic.png"), + action: WebhookTemplateCardAction.Link("https://example.com"), + mainTitle: new WebhookTemplateCardMainTitle("图文卡片", null)); + + var data = WriteChannelData(new WeChatWorkWebhookTemplateCardChannelData { TemplateCard = card }); + + var payload = ChannelDataResolver.Resolve(data); + + var restored = payload!.TemplateCard.ShouldBeOfType(); + restored.CardType.ShouldBe("news_notice"); + restored.CardImage.Url.ShouldBe("https://example.com/pic.png"); + } + + [Fact] + public void Should_Serialize_Card_With_CardType_Discriminator() + { + var json = Serialize(new WebhookTextNoticeCardMessage( + WebhookTemplateCardAction.Link("https://example.com"), + new WebhookTemplateCardMainTitle("标题", "副标题"))); + + // 判别符是还原具体类型所必需的 + json.ShouldContain("card_type"); + json.ShouldContain("text_notice"); + } + + // ---------- 3. 渠道隔离 ---------- + + [Fact] + public void Should_Not_Share_Keys_With_App_Message_Channel() + { + var data = WriteChannelData(new WeChatWorkWebhookTextChannelData { Content = "hello" }); + + // 应用消息渠道不得命中 Webhook 前缀的载荷 + ChannelDataResolver + .Resolve(data) + .ShouldBeNull(); + ChannelDataResolver + .IsDeclared(data, typeof(LINGYUN.Abp.Notifications.WeChat.Work.WeChatWorkTextCardChannelData)) + .ShouldBeFalse(); + } + + [Fact] + public void Should_Use_Its_Own_Provider_Name() + { + Provider.ShouldNotBe( + LINGYUN.Abp.Notifications.WeChat.Work.WeChatWorkNotificationPublishProvider.ProviderName); + WeChatWorkWebhookNotificationDataKeys.Prefix.ShouldNotBe( + LINGYUN.Abp.Notifications.WeChat.Work.WeChatWorkNotificationDataKeys.Prefix); + } + + // ---------- 4. 注册与工厂 ---------- + + [Fact] + public void Should_Register_All_Eight_Payloads() + { + var types = ChannelDataResolver.GetPayloadTypes(Provider); + + types.Count.ShouldBe(8); + types.ShouldContain(typeof(WeChatWorkWebhookTextChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookMarkdownChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookMarkdownV2ChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookImageChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookNewsChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookFileChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookVoiceChannelData)); + types.ShouldContain(typeof(WeChatWorkWebhookTemplateCardChannelData)); + } + + [Fact] + public void Should_Map_Every_Payload_Kind_To_Its_Own_MsgType() + { + var expected = new (NotificationChannelData Payload, string MsgType)[] + { + (new WeChatWorkWebhookTextChannelData { Content = "t" }, "text"), + (new WeChatWorkWebhookMarkdownChannelData { Content = "m" }, "markdown"), + (new WeChatWorkWebhookMarkdownV2ChannelData { Content = "m2" }, "markdown_v2"), + (new WeChatWorkWebhookImageChannelData { Image = new WebhookImageMessage("b", "m") }, "image"), + (new WeChatWorkWebhookNewsChannelData + { + News = new WebhookNewsMessage(new List + { + new WebhookArticleMessage("标题", "https://example.com") + }) + }, "news"), + (new WeChatWorkWebhookFileChannelData { File = new WebhookFileMessage("M") }, "file"), + (new WeChatWorkWebhookVoiceChannelData { Voice = new WebhookVoiceMessage("M") }, "voice"), + (new WeChatWorkWebhookTemplateCardChannelData + { + TemplateCard = new WebhookTextNoticeCardMessage( + WebhookTemplateCardAction.Link("https://example.com"), + new WebhookTemplateCardMainTitle("标题", "副标题")) + }, "template_card"), + }; + + foreach (var (payload, msgType) in expected) + { + BuildMessage(payload).MsgType.ShouldBe(msgType); + } + + MessageOptions.MessageKinds.Count.ShouldBe(8); + } + + // ---------- 5. 选项与优先级 ---------- + + [Fact] + public void Should_Enable_MarkdownV2_By_Default() + { + ChannelOptions.UseMarkdownV2.ShouldBeTrue(); + } + + [Fact] + public void Should_Resolve_Payloads_In_Priority_Order() + { + var data = WriteChannelData(new WeChatWorkWebhookTemplateCardChannelData + { + TemplateCard = new WebhookTextNoticeCardMessage( + WebhookTemplateCardAction.Link("https://example.com"), + new WebhookTemplateCardMainTitle("标题", "副标题")) + }); + MergeChannelData(data, new WeChatWorkWebhookTextChannelData { Content = "text" }); + + var payloads = ChannelDataResolver.Resolve(Provider, data); + + payloads.Count.ShouldBe(2); + // Priority: 文本 100 < 模板卡片 800 + payloads[0].ShouldBeOfType(); + payloads[1].ShouldBeOfType(); + } + + // ---------- 辅助 ---------- + + private WeChatWorkWebhookMessage BuildMessage(NotificationChannelData payload) + { + return MessageOptions.Create(new WeChatWorkWebhookMessageFactoryContext( + new NotificationInfo { Name = "Test", ContentType = NotificationContentType.Text }, + new NotificationStandardData("标题", "内容"), + (WeChatWorkWebhookChannelData)payload, + ChannelOptions)).Message; + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookDbJsonChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookDbJsonChannelData_Tests.cs new file mode 100644 index 000000000..54a4e0910 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookDbJsonChannelData_Tests.cs @@ -0,0 +1,186 @@ +using LINGYUN.Abp.WeChat.Work.Messages; +using LINGYUN.Abp.WeChat.Work.Messages.Models; +using Microsoft.Extensions.Options; +using Shouldly; +using System; +using System.Collections.Generic; +using Volo.Abp.Data; +using Xunit; + +namespace LINGYUN.Abp.Notifications.Webhook.WeChat.Work; + +/// +/// 从数据库 JSON 字符串解析渠道数据测试 +/// +/// +/// +/// 前面的测试都是"内存中写入 → 读取"的同进程路径, 验证不到持久化往返。 +/// 本组测试补上**真实链路**: 直接给出数据库里存的 JSON 字符串, +/// 还原为 后, 再走渠道侧解析与消息工厂, +/// 回答"从数据库取到数据后能否正常解析为渠道消息格式"。 +/// +/// +/// 关键点: 属性包里的值在持久化后是 **JSON 字符串**(而非嵌套对象), +/// 且模板卡片的判别符 card_type 必须保留, 否则抽象类型无法还原。 +/// +/// +public class WeChatWorkWebhookDbJsonChannelData_Tests + : AbpNotificationsWebhookWeChatWorkTestsBase +{ + private const string Provider = WeChatWorkWebhookNotificationProvider.ProviderName; + + private AbpNotificationsWebhookWeChatWorkMessageOptions MessageOptions + => GetRequiredService>().Value; + + private AbpNotificationsWebhookWeChatWorkOptions ChannelOptions + => GetRequiredService>().Value; + + // ---------- 1. 模板卡片(抽象类型 + 判别符) ---------- + + /// + /// 数据库中的模板卡片 JSON(转义形式, 与 EF 存的一致) + /// + private const string TemplateCardDbJson = + "{" + + "\"wx-work-hook:template_card\":\"{\\\"sub_title_text\\\":\\\"请查看日志\\\"," + + "\\\"card_type\\\":\\\"text_notice\\\"," + + "\\\"main_title\\\":{\\\"title\\\":\\\"构建失败\\\",\\\"desc\\\":\\\"构建 #1234 失败\\\"}," + + "\\\"horizontal_content_list\\\":[{\\\"keyname\\\":\\\"分支\\\",\\\"value\\\":\\\"main\\\"}]," + + "\\\"card_action\\\":{\\\"type\\\":1,\\\"url\\\":\\\"https://example.com/build/1\\\"}}\"" + + "}"; + + [Fact] + public void Should_Restore_TemplateCard_From_Db_Json() + { + var data = RestoreFromDbJson(TemplateCardDbJson); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.TemplateCard.ShouldNotBeNull(); + + // 抽象类型按 card_type 还原为具体类型 + var card = payload.TemplateCard.ShouldBeOfType(); + card.CardType.ShouldBe("text_notice"); + card.MainTitle!.Title.ShouldBe("构建失败"); + card.MainTitle!.Description.ShouldBe("构建 #1234 失败"); + card.SubTitleText.ShouldBe("请查看日志"); + card.Action!.Url.ShouldBe("https://example.com/build/1"); + + // 嵌套列表也要完整还原 + card.HorizontalContents.ShouldNotBeNull(); + card.HorizontalContents!.Count.ShouldBe(1); + card.HorizontalContents[0].KeyName.ShouldBe("分支"); + card.HorizontalContents[0].Value.ShouldBe("main"); + } + + [Fact] + public void Should_Build_TemplateCard_Message_From_Db_Json() + { + var data = RestoreFromDbJson(TemplateCardDbJson); + + var message = BuildMessage(Provider, data); + + message.MsgType.ShouldBe("template_card"); + + var card = message.ShouldBeOfType(); + card.TemplateCard.ShouldBeOfType() + .MainTitle!.Title.ShouldBe("构建失败"); + } + + // ---------- 2. 标量载荷 ---------- + + private const string TextDbJson = + "{\"wx-work-hook:text\":\"构建 #1234 失败\"}"; + + [Fact] + public void Should_Restore_Text_From_Db_Json() + { + var data = RestoreFromDbJson(TextDbJson); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.Content.ShouldBe("构建 #1234 失败"); + + BuildMessage(Provider, data) + .ShouldBeOfType() + .Text.Content.ShouldBe("构建 #1234 失败"); + } + + // ---------- 3. 基础参数与渠道数据共存 ---------- + + [Fact] + public void Should_Restore_Standard_Data_Alongside_Channel_Data() + { + // 真实库中既有通知基础参数, 也有渠道数据 + var data = RestoreFromDbJson( + "{\"title\":\"构建失败\",\"message\":\"构建 #1234 失败\",\"formUser\":\"ci\"," + + "\"wx-work-hook:text\":\"兜底文本\"}"); + + data.TryGetData("title").ShouldBe("构建失败"); + data.TryGetData("formUser").ShouldBe("ci"); + + var payload = ChannelDataResolver.Resolve(data); + payload.ShouldNotBeNull(); + payload!.Content.ShouldBe("兜底文本"); + } + + // ---------- 4. 无渠道数据时不误解析 ---------- + + [Fact] + public void Should_Resolve_Nothing_When_Db_Json_Has_No_Channel_Data() + { + var data = RestoreFromDbJson( + "{\"title\":\"构建失败\",\"message\":\"构建 #1234 失败\"}"); + + ChannelDataResolver.Resolve(Provider, data).ShouldBeEmpty(); + } + + // ---------- 5. 载荷非法时的行为 ---------- + + [Fact] + public void Should_Report_Declared_But_Resolve_Nothing_When_Db_Json_Payload_Is_Invalid() + { + // 模板卡片 JSON 缺少判别符 card_type, 抽象类型无法还原 + var data = RestoreFromDbJson( + "{\"wx-work-hook:template_card\":\"{\\\"main_title\\\":{\\\"title\\\":\\\"t\\\"}}\"}"); + + // 契约: 生产者确实写了该键 → IsDeclared 为 true, + // 但解析失败 → Resolve 返回空(仅记日志), 不抛异常 + ChannelDataResolver.IsDeclared(data, typeof(WeChatWorkWebhookTemplateCardChannelData)).ShouldBeTrue(); + ChannelDataResolver.Resolve(Provider, data).ShouldBeEmpty(); + + // 诊断信息仍能给出实际命中的键, 便于排查 + ChannelDataResolver.GetKey(data, typeof(WeChatWorkWebhookTemplateCardChannelData)) + .ShouldBe(WeChatWorkWebhookNotificationDataKeys.TemplateCard); + } + + // ---------- 辅助 ---------- + + /// + /// 模拟"从数据库取出 JSON 字符串"后还原通知数据 + /// + /// + /// 与 EF 的属性包值转换器一致: 属性包整体是一个扁平 JSON 对象, + /// 复杂渠道数据在其中以 转义后的 JSON 字符串 存放。 + /// + private NotificationData RestoreFromDbJson(string dbJson) + { + var extraProperties = JsonSerializer.Deserialize(dbJson); + + return new NotificationData { ExtraProperties = extraProperties }; + } + + private WeChatWorkWebhookMessage BuildMessage(string provider, NotificationData data) + { + var payload = ChannelDataResolver.Resolve(provider, data); + payload.ShouldNotBeEmpty(); + + return MessageOptions.Create(new WeChatWorkWebhookMessageFactoryContext( + new NotificationInfo { Name = "Test", ContentType = NotificationContentType.Text }, + new NotificationStandardData("标题", "内容"), + (WeChatWorkWebhookChannelData)payload[0], + ChannelOptions)).Message; + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestBase.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestBase.cs index 2a12ce9dd..3f3e15b72 100644 --- a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestBase.cs +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestBase.cs @@ -1,7 +1,6 @@ -using LINGYUN.Abp.Tests; - -namespace LINGYUN.Abp.Notifications.WxPusher; - -public abstract class AbpNotificationsWxPusherTestBase : AbpTestsBase -{ -} +namespace LINGYUN.Abp.Notifications.WxPusher; + +public abstract class AbpNotificationsWxPusherTestBase + : NotificationChannelDataTestsBase +{ +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestModule.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestModule.cs index 4e56c313d..07d807e27 100644 --- a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestModule.cs +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherTestModule.cs @@ -1,12 +1,19 @@ -using LINGYUN.Abp.WxPusher; -using Volo.Abp.Modularity; - -namespace LINGYUN.Abp.Notifications.WxPusher; - -[DependsOn( - typeof(AbpNotificationsWxPusherModule), - typeof(AbpWxPusherTestModule), - typeof(AbpNotificationsTestsModule))] -public class AbpNotificationsWxPusherTestModule : AbpModule -{ -} +using LINGYUN.Abp.WxPusher.Messages; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Volo.Abp.Modularity; + +namespace LINGYUN.Abp.Notifications.WxPusher; + +[DependsOn( + typeof(AbpNotificationsWxPusherModule), + typeof(AbpNotificationsTestsModule))] +public class AbpNotificationsWxPusherTestModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + // 用捕获式假实现替换真实发送, 避免真正调用 WxPusher 接口 + context.Services.Replace( + ServiceDescriptor.Singleton()); + } +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/FakeWxPusherMessageSender.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/FakeWxPusherMessageSender.cs new file mode 100644 index 000000000..6d5be6427 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/FakeWxPusherMessageSender.cs @@ -0,0 +1,38 @@ +using LINGYUN.Abp.WxPusher.Messages; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace LINGYUN.Abp.Notifications.WxPusher; + +/// +/// 捕获式 假实现 +/// +public class FakeWxPusherMessageSender : IWxPusherMessageSender +{ + public List SentMessages { get; } = new(); + + public Task> SendAsync( + string content, + string? summary = null, + MessageContentType contentType = MessageContentType.Text, + List? topicIds = null, + List? uids = null, + string? url = null, + CancellationToken cancellationToken = default) + { + SentMessages.Add(new SentMessageArgs(content, summary, contentType, topicIds, uids, url)); + + return Task.FromResult(new List()); + } + + public void Clear() => SentMessages.Clear(); + + public record SentMessageArgs( + string Content, + string? Summary, + MessageContentType ContentType, + List? TopicIds, + List? Uids, + string? Url); +} diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/NotificationSenderTests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/NotificationSenderTests.cs index 490acfa02..f582eadc1 100644 --- a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/NotificationSenderTests.cs +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/NotificationSenderTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; namespace LINGYUN.Abp.Notifications.WxPusher; @@ -26,7 +26,9 @@ public class NotificationSenderTests : AbpNotificationsWxPusherTestBase message, DateTime.Now, "xUnit Test"); - notificationData.SetUrl("https://www.baidu.com/"); + notificationData.TrySetData( + WxPusherNotificationDataKeys.Url, + "https://www.baidu.com/"); await NotificationSender.SendNofiterAsync( NotificationsTestsNames.Test1, @@ -47,7 +49,9 @@ public class NotificationSenderTests : AbpNotificationsWxPusherTestBase message, DateTime.Now, "xUnit Test"); - notificationData.SetUrl("https://www.baidu.com/"); + notificationData.TrySetData( + WxPusherNotificationDataKeys.Url, + "https://www.baidu.com/"); await NotificationSender.SendNofiterAsync( NotificationsTestsNames.Test2, @@ -68,7 +72,9 @@ public class NotificationSenderTests : AbpNotificationsWxPusherTestBase message, DateTime.Now, "xUnit Test"); - notificationData.SetUrl("https://www.baidu.com/"); + notificationData.TrySetData( + WxPusherNotificationDataKeys.Url, + "https://www.baidu.com/"); await NotificationSender.SendNofiterAsync( NotificationsTestsNames.Test3, diff --git a/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData_Tests.cs b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData_Tests.cs new file mode 100644 index 000000000..00c675ec6 --- /dev/null +++ b/aspnet-core/tests/LINGYUN.Abp.Notifications.WxPusher.Tests/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData_Tests.cs @@ -0,0 +1,110 @@ +using Shouldly; +using System; +using System.Threading.Tasks; +using Xunit; + +namespace LINGYUN.Abp.Notifications.WxPusher; + +/// +/// WxPusher 渠道数据测试 +/// +/// +/// 统一写法: 先 new 渠道数据 → 通过 IJsonSerializer 序列化写入通知数据 → +/// 再让渠道实际发布, 断言捕获到的消息参数。 +/// +public class WxPusherChannelData_Tests : AbpNotificationsWxPusherTestBase +{ + private const string Provider = WxPusherNotificationPublishProvider.ProviderName; + + private FakeWxPusherMessageSender Sender + => (FakeWxPusherMessageSender)GetRequiredService(); + + [Fact] + public void Should_Resolve_Url() + { + var data = WriteChannelData(new WxPusherChannelData + { + Url = "https://example.com/detail/123" + }); + + var payload = ChannelDataResolver.Resolve(data); + + payload.ShouldNotBeNull(); + payload!.Url.ShouldBe("https://example.com/detail/123"); + } + + [Fact] + public void Should_Not_Declare_Payload_When_Url_Absent() + { + ChannelDataResolver.IsDeclared(new NotificationData(), typeof(WxPusherChannelData)) + .ShouldBeFalse(); + } + + [Fact] + public void Should_Match_Key_Case_Insensitively() + { + var data = new NotificationData(); + data.TrySetData(WxPusherNotificationDataKeys.Url, "https://example.com/a"); + + ChannelDataResolver.Resolve(data)!.Url + .ShouldBe("https://example.com/a"); + + var upper = new NotificationData(); + upper.TrySetData("WX-PUSHER:URL", "https://example.com/b"); + + ChannelDataResolver.Resolve(upper)!.Url + .ShouldBe("https://example.com/b"); + } + + [Fact] + public async Task Should_Send_With_Resolved_Url() + { + Sender.Clear(); + + var data = WriteChannelData(new WxPusherChannelData + { + Url = "https://example.com/from-channel-data" + }); + data.WriteStandardData("标题", "内容", DateTime.Now, "system"); + + await PublishAsync(data); + + Sender.SentMessages.Count.ShouldBe(1); + Sender.SentMessages[0].Url.ShouldBe("https://example.com/from-channel-data"); + Sender.SentMessages[0].Content.ShouldBe("内容"); + Sender.SentMessages[0].Summary.ShouldBe("标题"); + } + + [Fact] + public async Task Should_Send_Without_Url_When_Not_Provided() + { + Sender.Clear(); + + var data = new NotificationData(); + data.WriteStandardData("标题", "内容", DateTime.Now, "system"); + + await PublishAsync(data); + + Sender.SentMessages.Count.ShouldBe(1); + Sender.SentMessages[0].Url.ShouldBeNull(); + } + + private async Task PublishAsync(NotificationData data) + { + var provider = GetRequiredService(); + + var notification = new NotificationInfo + { + Name = "Test", + ContentType = NotificationContentType.Text, + Data = data + }; + notification.SetId(1); + + var context = new NotificationPublishContext( + notification, + new[] { new UserIdentifier(Guid.NewGuid(), "tester") }); + + await provider.PublishAsync(context); + } +}