BotConfiguration.kt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. * Copyright 2019-2023 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/dev/LICENSE
  8. */
  9. @file:Suppress("unused", "DEPRECATION_ERROR", "EXPOSED_SUPER_CLASS", "MemberVisibilityCanBePrivate")
  10. @file:JvmMultifileClass
  11. @file:JvmName("Utils")
  12. package net.mamoe.mirai.utils
  13. import kotlinx.coroutines.Job
  14. import kotlinx.coroutines.SupervisorJob
  15. import kotlinx.serialization.json.Json
  16. import net.mamoe.mirai.Bot
  17. import net.mamoe.mirai.BotFactory
  18. import net.mamoe.mirai.Mirai
  19. import net.mamoe.mirai.auth.BotAuthorization
  20. import net.mamoe.mirai.event.events.BotOfflineEvent
  21. import kotlin.coroutines.CoroutineContext
  22. import kotlin.coroutines.EmptyCoroutineContext
  23. import kotlin.coroutines.coroutineContext
  24. import kotlin.time.Duration
  25. import kotlin.time.Duration.Companion.milliseconds
  26. /**
  27. * [Bot] 配置. 用于 [BotFactory.newBot].
  28. *
  29. * 部分平台相关配置位于 [AbstractBotConfiguration], 例如 `fileBasedDeviceInfo`.
  30. *
  31. * Kotlin 使用方法:
  32. * ```
  33. * val bot = BotFactory.newBot(...) {
  34. * // 在这里配置 Bot
  35. *
  36. * bogLoggerSupplier = { bot -> ... }
  37. * fileBasedDeviceInfo()
  38. * inheritCoroutineContext() // 使用 `coroutineScope` 的 Job 作为父 Job
  39. * }
  40. * ```
  41. *
  42. * Java 使用方法:
  43. * ```java
  44. * Bot bot = BotFactory.newBot(..., new BotConfiguration() {{
  45. * setBogLoggerSupplier((Bot bot) -> { ... })
  46. * fileBasedDeviceInfo()
  47. * ...
  48. * }})
  49. * ```
  50. */
  51. @OptIn(MiraiInternalApi::class)
  52. public open class BotConfiguration : AbstractBotConfiguration() { // open for Java
  53. ///////////////////////////////////////////////////////////////////////////
  54. // Coroutines
  55. ///////////////////////////////////////////////////////////////////////////
  56. /** 父 [CoroutineContext]. [Bot] 创建后会使用 [SupervisorJob] 覆盖其 [Job], 但会将这个 [Job] 作为父 [Job] */
  57. public var parentCoroutineContext: CoroutineContext = EmptyCoroutineContext
  58. /**
  59. * 使用当前协程的 [coroutineContext] 作为 [parentCoroutineContext].
  60. *
  61. * Bot 将会使用一个 [SupervisorJob] 覆盖 [coroutineContext] 当前协程的 [Job], 并使用当前协程的 [Job] 作为父 [Job]
  62. *
  63. * 用例:
  64. * ```
  65. * coroutineScope {
  66. * val bot = Bot(...) {
  67. * inheritCoroutineContext()
  68. * }
  69. * bot.login()
  70. * } // coroutineScope 会等待 Bot 退出
  71. * ```
  72. *
  73. *
  74. * **注意**: `bot.cancel` 时将会让父 [Job] 也被 cancel.
  75. * ```
  76. * coroutineScope { // this: CoroutineScope
  77. * launch {
  78. * while(isActive) {
  79. * delay(500)
  80. * println("I'm alive")
  81. * }
  82. * }
  83. *
  84. * val bot = Bot(...) {
  85. * inheritCoroutineContext() // 使用 `coroutineScope` 的 Job 作为父 Job
  86. * }
  87. * bot.login()
  88. * bot.cancel() // 取消了整个 `coroutineScope`, 因此上文不断打印 `"I'm alive"` 的协程也会被取消.
  89. * }
  90. * ```
  91. *
  92. * 因此, 此函数尤为适合在 `suspend fun main()` 中使用, 它能阻止主线程退出:
  93. * ```
  94. * suspend fun main() {
  95. * val bot = Bot() {
  96. * inheritCoroutineContext()
  97. * }
  98. * bot.eventChannel.subscribe { ... }
  99. *
  100. * // 主线程不会退出, 直到 Bot 离线.
  101. * }
  102. * ```
  103. *
  104. * 简言之,
  105. * - 若想让 [Bot] 作为 '守护进程' 运行, 则无需调用 [inheritCoroutineContext].
  106. * - 若想让 [Bot] 依赖于当前协程, 让当前协程等待 [Bot] 运行, 则使用 [inheritCoroutineContext]
  107. *
  108. * @see parentCoroutineContext
  109. */
  110. @JvmSynthetic
  111. @ConfigurationDsl
  112. public suspend inline fun inheritCoroutineContext() {
  113. parentCoroutineContext = coroutineContext
  114. }
  115. ///////////////////////////////////////////////////////////////////////////
  116. // Connection
  117. ///////////////////////////////////////////////////////////////////////////
  118. /** 连接心跳包周期. 过长会导致被服务器断开连接. */
  119. public var heartbeatPeriodMillis: Long = 60.secondsToMillis
  120. /**
  121. * 状态心跳包周期. 过长会导致掉线.
  122. * 该值会在登录时根据服务器下发的配置自动进行更新.
  123. * @since 2.6
  124. * @see heartbeatStrategy
  125. */
  126. public var statHeartbeatPeriodMillis: Long = 300.secondsToMillis
  127. /**
  128. * 心跳策略.
  129. * @since 2.6.3
  130. */
  131. public var heartbeatStrategy: HeartbeatStrategy = HeartbeatStrategy.STAT_HB
  132. /**
  133. * 心跳策略.
  134. * @since 2.6.3
  135. */
  136. public enum class HeartbeatStrategy { // IN ACTUAL DECLARATION DO NOT ADD EXTRA ELEMENTS.
  137. /**
  138. * 使用 2.6.0 增加的*状态心跳* (Stat Heartbeat). 通常推荐这个模式.
  139. *
  140. * 该模式大多数情况下更稳定. 但有些账号使用这个模式时会遇到一段时间后发送消息成功但客户端不可见的问题.
  141. */
  142. STAT_HB,
  143. /**
  144. * 不发送状态心跳, 而是发送*切换在线状态* (可能会导致频繁的好友或客户端上线提示, 也可能产生短暂 (几秒) 发送消息不可见的问题).
  145. *
  146. * 建议在 [STAT_HB] 不可用时使用 [REGISTER].
  147. */
  148. REGISTER,
  149. /**
  150. * 不主动维护会话. 多数账号会每 16 分钟掉线然后重连. 则会有短暂的不可用时间.
  151. *
  152. * 仅当 [STAT_HB] 和 [REGISTER] 都造成无法接收等问题时使用.
  153. * 同时请在 [https://github.com/mamoe/mirai/issues/1209] 提交问题.
  154. */
  155. NONE;
  156. }
  157. /**
  158. * 每次心跳时等待结果的时间.
  159. * 一旦心跳超时, 整个网络服务将会重启 (将消耗约 1s). 除正在进行的任务 (如图片上传) 会被中断外, 事件和插件均不受影响.
  160. */
  161. public var heartbeatTimeoutMillis: Long = 5.secondsToMillis
  162. /** 心跳失败后的第一次重连前的等待时间. */
  163. @Deprecated(
  164. "Useless since new network. Please just remove this.",
  165. level = DeprecationLevel.HIDDEN
  166. ) // deprecated since 2.7, error since 2.8
  167. @DeprecatedSinceMirai(warningSince = "2.7", errorSince = "2.8", hiddenSince = "2.10")
  168. public var firstReconnectDelayMillis: Long = 5.secondsToMillis
  169. /** 重连失败后, 继续尝试的每次等待时间 */
  170. @Deprecated(
  171. "Useless since new network. Please just remove this.",
  172. level = DeprecationLevel.HIDDEN
  173. ) // deprecated since 2.7, error since 2.8
  174. @DeprecatedSinceMirai(warningSince = "2.7", errorSince = "2.8", hiddenSince = "2.10")
  175. public var reconnectPeriodMillis: Long = 5.secondsToMillis
  176. /** 最多尝试多少次重连 */
  177. public var reconnectionRetryTimes: Int = Int.MAX_VALUE
  178. /**
  179. * 在被挤下线时 ([BotOfflineEvent.Force]) 自动重连. 默认为 `false`.
  180. *
  181. * 其他情况掉线都默认会自动重连, 详见 [BotOfflineEvent.reconnect]
  182. *
  183. * @since 2.1
  184. */
  185. public var autoReconnectOnForceOffline: Boolean = false
  186. /**
  187. * 验证码处理器
  188. *
  189. * - 在 Android 需要手动提供 [LoginSolver]
  190. * - 在 JVM, Mirai 会根据环境支持情况选择 Swing/CLI 实现
  191. *
  192. * 详见 [LoginSolver.Default]
  193. *
  194. * @see LoginSolver
  195. */
  196. public var loginSolver: LoginSolver? = LoginSolver.Default
  197. /** 使用协议类型 */
  198. public var protocol: MiraiProtocol = MiraiProtocol.ANDROID_PHONE
  199. public enum class MiraiProtocol {
  200. /**
  201. * Android 手机. 所有功能都支持.
  202. */
  203. ANDROID_PHONE,
  204. /**
  205. * Android 平板.
  206. */
  207. ANDROID_PAD,
  208. /**
  209. * Android 手表.
  210. *
  211. * 注意:
  212. * - 不支持戳一戳事件解析
  213. * - 由于该协议的省电特性, 当群被设置为不提醒的的时候, 服务器不会推送消息.
  214. */
  215. ANDROID_WATCH,
  216. /**
  217. * iPad - 来自MiraiGo
  218. *
  219. * @since 2.8
  220. */
  221. IPAD,
  222. /**
  223. * MacOS - 来自MiraiGo
  224. *
  225. * @since 2.8
  226. */
  227. MACOS,
  228. ;
  229. /**
  230. * 当前协议是否支持[二维码登录][BotAuthorization.byQRCode]
  231. *
  232. * @since 2.15.0
  233. */
  234. public val isQRLoginSupported: Boolean get() = data.isQRLoginSupported
  235. /**
  236. * 当前协议是否支持[戳一戳][Bot.nudge]
  237. *
  238. * @since 2.16.0
  239. */
  240. public val isNudgeSupported: Boolean get() = data.isNudgeSupported
  241. private inline val data: InternalProtocolDataExchange.InternalProtocolData
  242. get() = InternalProtocolDataExchange.instance.of(
  243. this
  244. )
  245. }
  246. /**
  247. * Highway 通道上传图片, 语音, 文件等资源时的协程数量.
  248. *
  249. * 每个协程的速度约为 200KB/s. 协程数量越多越快, 同时也更要求性能.
  250. * 默认为 CPU 核心数.
  251. *
  252. * @since 2.2
  253. */
  254. public var highwayUploadCoroutineCount: Int = availableProcessors()
  255. /**
  256. * 设置 [autoReconnectOnForceOffline] 为 `true`, 即在被挤下线时自动重连.
  257. * @since 2.1
  258. */
  259. @ConfigurationDsl
  260. public fun autoReconnectOnForceOffline() {
  261. autoReconnectOnForceOffline = true
  262. }
  263. ///////////////////////////////////////////////////////////////////////////
  264. // Device
  265. ///////////////////////////////////////////////////////////////////////////
  266. @JvmField
  267. internal var accountSecrets: Boolean = true
  268. /**
  269. * 禁止保存 `account.secrets`.
  270. *
  271. * `account.secrets` 保存账号的会话信息。
  272. * 它可加速登录过程,也可能可以减少出现验证码的次数。如果遇到一段时间后无法接收消息通知等同步问题时可尝试禁用。
  273. *
  274. * @since 2.11
  275. */
  276. public fun disableAccountSecretes() {
  277. accountSecrets = false
  278. }
  279. /**
  280. * 设备信息覆盖. 在没有手动指定时将会通过日志警告, 并使用随机设备信息.
  281. * @see fileBasedDeviceInfo 使用指定文件存储设备信息
  282. * @see randomDeviceInfo 使用随机设备信息
  283. */
  284. public final override var deviceInfo: ((Bot) -> DeviceInfo)? = deviceInfoStub // allows user to set `null` manually.
  285. /**
  286. * 使用随机设备信息.
  287. *
  288. * @see deviceInfo
  289. */
  290. @ConfigurationDsl
  291. public fun randomDeviceInfo() {
  292. deviceInfo = null
  293. }
  294. /**
  295. * 使用特定由 [DeviceInfo] 序列化产生的 JSON 的设备信息
  296. *
  297. * @see deviceInfo
  298. */
  299. @ConfigurationDsl
  300. public fun loadDeviceInfoJson(json: String) {
  301. deviceInfo = {
  302. DeviceInfoManager.deserialize(json, Companion.json)
  303. }
  304. }
  305. ///////////////////////////////////////////////////////////////////////////
  306. // Logging
  307. ///////////////////////////////////////////////////////////////////////////
  308. /**
  309. * 日志记录器
  310. *
  311. * - 默认打印到标准输出, 通过 [MiraiLogger.Factory.create]
  312. * - 忽略所有日志: [noBotLog]
  313. * - 重定向到一个目录: `botLoggerSupplier = { DirectoryLogger("Bot ${it.id}") }`
  314. * - 重定向到一个文件: `botLoggerSupplier = { SingleFileLogger("Bot ${it.id}") }`
  315. *
  316. * @see MiraiLogger
  317. */
  318. public final override var botLoggerSupplier: ((Bot) -> MiraiLogger) = {
  319. MiraiLogger.Factory.create(Bot::class, "Bot ${it.id}")
  320. }
  321. /**
  322. * 网络层日志构造器
  323. *
  324. * - 默认打印到标准输出, 通过 [MiraiLogger.Factory.create]
  325. * - 忽略所有日志: [noNetworkLog]
  326. * - 重定向到一个目录: `networkLoggerSupplier = { DirectoryLogger("Net ${it.id}") }`
  327. * - 重定向到一个文件: `networkLoggerSupplier = { SingleFileLogger("Net ${it.id}") }`
  328. *
  329. * @see MiraiLogger
  330. */
  331. public final override var networkLoggerSupplier: ((Bot) -> MiraiLogger) = {
  332. MiraiLogger.Factory.create(Bot::class, "Net ${it.id}")
  333. }
  334. /**
  335. * 不显示网络日志. 不推荐.
  336. * @see networkLoggerSupplier 更多日志处理方式
  337. */
  338. @ConfigurationDsl
  339. public fun noNetworkLog() {
  340. networkLoggerSupplier = { _ -> SilentLogger }
  341. }
  342. /**
  343. * 不显示 [Bot] 日志. 不推荐.
  344. * @see botLoggerSupplier 更多日志处理方式
  345. */
  346. @ConfigurationDsl
  347. public fun noBotLog() {
  348. botLoggerSupplier = { _ -> SilentLogger }
  349. }
  350. /**
  351. * 是否显示过于冗长的事件日志
  352. *
  353. * 默认为 `false`
  354. *
  355. * @since 2.8
  356. */
  357. public var isShowingVerboseEventLog: Boolean = false
  358. ///////////////////////////////////////////////////////////////////////////
  359. // Cache
  360. //////////////////////////////////////////////////////////////////////////
  361. /**
  362. * 联系人信息缓存配置. 将会保存在 `cacheDir` 中 `contacts` 目录
  363. * @since 2.4
  364. */
  365. public var contactListCache: ContactListCache = ContactListCache()
  366. /**
  367. * 联系人信息缓存配置
  368. * @see contactListCache
  369. * @see enableContactCache
  370. * @see disableContactCache
  371. * @since 2.4
  372. */
  373. public class ContactListCache {
  374. /**
  375. * 在有修改时自动保存间隔. 默认 60 秒. 在每次登录完成后有修改时都会立即保存一次.
  376. */
  377. public var saveIntervalMillis: Long = 60_000
  378. /**
  379. * 在有修改时自动保存间隔. 默认 60 秒. 在每次登录完成后有修改时都会立即保存一次.
  380. */ // was @ExperimentalTime before 2.9
  381. public inline var saveInterval: Duration
  382. @JvmSynthetic inline get() = saveIntervalMillis.milliseconds
  383. @JvmSynthetic inline set(v) {
  384. saveIntervalMillis = v.inWholeMilliseconds
  385. }
  386. /**
  387. * 开启好友列表缓存.
  388. */
  389. public var friendListCacheEnabled: Boolean = false
  390. /**
  391. * 开启群成员列表缓存.
  392. */
  393. public var groupMemberListCacheEnabled: Boolean = false
  394. }
  395. /**
  396. * 配置 [ContactListCache]
  397. * ```
  398. * contactListCache {
  399. * saveIntervalMillis = 30_000
  400. * friendListCacheEnabled = true
  401. * }
  402. * ```
  403. * @since 2.4
  404. */
  405. @JvmSynthetic
  406. public inline fun contactListCache(action: ContactListCache.() -> Unit) {
  407. action.invoke(this.contactListCache)
  408. }
  409. /**
  410. * 禁用好友列表和群成员列表的缓存.
  411. * @since 2.4
  412. */
  413. @ConfigurationDsl
  414. public fun disableContactCache() {
  415. contactListCache.friendListCacheEnabled = false
  416. contactListCache.groupMemberListCacheEnabled = false
  417. }
  418. /**
  419. * 启用好友列表和群成员列表的缓存.
  420. * @since 2.4
  421. */
  422. @ConfigurationDsl
  423. public fun enableContactCache() {
  424. contactListCache.friendListCacheEnabled = true
  425. contactListCache.groupMemberListCacheEnabled = true
  426. }
  427. /**
  428. * 登录缓存.
  429. *
  430. * 开始后在密码登录成功时会保存秘钥等信息, 在下次启动时通过这些信息登录, 而不提交密码.
  431. * 可以减少验证码出现的频率.
  432. *
  433. * 秘钥信息会由密码加密保存. 如果秘钥过期, 则会进行普通密码登录.
  434. *
  435. * 默认 `true` (开启).
  436. *
  437. * @since 2.6
  438. */
  439. public var loginCacheEnabled: Boolean = true
  440. ///////////////////////////////////////////////////////////////////////////
  441. // Misc
  442. ///////////////////////////////////////////////////////////////////////////
  443. @Suppress("DuplicatedCode")
  444. public fun copy(): BotConfiguration {
  445. return BotConfiguration().also { new ->
  446. // To structural order
  447. new.parentCoroutineContext = parentCoroutineContext
  448. new.heartbeatPeriodMillis = heartbeatPeriodMillis
  449. new.heartbeatTimeoutMillis = heartbeatTimeoutMillis
  450. new.statHeartbeatPeriodMillis = statHeartbeatPeriodMillis
  451. new.heartbeatStrategy = heartbeatStrategy
  452. new.reconnectionRetryTimes = reconnectionRetryTimes
  453. new.autoReconnectOnForceOffline = autoReconnectOnForceOffline
  454. new.loginSolver = loginSolver
  455. new.protocol = protocol
  456. new.highwayUploadCoroutineCount = highwayUploadCoroutineCount
  457. new.accountSecrets = accountSecrets
  458. new.deviceInfo = deviceInfo
  459. new.botLoggerSupplier = botLoggerSupplier
  460. new.networkLoggerSupplier = networkLoggerSupplier
  461. new.contactListCache = contactListCache
  462. new.convertLineSeparator = convertLineSeparator
  463. new.isShowingVerboseEventLog = isShowingVerboseEventLog
  464. applyMppCopy(new)
  465. }
  466. }
  467. /**
  468. * 是否处理接受到的特殊换行符, 默认为 `true`
  469. *
  470. * - 若为 `true`, 会将收到的 `CRLF(\r\n)` 和 `CR(\r)` 替换为 `LF(\n)`
  471. * - 若为 `false`, 则不做处理
  472. *
  473. * @since 2.4
  474. */
  475. @get:JvmName("isConvertLineSeparator")
  476. public var convertLineSeparator: Boolean = true
  477. /** 标注一个配置 DSL 函数 */
  478. @Target(AnnotationTarget.FUNCTION)
  479. @DslMarker
  480. public annotation class ConfigurationDsl
  481. public companion object {
  482. /** 默认的配置实例. 可以进行修改 */
  483. @JvmStatic
  484. public val Default: BotConfiguration = BotConfiguration()
  485. /**
  486. * Json 序列化器, 使用 'kotlinx.serialization'
  487. */
  488. internal val json: Json = kotlin.runCatching {
  489. Json {
  490. isLenient = true
  491. ignoreUnknownKeys = true
  492. prettyPrint = true
  493. }
  494. }.getOrElse {
  495. @Suppress("JSON_FORMAT_REDUNDANT_DEFAULT") // compatible for older versions
  496. (Json {})
  497. }
  498. }
  499. }
  500. /**
  501. * 构建一个 [BotConfiguration].
  502. *
  503. * @see BotConfiguration
  504. * @since 2.3
  505. */
  506. @JvmSynthetic
  507. public inline fun BotConfiguration(block: BotConfiguration.() -> Unit): BotConfiguration {
  508. return BotConfiguration().apply(block)
  509. }
  510. internal val deviceInfoStub: (Bot) -> DeviceInfo = {
  511. logger.warning("未指定设备信息, 已使用随机设备信息. 请查看 BotConfiguration.deviceInfo 以获取更多信息.")
  512. logger.warning("Device info isn't specified. Please refer to BotConfiguration.deviceInfo for more information")
  513. DeviceInfo.random()
  514. }
  515. private val logger by lazy {
  516. MiraiLogger.Factory.create(BotConfiguration::class)
  517. }
  518. /** @since 2.15.0 */
  519. @MiraiInternalApi
  520. public interface InternalProtocolDataExchange {
  521. @MiraiInternalApi
  522. public interface InternalProtocolData {
  523. public val isQRLoginSupported: Boolean
  524. public val isNudgeSupported: Boolean
  525. public val mainVersion: String
  526. public val buildVersion: String
  527. public val sdkVersion: String
  528. }
  529. @MiraiInternalApi
  530. public fun of(protocol: BotConfiguration.MiraiProtocol): InternalProtocolData
  531. @MiraiInternalApi
  532. public companion object {
  533. internal val instance by lazy {
  534. Mirai // ensure service loaded
  535. loadService(
  536. InternalProtocolDataExchange::class,
  537. "net.mamoe.mirai.internal.utils.MiraiProtocolInternal\$Exchange"
  538. )
  539. }
  540. }
  541. }