Browse Source

feat(notifications): Resolve channel specific payloads from the notification property bag

Every channel needs its own message shape (a WeChat Work template card, a webhook news
article, a wx-pusher URL), but the only way to carry it was to stuff those types into
`NotificationData`, which couples the producer to the channels and forces a schema change
whenever a channel gains a field. Channels now declare their own payload types and the
property bag carries them under per channel key prefixes, so one `ExtraProperties` column
serves every channel and no notification table has to change.

- add the channel data contract to `LINGYUN.Abp.Notifications.Core`:
  `NotificationChannelData` base type, `[NotificationChannelData]` /
  `[NotificationChannelProperty]` annotations, `NotificationChannelDataDescriptor`,
  `NotificationChannelDataFormat` and `NotificationChannelDataPresenceMode`
- add the implementation to `LINGYUN.Abp.Notifications`: `INotificationChannelDataResolver`
  dispatching payloads in priority order, `INotificationChannelDataAccessor` reading and
  writing typed values in the property bag, `INotificationChannelDataSerializer` for the
  producer side, `INotificationChannelDataPresenceProvider`, `AbpNotificationChannelDataOptions`
  and `AbpNotificationChannelDataConfigurationException` for registration time validation
- keys are namespaced per channel (`wx-work:`, `wx-work-hook:`, `wx-mp:`, `pusher:`, `plus:`)
  and matched case insensitively, so channels cannot collide in the shared property bag;
  complex payloads are stored as JSON strings and deserialized back with the configured
  `IJsonSerializer`
- the WeChat Work channel gains 18 channel data types plus `WeChatWorkMessageFactory`, and
  the webhook channel 16 plus `WeChatWorkWebhookMessageFactory`, covering text, markdown,
  markdown_v2, image, news, file, voice, template card, mini program notice and mp news
- PushPlus, WxPusher and the WeChat mini program channel adopt the same contract; the mini
  program keys are prefixed and the historical bare keys are kept as a read only fallback,
  marked `[Obsolete]` with the provider's `ApplyLegacyKeys` as the only sanctioned read site
- delete the WxPusher `NotificationDataExtensions.SetUrl` in favour of the typed accessor
- add `WebhookTemplateCardSystemTextJsonConverter` so the abstract webhook template card
  survives the property bag round trip, and make `WeChatWorkWebhookNewsMessage` public
- test projects `LINGYUN.Abp.Notifications.ChannelData.Tests`, `...PushPlus.Tests`,
  `...WeChat.Work.Tests` and `...Webhook.WeChat.Work.Tests` (real ABP container, fake
  senders registered through `context.Services.Replace` so no real API is called), the
  mini program and wx-pusher tests now drive a fake sender, and each channel verifies
  payloads restored from a raw database JSON string as well as from memory
pull/1619/head
colin 1 month ago
parent
commit
2064de2138
  1. 3
      aspnet-core/LINGYUN.MicroService.All.slnx
  2. 3
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MediaMessage.cs
  3. 13
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MiniProgramMessage.cs
  4. 17
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/MpNewMessage.cs
  5. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardActionMenu.cs
  6. 3
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardCardAction.cs
  7. 6
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardEmphasisContent.cs
  8. 4
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardHorizontalContent.cs
  9. 2
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardJump.cs
  10. 6
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardMainTitle.cs
  11. 8
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardQuoteArea.cs
  12. 2
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardSource.cs
  13. 2
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextCardMessage.cs
  14. 4
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TextTemplateCard.cs
  15. 2
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/VideoMessage.cs
  16. 37
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkMiniProgramMessage.cs
  17. 4
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WeChatWorkWebhookNewsMessage.cs
  18. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardAction.cs
  19. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardHorizontalContent.cs
  20. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardImageTextArea.cs
  21. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardJump.cs
  22. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardQuoteArea.cs
  23. 5
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSource.cs
  24. 225
      aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/WebhookTemplateCardSystemTextJsonConverter.cs
  25. 737
      aspnet-core/modules/realtime-notifications/CHANNEL-DATA-USAGE.md
  26. 375
      aspnet-core/modules/realtime-notifications/CHANNEL-DATA.md
  27. 23
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/AbpNotificationChannelDataConfigurationException.cs
  28. 26
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelData.cs
  29. 56
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAttribute.cs
  30. 53
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptor.cs
  31. 20
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataFormat.cs
  32. 32
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceMode.cs
  33. 44
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelPropertyAttribute.cs
  34. 8
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/AbpNotificationsPushPlusModule.cs
  35. 30
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusChannelData.cs
  36. 18
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationDataKeys.cs
  37. 8
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationPublishProvider.cs
  38. 8
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/AbpNotificationsWeChatMiniProgramModule.cs
  39. 100
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationDataKeys.cs
  40. 132
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramNotificationPublishProvider.cs
  41. 50
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.MiniProgram/LINGYUN/Abp/Notifications/WeChat/MiniProgram/WeChatMiniProgramSubscribeChannelData.cs
  42. 28
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/AbpNotificationsWeChatWorkModule.cs
  43. 79
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/AbpWeChatWorkNotificationMessageOptions.cs
  44. 21
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkChannelData.cs
  45. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkFileChannelData.cs
  46. 18
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMarkdownChannelData.cs
  47. 326
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactory.cs
  48. 48
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryContext.cs
  49. 30
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageFactoryResult.cs
  50. 52
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageKind.cs
  51. 74
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMessageOptions.cs
  52. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMiniProgramNoticeChannelData.cs
  53. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkMpNewChannelData.cs
  54. 48
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationContact.cs
  55. 55
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkNotificationDataKeys.cs
  56. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTemplateCardChannelData.cs
  57. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextCardChannelData.cs
  58. 18
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkTextChannelData.cs
  59. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVideoChannelData.cs
  60. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/ChannelData/WeChatWorkVoiceChannelData.cs
  61. 260
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WeChat.Work/LINGYUN/Abp/Notifications/WeChat/Work/WeChatWorkNotificationPublishProvider.cs
  62. 35
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/AbpNotificationsWebhookWeChatWorkModule.cs
  63. 75
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/AbpNotificationsWebhookWeChatWorkMessageOptions.cs
  64. 16
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookChannelData.cs
  65. 19
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookFileChannelData.cs
  66. 19
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookImageChannelData.cs
  67. 18
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownChannelData.cs
  68. 22
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMarkdownV2ChannelData.cs
  69. 92
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactory.cs
  70. 41
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryContext.cs
  71. 34
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageFactoryResult.cs
  72. 47
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookMessageKind.cs
  73. 19
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNewsChannelData.cs
  74. 56
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationDataKeys.cs
  75. 26
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookNotificationProvider.cs
  76. 24
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTemplateCardChannelData.cs
  77. 18
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookTextChannelData.cs
  78. 19
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/ChannelData/WeChatWorkWebhookVoiceChannelData.cs
  79. 191
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Webhook.WeChat.Work/LINGYUN/Abp/Notifications/Webhook/WeChat/Work/WeChatWorkWebhookNotificationContributor.cs
  80. 19
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/NotificationDataExtensions.cs
  81. 8
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/AbpNotificationsWxPusherModule.cs
  82. 19
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherChannelData.cs
  83. 14
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationDataKeys.cs
  84. 6
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationPublishProvider.cs
  85. 3
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN.Abp.Notifications.csproj
  86. 2
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/AbpNotificationsModule.cs
  87. 31
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataJsonSerializer.cs
  88. 100
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/AbpNotificationChannelDataOptions.cs
  89. 71
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataAccessor.cs
  90. 22
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataJsonSerializer.cs
  91. 28
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataPresenceProvider.cs
  92. 85
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataResolver.cs
  93. 40
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataSerializer.cs
  94. 381
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataAccessor.cs
  95. 15
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataDescriptorList.cs
  96. 158
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresence.cs
  97. 26
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceProvider.cs
  98. 59
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataProperty.cs
  99. 90
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPropertyCache.cs
  100. 279
      aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataResolver.cs

3
aspnet-core/LINGYUN.MicroService.All.slnx

@ -596,7 +596,10 @@
<Project Path="tests/LINGYUN.Abp.Logging.Tests/LINGYUN.Abp.Logging.Tests.csproj" Id="1e05270f-6652-443d-b76f-5d4360f2722e" />
<Project Path="tests/LINGYUN.Abp.MaxMindGeoIP2.Tests/LINGYUN.Abp.MaxMindGeoIP2.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Notifications.Tests/LINGYUN.Abp.Notifications.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Notifications.ChannelData.Tests/LINGYUN.Abp.Notifications.ChannelData.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests/LINGYUN.Abp.Notifications.Webhook.WeChat.Work.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests/LINGYUN.Abp.Notifications.WeChat.MiniProgram.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests/LINGYUN.Abp.Notifications.WeChat.Work.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.OpenObserve.Tests/LINGYUN.Abp.OpenObserve.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Rules.RulesEngine.Tests/LINGYUN.Abp.Rules.RulesEngine.Tests.csproj" />
<Project Path="tests/LINGYUN.Abp.Sms.Platform.Tests/LINGYUN.Abp.Sms.Platform.Tests.csproj" />

3
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;

13
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<MiniProgramContent>? 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;
}
}

17
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<MpNewMessage> Articles { get; set; }
[Newtonsoft.Json.JsonConstructor]
[System.Text.Json.Serialization.JsonConstructor]
public MpNewMessagePayload(List<MpNewMessage> articles)
{
Articles = articles;
@ -26,6 +29,8 @@ public class MpNewMessagePayload
/// </summary>
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!;
/// <summary>
/// 图文消息缩略图的media_id, 可以通过素材管理接口获得。此处thumb_media_id即上传接口返回的media_id
/// </summary>
[NotNull]
[JsonProperty("thumb_media_id")]
[JsonPropertyName("thumb_media_id")]
public string ThumbMediaId { get; set; }
public string ThumbMediaId { get; set; } = default!;
/// <summary>
/// 图文消息的作者,不超过64个字节
/// </summary>
[CanBeNull]
[JsonProperty("author")]
[JsonPropertyName("author")]
public string Author { get; set; }
public string? Author { get; set; }
/// <summary>
/// 图文消息点击“阅读原文”之后的页面链接
/// </summary>
[CanBeNull]
[JsonProperty("content_source_url")]
[JsonPropertyName("content_source_url")]
public string ContentSourceUrl { get; set; }
public string? ContentSourceUrl { get; set; }
/// <summary>
/// 图文消息的内容,支持html标签,不超过666 K个字节(支持id转译)
/// </summary>
[NotNull]
[JsonProperty("content")]
[JsonPropertyName("content")]
public string Content { get; set; }
public string Content { get; set; } = default!;
/// <summary>
/// 图文消息的描述,不超过512个字节,超过会自动截断(支持id转译)
/// </summary>
[CanBeNull]
[JsonProperty("digest")]
[JsonPropertyName("digest")]
public string Description { get; set; }
public string? Description { get; set; }
}

5
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; }
/// <summary>
/// 操作列表,列表长度取值范围为 [1, 3]
/// </summary>
@ -23,6 +23,9 @@ public class TemplateCardActionMenu
[JsonProperty("action_list")]
[JsonPropertyName("action_list")]
public List<TemplateCardAction> Actions { get; set;}
[Newtonsoft.Json.JsonConstructor]
[System.Text.Json.Serialization.JsonConstructor]
public TemplateCardActionMenu(List<TemplateCardAction> actions, string description = "")
{
Actions = actions;

3
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;
/// </summary>
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;

6
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;
/// </summary>
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; }
/// <summary>
/// 关键数据样式的数据描述内容,建议不超过22个字
/// </summary>
[CanBeNull]
[JsonProperty("desc")]
[JsonPropertyName("desc")]
public string Description { get; set; }
public string? Description { get; set; }
}

4
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!;
/// <summary>
/// 二级文本,如果horizontal_content_list.type是2,该字段代表文件名称(要包含文件类型),建议不超过30个字,(支持id转译)
/// </summary>

2
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;
/// </summary>
public class TemplateCardJump
{
[Newtonsoft.Json.JsonConstructor]
[System.Text.Json.Serialization.JsonConstructor]
public TemplateCardJump(string title, string url)
{
Type = 1;

6
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;
/// </summary>
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; }
/// <summary>
/// 标题辅助信息,建议不超过44个字,(支持id转译)
/// </summary>
[CanBeNull]
[JsonProperty("desc")]
[JsonPropertyName("desc")]
public string Description { get; set; }
public string? Description { get; set; }
}

8
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;
/// </summary>
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; }
/// <summary>
/// 点击跳转的url,quote_area.type是1时必填
/// </summary>
@ -57,12 +59,12 @@ public class TemplateCardQuoteArea
[CanBeNull]
[JsonProperty("title")]
[JsonPropertyName("title")]
public string Title { get; set; }
public string? Title { get; set; }
/// <summary>
/// 引用文献样式的引用文案
/// </summary>
[CanBeNull]
[JsonProperty("quote_text")]
[JsonPropertyName("quote_text")]
public string Text { get; set; }
public string? Text { get; set; }
}

2
aspnet-core/framework/wechat/LINGYUN.Abp.WeChat.Work/LINGYUN/Abp/WeChat/Work/Messages/Models/TemplateCardSource.cs

@ -18,6 +18,8 @@ public enum DescriptionColor
/// </summary>
public class TemplateCardSource
{
[Newtonsoft.Json.JsonConstructor]
[System.Text.Json.Serialization.JsonConstructor]
public TemplateCardSource(
string iconUrl = "",
string description = "",

2
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;
/// </summary>
public class TextCardMessage
{
[Newtonsoft.Json.JsonConstructor]
[System.Text.Json.Serialization.JsonConstructor]
public TextCardMessage(
string title,
string description,

4
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;
/// </summary>
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!;
}

2
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;
/// </summary>
public class VideoMessage
{
[Newtonsoft.Json.JsonConstructor]
[System.Text.Json.Serialization.JsonConstructor]
public VideoMessage(
string mediaId,
string title = "",

37
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;
/// <summary>
/// 企业微信小程序通知消息
/// </summary>
public class WeChatWorkMiniProgramMessage
public class WeChatWorkMiniProgramMessage : WeChatWorkMessage
{
/// <summary>
/// 指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)。
/// 特殊情况:指定为"@all",则向该企业应用的全部成员发送
/// </summary>
[JsonProperty("touser")]
[JsonPropertyName("touser")]
public virtual string? ToUser { get; set; }
/// <summary>
/// 指定接收消息的部门,部门ID列表,多个接收者用‘|’分隔,最多支持100个。
/// 当touser为"@all"时忽略本参数
/// </summary>
[JsonProperty("toparty")]
[JsonPropertyName("toparty")]
public virtual string? ToParty { get; set; }
/// <summary>
/// 指定接收消息的标签,标签ID列表,多个接收者用‘|’分隔,最多支持100个。
/// 当touser为"@all"时忽略本参数
/// </summary>
[JsonProperty("totag")]
[JsonPropertyName("totag")]
public virtual string? ToTag { get; set; }
/// <summary>
/// 消息类型
/// </summary>
[NotNull]
[JsonProperty("msgtype")]
[JsonPropertyName("msgtype")]
public virtual string MsgType { get; }
/// <summary>
/// 表示是否开启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";
}
}

4
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;
/// <summary>
/// 企业微信Webhook图文消息
/// </summary>
internal class WeChatWorkWebhookNewsMessage : WeChatWorkWebhookMessage
public class WeChatWorkWebhookNewsMessage : WeChatWorkWebhookMessage
{
/// <summary>
/// 图文消息体

5
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,

5
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,

5
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,

5
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,

5
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,

5
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)

225
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;
/// <summary>
/// Webhook 模板卡片消息 System.Text.Json 序列化
/// </summary>
/// <remarks>
/// <para>
/// <see cref="WebhookTemplateCardMessage"/> 是抽象类型, 且具体类型的构造函数带必填参数
/// (例如 <see cref="WebhookNewsNoticeCardMessage"/> 的 <c>cardImage</c> / <c>action</c> / <c>mainTitle</c>),
/// 因此无法通过无参构造还原 —— 模板卡片一旦作为通知数据持久化就再也无法反序列化。
/// </para>
/// <para>
/// 这里按 <c>card_type</c> 判别符还原具体类型。判别符由构造函数传递给基类, 通过读取构造函数
/// IL 中的字符串常量获得, 因此新增卡片类型无需修改本转换器。
/// </para>
/// <para>
/// 项目使用的 JSON 集成是 <c>Volo.Abp.Json.SystemTextJson</c>,
/// 因此由渠道模块在启动时自动注册到全局选项。
/// </para>
/// </remarks>
public class WebhookTemplateCardSystemTextJsonConverter : JsonConverter<WebhookTemplateCardMessage>
{
private const byte LdstrOpCode = 0x72;
private const string CardTypePropertyName = "card_type";
private static readonly Dictionary<string, Type> 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);
}
/// <summary>
/// 按 <c>card_type</c> 获取具体的卡片类型
/// </summary>
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;
}
}
/// <summary>
/// 获取卡片类型的判别符
/// </summary>
/// <remarks>
/// 判别符由构造函数传递给基类, 因此读取构造函数 IL 中的字符串常量。
/// 同时以类型名作为兜底键。
/// </remarks>
private static IEnumerable<string> GetDiscriminators(Type cardType)
{
var discriminators = new List<string>();
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;
}
}

737
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`。
> 它按载荷类型上标注的 <xref:NotificationChannelPropertyAttribute> 写入对应键,
> 生产侧与渠道侧共用同一份契约定义。
### 1.4 模板卡片(推荐用于审批/告警类)
```csharp
var card = new TextTemplateCard(
new TemplateCardCardAction("https://example.com/approval/123"))
{
MainTitle = new TemplateCardMainTitle("请假通过通知", "您的请假申请已通过"),
SubTitle = "请及时处理后续交接事项",
HorizontalContents = new List<TemplateCardHorizontalContent>
{
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<TemplateCardJump>
{
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<MiniProgramContent>
{
new MiniProgramContent("订单号", "SO20251001001"),
new MiniProgramContent("物流公司", "顺丰速运"),
}
}
});
```
### 1.6 图文 / 视频 / 语音 / 文件
```csharp
channelDataSerializer.Write(data, new WeChatWorkMpNewChannelData
{
MpNewMessage = new MpNewMessagePayload(new List<MpNewMessage>
{
new MpNewMessage(
title: "月度报告",
thumbMediaId: "MEDIA_ID",
content: "<p>报告正文</p>",
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>
{
WebhookTemplateCardHorizontalContent.Default("分支", "main"),
WebhookTemplateCardHorizontalContent.Default("提交", "a1b2c3d"),
})
});
```
图文消息示例:
```csharp
channelDataSerializer.Write(data, new WeChatWorkWebhookNewsChannelData
{
News = new WebhookNewsMessage(new List<WebhookArticleMessage>
{
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<AbpNotificationsWebhookWeChatWorkOptions>(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<AbpNotificationsPublishOptions>(options =>
{
options.PublishProviders.Add<DingTalkNotificationPublishProvider>();
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<DingTalkChannelData>();
});
}
}
```
> `AbpNotificationChannelDataOptions` 是纯数据对象, 注册期的存在性校验只依赖声明元数据、
> 不依赖任何服务, 因此 `Add()` 不要求任何初始化顺序, 也不需要额外的配置器类。
### 4.3 在渠道实现中解析
```csharp
public class DingTalkNotificationPublishProvider : NotificationPublishProvider
{
public const string ProviderName = "DingTalk";
public override string Name => ProviderName;
protected INotificationChannelDataResolver ChannelDataResolver
=> ServiceProvider.LazyGetRequiredService<INotificationChannelDataResolver>();
protected async override Task PublishAsync(
NotificationPublishContext context,
CancellationToken cancellationToken = default)
{
var data = context.Notification.Data;
// ① 载荷已声明但解析失败 => 生产者数据非法,明确报错而不是静默回退
if (ChannelDataResolver.IsDeclared(data, typeof(DingTalkChannelData))
&& ChannelDataResolver.Resolve<DingTalkChannelData>(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<DingTalkChannelData>(data)?.Webhook;
if (webhook.IsNullOrWhiteSpace())
{
context.Cancel("Unable to send dingtalk messages because the webhook is not set.");
return;
}
// ③ 需要标量选项时用类型化读取(不要用 as)
var timeout = ChannelDataResolver.GetValue<int>(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<bool>(data, WeChatWorkNotificationDataKeys.Safe);
var payload = channelDataResolver.Resolve<WxPusherChannelData>(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<WxPusherChannelData>(data)?.Url` |
| `data.GetWebhookOrNull()` (PushPlus) | `resolver.Resolve<PushPlusChannelData>(data)?.Webhook` |
| `data.GetCallbackUrlOrNull()` (PushPlus) | `resolver.Resolve<PushPlusChannelData>(data)?.CallbackUrl` |
| `data.TryGetMessagePayload<T>(key, out var m)` | `resolver.Resolve<TChannelData>(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<WeChatWorkTextCardChannelData>(data);
payload.ShouldNotBeNull();
payload!.TextCard!.Title.ShouldBe(message.Title);
payload.TextCard.Url.ShouldBe(message.Url);
}
}
```
公共基类 `NotificationChannelDataTestsBase<TStartupModule>`(位于
`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
```

375
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<AbpNotificationsPublishOptions>(options =>
{
options.PublishProviders.Add<MyNotificationPublishProvider>();
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<MyChannelData>();
});
}
}
```
**为什么不需要额外的配置器类、也不存在顺序问题**:
`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<AbpNotificationsPublishOptions>(options =>
{
options.PublishProviders.Add<MyNotificationPublishProvider>();
});
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<MyChannelData>();
});
}
}
```
### 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<INotificationChannelDataResolver>();
protected override Task PublishAsync(NotificationPublishContext context, CancellationToken ct)
{
var data = context.Notification.Data;
// 按类型解析
var payload = ChannelDataResolver.Resolve<MyChannelData>(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<AbpNotificationChannelDataOptions>` 中注册载荷;
5. 渠道实现中**不要**出现 `as byte?` / `as int?` 这类裸转换, 改用 `INotificationChannelDataResolver`;
6. 需要区分"未声明"与"数据非法"时, 组合使用 `IsDeclared` 与 `Resolve`;
7. 抽象类型载荷需要注册 JSON 类型转换器(注意 JSON 实现: STJ 或 Newtonsoft)。

23
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/AbpNotificationChannelDataConfigurationException.cs

@ -0,0 +1,23 @@
using System;
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 渠道数据配置异常
/// </summary>
/// <remarks>
/// 注册期契约校验失败时抛出, 目的: 让配置错误在启动阶段暴露,
/// 而不是在生产环境静默丢弃通知。
/// </remarks>
public class AbpNotificationChannelDataConfigurationException : Exception
{
public AbpNotificationChannelDataConfigurationException(string message)
: base(message)
{
}
public AbpNotificationChannelDataConfigurationException(string message, Exception innerException)
: base(message, innerException)
{
}
}

26
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelData.cs

@ -0,0 +1,26 @@
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 通知渠道数据(载荷)基类
/// </summary>
/// <remarks>
/// <para>
/// 渠道数据是"发布渠道能理解的强类型数据结构", 生产者用它表达渠道专属语义,
/// 渠道实现用它解析出具体的消息载体。
/// </para>
/// <para>
/// 派生类需要做两件事:
/// <list type="number">
/// <item>
/// 用 <see cref="NotificationChannelDataAttribute"/> 声明渠道、匹配顺序与
/// <see cref="NotificationChannelDataAttribute.Presence"/> 存在性判定模式;
/// </item>
/// <item>
/// 用 <see cref="NotificationChannelPropertyAttribute"/> 标注参与读写的属性。
/// </item>
/// </list>
/// </para>
/// </remarks>
public abstract class NotificationChannelData
{
}

56
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;
/// <summary>
/// 通知渠道数据契约
/// </summary>
/// <remarks>
/// <para>
/// 渠道数据(载荷)是发布渠道与生产者之间约定的数据结构。
/// 生产者通过 <see cref="INotificationChannelDataSerializer"/> 写入载荷,
/// 渠道通过 <see cref="INotificationChannelDataResolver"/> 解析载荷。
/// </para>
/// <para>
/// 载荷的存在性由 <see cref="Presence"/> 声明式表达, 结合
/// <see cref="NotificationChannelPropertyAttribute"/> 的键定义自动推导,
/// 无需在载荷类型中实现判定方法。
/// </para>
/// <para>
/// 若既未声明 <see cref="Presence"/>、又没有可参与匹配的属性,
/// 注册时会抛出 <see cref="AbpNotificationChannelDataConfigurationException"/>:
/// 让"忘了定义存在性"在启动阶段暴露, 而不是在生产环境静默丢弃通知。
/// </para>
/// </remarks>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class NotificationChannelDataAttribute : Attribute
{
/// <summary>
/// 渠道名称, 对应 <see cref="INotificationPublishProvider.Name"/>
/// </summary>
public string ProviderName { get; }
/// <summary>
/// 载荷在同一个渠道内的匹配顺序, 数值越小越先匹配
/// </summary>
/// <remarks>
/// 用于表达渠道内的显式规则, 匹配顺序必须声明,
/// 不允许依赖注册顺序或字段探测顺序。
/// </remarks>
public int Priority { get; set; }
/// <summary>
/// 存在性判定模式, 默认按"参与匹配的属性全部存在"判定
/// </summary>
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;
}
}

53
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;
/// <summary>
/// 通知渠道数据(载荷)描述符
/// </summary>
public sealed class NotificationChannelDataDescriptor
{
/// <summary>
/// 渠道名称
/// </summary>
public string ProviderName { get; }
/// <summary>
/// 载荷类型
/// </summary>
public Type PayloadType { get; }
/// <summary>
/// 匹配顺序, 数值越小越先匹配
/// </summary>
public int Priority { get; }
/// <summary>
/// 存在性判定模式
/// </summary>
public NotificationChannelDataPresenceMode Presence { get; }
/// <summary>
/// 判断通知数据中是否存在本载荷
/// </summary>
public Func<NotificationData, bool> IsPresent { get; }
public NotificationChannelDataDescriptor(
string providerName,
Type payloadType,
int priority,
NotificationChannelDataPresenceMode presence,
Func<NotificationData, bool> isPresent)
{
ProviderName = providerName;
PayloadType = payloadType;
Priority = priority;
Presence = presence;
IsPresent = isPresent;
}
public override string ToString()
{
return $"{ProviderName}:{PayloadType.Name}(Priority={Priority}, Presence={Presence})";
}
}

20
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataFormat.cs

@ -0,0 +1,20 @@
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 通知渠道数据(载荷)属性的存储格式
/// </summary>
public enum NotificationChannelDataFormat
{
/// <summary>
/// 自动识别(默认)
/// </summary>
/// <remarks>
/// 简单类型直接转换, 复杂类型序列化为 JSON 字符串,
/// 读取时同样兼容"对象实例"与"JSON 字符串"两种形态。
/// </remarks>
Auto = 0,
/// <summary>
/// 始终以 JSON 字符串存储
/// </summary>
Json = 1
}

32
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.Core/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataPresenceMode.cs

@ -0,0 +1,32 @@
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 渠道数据(载荷)存在性判定模式
/// </summary>
public enum NotificationChannelDataPresenceMode
{
/// <summary>
/// 载荷始终被视为存在
/// </summary>
/// <remarks>
/// 适用于不依赖通知数据的载荷(由渠道在运行时构造)。
/// </remarks>
None = 0,
/// <summary>
/// 参与匹配的属性全部存在时, 载荷被视为存在(默认)
/// </summary>
/// <remarks>
/// 适用于"某个键就是载荷标识"的场景, 例如企业微信的各消息类型。
/// </remarks>
DeclaredProperties = 1,
/// <summary>
/// 参与匹配的属性存在任意一个时, 载荷被视为存在
/// </summary>
/// <remarks>
/// 适用于"多个可选键中任意一个即可"的场景,
/// 例如 PushPlus 的 webhook 与 callback 二者其一。
/// </remarks>
AnyDeclaredProperty = 2
}

44
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;
/// <summary>
/// 标记通知渠道数据(载荷)的属性参与类型化读写
/// </summary>
/// <remarks>
/// <para>
/// 参与读写的属性名称默认取属性名, 也可以通过 <see cref="Name"/> 显式指定,
/// 以便兼容历史遗留的通知数据键(例如 <c>TemplateId</c> 这类未加前缀的键)。
/// </para>
/// <para>
/// 读写过程会做弱类型转换, 因此数据无论经历过多少次
/// JSON 序列化/反序列化(持久化、失败重试、跨进程投递)都不会丢失。
/// </para>
/// </remarks>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class NotificationChannelPropertyAttribute : Attribute
{
/// <summary>
/// 通知数据中的键名, 为空时取属性名
/// </summary>
public string? Name { get; }
/// <summary>
/// 匹配载荷时是否忽略本属性
/// </summary>
/// <remarks>
/// 适用于"投递选项"这类不决定载荷形态的属性,
/// 例如企业微信的接收人(to_user/toparty/totag)。
/// 投递选项单独存在时不代表某个消息载荷存在。
/// </remarks>
public bool IgnoreWhenMatching { get; set; }
public NotificationChannelPropertyAttribute()
{
}
public NotificationChannelPropertyAttribute(string name)
{
Name = name;
}
}

8
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<PushPlusNotificationPublishProvider>();
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<PushPlusChannelData>();
});
}
}

30
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;
/// <summary>
/// PushPlus 渠道数据(载荷)
/// </summary>
/// <remarks>
/// webhook 与 callback 是"可选参数"而非互斥的"载荷标识":
/// 写入其中任意一个即表示生产者要使用 PushPlus 渠道,
/// 因此存在性判定模式声明为 <see cref="NotificationChannelDataPresenceMode.AnyDeclaredProperty"/>。
/// </remarks>
[NotificationChannelData(
PushPlusNotificationPublishProvider.ProviderName,
Priority = 100,
Presence = NotificationChannelDataPresenceMode.AnyDeclaredProperty)]
public class PushPlusChannelData : NotificationChannelData
{
/// <summary>
/// webhook 地址
/// </summary>
[NotificationChannelProperty(PushPlusNotificationDataKeys.Webhook)]
public virtual string? Webhook { get; set; }
/// <summary>
/// 回调地址
/// </summary>
[NotificationChannelProperty(PushPlusNotificationDataKeys.CallbackUrl)]
public virtual string? CallbackUrl { get; set; }
}

18
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.PushPlus/LINGYUN/Abp/Notifications/PushPlus/PushPlusNotificationDataKeys.cs

@ -0,0 +1,18 @@
namespace LINGYUN.Abp.Notifications.PushPlus;
/// <summary>
/// PushPlus 通知数据键
/// </summary>
public static class PushPlusNotificationDataKeys
{
public const string Prefix = "push-plus:";
/// <summary>
/// webhook 地址
/// </summary>
public const string Webhook = Prefix + "webhook";
/// <summary>
/// 回调地址
/// </summary>
public const string CallbackUrl = Prefix + "callback";
}

8
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<IPushPlusMessageSender>();
protected INotificationDataSerializer NotificationDataSerializer => ServiceProvider.LazyGetRequiredService<INotificationDataSerializer>();
protected INotificationDefinitionManager NotificationDefinitionManager => ServiceProvider.LazyGetRequiredService<INotificationDefinitionManager>();
protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService<INotificationChannelDataResolver>();
protected async override Task<bool> 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<PushPlusChannelData>(context.Notification.Data);
var webhook = channelData?.Webhook ?? "";
var callbackUrl = channelData?.CallbackUrl ?? "";
var notificationData = await NotificationDataSerializer.ToStandard(context.Notification.Data);
await PushPlusMessageSender.SendWithChannelAsync(

8
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<WeChatMiniProgramNotificationPublishProvider>();
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<WeChatMiniProgramSubscribeChannelData>();
});
}
}

100
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;
/// <summary>
/// 微信小程序通知数据键
/// </summary>
/// <remarks>
/// <para>
/// 键名统一带本渠道前缀(<see cref="Prefix"/>), 与其它渠道保持一致,
/// 避免不同渠道的键在同一个通知数据属性包中相互冲突。
/// </para>
/// <para>
/// 读取过程大小写不敏感(精确匹配优先), 因此生产者使用任意大小写都能命中。
/// </para>
/// </remarks>
public static class WeChatMiniProgramNotificationDataKeys
{
/// <summary>
/// 本渠道的数据键前缀
/// </summary>
public const string Prefix = "wx-mp:";
/// <summary>
/// 小程序模板标识(载荷标识键)
/// </summary>
public const string TemplateId = Prefix + "template_id";
/// <summary>
/// 点击跳转的小程序页面
/// </summary>
public const string RedirectPage = Prefix + "redirect_page";
/// <summary>
/// 跳转小程序类型
/// </summary>
public const string WeAppState = Prefix + "weapp_state";
/// <summary>
/// 小程序语言
/// </summary>
public const string WeAppLanguage = Prefix + "weapp_language";
/// <summary>
/// 历史遗留的无前缀键
/// </summary>
/// <remarks>
/// <para>
/// 早期版本使用无前缀键, 已安装的生产者可能仍在写入, 因此保留**只读兼容**。
/// </para>
/// <para>
/// <b>已弃用</b>: 新代码请使用带前缀的常量(<see cref="TemplateId"/> 等)。
/// 唯一允许的读取点是渠道侧的历史回退
/// (<c>WeChatMiniProgramNotificationPublishProvider.ApplyLegacyKeys</c>),
/// 它命中遗留键时会记录告警以推动生产者迁移。
/// </para>
/// </remarks>
[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
/// <summary>
/// 历史: 小程序模板标识
/// </summary>
[Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.TemplateId instead.")]
public const string TemplateId = "TemplateId";
/// <summary>
/// 历史: 点击跳转的小程序页面
/// </summary>
[Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.RedirectPage instead.")]
public const string RedirectPage = "RedirectPage";
/// <summary>
/// 历史: 跳转小程序类型
/// </summary>
[Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.WeAppState instead.")]
public const string WeAppState = "WeAppState";
/// <summary>
/// 历史: 小程序语言
/// </summary>
[Obsolete("The legacy non-prefixed key is deprecated. Use WeChatMiniProgramNotificationDataKeys.WeAppLanguage instead.")]
public const string WeAppLanguage = "WeAppLanguage";
/// <summary>
/// 全部历史键
/// </summary>
public static readonly string[] All =
{
TemplateId,
RedirectPage,
WeAppState,
WeAppLanguage
};
#pragma warning restore CS0618
}
}

132
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;
/// <summary>
/// 微信小程序消息推送提供者
/// </summary>
/// <remarks>
/// 小程序订阅消息的模板数据本身就是动态键值对, 因此载荷只声明标量字段,
/// 模板数据仍然直接取自通知数据的属性包。
/// </remarks>
public class WeChatMiniProgramNotificationPublishProvider : NotificationPublishProvider
{
public const string ProviderName = NotificationProviderNames.WechatMiniProgram;
@ -21,6 +25,7 @@ public class WeChatMiniProgramNotificationPublishProvider : NotificationPublishP
protected IFeatureChecker FeatureChecker => ServiceProvider.LazyGetRequiredService<IFeatureChecker>();
protected ISubscribeMessager SubscribeMessager => ServiceProvider.LazyGetRequiredService<ISubscribeMessager>();
protected IOptions<AbpNotificationsWeChatMiniProgramOptions> Options => ServiceProvider.LazyGetRequiredService<IOptions<AbpNotificationsWeChatMiniProgramOptions>>();
protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService<INotificationChannelDataResolver>();
protected async override Task<bool> 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)
/// <summary>
/// 解析小程序渠道数据
/// </summary>
/// <remarks>
/// 键名带本渠道前缀, 读取大小写不敏感;
/// 为了让已安装的生产者平滑升级, 这里对历史遗留的**无前缀键**做只读回退;
/// 缺省值来自渠道配置。
/// </remarks>
protected virtual WeChatMiniProgramSubscribeChannelData ResolveChannelData(NotificationData notificationData)
{
var channelData = ChannelDataResolver.Resolve<WeChatMiniProgramSubscribeChannelData>(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;
}
/// <summary>
/// 回退读取历史遗留的无前缀键
/// </summary>
/// <remarks>
/// <para>
/// 早期版本使用 <c>TemplateId</c> 这类无前缀键, 已安装的生产者可能仍在写入。
/// 带前缀的键优先; 命中遗留键时记录一次警告以便推动迁移。
/// </para>
/// </remarks>
#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;
}
}

50
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;
/// <summary>
/// 微信小程序渠道数据(载荷)
/// </summary>
/// <remarks>
/// <para>
/// 小程序订阅消息的载荷是"广播式"的: 除模板标识与跳转参数外,
/// 模板数据(<c>data</c>)直接来自通知数据的属性包, 因此这里只声明
/// 需要类型化读取的标量字段。
/// </para>
/// <para>
/// 键名带本渠道前缀(<see cref="WeChatMiniProgramNotificationDataKeys.Prefix"/>),
/// 读取大小写不敏感; 存在性由模板标识键推导, 因此把跳转参数声明为
/// "仅读取、不参与匹配" —— 生产者可能只写模板标识。
/// </para>
/// <para>
/// 历史遗留的无前缀键由渠道在解析时回退读取(见
/// <c>WeChatMiniProgramNotificationPublishProvider.ResolveChannelData</c>)。
/// </para>
/// </remarks>
[NotificationChannelData(WeChatMiniProgramNotificationPublishProvider.ProviderName, Priority = 100)]
public class WeChatMiniProgramSubscribeChannelData : NotificationChannelData
{
/// <summary>
/// 小程序模板标识(载荷标识键)
/// </summary>
[NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.TemplateId)]
public virtual string? TemplateId { get; set; }
/// <summary>
/// 点击跳转的小程序页面
/// </summary>
[NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.RedirectPage, IgnoreWhenMatching = true)]
public virtual string? RedirectPage { get; set; }
/// <summary>
/// 跳转小程序类型
/// </summary>
[NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.WeAppState, IgnoreWhenMatching = true)]
public virtual string? WeAppState { get; set; }
/// <summary>
/// 小程序语言
/// </summary>
[NotificationChannelProperty(WeChatMiniProgramNotificationDataKeys.WeAppLanguage, IgnoreWhenMatching = true)]
public virtual string? WeAppLanguage { get; set; }
}

28
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<WeChatWorkNotificationPublishProvider>();
});
// 模板卡片是抽象类型: 注册类型转换器, 使其能在渠道数据(JSON)中往返
Configure<AbpSystemTextJsonSerializerOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new TemplateCardSystemTextJsonConverter());
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<WeChatWorkMiniProgramNoticeChannelData>();
options.Add<WeChatWorkMpNewChannelData>();
options.Add<WeChatWorkTemplateCardChannelData>();
options.Add<WeChatWorkTextCardChannelData>();
options.Add<WeChatWorkVideoChannelData>();
options.Add<WeChatWorkVoiceChannelData>();
options.Add<WeChatWorkFileChannelData>();
});
// 消息载体工厂分派
Configure<AbpWeChatWorkNotificationMessageOptions>(options =>
{
options.MapDefaultMessageFactories();
});
}
}

79
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;
/// <summary>
/// 企业微信消息构造选项
/// </summary>
/// <remarks>
/// <para>
/// 渠道数据的形态到消息载体的转换集中注册在这里, 新增一种消息类型只需要
/// <c>options.Map(kind, factory)</c>, 不需要修改 Provider 的发布逻辑。
/// </para>
/// <para>
/// 相比旧的 <c>if/else</c> 探测链, 这里的分派是 O(1) 且显式的:
/// 载荷类型与工厂键不一致时会直接抛出异常, 而不是静默发出错误的消息。
/// </para>
/// </remarks>
public class AbpWeChatWorkNotificationMessageOptions
{
private readonly Dictionary<WeChatWorkMessageKind, Func<WeChatWorkMessageFactoryContext, WeChatWorkMessageFactoryResult>> _factories
= new Dictionary<WeChatWorkMessageKind, Func<WeChatWorkMessageFactoryContext, WeChatWorkMessageFactoryResult>>();
/// <summary>
/// 已注册的消息类型
/// </summary>
public IReadOnlyCollection<WeChatWorkMessageKind> MessageKinds => _factories.Keys;
/// <summary>
/// 注册消息构造工厂
/// </summary>
public AbpWeChatWorkNotificationMessageOptions Map(
WeChatWorkMessageKind kind,
Func<WeChatWorkMessageFactoryContext, WeChatWorkMessageFactoryResult> factory)
{
Check.NotNull(factory, nameof(factory));
_factories[kind] = factory;
return this;
}
/// <summary>
/// 构造消息载体
/// </summary>
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;
}
/// <summary>
/// 获取已注册的工厂
/// </summary>
public bool TryGetFactory(
WeChatWorkMessageKind kind,
out Func<WeChatWorkMessageFactoryContext, WeChatWorkMessageFactoryResult>? factory)
{
return _factories.TryGetValue(kind, out factory);
}
}

21
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;
/// <summary>
/// 企业微信渠道数据(载荷)基类
/// </summary>
/// <remarks>
/// 每个载荷对应一种企业微信消息载体, 通过 <see cref="Kind"/> 显式声明形态,
/// 渠道侧使用工厂字典做 O(1) 分派, 不再依赖 if/else 探测顺序。
/// <para>
/// 存在性由 <see cref="NotificationChannelDataAttribute.Presence"/> 声明式推导:
/// 每个载荷都只有一个"标识键", 因此默认的"参与匹配的属性全部存在"即为正确语义,
/// 无需在载荷类型中实现判定方法。
/// </para>
/// </remarks>
public abstract class WeChatWorkChannelData : NotificationChannelData
{
/// <summary>
/// 消息载体类型
/// </summary>
public abstract WeChatWorkMessageKind Kind { get; }
}

16
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;
/// <summary>
/// 文件消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 700)]
public class WeChatWorkFileChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.File;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.FileMessage)]
public virtual MediaMessage? File { get; set; }
}

18
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;
/// <summary>
/// markdown消息载荷
/// </summary>
/// <remarks>
/// 不参与渠道解析: 由通知定义的 <c>ContentType</c> 推导,
/// 生产者不需要为它准备任何渠道专属数据。
/// </remarks>
public class WeChatWorkMarkdownChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Markdown;
/// <summary>
/// 消息内容, 为空时使用通知标准数据
/// </summary>
public virtual string? Content { get; set; }
}

326
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;
/// <summary>
/// 企业微信默认消息构造工厂
/// </summary>
/// <remarks>
/// <para>
/// 每一种渠道数据(载荷)与消息载体的映射都是显式的, 新增消息类型只需追加一个
/// <c>Map</c> 调用, 不需要修改 Provider 的发布逻辑。
/// </para>
/// <para>
/// 企业微信各消息载体支持的选项并不一致, 因此按具体载体类型分别重载,
/// 由编译器保证只设置载体真正支持的字段, 而不是像旧实现那样无差别赋值。
/// </para>
/// </remarks>
public static class WeChatWorkMessageFactoryExtensions
{
/// <summary>
/// 注册内置的消息构造工厂
/// </summary>
public static AbpWeChatWorkNotificationMessageOptions MapDefaultMessageFactories(
this AbpWeChatWorkNotificationMessageOptions options)
{
Check.NotNull(options, nameof(options));
options.Map(WeChatWorkMessageKind.MiniProgramNotice, context =>
{
var channelData = Cast<WeChatWorkMiniProgramNoticeChannelData>(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<WeChatWorkMpNewChannelData>(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<WeChatWorkTemplateCardChannelData>(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<WeChatWorkTextCardChannelData>(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<WeChatWorkVideoChannelData>(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<WeChatWorkVoiceChannelData>(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<WeChatWorkFileChannelData>(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<TChannelData>(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;
}
/// <summary>
/// 应用接收者
/// </summary>
private static TMessage ApplyContact<TMessage>(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;
}
/// <summary>
/// 文本消息: 支持 safe、enable_id_trans、enable_duplicate_check
/// </summary>
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;
}
/// <summary>
/// 图文消息: 支持 safe、enable_id_trans、enable_duplicate_check
/// </summary>
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;
}
/// <summary>
/// 文件消息: 支持 safe、enable_duplicate_check, 不支持 enable_id_trans
/// </summary>
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;
}
/// <summary>
/// 视频消息: 支持 safe、enable_duplicate_check, 不支持 enable_id_trans
/// </summary>
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;
}
/// <summary>
/// 语音消息: 不支持 safe, 也不支持 enable_id_trans
/// </summary>
private static WeChatWorkVoiceMessage Apply(
WeChatWorkVoiceMessage message,
WeChatWorkMessageFactoryContext context)
{
ApplyContact(message, context);
message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue;
message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue;
return message;
}
/// <summary>
/// markdown消息: 支持 enable_duplicate_check, 不支持 safe
/// </summary>
private static WeChatWorkMarkdownMessage Apply(
WeChatWorkMarkdownMessage message,
WeChatWorkMessageFactoryContext context)
{
ApplyContact(message, context);
message.EnableDuplicateCheck = context.Options.EnableDuplicateCheckValue;
message.DuplicateCheckInterval = context.Options.DuplicateCheckIntervalValue;
return message;
}
/// <summary>
/// 文本卡片消息: 不支持 safe
/// </summary>
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;
}
/// <summary>
/// 模板卡片消息: 不支持 safe
/// </summary>
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;
}
/// <summary>
/// 小程序通知消息: 不支持 safe
/// </summary>
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;
}
}

48
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;
/// <summary>
/// 企业微信消息构造上下文
/// </summary>
public class WeChatWorkMessageFactoryContext
{
/// <summary>
/// 通知消息
/// </summary>
public NotificationInfo Notification { get; }
/// <summary>
/// 通知标准数据(已完成本地化与模板渲染)
/// </summary>
public NotificationStandardData StandardData { get; }
/// <summary>
/// 渠道数据(载荷)
/// </summary>
public WeChatWorkChannelData ChannelData { get; }
/// <summary>
/// 消息接收者
/// </summary>
public WeChatWorkNotificationContact Contact { get; }
/// <summary>
/// 消息公共选项
/// </summary>
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;
}
}

30
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;
/// <summary>
/// 企业微信消息构造结果
/// </summary>
public class WeChatWorkMessageFactoryResult
{
/// <summary>
/// 消息载体
/// </summary>
public WeChatWorkMessage Message { get; }
/// <summary>
/// 消息载体类型, 用于日志与排障
/// </summary>
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);
}
}

52
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;
/// <summary>
/// 企业微信消息载体类型
/// </summary>
/// <remarks>
/// 显式声明渠道数据的形态, 替代旧实现中"按字段逐个探测"的隐式优先级,
/// 生产者也因此可以明确表达自己的意图。
/// </remarks>
public enum WeChatWorkMessageKind
{
/// <summary>
/// 未指定, 由渠道按内容类型推导
/// </summary>
None = 0,
/// <summary>
/// 小程序通知消息
/// </summary>
MiniProgramNotice = 1,
/// <summary>
/// 图文消息(mpnews)
/// </summary>
MpNews = 2,
/// <summary>
/// 模板卡片消息
/// </summary>
TemplateCard = 3,
/// <summary>
/// 文本卡片消息
/// </summary>
TextCard = 4,
/// <summary>
/// 视频消息
/// </summary>
Video = 5,
/// <summary>
/// 语音消息
/// </summary>
Voice = 6,
/// <summary>
/// 文件消息
/// </summary>
File = 7,
/// <summary>
/// 文本消息
/// </summary>
Text = 8,
/// <summary>
/// markdown消息
/// </summary>
Markdown = 9
}

74
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;
/// <summary>
/// 企业微信消息公共选项
/// </summary>
public class WeChatWorkMessageOptions
{
/// <summary>
/// 消息应用标识, 由渠道在发布时填充
/// </summary>
public string AgentId { get; set; } = default!;
/// <summary>
/// 是否是保密消息
/// </summary>
public bool? Safe { get; set; }
/// <summary>
/// 是否开启id转译
/// </summary>
public bool? EnableIdTrans { get; set; }
/// <summary>
/// 是否开启重复消息检查
/// </summary>
public bool? EnableDuplicateCheck { get; set; }
/// <summary>
/// 重复消息检查的时间间隔(秒)
/// </summary>
public int? DuplicateCheckInterval { get; set; }
/// <summary>
/// 从通知数据中解析公共选项
/// </summary>
public static WeChatWorkMessageOptions From(
INotificationChannelDataResolver resolver,
NotificationData notificationData)
{
Check.NotNull(resolver, nameof(resolver));
Check.NotNull(notificationData, nameof(notificationData));
return new WeChatWorkMessageOptions
{
Safe = resolver.GetValue<bool>(notificationData, WeChatWorkNotificationDataKeys.Safe),
EnableIdTrans = resolver.GetValue<bool>(notificationData, WeChatWorkNotificationDataKeys.EnableIdTrans),
EnableDuplicateCheck = resolver.GetValue<bool>(notificationData, WeChatWorkNotificationDataKeys.EnableDuplicateCheck),
DuplicateCheckInterval = resolver.GetValue<int>(notificationData, WeChatWorkNotificationDataKeys.DuplicateCheckInterval)
};
}
/// <summary>
/// 保密消息标记
/// </summary>
public byte SafeValue => Safe == true ? (byte)1 : (byte)0;
/// <summary>
/// id转译标记
/// </summary>
public byte EnableIdTransValue => EnableIdTrans == true ? (byte)1 : (byte)0;
/// <summary>
/// 重复消息检查标记
/// </summary>
public byte EnableDuplicateCheckValue => EnableDuplicateCheck == true ? (byte)1 : (byte)0;
/// <summary>
/// 重复消息检查间隔, 未设置时使用企业微信默认值
/// </summary>
public int DuplicateCheckIntervalValue => DuplicateCheckInterval ?? 1800;
}

16
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;
/// <summary>
/// 小程序通知消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 100)]
public class WeChatWorkMiniProgramNoticeChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.MiniProgramNotice;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.MiniProgramMessage)]
public virtual MiniProgramMessage? MiniProgram { get; set; }
}

16
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;
/// <summary>
/// 图文消息(mpnews)载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 200)]
public class WeChatWorkMpNewChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.MpNews;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.MpNewMessage)]
public virtual MpNewMessagePayload? MpNewMessage { get; set; }
}

48
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;
/// <summary>
/// 企业微信消息接收者
/// </summary>
/// <remarks>
/// 企业微信要求 touser / toparty / totag 不能同时为空,
/// 因此接收者必须作为整体传递给消息构造过程。
/// </remarks>
public class WeChatWorkNotificationContact
{
/// <summary>
/// 成员ID列表, 多个接收者使用"|"分隔
/// </summary>
public string? ToUser { get; set; }
/// <summary>
/// 部门ID列表, 多个接收者使用"|"分隔
/// </summary>
public string? ToParty { get; set; }
/// <summary>
/// 标签ID列表, 多个接收者使用"|"分隔
/// </summary>
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
};
}
}

55
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;
/// <summary>
/// 企业微信通知数据键
/// </summary>
/// <remarks>
/// 键名与历史实现保持一致(<c>wx-work:</c> 前缀), 保证已上线的生产者不受影响。
/// </remarks>
public static class WeChatWorkNotificationDataKeys
{
public const string Prefix = "wx-work:";
/// <summary>
/// 指定接收消息的成员
/// </summary>
public const string ToUser = Prefix + "to_user";
/// <summary>
/// 指定接收消息的部门
/// </summary>
public const string ToParty = Prefix + "to_party";
/// <summary>
/// 指定接收消息的标签
/// </summary>
public const string ToTag = Prefix + "to_tag";
/// <summary>
/// 应用标识
/// </summary>
public const string AgentId = Prefix + "agent_id";
/// <summary>
/// 是否是保密消息
/// </summary>
public const string Safe = Prefix + "safe";
/// <summary>
/// 是否开启id转译
/// </summary>
public const string EnableIdTrans = Prefix + "enable_id_trans";
/// <summary>
/// 是否开启重复消息检查
/// </summary>
public const string EnableDuplicateCheck = Prefix + "enable_duplicate_check";
/// <summary>
/// 重复消息检查的时间间隔
/// </summary>
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";
}

16
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;
/// <summary>
/// 模板卡片消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 300)]
public class WeChatWorkTemplateCardChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.TemplateCard;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.TemplateCardMessage)]
public virtual TemplateCard? TemplateCard { get; set; }
}

16
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;
/// <summary>
/// 文本卡片消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 400)]
public class WeChatWorkTextCardChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.TextCard;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.TextCardMessage)]
public virtual TextCardMessage? TextCard { get; set; }
}

18
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;
/// <summary>
/// 文本消息载荷
/// </summary>
/// <remarks>
/// 不参与渠道解析: 文本消息由通知标准数据(title/message)推导,
/// 生产者不需要为它准备任何渠道专属数据。
/// </remarks>
public class WeChatWorkTextChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Text;
/// <summary>
/// 消息内容, 为空时使用通知标准数据
/// </summary>
public virtual string? Content { get; set; }
}

16
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;
/// <summary>
/// 视频消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 500)]
public class WeChatWorkVideoChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Video;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.VideoMessage)]
public virtual VideoMessage? Video { get; set; }
}

16
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;
/// <summary>
/// 语音消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkNotificationPublishProvider.ProviderName, Priority = 600)]
public class WeChatWorkVoiceChannelData : WeChatWorkChannelData
{
public override WeChatWorkMessageKind Kind => WeChatWorkMessageKind.Voice;
[NotificationChannelProperty(WeChatWorkNotificationDataKeys.VoiceMessage)]
public virtual MediaMessage? Voice { get; set; }
}

260
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;
/// <summary>
/// 企业微信通知发布渠道
/// </summary>
public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider
{
public const string ProviderName = NotificationProviderNames.WechatWork;
public override string Name => ProviderName;
protected IFeatureChecker FeatureChecker => ServiceProvider.LazyGetRequiredService<IFeatureChecker>();
protected ISettingProvider SettingProvider => ServiceProvider.LazyGetRequiredService<ISettingProvider>();
protected IWeChatWorkMessageSender WeChatWorkMessageSender => ServiceProvider.LazyGetRequiredService<IWeChatWorkMessageSender>();
protected INotificationDataSerializer NotificationDataSerializer => ServiceProvider.LazyGetRequiredService<INotificationDataSerializer>();
protected IWeChatWorkUserClaimProvider WeChatWorkInternalUserFinder => ServiceProvider.LazyGetRequiredService<IWeChatWorkUserClaimProvider>();
protected INotificationDefinitionManager NotificationDefinitionManager => ServiceProvider.LazyGetRequiredService<INotificationDefinitionManager>();
protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService<INotificationChannelDataResolver>();
protected IOptions<AbpWeChatWorkNotificationMessageOptions> MessageOptions => ServiceProvider.LazyGetRequiredService<IOptions<AbpWeChatWorkNotificationMessageOptions>>();
protected async override Task<bool> CanPublishAsync(NotificationInfo notification, CancellationToken cancellationToken = default)
{
@ -44,8 +52,6 @@ public class WeChatWorkNotificationPublishProvider : NotificationPublishProvider
NotificationPublishContext context,
CancellationToken cancellationToken = default)
{
var sendToAgentIds = new List<string>();
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<Exception>();
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(
/// <summary>
/// 解析消息接收者
/// </summary>
/// <remarks>
/// 成员标识由企业微信身份绑定关系解析, 部门与标签优先取通知数据, 其次取通知定义。
/// </remarks>
protected async virtual Task<WeChatWorkNotificationContact> 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);
}
/// <summary>
/// 解析待发送的消息载体集合
/// </summary>
/// <remarks>
/// 优先使用生产者显式声明的渠道数据(载荷);
/// 未声明时按通知内容类型推导默认载体, 保证既有生产者的行为不变。
/// </remarks>
protected virtual List<WeChatWorkMessageFactoryResult> ResolveMessages(
NotificationPublishContext context,
NotificationStandardData standardData,
WeChatWorkNotificationContact contact,
WeChatWorkMessageOptions options)
{
var messages = new List<WeChatWorkMessageFactoryResult>();
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;
}
/// <summary>
/// 解析渠道数据(载荷)
/// </summary>
/// <remarks>
/// 区分"生产者未写入载荷"与"载荷已写入但无法解析":
/// 后者是生产者错误, 必须明确报错, 而不是静默回退到默认载体。
/// </remarks>
protected virtual bool TryResolveChannelData(
NotificationPublishContext context,
out string? invalidPayloadKey,
out List<NotificationChannelData> resolvedPayloads)
{
invalidPayloadKey = null;
resolvedPayloads = new List<NotificationChannelData>();
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;
}
/// <summary>
/// 按通知内容类型推导默认的消息载体
/// </summary>
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);
}
}

35
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<AbpNotificationsWebhookWeChatWorkOptions>();
Configure<AbpNotificationsWebhookWeChatWorkOptions>(options =>
{
options.UseMarkdownV2 = true;
preActions.Configure(options);
});
Configure<AbpNotificationsWebhookOptions>(options =>
{
options.Contributors.Add(new WeChatWorkWebhookNotificationContributor());
});
// 模板卡片是抽象类型: 注册类型转换器, 使其能在渠道数据(JSON)中往返
Configure<AbpSystemTextJsonSerializerOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new WebhookTemplateCardSystemTextJsonConverter());
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<WeChatWorkWebhookTextChannelData>();
options.Add<WeChatWorkWebhookMarkdownChannelData>();
options.Add<WeChatWorkWebhookMarkdownV2ChannelData>();
options.Add<WeChatWorkWebhookImageChannelData>();
options.Add<WeChatWorkWebhookNewsChannelData>();
options.Add<WeChatWorkWebhookFileChannelData>();
options.Add<WeChatWorkWebhookVoiceChannelData>();
options.Add<WeChatWorkWebhookTemplateCardChannelData>();
});
// 消息载体工厂分派
Configure<AbpNotificationsWebhookWeChatWorkMessageOptions>(options =>
{
options.MapDefaultMessageFactories();
});
}
}

75
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;
/// <summary>
/// 企业微信 Webhook 消息构造选项
/// </summary>
/// <remarks>
/// <para>
/// 渠道数据的形态到消息载体的转换集中注册在这里, 新增一种消息类型只需要
/// <c>options.Map(kind, factory)</c>, 不需要修改贡献者的发布逻辑。
/// </para>
/// </remarks>
public class AbpNotificationsWebhookWeChatWorkMessageOptions
{
private readonly Dictionary<WeChatWorkWebhookMessageKind, Func<WeChatWorkWebhookMessageFactoryContext, WeChatWorkWebhookMessageFactoryResult>> _factories
= new Dictionary<WeChatWorkWebhookMessageKind, Func<WeChatWorkWebhookMessageFactoryContext, WeChatWorkWebhookMessageFactoryResult>>();
/// <summary>
/// 已注册的消息类型
/// </summary>
public IReadOnlyCollection<WeChatWorkWebhookMessageKind> MessageKinds => _factories.Keys;
/// <summary>
/// 注册消息构造工厂
/// </summary>
public AbpNotificationsWebhookWeChatWorkMessageOptions Map(
WeChatWorkWebhookMessageKind kind,
Func<WeChatWorkWebhookMessageFactoryContext, WeChatWorkWebhookMessageFactoryResult> factory)
{
Check.NotNull(factory, nameof(factory));
_factories[kind] = factory;
return this;
}
/// <summary>
/// 构造消息载体
/// </summary>
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;
}
/// <summary>
/// 获取已注册的工厂
/// </summary>
public bool TryGetFactory(
WeChatWorkWebhookMessageKind kind,
out Func<WeChatWorkWebhookMessageFactoryContext, WeChatWorkWebhookMessageFactoryResult>? factory)
{
return _factories.TryGetValue(kind, out factory);
}
}

16
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;
/// <summary>
/// 企业微信 Webhook 渠道数据(载荷)基类
/// </summary>
/// <remarks>
/// 每个载荷对应一种 Webhook 消息载体, 通过 <see cref="Kind"/> 显式声明形态,
/// 渠道侧使用工厂字典做 O(1) 分派。
/// </remarks>
public abstract class WeChatWorkWebhookChannelData : NotificationChannelData
{
/// <summary>
/// 消息载体类型
/// </summary>
public abstract WeChatWorkWebhookMessageKind Kind { get; }
}

19
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;
/// <summary>
/// 文件消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 600)]
public class WeChatWorkWebhookFileChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.File;
/// <summary>
/// 文件消息体(素材 ID)
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.File)]
public virtual WebhookFileMessage? File { get; set; }
}

19
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;
/// <summary>
/// 图片消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 400)]
public class WeChatWorkWebhookImageChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Image;
/// <summary>
/// 图片内容(base64 编码, 不超过 2MB)
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Image)]
public virtual WebhookImageMessage? Image { get; set; }
}

18
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;
/// <summary>
/// markdown 消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 200)]
public class WeChatWorkWebhookMarkdownChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Markdown;
/// <summary>
/// markdown 内容
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Markdown)]
public virtual string? Content { get; set; }
}

22
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;
/// <summary>
/// markdown_v2 消息载荷
/// </summary>
/// <remarks>
/// markdown_v2 支持表格、代码块等更丰富的语法,
/// 详见 https://developer.work.weixin.qq.com/document/path/99110#markdown-v2%E7%B1%BB%E5%9E%8B
/// </remarks>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 300)]
public class WeChatWorkWebhookMarkdownV2ChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.MarkdownV2;
/// <summary>
/// markdown_v2 内容
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.MarkdownV2)]
public virtual string? Content { get; set; }
}

92
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;
/// <summary>
/// 企业微信 Webhook 消息工厂
/// </summary>
public static class WeChatWorkWebhookMessageFactory
{
/// <summary>
/// 注册内置消息工厂
/// </summary>
/// <remarks>
/// 每种载荷对应一种 <c>msgtype</c>, 一一映射, 不做隐式降级:
/// 生产者选择了模板卡片, 就一定发模板卡片, 而不是静默发成文本。
/// 唯一的例外是 markdown 与 markdown_v2 的取舍, 由渠道选项
/// <see cref="AbpNotificationsWebhookWeChatWorkOptions.UseMarkdownV2"/> 决定。
/// </remarks>
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);
});
}
}

41
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;
/// <summary>
/// 企业微信 Webhook 消息构造上下文
/// </summary>
public class WeChatWorkWebhookMessageFactoryContext
{
/// <summary>
/// 通知消息
/// </summary>
public NotificationInfo Notification { get; }
/// <summary>
/// 通知标准数据(已完成本地化与模板渲染)
/// </summary>
public NotificationStandardData StandardData { get; }
/// <summary>
/// 渠道数据(载荷)
/// </summary>
public WeChatWorkWebhookChannelData ChannelData { get; }
/// <summary>
/// 渠道选项
/// </summary>
public AbpNotificationsWebhookWeChatWorkOptions Options { get; }
public WeChatWorkWebhookMessageFactoryContext(
NotificationInfo notification,
NotificationStandardData standardData,
WeChatWorkWebhookChannelData channelData,
AbpNotificationsWebhookWeChatWorkOptions options)
{
Notification = notification;
StandardData = standardData;
ChannelData = channelData;
Options = options;
}
}

34
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;
/// <summary>
/// 企业微信 Webhook 消息构造结果
/// </summary>
public class WeChatWorkWebhookMessageFactoryResult
{
/// <summary>
/// 消息载体
/// </summary>
public WeChatWorkWebhookMessage Message { get; }
/// <summary>
/// 消息载体类型, 用于日志与排障
/// </summary>
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);
}
}

47
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;
/// <summary>
/// 企业微信 Webhook 消息载体类型
/// </summary>
/// <remarks>
/// 取值与框架 <c>WeChatWorkWebhookMessage.MsgType</c> 一致。
/// </remarks>
public enum WeChatWorkWebhookMessageKind
{
/// <summary>
/// 未指定
/// </summary>
None = 0,
/// <summary>
/// 文本
/// </summary>
Text = 1,
/// <summary>
/// markdown
/// </summary>
Markdown = 2,
/// <summary>
/// markdown_v2
/// </summary>
MarkdownV2 = 3,
/// <summary>
/// 图片
/// </summary>
Image = 4,
/// <summary>
/// 图文
/// </summary>
News = 5,
/// <summary>
/// 文件
/// </summary>
File = 6,
/// <summary>
/// 语音
/// </summary>
Voice = 7,
/// <summary>
/// 模板卡片
/// </summary>
TemplateCard = 8
}

19
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;
/// <summary>
/// 图文消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 500)]
public class WeChatWorkWebhookNewsChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.News;
/// <summary>
/// 图文消息体
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.News)]
public virtual WebhookNewsMessage? News { get; set; }
}

56
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;
/// <summary>
/// 企业微信 Webhook 通知数据键
/// </summary>
/// <remarks>
/// <para>
/// 前缀 <c>wx-work-hook:</c> 归属 Webhook 渠道自身。
/// 企业微信**应用消息**渠道使用 <c>wx-work:</c> 前缀 —— 两者是不同传输方式,
/// 键空间必须分开, 否则同一个通知被两个渠道同时订阅时,
/// 载荷会被两边都解析并各发一条。
/// </para>
/// <para>
/// 读取过程大小写不敏感(精确匹配优先)。
/// </para>
/// </remarks>
public static class WeChatWorkWebhookNotificationDataKeys
{
/// <summary>
/// 本渠道的数据键前缀
/// </summary>
public const string Prefix = "wx-work-hook:";
/// <summary>
/// 文本消息
/// </summary>
public const string Text = Prefix + "text";
/// <summary>
/// markdown 消息
/// </summary>
public const string Markdown = Prefix + "markdown";
/// <summary>
/// markdown_v2 消息
/// </summary>
public const string MarkdownV2 = Prefix + "markdown_v2";
/// <summary>
/// 图片消息(base64 + md5)
/// </summary>
public const string Image = Prefix + "image";
/// <summary>
/// 图文消息
/// </summary>
public const string News = Prefix + "news";
/// <summary>
/// 文件消息
/// </summary>
public const string File = Prefix + "file";
/// <summary>
/// 语音消息
/// </summary>
public const string Voice = Prefix + "voice";
/// <summary>
/// 模板卡片消息
/// </summary>
public const string TemplateCard = Prefix + "template_card";
}

26
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;
/// <summary>
/// 企业微信 Webhook 通知渠道名
/// </summary>
/// <remarks>
/// <para>
/// Webhook 的**发布**仍走 <c>WebhookNotificationPublishProvider</c>(渠道名 <c>Webhook</c>),
/// 本常量只作为**载荷注册表的键**使用:
/// 企业微信应用消息(渠道名 <c>WeChat.Work</c>)与 Webhook 是两种传输方式、
/// 两套载体模型, 因此必须使用不同的注册表键, 避免载荷被对方误解析。
/// </para>
/// <para>
/// 生产者侧: 通知定义中仍声明 <c>ProviderName</c> 为 <c>"Webhook"</c> 才会被发布,
/// 载荷用本渠道的数据键(前缀 <c>wx-work-hook:</c>)写入。
/// </para>
/// </remarks>
public static class WeChatWorkWebhookNotificationProvider
{
/// <summary>
/// 本渠道的载荷注册表键
/// </summary>
public const string ProviderName = "WeChat.Work.Webhook";
}

24
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;
/// <summary>
/// 模板卡片消息载荷
/// </summary>
/// <remarks>
/// 抽象类型 <see cref="WebhookTemplateCardMessage"/> 的两个具体实现
/// (<see cref="WebhookTextNoticeCardMessage"/> / <see cref="WebhookNewsNoticeCardMessage"/>)
/// 都需要 JSON 多态转换器才能在通知数据中往返, 由渠道模块注册。
/// </remarks>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 800)]
public class WeChatWorkWebhookTemplateCardChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.TemplateCard;
/// <summary>
/// 模板卡片消息体
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.TemplateCard)]
public virtual WebhookTemplateCardMessage? TemplateCard { get; set; }
}

18
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;
/// <summary>
/// 文本消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 100)]
public class WeChatWorkWebhookTextChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Text;
/// <summary>
/// 文本内容
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Text)]
public virtual string? Content { get; set; }
}

19
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;
/// <summary>
/// 语音消息载荷
/// </summary>
[NotificationChannelData(WeChatWorkWebhookNotificationProvider.ProviderName, Priority = 700)]
public class WeChatWorkWebhookVoiceChannelData : WeChatWorkWebhookChannelData
{
public override WeChatWorkWebhookMessageKind Kind => WeChatWorkWebhookMessageKind.Voice;
/// <summary>
/// 语音消息体(素材 ID)
/// </summary>
[NotificationChannelProperty(WeChatWorkWebhookNotificationDataKeys.Voice)]
public virtual WebhookVoiceMessage? Voice { get; set; }
}

191
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;
/// <summary>
/// 企业微信 Webhook 通知贡献者
/// </summary>
/// <remarks>
/// <para>
/// 优先解析生产者写入的**渠道数据(载荷)**, 载荷缺失时才回退到按
/// <see cref="NotificationInfo.ContentType"/> 推导,
/// 因此历史用法(只写标准数据)行为不变。
/// </para>
/// <para>
/// 一个 Webhook 只能承载一条消息, 因此声明多个载荷时取
/// <see cref="NotificationChannelDataAttribute.Priority"/> 最小的那个,
/// 并按 1:1 映射构造载体 —— 不再像旧实现那样把未知内容类型静默丢弃。
/// </para>
/// </remarks>
public class WeChatWorkWebhookNotificationContributor : IWebhookNotificationContributor
{
public string Name => "WeChat.Work";
/// <summary>
/// 贡献者名称(仅用于日志)
/// </summary>
public string Name => WeChatWorkWebhookNotificationProvider.ProviderName;
public async virtual Task ContributeAsync(IWebhookNotificationContext context)
{
var options = context.ServiceProvider.GetRequiredService<IOptions<AbpNotificationsWebhookWeChatWorkOptions>>().Value;
var notificationDataSerializer = context.ServiceProvider.GetRequiredService<INotificationDataSerializer>();
Check.NotNull(context, nameof(context));
var options = context.ServiceProvider
.GetRequiredService<IOptions<AbpNotificationsWebhookWeChatWorkOptions>>().Value;
var messageOptions = context.ServiceProvider
.GetRequiredService<IOptions<AbpNotificationsWebhookWeChatWorkMessageOptions>>().Value;
var resolver = context.ServiceProvider
.GetRequiredService<INotificationChannelDataResolver>();
var notificationDataSerializer = context.ServiceProvider
.GetRequiredService<INotificationDataSerializer>();
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<ILogger<WeChatWorkWebhookNotificationContributor>>()
?.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<ILogger<WeChatWorkWebhookNotificationContributor>>()
?.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);
}
}
/// <summary>
/// 按通知内容类型推导载荷(兼容未写入渠道数据的历史生产者)
/// </summary>
protected virtual IReadOnlyList<NotificationChannelData> 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<NotificationChannelData>();
}
}
/// <summary>
/// 用标准数据补全载荷中未指定的内容
/// </summary>
/// <remarks>
/// 生产者只声明"用哪种载体"而不写内容时(例如只写 <c>wx-work-hook:markdown</c>),
/// 使用已本地化/渲染完成的通知正文, 避免发出空内容。
/// </remarks>
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<ILogger<WeChatWorkWebhookNotificationContributor>>()
?? NullLogger<WeChatWorkWebhookNotificationContributor>.Instance;
}
}

19
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/NotificationDataExtensions.cs

@ -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();
}
}

8
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<WxPusherNotificationPublishProvider>();
});
// 声明本渠道支持的载荷形态(注册期即校验存在性契约)
Configure<AbpNotificationChannelDataOptions>(options =>
{
options.Add<WxPusherChannelData>();
});
}
}

19
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;
/// <summary>
/// WxPusher 渠道数据(载荷)
/// </summary>
/// <remarks>
/// 存在性由 url 键推导(默认 Presence = DeclaredProperties), 无需实现判定方法。
/// </remarks>
[NotificationChannelData(WxPusherNotificationPublishProvider.ProviderName, Priority = 100)]
public class WxPusherChannelData : NotificationChannelData
{
/// <summary>
/// 消息点击后的跳转地址
/// </summary>
[NotificationChannelProperty(WxPusherNotificationDataKeys.Url)]
public virtual string? Url { get; set; }
}

14
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications.WxPusher/LINGYUN/Abp/Notifications/WxPusher/WxPusherNotificationDataKeys.cs

@ -0,0 +1,14 @@
namespace LINGYUN.Abp.Notifications.WxPusher;
/// <summary>
/// WxPusher 通知数据键
/// </summary>
public static class WxPusherNotificationDataKeys
{
public const string Prefix = "wx-pusher:";
/// <summary>
/// 消息点击后的跳转地址
/// </summary>
public const string Url = Prefix + "url";
}

6
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<IWxPusherMessageSender>();
protected INotificationDataSerializer NotificationDataSerializer => ServiceProvider.LazyGetRequiredService<INotificationDataSerializer>();
protected INotificationDefinitionManager NotificationDefinitionManager => ServiceProvider.LazyGetRequiredService<INotificationDefinitionManager>();
protected INotificationChannelDataResolver ChannelDataResolver => ServiceProvider.LazyGetRequiredService<INotificationChannelDataResolver>();
protected async override Task<bool> 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<WxPusherChannelData>(context.Notification.Data);
var url = channelData?.Url ?? notificationDefine?.GetUrlOrNull();
topics ??= notificationDefine?.GetTopics();
var contentType = notificationDefine?.GetContentTypeOrDefault(MessageContentType.Text)
?? MessageContentType.Text;

3
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN.Abp.Notifications.csproj

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\..\configureawait.props" />
<Import Project="..\..\..\..\common.props" />
@ -24,6 +24,7 @@
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" />
<PackageReference Include="Volo.Abp.EventBus" />
<PackageReference Include="Volo.Abp.Json" />
<PackageReference Include="Volo.Abp.BackgroundJobs.Abstractions" />
<PackageReference Include="Volo.Abp.TextTemplating.Core" />
</ItemGroup>

2
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
{

31
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);
}
}

100
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;
/// <summary>
/// 通知渠道数据(载荷)选项
/// </summary>
public class AbpNotificationChannelDataOptions
{
private readonly Dictionary<string, NotificationChannelDataDescriptorList> _providers
= new(StringComparer.OrdinalIgnoreCase);
private readonly List<Type> _payloadTypes = new();
/// <summary>
/// 已注册的载荷类型
/// </summary>
public IReadOnlyList<Type> PayloadTypes => _payloadTypes;
/// <summary>
/// 获取指定渠道的载荷集合(按匹配顺序排列)
/// </summary>
public NotificationChannelDataDescriptorList GetProviderData(string providerName)
{
if (!_providers.TryGetValue(providerName, out var list))
{
list = new NotificationChannelDataDescriptorList();
_providers[providerName] = list;
}
return list;
}
/// <summary>
/// 注册渠道数据(载荷)
/// </summary>
/// <remarks>
/// 渠道名称、匹配顺序与存在性判定模式来自
/// <see cref="NotificationChannelDataAttribute"/>。
/// </remarks>
public AbpNotificationChannelDataOptions Add<TChannelData>()
where TChannelData : NotificationChannelData
{
return Add(typeof(TChannelData));
}
/// <summary>
/// 注册渠道数据(载荷)
/// </summary>
/// <exception cref="AbpNotificationChannelDataConfigurationException">
/// 缺少 <see cref="NotificationChannelDataAttribute"/>、
/// 未声明存在性规则, 或同渠道优先级冲突
/// </exception>
public AbpNotificationChannelDataOptions Add(Type channelDataType)
{
Check.NotNull(channelDataType, nameof(channelDataType));
if (_payloadTypes.Contains(channelDataType))
{
return this;
}
var attribute = channelDataType.GetCustomAttribute<NotificationChannelDataAttribute>(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;
}
}

71
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataAccessor.cs

@ -0,0 +1,71 @@
using System;
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 通知渠道数据(载荷)存取器
/// </summary>
/// <remarks>
/// <para>
/// 通知数据在持久化、失败重试、跨进程投递等链路中必然经历 JSON 往返,
/// 往返之后 <c>ExtraPropertyDictionary</c> 中的值是 JSON 节点而不是原始 CLR 实例:
/// <c>byte 1</c> 会变成 <c>long 1</c> / <c>JsonElement(Number)</c>,
/// 原有的 <c>x as byte?</c> 将永远返回 null。
/// </para>
/// <para>
/// 本服务是渠道数据"弱类型属性包 ↔ 强类型值"转换的唯一实现,
/// 由 <see cref="INotificationChannelDataSerializer"/> 与
/// <see cref="INotificationChannelDataResolver"/> 共用,
/// 并保证与所用 JSON 实现无关。
/// </para>
/// </remarks>
public interface INotificationChannelDataAccessor
{
/// <summary>
/// 获取载荷的数据类型键
/// </summary>
/// <returns>键名, 类型无全名时返回 null</returns>
string? GetDataTypeKey(Type payloadType);
/// <summary>
/// 是否存在键(大小写不敏感)
/// </summary>
bool IsPresent(NotificationData notificationData, string key);
/// <summary>
/// 读取原始值(大小写不敏感)
/// </summary>
/// <param name="notificationData">通知数据</param>
/// <param name="key">键名</param>
/// <param name="value">原始值</param>
/// <param name="matchedKey">实际命中的键名(可能与入参大小写不同)</param>
bool TryGetRawValue(NotificationData notificationData, string key, out object? value, out string? matchedKey);
/// <summary>
/// 读取并转换为目标类型
/// </summary>
/// <returns>转换后的值; 键不存在或无法转换时返回 null</returns>
object? Get(NotificationData notificationData, string key, Type targetType);
/// <summary>
/// 类型化读取(未设置时返回 null, 以便区分"未设置"与"显式 false/0")
/// </summary>
TValue? GetValue<TValue>(NotificationData notificationData, string key)
where TValue : struct;
/// <summary>
/// 类型化读取, 未设置时返回默认值
/// </summary>
TValue GetValue<TValue>(NotificationData notificationData, string key, TValue defaultValue)
where TValue : struct;
/// <summary>
/// 按顺序读取第一个非空字符串值(大小写不敏感)
/// </summary>
string? GetOrNull(NotificationData notificationData, params string[] keys);
/// <summary>
/// 写入值, 复杂类型以 JSON 形式存储
/// </summary>
void Set(NotificationData notificationData, string key, Type valueType, object? value, NotificationChannelDataFormat format);
}

22
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataJsonSerializer.cs

@ -0,0 +1,22 @@
using System;
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 通知渠道数据(载荷)的 JSON 序列化抽象
/// </summary>
public interface INotificationChannelDataJsonSerializer
{
/// <summary>
/// 序列化
/// </summary>
string Serialize(object value, Type valueType);
/// <summary>
/// 反序列化
/// </summary>
/// <param name="json">JSON 字符串</param>
/// <param name="targetType">目标类型</param>
/// <returns>实例, 类型不支持时返回 null</returns>
object? Deserialize(string json, Type targetType);
}

28
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;
/// <summary>
/// 渠道数据存在性判定提供者
/// </summary>
public interface INotificationChannelDataPresenceProvider
{
/// <summary>
/// 获取载荷声明的存在性判定模式
/// </summary>
NotificationChannelDataPresenceMode GetPresenceMode(Type channelDataType);
/// <summary>
/// 获取参与匹配的属性键
/// </summary>
IReadOnlyList<string> GetMatchingKeys(Type channelDataType);
/// <summary>
/// 创建存在性判定委托
/// </summary>
/// <exception cref="AbpNotificationChannelDataConfigurationException">
/// 声明了按键判定, 却没有任何可参与匹配的属性
/// </exception>
Func<NotificationData, bool> Create(Type channelDataType);
}

85
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;
/// <summary>
/// 通知渠道数据(载荷)解析器
/// </summary>
public interface INotificationChannelDataResolver
{
/// <summary>
/// 按匹配顺序解析指定渠道的载荷
/// </summary>
/// <remarks>
/// 仅返回"已写入且可解析"的载荷; 传入非法数据时会被跳过并记录日志,
/// 渠道如果需要区分该情况, 应配合 <see cref="IsDeclared"/> 使用。
/// </remarks>
IReadOnlyList<NotificationChannelData> Resolve(string providerName, NotificationData notificationData);
/// <summary>
/// 解析指定类型的渠道数据
/// </summary>
/// <returns>载荷实例, 未写入或无法解析时返回 null</returns>
TChannelData? Resolve<TChannelData>(NotificationData notificationData)
where TChannelData : NotificationChannelData;
/// <summary>
/// 解析指定类型的渠道数据
/// </summary>
NotificationChannelData? Resolve(Type payloadType, NotificationData notificationData);
/// <summary>
/// 判断生产者是否声明了指定类型的渠道数据
/// </summary>
/// <remarks>
/// 与解析结果配合使用, 可以区分
/// "生产者未写入载荷" 与 "载荷已写入但无法解析(数据非法)"。
/// 后者属于生产者错误, 渠道应当明确报错而不是静默回退。
/// </remarks>
bool IsDeclared(NotificationData notificationData, Type payloadType);
/// <summary>
/// 获取指定渠道的载荷类型集合
/// </summary>
IReadOnlyList<Type> GetPayloadTypes(string providerName);
/// <summary>
/// 获取载荷的标识键
/// </summary>
/// <remarks>
/// 返回该载荷第一个"参与存在性判定"的属性键(数据中的实际键名),
/// 用于诊断信息(例如"哪个键解析失败")。未声明可匹配属性时返回 null。
/// </remarks>
string? GetKey(NotificationData notificationData, Type payloadType);
/// <summary>
/// 弱类型读取, 并转换为目标类型
/// </summary>
object? Get(NotificationData notificationData, string key, Type targetType);
/// <summary>
/// 类型化读取渠道数据键
/// </summary>
/// <remarks>
/// 用于读取"散落的标量选项"(如企业微信的 safe、enable_id_trans),
/// 这类值不需要独立载荷类型, 但同样必须经过弱类型转换。
/// </remarks>
TValue? GetValue<TValue>(NotificationData notificationData, string key)
where TValue : struct;
/// <summary>
/// 类型化读取渠道数据键, 未设置时返回默认值
/// </summary>
TValue GetValue<TValue>(NotificationData notificationData, string key, TValue defaultValue)
where TValue : struct;
/// <summary>
/// 大小写不敏感地读取渠道数据键
/// </summary>
/// <remarks>
/// 用于兼容历史渠道实现中大小写敏感的遗留键(如 <c>TemplateId</c>),
/// 避免生产者因为大小写差异而静默失效。
/// </remarks>
string? GetOrNull(NotificationData notificationData, params string[] keys);
}

40
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/INotificationChannelDataSerializer.cs

@ -0,0 +1,40 @@
using System;
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 通知渠道数据(载荷)序列化器
/// </summary>
/// <remarks>
/// 生产者侧的统一入口, 负责把强类型载荷写入 <see cref="NotificationData"/>。
/// </remarks>
public interface INotificationChannelDataSerializer
{
/// <summary>
/// 写入渠道数据(载荷)
/// </summary>
/// <typeparam name="TChannelData">载荷类型</typeparam>
/// <param name="notificationData">通知数据</param>
/// <param name="channelData">载荷实例</param>
NotificationData Write<TChannelData>(NotificationData notificationData, TChannelData channelData)
where TChannelData : class;
/// <summary>
/// 写入渠道数据(载荷)
/// </summary>
/// <param name="notificationData">通知数据</param>
/// <param name="channelData">载荷实例</param>
NotificationData Write(NotificationData notificationData, NotificationChannelData channelData);
/// <summary>
/// 按载荷类型清除渠道数据
/// </summary>
NotificationData Clear<TChannelData>(NotificationData notificationData)
where TChannelData : class;
/// <summary>
/// 判断通知数据中是否存在指定载荷
/// </summary>
bool Has<TPayload>(NotificationData notificationData)
where TPayload : class;
}

381
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;
/// <summary>
/// 通知渠道数据(载荷)存取器
/// </summary>
/// <remarks>
/// 渠道数据"弱类型属性包 ↔ 强类型值"转换的唯一实现,
/// 由 <see cref="INotificationChannelDataSerializer"/> 与
/// <see cref="INotificationChannelDataResolver"/> 共用, 并保证与所用 JSON 实现无关。
/// </remarks>
public class NotificationChannelDataAccessor : INotificationChannelDataAccessor, ISingletonDependency
{
protected ILogger<NotificationChannelDataAccessor> Logger { get; }
protected INotificationChannelDataJsonSerializer JsonSerializer { get; }
public NotificationChannelDataAccessor(
INotificationChannelDataJsonSerializer jsonSerializer,
ILogger<NotificationChannelDataAccessor>? logger = null)
{
JsonSerializer = jsonSerializer;
Logger = logger ?? NullLogger<NotificationChannelDataAccessor>.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<TValue>(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<TValue>(NotificationData notificationData, string key, TValue defaultValue)
where TValue : struct
{
return GetValue<TValue>(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);
}
/// <summary>
/// 还原 JSON 中间表示
/// </summary>
/// <remarks>
/// System.Text.Json 产生 <c>JsonElement</c>, Newtonsoft 产生 <c>JValue</c>;
/// 两者都还原为 CLR 原始值, 使转换逻辑与 JSON 实现无关。
/// </remarks>
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;
}
}
/// <summary>
/// 尝试把各种表示形式转换为布尔值
/// </summary>
/// <remarks>
/// 数值型 <c>0/1</c> 与字符串 <c>"0"/"1"</c> / <c>"true"/"false"</c> 都会被识别,
/// <c>Convert.ChangeType</c> 只接受 <c>"True"/"False"</c>, 因此需要单独处理。
/// </remarks>
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;
}
}

15
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;
/// <summary>
/// 通知渠道数据(载荷)类型集合
/// </summary>
/// <remarks>
/// 同一个渠道内的载荷按 <see cref="NotificationChannelDataAttribute.Priority"/> 排序,
/// 匹配顺序必须显式声明, 不允许依赖注册顺序或字段探测顺序。
/// </remarks>
public sealed class NotificationChannelDataDescriptorList : List<NotificationChannelDataDescriptor>
{
}

158
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;
/// <summary>
/// 渠道数据存在性判定
/// </summary>
/// <remarks>
public static class NotificationChannelDataPresence
{
private static readonly Dictionary<string, Func<NotificationData, bool>> Delegates = new();
private static readonly object SyncLock = new();
/// <summary>
/// 获取载荷声明的存在性判定模式
/// </summary>
public static NotificationChannelDataPresenceMode GetPresenceMode(Type channelDataType)
{
var attribute = channelDataType.GetCustomAttribute<NotificationChannelDataAttribute>(inherit: false);
return attribute?.Presence ?? NotificationChannelDataPresenceMode.DeclaredProperties;
}
/// <summary>
/// 获取参与匹配的属性键
/// </summary>
public static IReadOnlyList<string> GetMatchingKeys(Type channelDataType)
{
return channelDataType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(property => new
{
Property = property,
Attribute = property.GetCustomAttribute<NotificationChannelPropertyAttribute>(inherit: true)
})
.Where(x => x.Attribute != null && !x.Attribute.IgnoreWhenMatching)
.Select(x => x.Attribute!.Name.IsNullOrWhiteSpace() ? x.Property.Name : x.Attribute!.Name!)
.Distinct()
.ToArray();
}
/// <summary>
/// 校验载荷的存在性声明
/// </summary>
/// <exception cref="AbpNotificationChannelDataConfigurationException">
/// 声明了按键判定, 却没有任何可参与匹配的属性
/// </exception>
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.");
}
}
/// <summary>
/// 创建存在性判定委托
/// </summary>
public static Func<NotificationData, bool> 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;
}
}
/// <summary>
/// 判断通知数据中是否存在该键(大小写不敏感)
/// </summary>
/// <remarks>
/// 精确匹配优先, 未命中时按大小写不敏感匹配,
/// 与 <see cref="INotificationChannelDataAccessor.TryGetRawValue"/> 的规则保持一致。
/// </remarks>
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<NotificationData, bool> Build(
NotificationChannelDataPresenceMode mode,
IReadOnlyList<string> 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<Func<NotificationData, bool>>(body!, notificationData)
.Compile();
}
}

26
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;
/// <summary>
/// 渠道数据存在性判定提供者
/// </summary>
public class NotificationChannelDataPresenceProvider : INotificationChannelDataPresenceProvider, ISingletonDependency
{
public virtual NotificationChannelDataPresenceMode GetPresenceMode(Type channelDataType)
{
return NotificationChannelDataPresence.GetPresenceMode(channelDataType);
}
public virtual IReadOnlyList<string> GetMatchingKeys(Type channelDataType)
{
return NotificationChannelDataPresence.GetMatchingKeys(channelDataType);
}
public virtual Func<NotificationData, bool> Create(Type channelDataType)
{
return NotificationChannelDataPresence.Create(channelDataType);
}
}

59
aspnet-core/modules/realtime-notifications/LINGYUN.Abp.Notifications/LINGYUN/Abp/Notifications/ChannelData/NotificationChannelDataProperty.cs

@ -0,0 +1,59 @@
using System;
namespace LINGYUN.Abp.Notifications;
/// <summary>
/// 渠道数据属性元数据
/// </summary>
/// <remarks>
/// 由 <see cref="NotificationChannelPropertyAttribute"/> 推导而来,
/// 描述"写入/读取哪个键、类型是什么、是否参与存在性判定"。
/// </remarks>
public sealed class NotificationChannelDataProperty
{
/// <summary>
/// 数据键名
/// </summary>
public string Key { get; }
/// <summary>
/// 属性声明类型
/// </summary>
public Type PropertyType { get; }
/// <summary>
/// 存储格式
/// </summary>
public NotificationChannelDataFormat Format { get; }
/// <summary>
/// 是否在存在性判定时忽略本属性
/// </summary>
public bool IgnoreWhenMatching { get; }
/// <summary>
/// 读取委托
/// </summary>
public Func<object, object?> GetValue { get; }
/// <summary>
/// 写入委托
/// </summary>
public Action<object, object?> SetValue { get; }
public NotificationChannelDataProperty(
string key,
Type propertyType,
NotificationChannelDataFormat format,
bool ignoreWhenMatching,
Func<object, object?> getValue,
Action<object, object?> setValue)
{
Key = key;
PropertyType = propertyType;
Format = format;
IgnoreWhenMatching = ignoreWhenMatching;
GetValue = getValue;
SetValue = setValue;
}
}

90
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;
/// <summary>
/// 渠道数据属性元数据缓存
/// </summary>
/// <remarks>
/// 纯反射元数据缓存(无 JSON、无日志、无配置依赖), 因此保持静态以避免
/// 在序列化器、解析器、存在性提供者之间重复注入。
/// </remarks>
public static class NotificationChannelDataPropertyCache
{
private static readonly Dictionary<Type, NotificationChannelDataProperty[]> PropertiesCache = new();
private static readonly object SyncLock = new();
/// <summary>
/// 获取载荷类型的属性元数据
/// </summary>
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<NotificationChannelPropertyAttribute>(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<object, object?> 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<Func<object, object?>>(Expression.Convert(propertyAccess, typeof(object)), instance)
.Compile();
}
private static Action<object, object?> 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<Action<object, object?>>(assign, instance, value)
.Compile();
}
}

279
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;
/// <summary>
/// 通知渠道数据(载荷)解析器
/// </summary>
public class NotificationChannelDataResolver : INotificationChannelDataResolver, ISingletonDependency
{
protected IServiceProvider ServiceProvider { get; }
protected INotificationChannelDataAccessor Accessor { get; }
protected INotificationChannelDataPresenceProvider PresenceProvider { get; }
protected ILogger<NotificationChannelDataResolver> Logger { get; }
private readonly IOptions<AbpNotificationChannelDataOptions> _options;
private readonly Dictionary<string, List<ChannelDataRegistration>> _registrations;
private readonly Dictionary<Type, ChannelDataRegistration> _registrationsByType;
private readonly object _syncLock = new();
public NotificationChannelDataResolver(
IServiceProvider serviceProvider,
IOptions<AbpNotificationChannelDataOptions> options,
INotificationChannelDataAccessor accessor,
INotificationChannelDataPresenceProvider presenceProvider,
ILogger<NotificationChannelDataResolver>? logger = null)
{
ServiceProvider = serviceProvider;
_options = options;
Accessor = accessor;
PresenceProvider = presenceProvider;
Logger = logger ?? NullLogger<NotificationChannelDataResolver>.Instance;
_registrations = new Dictionary<string, List<ChannelDataRegistration>>(StringComparer.OrdinalIgnoreCase);
_registrationsByType = new Dictionary<Type, ChannelDataRegistration>();
}
public virtual IReadOnlyList<NotificationChannelData> Resolve(string providerName, NotificationData notificationData)
{
Check.NotNull(providerName, nameof(providerName));
Check.NotNull(notificationData, nameof(notificationData));
var result = new List<NotificationChannelData>();
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<TChannelData>(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<Type> 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<TValue>(NotificationData notificationData, string key)
where TValue : struct
{
return Accessor.GetValue<TValue>(notificationData, key);
}
public virtual TValue GetValue<TValue>(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;
}
/// <summary>
/// 转换载荷属性值
/// </summary>
/// <returns>转换结果; 无法转换或类型不符时返回 null</returns>
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<ChannelDataRegistration> 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));
}
/// <summary>
/// 渠道数据注册项
/// </summary>
protected sealed class ChannelDataRegistration
{
public NotificationChannelDataDescriptor Descriptor { get; }
public Func<IServiceProvider, object> Factory { get; }
public Func<NotificationData, bool> IsPresent => Descriptor.IsPresent;
public ChannelDataRegistration(
NotificationChannelDataDescriptor descriptor,
Func<IServiceProvider, object> factory)
{
Descriptor = descriptor;
Factory = factory;
}
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save