EventChannel.kt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. * Copyright 2019-2021 Mamoe Technologies and contributors.
  3. *
  4. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  5. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  6. *
  7. * https://github.com/mamoe/mirai/blob/master/LICENSE
  8. */
  9. @file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "MemberVisibilityCanBePrivate", "unused")
  10. @file:JvmMultifileClass
  11. @file:JvmName("EventChannelKt")
  12. package net.mamoe.mirai.event
  13. import kotlinx.coroutines.*
  14. import kotlinx.coroutines.channels.Channel
  15. import kotlinx.coroutines.sync.Mutex
  16. import net.mamoe.mirai.Bot
  17. import net.mamoe.mirai.event.ConcurrencyKind.CONCURRENT
  18. import net.mamoe.mirai.event.ConcurrencyKind.LOCKED
  19. import net.mamoe.mirai.event.events.BotEvent
  20. import net.mamoe.mirai.internal.event.GlobalEventListeners
  21. import net.mamoe.mirai.internal.event.Handler
  22. import net.mamoe.mirai.internal.event.ListenerRegistry
  23. import net.mamoe.mirai.internal.event.registerEventHandler
  24. import net.mamoe.mirai.utils.MiraiExperimentalApi
  25. import net.mamoe.mirai.utils.MiraiLogger
  26. import net.mamoe.mirai.utils.cast
  27. import net.mamoe.mirai.utils.runBIO
  28. import java.util.function.Consumer
  29. import kotlin.coroutines.CoroutineContext
  30. import kotlin.coroutines.EmptyCoroutineContext
  31. import kotlin.internal.LowPriorityInOverloadResolution
  32. import kotlin.reflect.KClass
  33. /**
  34. * 事件通道. 事件通道是监听事件的入口. **在不同的事件通道中可以监听到不同类型的事件**.
  35. *
  36. * [GlobalEventChannel] 是最大的通道: 所有的事件都可以在 [GlobalEventChannel] 监听到.
  37. * 通过 [Bot.eventChannel] 得到的通道只能监听到来自这个 [Bot] 的事件.
  38. *
  39. * ### 对通道的操作
  40. * - "缩窄" 通道: 通过 [EventChannel.filter]. 例如 `filter { it is BotEvent }` 得到一个只能监听到 [BotEvent] 的事件通道.
  41. * - 转换为 Kotlin 协程 [Channel]: [EventChannel.asChannel]
  42. * - 添加 [CoroutineContext]: [context], [parentJob], [parentScope], [exceptionHandler]
  43. *
  44. * ### 创建事件监听
  45. * - [EventChannel.subscribe] 创建带条件的一个事件监听器.
  46. * - [EventChannel.subscribeAlways] 创建一个总是监听事件的事件监听器.
  47. * - [EventChannel.subscribeOnce] 创建一个只监听单次的事件监听器.
  48. *
  49. * ### 获取事件通道
  50. * - 全局事件通道: [GlobalEventChannel]
  51. * - [BotEvent] 通道: [Bot.eventChannel]
  52. *
  53. * @see subscribe
  54. */
  55. public open class EventChannel<out BaseEvent : Event> @JvmOverloads internal constructor(
  56. public val baseEventClass: KClass<out BaseEvent>,
  57. /**
  58. * 此事件通道的默认 [CoroutineScope.coroutineContext]. 将会被添加给所有注册的事件监听器.
  59. */
  60. public val defaultCoroutineContext: CoroutineContext = EmptyCoroutineContext,
  61. ) {
  62. /**
  63. * 创建事件监听并将监听结果发送在 [Channel]. 将返回值 [Channel] [关闭][Channel.close] 时将会同时关闭事件监听.
  64. *
  65. * 标注 [ExperimentalCoroutinesApi] 是因为使用了 [Channel.invokeOnClose]
  66. *
  67. * @param capacity Channel 容量. 详见 [Channel] 构造.
  68. *
  69. * @see subscribeAlways
  70. * @see Channel
  71. */
  72. @MiraiExperimentalApi
  73. @ExperimentalCoroutinesApi
  74. public fun asChannel(
  75. capacity: Int = Channel.RENDEZVOUS,
  76. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  77. concurrency: ConcurrencyKind = CONCURRENT,
  78. priority: EventPriority = EventPriority.NORMAL,
  79. ): Channel<out BaseEvent> {
  80. val channel = Channel<BaseEvent>(capacity)
  81. val listener = subscribeAlways(baseEventClass, coroutineContext, concurrency, priority) { channel.send(it) }
  82. channel.invokeOnClose {
  83. if (it != null) listener.completeExceptionally(it)
  84. else listener.complete()
  85. }
  86. return channel
  87. }
  88. // region transforming operations
  89. /**
  90. * 添加一个过滤器. 过滤器将在收到任何事件之后, 传递给通过 [EventChannel.subscribe] 注册的监听器之前调用.
  91. *
  92. * 若 [filter] 返回 `true`, 该事件将会被传给监听器. 否则将会被忽略, **监听器继续监听**.
  93. *
  94. * ## 线性顺序
  95. * 多个 [filter] 的处理是线性且有顺序的. 若一个 [filter] 已经返回了 `false` (代表忽略这个事件), 则会立即忽略, 而不会传递给后续过滤器.
  96. *
  97. * 示例:
  98. * ```
  99. * GlobalEventChannel // GlobalEventChannel 会收到全局所有事件, 事件类型是 Event
  100. * .filterIsInstance<BotEvent>() // 过滤, 只接受 BotEvent
  101. * .filter { event: BotEvent ->
  102. * // 此时的 event 一定是 BotEvent
  103. * event.bot.id == 123456 // 再过滤 event 的 bot.id
  104. * }
  105. * .subscribeAlways { event: BotEvent ->
  106. * // 现在 event 是 BotEvent, 且 bot.id == 123456
  107. * }
  108. * ```
  109. *
  110. * ## 过滤器挂起
  111. * [filter] 允许挂起协程. **过滤器的挂起将被认为是事件监听器的挂起**.
  112. *
  113. * 过滤器挂起是否会影响事件处理,
  114. * 取决于 [subscribe] 时的 [ConcurrencyKind] 和 [EventPriority].
  115. *
  116. * ## 过滤器异常处理
  117. * 若 [filter] 抛出异常, 将被包装为 [ExceptionInEventChannelFilterException] 并重新抛出.
  118. *
  119. * @see filterIsInstance 过滤指定类型的事件
  120. */
  121. @JvmSynthetic
  122. public fun filter(filter: suspend (event: BaseEvent) -> Boolean): EventChannel<BaseEvent> {
  123. val parent = this
  124. return object : EventChannel<BaseEvent>(baseEventClass, defaultCoroutineContext) {
  125. private inline val innerThis get() = this
  126. override fun <E : Event> (suspend (E) -> ListeningStatus).intercepted(): suspend (E) -> ListeningStatus {
  127. val thisIntercepted: suspend (E) -> ListeningStatus = { ev ->
  128. val filterResult = try {
  129. @Suppress("UNCHECKED_CAST")
  130. baseEventClass.isInstance(ev) && filter(ev as BaseEvent)
  131. } catch (e: Throwable) {
  132. if (e is ExceptionInEventChannelFilterException) throw e // wrapped by another filter
  133. throw ExceptionInEventChannelFilterException(ev, innerThis, cause = e)
  134. }
  135. if (filterResult) [email protected](ev)
  136. else ListeningStatus.LISTENING
  137. }
  138. return parent.intercept(thisIntercepted)
  139. }
  140. }
  141. }
  142. /**
  143. * [EventChannel.filter] 的 Java 版本.
  144. *
  145. * 添加一个过滤器. 过滤器将在收到任何事件之后, 传递给通过 [EventChannel.subscribe] 注册的监听器之前调用.
  146. *
  147. * 若 [filter] 返回 `true`, 该事件将会被传给监听器. 否则将会被忽略, **监听器继续监听**.
  148. *
  149. * ## 线性顺序
  150. * 多个 [filter] 的处理是线性且有顺序的. 若一个 [filter] 已经返回了 `false` (代表忽略这个事件), 则会立即忽略, 而不会传递给后续过滤器.
  151. *
  152. * 示例:
  153. * ```
  154. * GlobalEventChannel // GlobalEventChannel 会收到全局所有事件, 事件类型是 Event
  155. * .filterIsInstance(BotEvent.class) // 过滤, 只接受 BotEvent
  156. * .filter(event ->
  157. * // 此时的 event 一定是 BotEvent
  158. * event.bot.id == 123456 // 再过滤 event 的 bot.id
  159. * )
  160. * .subscribeAlways(event -> {
  161. * // 现在 event 是 BotEvent, 且 bot.id == 123456
  162. * })
  163. * ```
  164. *
  165. * ## 过滤器阻塞
  166. * [filter] 允许阻塞线程. **过滤器的阻塞将被认为是事件监听器的阻塞**.
  167. *
  168. * 过滤器阻塞是否会影响事件处理,
  169. * 取决于 [subscribe] 时的 [ConcurrencyKind] 和 [EventPriority].
  170. *
  171. * ## 过滤器异常处理
  172. * 若 [filter] 抛出异常, 将被包装为 [ExceptionInEventChannelFilterException] 并重新抛出.
  173. *
  174. * @see filterIsInstance 过滤指定类型的事件
  175. *
  176. * @since 2.2
  177. */
  178. @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
  179. @kotlin.internal.LowPriorityInOverloadResolution
  180. public fun filter(filter: (event: BaseEvent) -> Boolean): EventChannel<BaseEvent> {
  181. return filter { runBIO { filter(it) } }
  182. }
  183. /**
  184. * 过滤事件的类型. 返回一个只包含 [E] 类型事件的 [EventChannel]
  185. * @see filter 获取更多信息
  186. */
  187. @JvmSynthetic
  188. public inline fun <reified E : Event> filterIsInstance(): EventChannel<E> =
  189. filterIsInstance(E::class)
  190. /**
  191. * 过滤事件的类型. 返回一个只包含 [E] 类型事件的 [EventChannel]
  192. * @see filter 获取更多信息
  193. */
  194. public fun <E : Event> filterIsInstance(kClass: KClass<out E>): EventChannel<E> {
  195. return filter { kClass.isInstance(it) }.cast()
  196. }
  197. /**
  198. * 过滤事件的类型. 返回一个只包含 [E] 类型事件的 [EventChannel]
  199. * @see filter 获取更多信息
  200. */
  201. public fun <E : Event> filterIsInstance(clazz: Class<out E>): EventChannel<E> =
  202. filterIsInstance(clazz.kotlin)
  203. /**
  204. * 创建一个新的 [EventChannel], 该 [EventChannel] 包含 [`this.coroutineContext`][defaultCoroutineContext] 和添加的 [coroutineContexts].
  205. * [coroutineContexts] 会覆盖 [defaultCoroutineContext] 中的重复元素.
  206. *
  207. * 此操作不会修改 [`this.coroutineContext`][defaultCoroutineContext], 只会创建一个新的 [EventChannel].
  208. */
  209. public fun context(vararg coroutineContexts: CoroutineContext): EventChannel<BaseEvent> {
  210. val origin = this
  211. return object : EventChannel<BaseEvent>(
  212. baseEventClass,
  213. coroutineContexts.fold(this.defaultCoroutineContext) { acc, element -> acc + element }
  214. ) {
  215. override fun <E : Event> (suspend (E) -> ListeningStatus).intercepted(): suspend (E) -> ListeningStatus {
  216. return origin.intercept(this)
  217. }
  218. }
  219. }
  220. /**
  221. * 创建一个新的 [EventChannel], 该 [EventChannel] 包含 [this.coroutineContext][defaultCoroutineContext] 和添加的 [coroutineExceptionHandler]
  222. * @see context
  223. */
  224. @LowPriorityInOverloadResolution
  225. public fun exceptionHandler(coroutineExceptionHandler: CoroutineExceptionHandler): EventChannel<BaseEvent> {
  226. return context(coroutineExceptionHandler)
  227. }
  228. /**
  229. * 创建一个新的 [EventChannel], 该 [EventChannel] 包含 [`this.coroutineContext`][defaultCoroutineContext] 和添加的 [coroutineExceptionHandler]
  230. * @see context
  231. */
  232. public fun exceptionHandler(coroutineExceptionHandler: (exception: Throwable) -> Unit): EventChannel<BaseEvent> {
  233. return context(CoroutineExceptionHandler { _, throwable ->
  234. coroutineExceptionHandler(throwable)
  235. })
  236. }
  237. /**
  238. * 将 [coroutineScope] 作为这个 [EventChannel] 的父作用域.
  239. *
  240. * 实际作用为创建一个新的 [EventChannel],
  241. * 该 [EventChannel] 包含 [`this.coroutineContext`][defaultCoroutineContext] 和添加的 [CoroutineScope.coroutineContext],
  242. * 并以 [CoroutineScope] 中 [Job] (如果有) [作为父 Job][parentJob]
  243. *
  244. * @see parentJob
  245. * @see context
  246. *
  247. * @see CoroutineScope.globalEventChannel `GlobalEventChannel.parentScope()` 的扩展
  248. */
  249. public fun parentScope(coroutineScope: CoroutineScope): EventChannel<BaseEvent> {
  250. return context(coroutineScope.coroutineContext)
  251. }
  252. /**
  253. * 指定协程父 [Job]. 之后在此 [EventChannel] 下创建的事件监听器都会成为 [job] 的子任务, 当 [job] 被取消时, 所有的事件监听器都会被取消.
  254. *
  255. * 注意: 监听器不会失败 ([Job.cancel]). 监听器处理过程的异常都会被捕获然后交由 [CoroutineExceptionHandler] 处理, 因此 [job] 不会因为子任务监听器的失败而被取消.
  256. *
  257. * @see parentScope
  258. * @see context
  259. */
  260. public fun parentJob(job: Job): EventChannel<BaseEvent> {
  261. return context(job)
  262. }
  263. // endregion
  264. // region subscribe
  265. /**
  266. * 创建一个事件监听器, 监听事件通道中所有 [E] 及其子类事件.
  267. *
  268. * 每当 [事件广播][Event.broadcast] 时, [handler] 都会被执行.
  269. *
  270. *
  271. * ## 创建监听
  272. * 调用本函数:
  273. * ```
  274. * eventChannel.subscribe<E> { /* 会收到此通道中的所有是 E 的事件 */ }
  275. * ```
  276. *
  277. * ## 生命周期
  278. *
  279. * ### 通过协程作用域管理监听器
  280. * 本函数将会创建一个 [Job], 成为 [parentJob] 中的子任务. 可创建一个 [CoroutineScope] 来管理所有的监听器:
  281. * ```
  282. * val scope = CoroutineScope(SupervisorJob())
  283. *
  284. * val scopedChannel = eventChannel.parentScope(scope) // 将协程作用域 scope 附加到这个 EventChannel
  285. *
  286. * scopedChannel.subscribeAlways<MemberJoinEvent> { /* ... */ } // 启动监听, 监听器协程会作为 scope 的子任务
  287. * scopedChannel.subscribeAlways<MemberMuteEvent> { /* ... */ } // 启动监听, 监听器协程会作为 scope 的子任务
  288. *
  289. * scope.cancel() // 停止了协程作用域, 也就取消了两个监听器
  290. * ```
  291. *
  292. * 这个函数返回 [Listener], 它是一个 [CompletableJob]. 它会成为 [parentJob] 或 [parentScope] 的一个 [子任务][Job]
  293. *
  294. * ### 停止监听
  295. * 如果 [handler] 返回 [ListeningStatus.STOPPED] 监听器将被停止.
  296. *
  297. * 也可以通过 [subscribe] 返回值 [Listener] 的 [Listener.complete]
  298. *
  299. * ## 监听器调度
  300. * 监听器会被创建一个协程任务, 语义上在 [parentScope] 下运行.
  301. * 通过 Kotlin [默认协程调度器][Dispatchers.Default] 在固定的全局共享线程池里执行, 除非有 [coroutineContext] 指定.
  302. *
  303. * 默认在 [handler] 中不能处理阻塞任务. 阻塞任务将会阻塞一个 Kotlin 全局协程调度线程并可能导致严重问题.
  304. * 请通过 `withContext(Dispatchers.IO) { }` 等方法执行阻塞工作.
  305. *
  306. * ## 异常处理
  307. * - 当参数 [handler] 处理抛出异常时, 将会按如下顺序寻找 [CoroutineExceptionHandler] 处理异常:
  308. * 1. 参数 [coroutineContext]
  309. * 2. [EventChannel.defaultCoroutineContext]
  310. * 3. [Event.broadcast] 调用者的 [coroutineContext]
  311. * 4. 若事件为 [BotEvent], 则从 [BotEvent.bot] 获取到 [Bot], 进而在 [Bot.coroutineContext] 中寻找
  312. * 5. 若以上四个步骤均无法获取 [CoroutineExceptionHandler], 则使用 [MiraiLogger.Companion] 通过日志记录. 但这种情况理论上不应发生.
  313. *
  314. *
  315. * 事件处理时抛出异常不会停止监听器.
  316. *
  317. * 建议在事件处理中 (即 [handler] 里) 处理异常,
  318. * 或在参数 [coroutineContext] 中添加 [CoroutineExceptionHandler], 或通过 [EventChannel.exceptionHandler].
  319. *
  320. * ## 并发安全性
  321. * 基于 [concurrency] 参数, 事件监听器可以被允许并行执行.
  322. *
  323. * - 若 [concurrency] 为 [ConcurrencyKind.CONCURRENT], [handler] 可能被并行调用, 需要保证并发安全.
  324. * - 若 [concurrency] 为 [ConcurrencyKind.LOCKED], [handler] 会被 [Mutex] 限制.
  325. *
  326. * @param coroutineContext 在 [defaultCoroutineContext] 的基础上, 给事件监听协程的额外的 [CoroutineContext].
  327. * @param concurrency 并发类型. 查看 [ConcurrencyKind]
  328. * @param priority 监听优先级,优先级越高越先执行
  329. * @param handler 事件处理器. 在接收到事件时会调用这个处理器. 其返回值意义参考 [ListeningStatus]. 其异常处理参考上文
  330. *
  331. * @return 监听器实例. 此监听器已经注册到指定事件上, 在事件广播时将会调用 [handler]
  332. *
  333. * @see syncFromEvent 挂起当前协程, 监听一个事件, 并尝试从这个事件中**同步**一个值
  334. * @see asyncFromEvent 异步监听一个事件, 并尝试从这个事件中获取一个值.
  335. *
  336. * @see nextEvent 挂起当前协程, 直到监听到事件 [E] 的广播, 返回这个事件实例.
  337. *
  338. * @see selectMessages 以 `when` 的语法 '选择' 即将到来的一条消息.
  339. * @see whileSelectMessages 以 `when` 的语法 '选择' 即将到来的所有消息, 直到不满足筛选结果.
  340. *
  341. * @see subscribeAlways 一直监听
  342. * @see subscribeOnce 只监听一次
  343. *
  344. * @see subscribeMessages 监听消息 DSL
  345. */
  346. @JvmSynthetic
  347. public inline fun <reified E : Event> subscribe(
  348. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  349. concurrency: ConcurrencyKind = LOCKED,
  350. priority: EventPriority = EventPriority.NORMAL,
  351. noinline handler: suspend E.(E) -> ListeningStatus,
  352. ): Listener<E> = subscribe(E::class, coroutineContext, concurrency, priority, handler)
  353. /**
  354. * 与 [subscribe] 的区别是接受 [eventClass] 参数, 而不使用 `reified` 泛型. 通常推荐使用具体化类型参数.
  355. *
  356. * @return 监听器实例. 此监听器已经注册到指定事件上, 在事件广播时将会调用 [handler]
  357. * @see subscribe
  358. */
  359. @JvmSynthetic
  360. public fun <E : Event> subscribe(
  361. eventClass: KClass<out E>,
  362. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  363. concurrency: ConcurrencyKind = LOCKED,
  364. priority: EventPriority = EventPriority.NORMAL,
  365. handler: suspend E.(E) -> ListeningStatus,
  366. ): Listener<E> = subscribeInternal(
  367. eventClass,
  368. createListener(coroutineContext, concurrency, priority) { it.handler(it); }
  369. )
  370. /**
  371. * 创建一个事件监听器, 监听事件通道中所有 [E] 及其子类事件.
  372. * 每当 [事件广播][Event.broadcast] 时, [handler] 都会被执行.
  373. *
  374. * 可在任意时候通过 [Listener.complete] 来主动停止监听.
  375. *
  376. * @param concurrency 并发类型默认为 [CONCURRENT]
  377. * @param coroutineContext 在 [defaultCoroutineContext] 的基础上, 给事件监听协程的额外的 [CoroutineContext]
  378. * @param priority 处理优先级, 优先级高的先执行
  379. *
  380. * @return 监听器实例. 此监听器已经注册到指定事件上, 在事件广播时将会调用 [handler]
  381. *
  382. * @see subscribe 获取更多说明
  383. */
  384. @JvmSynthetic
  385. public inline fun <reified E : Event> subscribeAlways(
  386. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  387. concurrency: ConcurrencyKind = CONCURRENT,
  388. priority: EventPriority = EventPriority.NORMAL,
  389. noinline handler: suspend E.(E) -> Unit,
  390. ): Listener<E> = subscribeAlways(E::class, coroutineContext, concurrency, priority, handler)
  391. /**
  392. * @see subscribe
  393. * @see subscribeAlways
  394. */
  395. @JvmSynthetic
  396. public fun <E : Event> subscribeAlways(
  397. eventClass: KClass<out E>,
  398. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  399. concurrency: ConcurrencyKind = CONCURRENT,
  400. priority: EventPriority = EventPriority.NORMAL,
  401. handler: suspend E.(E) -> Unit,
  402. ): Listener<E> = subscribeInternal(
  403. eventClass,
  404. createListener(coroutineContext, concurrency, priority) { it.handler(it); ListeningStatus.LISTENING }
  405. )
  406. /**
  407. * 创建一个事件监听器, 监听事件通道中所有 [E] 及其子类事件, 只监听一次.
  408. * 当 [事件广播][Event.broadcast] 时, [handler] 会被执行.
  409. *
  410. * 可在任意时候通过 [Listener.complete] 来主动停止监听.
  411. *
  412. * @param coroutineContext 在 [defaultCoroutineContext] 的基础上, 给事件监听协程的额外的 [CoroutineContext]
  413. * @param priority 处理优先级, 优先级高的先执行
  414. *
  415. * @see subscribe 获取更多说明
  416. */
  417. @JvmSynthetic
  418. public inline fun <reified E : Event> subscribeOnce(
  419. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  420. priority: EventPriority = EventPriority.NORMAL,
  421. noinline handler: suspend E.(E) -> Unit,
  422. ): Listener<E> = subscribeOnce(E::class, coroutineContext, priority, handler)
  423. /**
  424. * @see subscribeOnce
  425. */
  426. public fun <E : Event> subscribeOnce(
  427. eventClass: KClass<out E>,
  428. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  429. priority: EventPriority = EventPriority.NORMAL,
  430. handler: suspend E.(E) -> Unit,
  431. ): Listener<E> = subscribeInternal(
  432. eventClass,
  433. createListener(coroutineContext, LOCKED, priority) { it.handler(it); ListeningStatus.STOPPED }
  434. )
  435. // endregion
  436. /**
  437. * 注册 [ListenerHost] 中的所有 [EventHandler] 标注的方法到这个 [EventChannel]. 查看 [EventHandler].
  438. *
  439. * @param coroutineContext 在 [defaultCoroutineContext] 的基础上, 给事件监听协程的额外的 [CoroutineContext]
  440. *
  441. * @see subscribe
  442. * @see EventHandler
  443. * @see ListenerHost
  444. */
  445. @JvmOverloads
  446. public fun registerListenerHost(
  447. host: ListenerHost,
  448. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  449. ) {
  450. for (method in host.javaClass.declaredMethods) {
  451. method.getAnnotation(EventHandler::class.java)?.let {
  452. method.registerEventHandler(host, this, it, coroutineContext)
  453. }
  454. }
  455. }
  456. // region Java API
  457. /**
  458. * Java API. 查看 [subscribeAlways] 获取更多信息.
  459. *
  460. * ```java
  461. * eventChannel.subscribeAlways(GroupMessageEvent.class, (event) -> { });
  462. * ```
  463. *
  464. * @see subscribe
  465. * @see subscribeAlways
  466. */
  467. @JvmOverloads
  468. @LowPriorityInOverloadResolution
  469. public fun <E : Event> subscribeAlways(
  470. eventClass: Class<out E>,
  471. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  472. concurrency: ConcurrencyKind = CONCURRENT,
  473. priority: EventPriority = EventPriority.NORMAL,
  474. handler: Consumer<E>,
  475. ): Listener<E> = subscribeInternal(
  476. eventClass.kotlin,
  477. createListener(coroutineContext, concurrency, priority) { event ->
  478. runInterruptible(Dispatchers.IO) { handler.accept(event) }
  479. ListeningStatus.LISTENING
  480. }
  481. )
  482. /**
  483. * Java API. 查看 [subscribe] 获取更多信息.
  484. *
  485. * ```java
  486. * eventChannel.subscribe(GroupMessageEvent.class, (event) -> {
  487. * return ListeningStatus.LISTENING;
  488. * });
  489. * ```
  490. *
  491. * @see subscribe
  492. */
  493. @JvmOverloads
  494. @LowPriorityInOverloadResolution
  495. public fun <E : Event> subscribe(
  496. eventClass: Class<out E>,
  497. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  498. concurrency: ConcurrencyKind = CONCURRENT,
  499. priority: EventPriority = EventPriority.NORMAL,
  500. handler: java.util.function.Function<E, ListeningStatus>,
  501. ): Listener<E> = subscribeInternal(
  502. eventClass.kotlin,
  503. createListener(coroutineContext, concurrency, priority) { event ->
  504. runInterruptible(Dispatchers.IO) { handler.apply(event) }
  505. }
  506. )
  507. /**
  508. * Java API. 查看 [subscribeOnce] 获取更多信息.
  509. *
  510. * ```java
  511. * eventChannel.subscribeOnce(GroupMessageEvent.class, (event) -> { });
  512. * ```
  513. *
  514. * @see subscribe
  515. * @see subscribeOnce
  516. */
  517. @JvmOverloads
  518. @LowPriorityInOverloadResolution
  519. public fun <E : Event> subscribeOnce(
  520. eventClass: Class<out E>,
  521. coroutineContext: CoroutineContext = EmptyCoroutineContext,
  522. concurrency: ConcurrencyKind = CONCURRENT,
  523. priority: EventPriority = EventPriority.NORMAL,
  524. handler: Consumer<E>,
  525. ): Listener<E> = subscribeInternal(
  526. eventClass.kotlin,
  527. createListener(coroutineContext, concurrency, priority) { event ->
  528. runInterruptible(Dispatchers.IO) { handler.accept(event) }
  529. ListeningStatus.STOPPED
  530. }
  531. )
  532. // endregion
  533. // region impl
  534. /**
  535. * 由子类实现,可以为 handler 包装一个过滤器等. 每个 handler 都会经过此函数处理.
  536. */
  537. @MiraiExperimentalApi
  538. protected open fun <E : Event> (suspend (E) -> ListeningStatus).intercepted(): (suspend (E) -> ListeningStatus) {
  539. return this
  540. }
  541. private fun <E : Event> intercept(listener: (suspend (E) -> ListeningStatus)): suspend (E) -> ListeningStatus {
  542. return listener.intercepted()
  543. }
  544. private fun <L : Listener<E>, E : Event> subscribeInternal(eventClass: KClass<out E>, listener: L): L {
  545. with(GlobalEventListeners[listener.priority]) {
  546. @Suppress("UNCHECKED_CAST")
  547. val node = ListenerRegistry(listener as Listener<Event>, eventClass)
  548. add(node)
  549. listener.invokeOnCompletion {
  550. this.remove(node)
  551. }
  552. }
  553. return listener
  554. }
  555. @Suppress("FunctionName")
  556. private fun <E : Event> createListener(
  557. coroutineContext: CoroutineContext,
  558. concurrencyKind: ConcurrencyKind,
  559. priority: EventPriority = EventPriority.NORMAL,
  560. handler: suspend (E) -> ListeningStatus,
  561. ): Listener<E> {
  562. val context = this.defaultCoroutineContext + coroutineContext
  563. return Handler(
  564. parentJob = context[Job],
  565. subscriberContext = context,
  566. handler = handler.intercepted(),
  567. concurrencyKind = concurrencyKind,
  568. priority = priority
  569. )
  570. }
  571. // endregion
  572. }