-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathMiraiImpl.kt
936 lines (849 loc) · 35.8 KB
/
MiraiImpl.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
/*
* Copyright 2019-2021 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
package net.mamoe.mirai.internal
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.util.*
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.io.core.discardExact
import kotlinx.io.core.readBytes
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import net.mamoe.mirai.*
import net.mamoe.mirai.contact.*
import net.mamoe.mirai.data.*
import net.mamoe.mirai.event.Event
import net.mamoe.mirai.event.broadcast
import net.mamoe.mirai.event.events.*
import net.mamoe.mirai.internal.contact.*
import net.mamoe.mirai.internal.contact.info.FriendInfoImpl
import net.mamoe.mirai.internal.contact.info.FriendInfoImpl.Companion.impl
import net.mamoe.mirai.internal.contact.info.MemberInfoImpl
import net.mamoe.mirai.internal.contact.info.StrangerInfoImpl.Companion.impl
import net.mamoe.mirai.internal.message.*
import net.mamoe.mirai.internal.message.DeepMessageRefiner.refineDeep
import net.mamoe.mirai.internal.network.components.EventDispatcher
import net.mamoe.mirai.internal.network.components.EventDispatcherScopeFlag
import net.mamoe.mirai.internal.network.highway.ChannelKind
import net.mamoe.mirai.internal.network.highway.ResourceKind
import net.mamoe.mirai.internal.network.highway.tryDownload
import net.mamoe.mirai.internal.network.highway.tryServersDownload
import net.mamoe.mirai.internal.network.protocol.data.jce.SvcDevLoginInfo
import net.mamoe.mirai.internal.network.protocol.data.proto.ImMsgBody
import net.mamoe.mirai.internal.network.protocol.data.proto.LongMsg
import net.mamoe.mirai.internal.network.protocol.data.proto.MsgComm
import net.mamoe.mirai.internal.network.protocol.data.proto.MsgTransmit
import net.mamoe.mirai.internal.network.protocol.packet.chat.MultiMsg
import net.mamoe.mirai.internal.network.protocol.packet.chat.NewContact
import net.mamoe.mirai.internal.network.protocol.packet.chat.NudgePacket
import net.mamoe.mirai.internal.network.protocol.packet.chat.PbMessageSvc
import net.mamoe.mirai.internal.network.protocol.packet.chat.voice.PttStore
import net.mamoe.mirai.internal.network.protocol.packet.list.FriendList
import net.mamoe.mirai.internal.network.protocol.packet.login.StatSvc
import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
import net.mamoe.mirai.internal.network.protocol.packet.summarycard.SummaryCard
import net.mamoe.mirai.internal.network.psKey
import net.mamoe.mirai.internal.network.sKey
import net.mamoe.mirai.internal.utils.ImagePatcher
import net.mamoe.mirai.internal.utils.MiraiProtocolInternal
import net.mamoe.mirai.internal.utils.crypto.TEA
import net.mamoe.mirai.internal.utils.io.serialization.loadAs
import net.mamoe.mirai.message.MessageSerializers
import net.mamoe.mirai.message.action.Nudge
import net.mamoe.mirai.message.data.*
import net.mamoe.mirai.utils.*
internal fun getMiraiImpl() = Mirai as MiraiImpl
@OptIn(LowLevelApi::class)
// not object for ServiceLoader.
internal open class MiraiImpl : IMirai, LowLevelApiAccessor {
companion object INSTANCE : MiraiImpl() {
@Suppress("ObjectPropertyName", "unused", "DEPRECATION_ERROR")
private val _init = Mirai.let {
MessageSerializers.registerSerializer(OfflineGroupImage::class, OfflineGroupImage.serializer())
MessageSerializers.registerSerializer(OfflineFriendImage::class, OfflineFriendImage.serializer())
MessageSerializers.registerSerializer(OnlineFriendImageImpl::class, OnlineFriendImageImpl.serializer())
MessageSerializers.registerSerializer(OnlineGroupImageImpl::class, OnlineGroupImageImpl.serializer())
MessageSerializers.registerSerializer(MarketFaceImpl::class, MarketFaceImpl.serializer())
MessageSerializers.registerSerializer(FileMessageImpl::class, FileMessageImpl.serializer())
// MessageSource
MessageSerializers.registerSerializer(
OnlineMessageSourceFromGroupImpl::class,
OnlineMessageSourceFromGroupImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceFromFriendImpl::class,
OnlineMessageSourceFromFriendImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceFromTempImpl::class,
OnlineMessageSourceFromTempImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceFromStrangerImpl::class,
OnlineMessageSourceFromStrangerImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceToGroupImpl::class,
OnlineMessageSourceToGroupImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceToFriendImpl::class,
OnlineMessageSourceToFriendImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceToTempImpl::class,
OnlineMessageSourceToTempImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineMessageSourceToStrangerImpl::class,
OnlineMessageSourceToStrangerImpl.serializer()
)
MessageSerializers.registerSerializer(
OfflineMessageSourceImplData::class,
OfflineMessageSourceImplData.serializer()
)
MessageSerializers.registerSerializer(
OfflineMessageSourceImplData::class,
OfflineMessageSourceImplData.serializer()
)
MessageSerializers.registerSerializer(
UnsupportedMessageImpl::class,
UnsupportedMessageImpl.serializer()
)
MessageSerializers.registerSerializer(
OnlineAudioImpl::class,
OnlineAudioImpl.serializer()
)
MessageSerializers.registerSerializer(
OfflineAudioImpl::class,
OfflineAudioImpl.serializer()
)
}
}
@Suppress("DEPRECATION")
override val BotFactory: BotFactory
get() = BotFactoryImpl
override var FileCacheStrategy: FileCacheStrategy = net.mamoe.mirai.utils.FileCacheStrategy.PlatformDefault
override var Http: HttpClient = HttpClient(OkHttp) {
install(HttpTimeout) {
this.requestTimeoutMillis = 30_0000
this.connectTimeoutMillis = 30_0000
this.socketTimeoutMillis = 30_0000
}
}
@OptIn(LowLevelApi::class)
override suspend fun acceptNewFriendRequest(event: NewFriendRequestEvent) {
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
check(event.responded.compareAndSet(false, true)) {
"the request $this has already been responded"
}
check(!event.bot.friends.contains(event.fromId)) {
"the request $event is outdated: You had already responded it on another device."
}
solveNewFriendRequestEvent(
event.bot,
eventId = event.eventId,
fromId = event.fromId,
fromNick = event.fromNick,
accept = true,
blackList = false
)
event.bot.getFriend(event.fromId)?.let { friend ->
FriendAddEvent(friend).broadcast()
}
}
override suspend fun refreshKeys(bot: Bot) {
// TODO: 2021/4/14 MiraiImpl.refreshKeysNow
}
override suspend fun rejectNewFriendRequest(event: NewFriendRequestEvent, blackList: Boolean) {
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
check(event.responded.compareAndSet(false, true)) {
"the request $event has already been responded"
}
check(!event.bot.friends.contains(event.fromId)) {
"the request $event is outdated: You had already responded it on another device."
}
solveNewFriendRequestEvent(
event.bot,
eventId = event.eventId,
fromId = event.fromId,
fromNick = event.fromNick,
accept = false,
blackList = blackList
)
}
override suspend fun acceptMemberJoinRequest(event: MemberJoinRequestEvent) {
@Suppress("DuplicatedCode")
checkGroupPermission(event.bot, event.groupId) { event::class.simpleName ?: "<anonymous class>" }
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
check(event.responded.compareAndSet(false, true)) {
"the request $this has already been responded"
}
if (event.group?.contains(event.fromId) == true) return
solveMemberJoinRequestEvent(
bot = event.bot,
eventId = event.eventId,
fromId = event.fromId,
fromNick = event.fromNick,
groupId = event.groupId,
accept = true,
blackList = false
)
}
@Suppress("DuplicatedCode")
override suspend fun rejectMemberJoinRequest(event: MemberJoinRequestEvent, blackList: Boolean, message: String) {
checkGroupPermission(event.bot, event.groupId) { event::class.simpleName ?: "<anonymous class>" }
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
check(event.responded.compareAndSet(false, true)) {
"the request $this has already been responded"
}
if (event.group?.contains(event.fromId) == true) return
solveMemberJoinRequestEvent(
bot = event.bot,
eventId = event.eventId,
fromId = event.fromId,
fromNick = event.fromNick,
groupId = event.groupId,
accept = false,
blackList = blackList,
message = message
)
}
private inline fun checkGroupPermission(eventBot: Bot, groupId: Long, eventName: () -> String) {
val group = eventBot.getGroup(groupId)
?: kotlin.run {
error(
"A ${eventName()} is outdated. Group $groupId not found for bot ${eventBot.id}. " +
"This is because bot isn't in the group anymore"
)
}
group.checkBotPermission(MemberPermission.ADMINISTRATOR)
}
override suspend fun getOnlineOtherClientsList(bot: Bot, mayIncludeSelf: Boolean): List<OtherClientInfo> {
bot.asQQAndroidBot()
val response = bot.network.run {
StatSvc.GetDevLoginInfo(bot.client).sendAndExpect()
}
fun SvcDevLoginInfo.toOtherClientInfo() = OtherClientInfo(
iAppId.toInt(),
Platform.getByTerminalId(iTerType?.toInt() ?: 0),
deviceName.orEmpty(),
deviceTypeInfo.orEmpty()
)
return response.deviceList.map { it.toOtherClientInfo() }.let { result ->
if (mayIncludeSelf) result else result.filterNot {
it.appId == MiraiProtocolInternal[bot.configuration.protocol].id.toInt()
}
}
}
override suspend fun ignoreMemberJoinRequest(event: MemberJoinRequestEvent, blackList: Boolean) {
checkGroupPermission(event.bot, event.groupId) { event::class.simpleName ?: "<anonymous class>" }
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
check(event.responded.compareAndSet(false, true)) {
"the request $this has already been responded"
}
solveMemberJoinRequestEvent(
bot = event.bot,
eventId = event.eventId,
fromId = event.fromId,
fromNick = event.fromNick,
groupId = event.groupId,
accept = null,
blackList = blackList
)
}
override suspend fun acceptInvitedJoinGroupRequest(event: BotInvitedJoinGroupRequestEvent) =
solveInvitedJoinGroupRequest(event, accept = true)
override suspend fun ignoreInvitedJoinGroupRequest(event: BotInvitedJoinGroupRequestEvent) =
solveInvitedJoinGroupRequest(event, accept = false)
override suspend fun broadcastEvent(event: Event) {
if (currentCoroutineContext()[EventDispatcherScopeFlag] != null) {
// called by [EventDispatcher]
return super.broadcastEvent(event)
}
if (event is BotEvent) {
val bot = event.bot
if (bot is AbstractBot) {
bot.components[EventDispatcher].broadcast(event)
}
} else {
super.broadcastEvent(event)
}
}
private suspend fun solveInvitedJoinGroupRequest(event: BotInvitedJoinGroupRequestEvent, accept: Boolean) {
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
check(event.responded.compareAndSet(false, true)) {
"the request $this has already been responded"
}
check(!event.bot.groups.contains(event.groupId)) {
"the request $this is outdated: Bot has been already in the group."
}
solveBotInvitedJoinGroupRequestEvent(
bot = event.bot,
eventId = event.eventId,
invitorId = event.invitorId,
groupId = event.groupId,
accept = accept
)
}
@LowLevelApi
override fun newFriend(bot: Bot, friendInfo: FriendInfo): FriendImpl {
return FriendImpl(
bot.asQQAndroidBot(),
bot.coroutineContext,
friendInfo.impl(),
)
}
@LowLevelApi
override fun newStranger(bot: Bot, strangerInfo: StrangerInfo): StrangerImpl {
return StrangerImpl(
bot.asQQAndroidBot(),
bot.coroutineContext,
strangerInfo.impl(),
)
}
@OptIn(LowLevelApi::class)
override suspend fun getRawGroupList(bot: Bot): Sequence<Long> {
bot.asQQAndroidBot()
return bot.network.run {
FriendList.GetTroopListSimplify(bot.client).sendAndExpect(retry = 2)
}.groups.asSequence().map { it.groupUin.shl(32) and it.groupCode }
}
@OptIn(LowLevelApi::class)
override suspend fun getRawGroupMemberList(
bot: Bot,
groupUin: Long,
groupCode: Long,
ownerId: Long
): Sequence<MemberInfo> =
bot.asQQAndroidBot().network.run {
var nextUin = 0L
var sequence = sequenceOf<MemberInfoImpl>()
while (true) {
val data = FriendList.GetTroopMemberList(
client = bot.client,
targetGroupUin = groupUin,
targetGroupCode = groupCode,
nextUin = nextUin
).sendAndExpect(retry = 3)
sequence += data.members.asSequence().map { troopMemberInfo ->
MemberInfoImpl(bot.client, troopMemberInfo, ownerId)
}
nextUin = data.nextUin
if (nextUin == 0L) {
break
}
}
return sequence
}
override suspend fun recallGroupMessageRaw(
bot: Bot,
groupCode: Long,
messageIds: IntArray,
messageInternalIds: IntArray,
): Boolean = bot.asQQAndroidBot().run {
val response = network.run {
PbMessageSvc.PbMsgWithDraw.createForGroupMessage(
client,
groupCode,
messageIds,
messageInternalIds
).sendAndExpect()
}
response is PbMessageSvc.PbMsgWithDraw.Response.Success
}
override suspend fun recallFriendMessageRaw(
bot: Bot,
targetId: Long,
messageIds: IntArray,
messageInternalIds: IntArray,
time: Int,
): Boolean = bot.asQQAndroidBot().run {
val response = network.run {
PbMessageSvc.PbMsgWithDraw.createForFriendMessage(
client,
targetId,
messageIds,
messageInternalIds,
time,
).sendAndExpect()
}
response is PbMessageSvc.PbMsgWithDraw.Response.Success
}
override suspend fun recallGroupTempMessageRaw(
bot: Bot,
groupUin: Long,
targetId: Long,
messageIds: IntArray,
messageInternalIds: IntArray,
time: Int
): Boolean = bot.asQQAndroidBot().run {
val response = network.run {
PbMessageSvc.PbMsgWithDraw.createForGroupTempMessage(
client,
groupUin,
targetId,
messageIds,
messageInternalIds,
time,
).sendAndExpect()
}
response is PbMessageSvc.PbMsgWithDraw.Response.Success
}
@Suppress("RemoveExplicitTypeArguments") // false positive
override suspend fun recallMessage(bot: Bot, source: MessageSource) = bot.asQQAndroidBot().run {
check(source is MessageSourceInternal)
source.ensureSequenceIdAvailable()
@Suppress("BooleanLiteralArgument", "INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") // false positive
check(!source.isRecalledOrPlanned.get() && source.isRecalledOrPlanned.compareAndSet(false, true)) {
"$source had already been recalled."
}
val response: PbMessageSvc.PbMsgWithDraw.Response = when (source) {
is OnlineMessageSourceToGroupImpl,
is OnlineMessageSourceFromGroupImpl
-> {
val group: Group = when (source) {
is OnlineMessageSourceToGroupImpl -> source.subject
is OnlineMessageSourceFromGroupImpl -> source.subject
else -> error("stub")
}
if (bot.id != source.fromId) {
// if member leave, messageSource will throw exception(#1661)
when (group[source.fromId]?.permission ?: MemberPermission.MEMBER) {
MemberPermission.MEMBER -> group.checkBotPermission(MemberPermission.ADMINISTRATOR)
MemberPermission.ADMINISTRATOR -> group.checkBotPermission(MemberPermission.OWNER)
// bot cannot be owner
MemberPermission.OWNER -> throw PermissionDeniedException("Permission denied: cannot recall message from owner")
}
}
network.run {
PbMessageSvc.PbMsgWithDraw.createForGroupMessage(
bot.asQQAndroidBot().client,
group.id,
source.sequenceIds,
source.internalIds
).sendAndExpect()
}
}
is OnlineMessageSourceFromFriendImpl,
is OnlineMessageSourceToFriendImpl,
is OnlineMessageSourceFromStrangerImpl,
is OnlineMessageSourceToStrangerImpl,
-> network.run {
check(source.fromId == bot.id) {
"can only recall a message sent by bot"
}
PbMessageSvc.PbMsgWithDraw.createForFriendMessage(
bot.client,
source.targetId,
source.sequenceIds,
source.internalIds,
source.time
).sendAndExpect<PbMessageSvc.PbMsgWithDraw.Response>()
}
is OnlineMessageSourceFromTempImpl,
is OnlineMessageSourceToTempImpl
-> network.run {
check(source.fromId == bot.id) {
"can only recall a message sent by bot"
}
source as OnlineMessageSourceToTempImpl
PbMessageSvc.PbMsgWithDraw.createForGroupTempMessage(
bot.client,
(source.target.group as GroupImpl).uin,
source.targetId,
source.sequenceIds,
source.internalIds,
source.time
).sendAndExpect<PbMessageSvc.PbMsgWithDraw.Response>()
}
is OfflineMessageSource -> network.run {
when (source.kind) {
MessageSourceKind.FRIEND, MessageSourceKind.STRANGER -> {
check(source.fromId == bot.id) {
"can only recall a message sent by bot"
}
PbMessageSvc.PbMsgWithDraw.createForFriendMessage(
bot.client,
source.targetId,
source.sequenceIds,
source.internalIds,
source.time
).sendAndExpect<PbMessageSvc.PbMsgWithDraw.Response>()
}
MessageSourceKind.TEMP -> {
check(source.fromId == bot.id) {
"can only recall a message sent by bot"
}
PbMessageSvc.PbMsgWithDraw.createForGroupTempMessage(
bot.client,
source.targetId, // groupUin
source.targetId, // memberUin
source.sequenceIds,
source.internalIds,
source.time
).sendAndExpect<PbMessageSvc.PbMsgWithDraw.Response>()
}
MessageSourceKind.GROUP -> {
PbMessageSvc.PbMsgWithDraw.createForGroupMessage(
bot.client,
source.targetId,
source.sequenceIds,
source.internalIds
).sendAndExpect<PbMessageSvc.PbMsgWithDraw.Response>()
}
}
}
else -> error("stub!")
}
// 1001: No message meets the requirements (实际上是没权限, 管理员在尝试撤回群主的消息)
// 154: timeout
// 3: <no message>
check(response is PbMessageSvc.PbMsgWithDraw.Response.Success) { "Failed to recall message #${source.ids.contentToString()}: $response" }
}
private val json = Json {
isLenient = true
ignoreUnknownKeys = true
}
@LowLevelApi
@MiraiExperimentalApi
override suspend fun getRawGroupActiveData(bot: Bot, groupId: Long, page: Int): GroupActiveData =
bot.asQQAndroidBot().run {
val rep = network.run {
Mirai.Http.get<String> {
url("https://qqweb.qq.com/c/activedata/get_mygroup_data")
parameter("bkn", client.wLoginSigInfo.bkn)
parameter("gc", groupId)
if (page != -1) {
parameter("page", page)
}
headers {
@OptIn(InternalAPI::class) // ktor bug
append(
"cookie",
"uin=o${bot.id}; skey=${bot.sKey}; p_uin=o${bot.id}; p_skey=${bot.psKey("qqweb.qq.com")};"
)
}
}
}
return json.decodeFromString(GroupActiveData.serializer(), rep)
}
@LowLevelApi
@MiraiExperimentalApi
override suspend fun getRawGroupHonorListData(
bot: Bot,
groupId: Long,
type: GroupHonorType
): GroupHonorListData? = bot.asQQAndroidBot().run {
val rep = network.run {
Mirai.Http.get<String> {
url("https://qun.qq.com/interactive/honorlist")
parameter("gc", groupId)
parameter("type", type.value)
headers {
@OptIn(InternalAPI::class) // ktor bug
append(
"cookie",
"uin=o${bot.id};" +
" skey=${bot.sKey};" +
" p_uin=o${bot.id};" +
" p_skey=${bot.psKey("qun.qq.com")}; "
)
}
}
}
val jsonText = Regex("""window.__INITIAL_STATE__=(.+?)</script>""").find(rep)?.groupValues?.get(1)
return jsonText?.let { json.decodeFromString(GroupHonorListData.serializer(), it) }
}
internal open suspend fun uploadMessageHighway(
bot: Bot,
sendMessageHandler: SendMessageHandler<*>,
message: Collection<ForwardMessage.INode>,
isLong: Boolean,
): String {
bot.asQQAndroidBot()
message.forEach {
it.messageChain.ensureSequenceIdAvailable()
}
val uploader = MultiMsgUploader(
client = bot.client,
isLong = isLong,
handler = sendMessageHandler,
).also { it.emitMain(message) }
return uploader.uploadAndReturnResId()
}
override suspend fun solveNewFriendRequestEvent(
bot: Bot,
eventId: Long,
fromId: Long,
fromNick: String,
accept: Boolean,
blackList: Boolean
): Unit = bot.asQQAndroidBot().run {
network.apply {
NewContact.SystemMsgNewFriend.Action(
bot.client,
eventId = eventId,
fromId = fromId,
accept = accept,
blackList = blackList
).sendWithoutExpect()
if (!accept) return@apply
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
bot.friends.delegate.add(newFriend(bot, FriendInfoImpl(fromId, fromNick, "")))
}
}
override suspend fun solveBotInvitedJoinGroupRequestEvent(
bot: Bot,
eventId: Long,
invitorId: Long,
groupId: Long,
accept: Boolean
) = bot.asQQAndroidBot().run {
network.run {
NewContact.SystemMsgNewGroup.Action(
bot.client,
eventId = eventId,
fromId = invitorId,
groupId = groupId,
isInvited = true,
accept = accept
).sendWithoutExpect()
}
}
override suspend fun solveMemberJoinRequestEvent(
bot: Bot,
eventId: Long,
fromId: Long,
fromNick: String,
groupId: Long,
accept: Boolean?,
blackList: Boolean,
message: String
) = bot.asQQAndroidBot().run {
network.run {
NewContact.SystemMsgNewGroup.Action(
bot.client,
eventId = eventId,
fromId = fromId,
groupId = groupId,
isInvited = false,
accept = accept,
blackList = blackList,
message = message
).sendWithoutExpect()
}
// Add member in MsgOnlinePush.PbPushMsg
}
@OptIn(ExperimentalStdlibApi::class)
@LowLevelApi
override suspend fun getGroupVoiceDownloadUrl(
bot: Bot,
md5: ByteArray,
groupId: Long,
dstUin: Long
): String {
bot.asQQAndroidBot().network.run {
val response = PttStore.GroupPttDown(bot.client, groupId, dstUin, md5).sendAndExpect()
return "http://${response.strDomain}${response.downPara.decodeToString()}"
}
}
override suspend fun muteAnonymousMember(
bot: Bot,
anonymousId: String,
anonymousNick: String,
groupId: Long,
seconds: Int
) {
bot as QQAndroidBot
val response = Mirai.Http.post<String> {
url("https://qqweb.qq.com/c/anonymoustalk/blacklist")
body = MultiPartFormDataContent(formData {
append("anony_id", anonymousId)
append("group_code", groupId)
append("seconds", seconds)
append("anony_nick", anonymousNick)
append("bkn", bot.client.wLoginSigInfo.bkn)
})
headers {
@OptIn(InternalAPI::class) // ktor bug
append(
"cookie",
"uin=o${bot.id}; skey=${bot.sKey};"
)
}
}
val jsonObj = Json.decodeFromString(JsonObject.serializer(), response)
if ((jsonObj["retcode"] ?: jsonObj["cgicode"] ?: error("missing response code")).jsonPrimitive.long != 0L) {
throw IllegalStateException(response)
}
}
override fun createFileMessage(id: String, internalId: Int, name: String, size: Long): FileMessage {
return FileMessageImpl(id, internalId, name, size)
}
override fun createUnsupportedMessage(struct: ByteArray): UnsupportedMessage =
UnsupportedMessageImpl(struct.loadAs(ImMsgBody.Elem.serializer()))
@Suppress("DEPRECATION", "OverridingDeprecatedMember")
override suspend fun queryImageUrl(bot: Bot, image: Image): String = when (image) {
is ConstOriginUrlAware -> image.originUrl
is DeferredOriginUrlAware -> image.getUrl(bot)
is SuspendDeferredOriginUrlAware -> image.getUrl(bot)
else -> error("Internal error: unsupported image class: ${image::class.simpleName}")
}
override suspend fun queryProfile(bot: Bot, targetId: Long): UserProfile {
bot.asQQAndroidBot().network.apply {
return SummaryCard.ReqSummaryCard(bot.client, targetId)
.sendAndExpect()
}
}
override suspend fun sendNudge(bot: Bot, nudge: Nudge, receiver: Contact): Boolean {
if ((bot.configuration.protocol != BotConfiguration.MiraiProtocol.ANDROID_PHONE) && (bot.configuration.protocol != BotConfiguration.MiraiProtocol.IPAD)) {
throw UnsupportedOperationException("nudge is supported only with protocol ANDROID_PHONE or IPAD")
}
bot.asQQAndroidBot()
bot.network.run {
return if (receiver is Group) {
receiver.checkIsGroupImpl()
NudgePacket.troopInvoke(
client = bot.client,
messageReceiverGroupCode = receiver.id,
nudgeTargetId = nudge.target.id,
).sendAndExpect<NudgePacket.Response>().success
} else {
NudgePacket.friendInvoke(
client = bot.client,
messageReceiverUin = receiver.id,
nudgeTargetId = nudge.target.id,
).sendAndExpect<NudgePacket.Response>().success
}
}
}
override fun getUin(contactOrBot: ContactOrBot): Long {
return when (contactOrBot) {
is Group -> contactOrBot.uin
is User -> contactOrBot.uin
is Bot -> contactOrBot.uin
else -> contactOrBot.id
}
}
override fun constructMessageSource(
botId: Long,
kind: MessageSourceKind,
fromId: Long,
targetId: Long,
ids: IntArray,
time: Int,
internalIds: IntArray,
originalMessage: MessageChain
): OfflineMessageSource = OfflineMessageSourceImplData(
kind, ids, botId, time, fromId, targetId, originalMessage, internalIds
)
override suspend fun downloadLongMessage(bot: Bot, resourceId: String): MessageChain {
try {
return downloadMultiMsgTransmit(bot, resourceId, ResourceKind.LONG_MESSAGE).msg
.toMessageChainNoSource(bot, 0, MessageSourceKind.GROUP)
.refineDeep(bot)
} catch (error: Throwable) {
throw IllegalStateException("Failed to download long message `$resourceId`", error)
}
}
override suspend fun downloadForwardMessage(bot: Bot, resourceId: String): List<ForwardMessage.Node> {
try {
return downloadMultiMsgTransmit(bot, resourceId, ResourceKind.FORWARD_MESSAGE).toForwardMessageNodes(bot)
} catch (error: Throwable) {
throw IllegalStateException("Failed to download forward message `$resourceId`", error)
}
}
internal open suspend fun MsgTransmit.PbMultiMsgNew.toForwardMessageNodes(
bot: Bot,
context: RefineContext
): List<ForwardMessage.Node> {
return msg.map { it.toNode(bot, context) }
}
internal open suspend fun MsgTransmit.PbMultiMsgTransmit.toForwardMessageNodes(bot: Bot): List<ForwardMessage.Node> {
val pbs = this.pbItemList.associate {
it.fileName to it.buffer.loadAs(MsgTransmit.PbMultiMsgNew.serializer())
}
val main = pbs["MultiMsg"] ?: return this.msg.map { it.toNode(bot, EmptyRefineContext) }
val context = SimpleRefineContext(mutableMapOf())
context[ForwardMessageInternal.MsgTransmits] = pbs
return main.toForwardMessageNodes(bot, context)
}
protected open suspend fun MsgComm.Msg.toNode(bot: Bot, refineContext: RefineContext): ForwardMessage.Node {
val msg = this
return ForwardMessage.Node(
senderId = msg.msgHead.fromUin,
time = msg.msgHead.msgTime,
senderName = msg.msgHead.groupInfo?.groupCard
?: msg.msgHead.fromNick.takeIf { it.isNotEmpty() }
?: msg.msgHead.fromUin.toString(),
messageChain = listOf(msg)
.toMessageChainNoSource(bot, 0, MessageSourceKind.GROUP)
.refineDeep(bot, refineContext)
)
}
private suspend fun downloadMultiMsgTransmit(
bot: Bot,
resourceId: String,
resourceKind: ResourceKind,
): MsgTransmit.PbMultiMsgTransmit {
bot.asQQAndroidBot()
when (val resp = MultiMsg.ApplyDown(bot.client, 2, resourceId, 1).sendAndExpect(bot)) {
is MultiMsg.ApplyDown.Response.RequireDownload -> {
val http = Mirai.Http
val origin = resp.origin
val data: ByteArray = if (origin.msgExternInfo?.channelType == 2) {
tryDownload(
bot = bot,
host = "https://ssl.htdata.qq.com",
port = 443,
times = 3,
resourceKind = resourceKind,
channelKind = ChannelKind.HTTP
) { host, _ ->
http.get("$host${origin.thumbDownPara}")
}
} else tryServersDownload(
bot = bot,
servers = origin.uint32DownIp.zip(origin.uint32DownPort),
resourceKind = resourceKind,
channelKind = ChannelKind.HTTP
) { ip, port ->
http.get("http://$ip:$port${origin.thumbDownPara}")
}
val body = data.read {
check(readByte() == 40.toByte()) {
"bad data while MultiMsg.ApplyDown: ${data.toUHexString()}"
}
val headLength = readInt()
val bodyLength = readInt()
discardExact(headLength)
readBytes(bodyLength)
}
val decrypted = TEA.decrypt(body, origin.msgKey)
val longResp =
decrypted.loadAs(LongMsg.RspBody.serializer())
val down = longResp.msgDownRsp.single()
check(down.result == 0) {
"Message download failed, result=${down.result}, resId=${down.msgResid.decodeToString()}, msgContent=${down.msgContent.toUHexString()}"
}
val content = down.msgContent.ungzip()
return content.loadAs(MsgTransmit.PbMultiMsgTransmit.serializer())
}
MultiMsg.ApplyDown.Response.MessageTooLarge -> {
error("Message is too large and cannot download")
}
}
}
}