diff --git a/src/main/kotlin/me/kuku/telegram/context/Context.kt b/src/main/kotlin/me/kuku/telegram/context/Context.kt index 8388088..472799c 100644 --- a/src/main/kotlin/me/kuku/telegram/context/Context.kt +++ b/src/main/kotlin/me/kuku/telegram/context/Context.kt @@ -88,7 +88,6 @@ private val callbackAfter by lazy { CacheManager.getCache("callbackAfter", Duration.ofMinutes(5)) } -@Suppress("ConstPropertyName") private data class History(var message: Message?, var data: String, var text: String? = null): Serializable { companion object { private const val serialVersionUID = 1L diff --git a/src/main/kotlin/me/kuku/telegram/entity/AliDriveEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/AliDriveEntity.kt deleted file mode 100644 index 87d9ccc..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/AliDriveEntity.kt +++ /dev/null @@ -1,71 +0,0 @@ -package me.kuku.telegram.entity - -import kotlinx.coroutines.flow.toList -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service - -@Document("ali_driver") -class AliDriveEntity: BaseEntity() { - @Id - var id: String? = null - var refreshToken: String = "" - var deviceId: String = "" - var backupDeviceId: String = "" - var backupDesktopDeviceId: String = "" - var sign: Status = Status.OFF - var receive: Status = Status.OFF - var task: Status = Status.OFF - var receiveTask: Status = Status.OFF - var deviceRoom: Status = Status.OFF - var card: Status = Status.OFF - - var uploads: MutableList = mutableListOf() - data class Upload(val driveId: Int, val fileId: String) -} - -interface AliDriveRepository: CoroutineCrudRepository { - - suspend fun findByTgIdAndTgName(tgId: Long, tgName: String?): AliDriveEntity? - - suspend fun deleteByTgIdAndTgName(tgId: Long, tgName: String?) - - suspend fun findBySign(sign: Status): List - - suspend fun findByTask(task: Status): List - - suspend fun findByReceiveTask(task: Status): List - - suspend fun findByDeviceRoom(deviceRoom: Status): List - - suspend fun findByCard(card: Status): List -} - -@Service -class AliDriveService( - private val aliDriveRepository: AliDriveRepository -) { - - suspend fun findByTgId(tgId: Long) = aliDriveRepository.findEnableEntityByTgId(tgId) as? AliDriveEntity - - suspend fun findBySign(sign: Status) = aliDriveRepository.findBySign(sign) - - suspend fun save(aliDriveEntity: AliDriveEntity): AliDriveEntity = aliDriveRepository.save(aliDriveEntity) - - suspend fun delete(aliDriveEntity: AliDriveEntity) = aliDriveRepository.delete(aliDriveEntity) - - suspend fun deleteByTgId(tgId: Long) = aliDriveRepository.deleteEnableEntityByTgId(tgId) - - suspend fun findByTask(task: Status) = aliDriveRepository.findByTask(task) - - suspend fun findByReceiveTask(task: Status) = aliDriveRepository.findByReceiveTask(task) - - suspend fun findAll() = aliDriveRepository.findAll().toList() - - suspend fun findById(id: String) = aliDriveRepository.findById(id) - - suspend fun findByDeviceRoom(deviceRoom: Status) = aliDriveRepository.findByDeviceRoom(deviceRoom) - - suspend fun findByCard(card: Status) = aliDriveRepository.findByCard(card) -} diff --git a/src/main/kotlin/me/kuku/telegram/entity/GlaDosEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/GlaDosEntity.kt deleted file mode 100644 index 9799240..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/GlaDosEntity.kt +++ /dev/null @@ -1,39 +0,0 @@ -package me.kuku.telegram.entity - -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service - -@Document("glo_dos") -class GlaDosEntity: BaseEntity() { - @Id - var id: String? = null - var cookie: String = "" - var sign: Status = Status.OFF -} - -interface GlaDosRepository: CoroutineCrudRepository { - - suspend fun findBySign(sign: Status): List - - suspend fun findByTgIdAndTgName(tgId: Long, tgName: String?): GlaDosEntity? - - suspend fun deleteByTgIdAndTgName(tgId: Long, tgName: String?) - -} - -@Service -class GlaDosService( - private val glaDosRepository: GlaDosRepository -) { - - suspend fun save(glaDosEntity: GlaDosEntity) = glaDosRepository.save(glaDosEntity) - - suspend fun findBySign(sign: Status) = glaDosRepository.findBySign(sign) - - suspend fun findByTgId(tgId: Long) = glaDosRepository.findEnableEntityByTgId(tgId) as? GlaDosEntity - - suspend fun deleteByTgId(tgId: Long) = glaDosRepository.deleteEnableEntityByTgId(tgId) - -} diff --git a/src/main/kotlin/me/kuku/telegram/entity/IqyEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/IqyEntity.kt deleted file mode 100644 index 8a06106..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/IqyEntity.kt +++ /dev/null @@ -1,41 +0,0 @@ -package me.kuku.telegram.entity - -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service - -@Document("iqy") -class IqyEntity: BaseEntity() { - @Id - var id: String? = null - var platform: String = "" - var deviceId: String = "" - var cookie: String = "" - var authCookie: String = "" - var p00001: String = "" - var qyId: String = "" - var userid: Long = 0 - var sign: Status = Status.OFF -} - -interface IqyRepository: CoroutineCrudRepository { - suspend fun findByTgIdAndTgName(tgId: Long, tgName: String?): IqyEntity? - suspend fun findBySign(status: Status): List - suspend fun deleteByTgIdAndTgName(tgId: Long, tgName: String?) -} - -@Service -class IqyService( - private val iqyRepository: IqyRepository -) { - - suspend fun findByTgId(tgId: Long) = iqyRepository.findEnableEntityByTgId(tgId) as? IqyEntity - - suspend fun save(entity: IqyEntity) = iqyRepository.save(entity) - - suspend fun findBySign(status: Status) = iqyRepository.findBySign(status) - - suspend fun deleteByTgId(tgId: Long) = iqyRepository.deleteEnableEntityByTgId(tgId) - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt deleted file mode 100644 index a8955ef..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt +++ /dev/null @@ -1,71 +0,0 @@ -package me.kuku.telegram.entity - -import kotlinx.coroutines.flow.toList -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional - -open class NetEaseBaseEntity: BaseEntity() { - var musicU: String = "" - var csrf: String = "" - - fun cookie() = "channel=netease; __remember_me=true; MUSIC_U=$musicU; __csrf=$csrf; " - - fun pcCookie() = "os=pc; ${cookie()}" - - fun androidCookie() = "os=android; ${cookie()}" -} - -@Document("net_ease") -class NetEaseEntity: NetEaseBaseEntity() { - @Id - var id: String? = null - var sign: Status = Status.OFF - var musicianSign: Status = Status.OFF - var vipSign: Status = Status.OFF - var listen: Status = Status.OFF - - -} - -interface NetEaseRepository: CoroutineCrudRepository { - - suspend fun findByTgIdAndTgName(tgId: Long, tgName: String?): NetEaseEntity? - - suspend fun findBySign(sign: Status): List - - suspend fun findByMusicianSign(musicianSign: Status): List - - suspend fun deleteByTgIdAndTgName(tgId: Long, tgName: String?) - - suspend fun findByVipSign(status: Status): List - - suspend fun findByListen(listen: Status): List - -} - -@Service -class NetEaseService( - private val netEaseRepository: NetEaseRepository -) { - - suspend fun findByTgId(tgId: Long) = netEaseRepository.findEnableEntityByTgId(tgId) as? NetEaseEntity - - suspend fun findBySign(sign: Status): List = netEaseRepository.findBySign(sign) - - suspend fun findByMusicianSign(musicianSign: Status): List = netEaseRepository.findByMusicianSign(musicianSign) - - suspend fun save(netEaseEntity: NetEaseEntity): NetEaseEntity = netEaseRepository.save(netEaseEntity) - - suspend fun findAll(netEaseEntity: NetEaseEntity): List = netEaseRepository.findAll().toList() - - @Transactional - suspend fun deleteByTgId(tgId: Long) = netEaseRepository.deleteEnableEntityByTgId(tgId) - - suspend fun findByVipSign(status: Status) = netEaseRepository.findByVipSign(status) - - suspend fun findByListen(listen: Status) = netEaseRepository.findByListen(listen) - -} diff --git a/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt deleted file mode 100644 index 5f91b35..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt +++ /dev/null @@ -1,42 +0,0 @@ -package me.kuku.telegram.entity - -import kotlinx.coroutines.flow.toList -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service -import java.time.LocalDateTime -import java.time.temporal.ChronoUnit -import kotlin.math.absoluteValue - -@Document("net_ease_small") -class NetEaseSmallEntity: NetEaseBaseEntity() { - @Id - var id: String? = null - var username: String = "" - var password: String = "" - var status: Status = Status.OFF - var reason: String = "" - - fun oneDayAgo() = ChronoUnit.DAYS.between(LocalDateTime.now(), super.updateTime).absoluteValue >= 1 -} - -interface NetEaseSmallRepository: CoroutineCrudRepository { - suspend fun findByUsername(username: String): NetEaseSmallEntity? - suspend fun findByStatus(status: Status): List -} - -@Service -class NetEaseSmallService( - private val netEaseSmallRepository: NetEaseSmallRepository -) { - suspend fun save(netEaseSmallEntity: NetEaseSmallEntity): NetEaseSmallEntity = netEaseSmallRepository.save(netEaseSmallEntity) - - suspend fun findByUsername(username: String): NetEaseSmallEntity? = netEaseSmallRepository.findByUsername(username) - - suspend fun findAll(): List = netEaseSmallRepository.findAll().toList() - - suspend fun delete(entity: NetEaseSmallEntity) = netEaseSmallRepository.delete(entity) - - suspend fun findByStatus(status: Status) = netEaseSmallRepository.findByStatus(status) -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/entity/OtherPushEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/OtherPushEntity.kt deleted file mode 100644 index 7e84148..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/OtherPushEntity.kt +++ /dev/null @@ -1,46 +0,0 @@ -package me.kuku.telegram.entity - -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service - -@Document("other_push") -class OtherPushEntity { - @Id - var id: String? = null - var tgId: Long = 0 - var pushTypes: MutableSet = mutableSetOf() - var complex: Complex = Complex() - - enum class OtherPushType { - Email - } - - class Complex { - var receiveEmail: String = "" - } -} - -interface OtherPushRepository: CoroutineCrudRepository { - - suspend fun findByTgId(tgId: Long): OtherPushEntity? - -} - -@Service -class OtherPushService( - private val otherPushRepository: OtherPushRepository -) { - - suspend fun save(entity: OtherPushEntity) = otherPushRepository.save(entity) - - suspend fun findByTgId(tgId: Long): OtherPushEntity { - return otherPushRepository.findByTgId(tgId) ?: kotlin.run { - val addEntity = OtherPushEntity() - addEntity.tgId = tgId - otherPushRepository.save(addEntity) - } - } - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/entity/PixivEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/PixivEntity.kt deleted file mode 100644 index 95ddb1d..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/PixivEntity.kt +++ /dev/null @@ -1,42 +0,0 @@ -package me.kuku.telegram.entity - -import org.springframework.data.annotation.Id -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional - -@Document("pixiv") -class PixivEntity: BaseEntity() { - @Id - var id: String? = null - var cookie: String = "" - var push: Status = Status.OFF -} - - -interface PixivRepository: CoroutineCrudRepository { - - suspend fun findByTgIdAndTgName(tgId: Long, tgName: String?): PixivEntity? - - suspend fun findByPush(push: Status): List - - suspend fun deleteByTgIdAndTgName(tgId: Long, tgName: String?) - -} - -@Service -class PixivService( - private val pixivRepository: PixivRepository -) { - - suspend fun findByTgId(tgId: Long) = pixivRepository.findEnableEntityByTgId(tgId) as? PixivEntity - - suspend fun findByPush(push: Status): List = pixivRepository.findByPush(push) - - suspend fun save(piXivEntity: PixivEntity): PixivEntity = pixivRepository.save(piXivEntity) - - @Transactional - suspend fun deleteByTgId(tgId: Long) = pixivRepository.deleteEnableEntityByTgId(tgId) - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/entity/SwitchEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/SwitchEntity.kt index b2d139e..a45fbbe 100644 --- a/src/main/kotlin/me/kuku/telegram/entity/SwitchEntity.kt +++ b/src/main/kotlin/me/kuku/telegram/entity/SwitchEntity.kt @@ -81,10 +81,10 @@ class SwitchService( } private val clazzList = mutableListOf( - AliDriveRepository::class, BaiduRepository::class, BiliBiliRepository::class, + BaiduRepository::class, BiliBiliRepository::class, DouYuRepository::class, ECloudRepository::class, - GlaDosRepository::class, HostLocRepository::class, HuYaRepository::class, - IqyRepository::class, KuGouRepository::class, LeiShenRepository::class, - LogRepository::class, MiHoYoRepository::class, NetEaseRepository::class, - NodeSeekRepository::class, PixivRepository::class, SmZdmRepository::class, StepRepository::class, - TwitterRepository::class, WeiboRepository::class) + HostLocRepository::class, HuYaRepository::class, + KuGouRepository::class, LeiShenRepository::class, + LogRepository::class, MiHoYoRepository::class, + NodeSeekRepository::class, SmZdmRepository::class, StepRepository::class, + WeiboRepository::class) diff --git a/src/main/kotlin/me/kuku/telegram/entity/TwitterEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/TwitterEntity.kt deleted file mode 100644 index 6bed10e..0000000 --- a/src/main/kotlin/me/kuku/telegram/entity/TwitterEntity.kt +++ /dev/null @@ -1,45 +0,0 @@ -package me.kuku.telegram.entity - -import kotlinx.coroutines.flow.toList -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.repository.kotlin.CoroutineCrudRepository -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional - -@Document("twitter") -class TwitterEntity: BaseEntity() { - var id: String? = null - var tId: String = "" - var tRestId: String = "" - var cookie: String = "" - var csrf: String = "" - var push: Status = Status.OFF -} - -interface TwitterRepository: CoroutineCrudRepository { - - suspend fun findByTgIdAndTgName(tgId: Long, tgName: String?): TwitterEntity? - - suspend fun findByPush(push: Status): List - - suspend fun deleteByTgIdAndTgName(tgId: Long, tgName: String?) - -} - -@Service -class TwitterService( - private val twitterRepository: TwitterRepository -) { - - suspend fun findByTgId(tgId: Long) = twitterRepository.findEnableEntityByTgId(tgId) as? TwitterEntity - - suspend fun findAll(): List = twitterRepository.findAll().toList() - - suspend fun save(entity: TwitterEntity): TwitterEntity = twitterRepository.save(entity) - - suspend fun findByPush(push: Status): List = twitterRepository.findByPush(push) - - @Transactional - suspend fun deleteByTgId(tgId: Long) = twitterRepository.deleteEnableEntityByTgId(tgId) - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/extension/DeleteExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/DeleteExtension.kt index ef36b10..15ade4f 100644 --- a/src/main/kotlin/me/kuku/telegram/extension/DeleteExtension.kt +++ b/src/main/kotlin/me/kuku/telegram/extension/DeleteExtension.kt @@ -17,17 +17,11 @@ class DeleteExtension( private val huYaService: HuYaService, private val kuGouService: KuGouService, private val miHoYoService: MiHoYoService, - private val netEaseService: NetEaseService, private val stepService: StepService, private val weiboService: WeiboService, - private val twitterService: TwitterService, - private val pixivService: PixivService, private val smZdmService: SmZdmService, - private val aliDriveService: AliDriveService, private val leiShenService: LeiShenService, private val nodeSeekService: NodeSeekService, - private val gloDosService: GlaDosService, - private val iqyService: IqyService, private val eCloudService: ECloudService ) { @@ -39,28 +33,20 @@ class DeleteExtension( val huYaButton = InlineKeyboardButton("虎牙").callbackData("huYaDelete") val kuGouButton = InlineKeyboardButton("酷狗").callbackData("kuGouDelete") val miHoYoButton = InlineKeyboardButton("米忽悠").callbackData("miHoYoDelete") - val netEaseButton = InlineKeyboardButton("网易云音乐").callbackData("netEaseDelete") val stepButton = InlineKeyboardButton("修改步数").callbackData("stepDelete") val weiboStepButton = InlineKeyboardButton("微博").callbackData("weiboDelete") - val twitterButton = InlineKeyboardButton("twitter").callbackData("twitterDelete") - val pixivButton = InlineKeyboardButton("pixiv").callbackData("pixivDelete") val smZdmButton = inlineKeyboardButton("什么值得买", "smZdmDelete") - val aliDriveButton = inlineKeyboardButton("阿里云盘", "aliDriveDelete") val leiShenDelete = inlineKeyboardButton("雷神加速器", "leiShenDelete") val nodeSeek = inlineKeyboardButton("NodeSeek", "nodeSeekDelete") - val gloDos = inlineKeyboardButton("GloDos", "gloDosDelete") - val iqy = inlineKeyboardButton("爱奇艺", "iqyDelete") val eCloud = inlineKeyboardButton("天翼云盘", "eCloudDelete") return InlineKeyboardMarkup( arrayOf(baiduButton, biliBiliButton), arrayOf(douYuButton, hostLocButton), arrayOf(huYaButton, kuGouButton), - arrayOf(miHoYoButton, netEaseButton), + arrayOf(miHoYoButton), arrayOf(stepButton, weiboStepButton), - arrayOf(twitterButton, pixivButton), - arrayOf(smZdmButton, aliDriveButton), + arrayOf(smZdmButton), arrayOf(leiShenDelete, nodeSeek), - arrayOf(gloDos, iqy), arrayOf(eCloud) ) } @@ -100,10 +86,6 @@ class DeleteExtension( miHoYoService.deleteByTgId(tgId) editMessageText("删除米哈游成功") } - callback("netEaseDelete") { - netEaseService.deleteByTgId(tgId) - editMessageText("删除网易云音乐成功") - } callback("stepDelete") { stepService.deleteByTgId(tgId) editMessageText("删除修改步数成功") @@ -112,22 +94,10 @@ class DeleteExtension( weiboService.deleteByTgId(tgId) editMessageText("删除微博成功") } - callback("twitterDelete") { - twitterService.deleteByTgId(tgId) - editMessageText("删除Twitter成功") - } - callback("pixivDelete") { - pixivService.deleteByTgId(tgId) - editMessageText("删除Pixiv成功") - } callback("smZdmDelete") { smZdmService.deleteByTgId(tgId) editMessageText("删除什么值得买成功") } - callback("aliDriveDelete") { - aliDriveService.deleteByTgId(tgId) - editMessageText("删除阿里云盘成功") - } callback("leiShenDelete") { leiShenService.deleteByTgId(tgId) editMessageText("删除雷神加速器成功") @@ -136,14 +106,6 @@ class DeleteExtension( nodeSeekService.deleteByTgId(tgId) editMessageText("删除NodeSeek成功") } - callback("gloDosDelete") { - gloDosService.deleteByTgId(tgId) - editMessageText("删除GloDos成功") - } - callback("iqyDelete") { - iqyService.deleteByTgId(tgId) - editMessageText("删除爱奇艺成功") - } callback("eCloudDelete") { eCloudService.deleteByTgId(tgId) editMessageText("删除天翼云盘成功") diff --git a/src/main/kotlin/me/kuku/telegram/extension/ExecExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/ExecExtension.kt index ec9ccc9..0d28ecb 100644 --- a/src/main/kotlin/me/kuku/telegram/extension/ExecExtension.kt +++ b/src/main/kotlin/me/kuku/telegram/extension/ExecExtension.kt @@ -15,15 +15,11 @@ class ExecExtension( private val hostLocService: HostLocService, private val kuGouService: KuGouService, private val kuGouLogic: KuGouLogic, private val miHoYoService: MiHoYoService, private val miHoYoLogic: MiHoYoLogic, - private val netEaseService: NetEaseService, private val stepService: StepService, private val weiboService: WeiboService, private val douYuService: DouYuService, private val douYuLogic: DouYuLogic, private val smZdmService: SmZdmService, private val smZdmLogic: SmZdmLogic, - private val aliDriveService: AliDriveService, private val aliDriveLogic: AliDriveLogic, private val nodeSeekService: NodeSeekService, - private val glaDosService: GlaDosService, - private val iqyService: IqyService, private val eCloudService: ECloudService, private val eCloudLogic: ECloudLogic ) { @@ -33,24 +29,19 @@ class ExecExtension( val hostLocButton = InlineKeyboardButton("HostLoc").callbackData("hostLocExec") val kuGouButton = InlineKeyboardButton("酷狗").callbackData("kuGouExec") val miHoYoButton = InlineKeyboardButton("米哈游").callbackData("miHoYoExec") - val netEaseButton = InlineKeyboardButton("网易云音乐").callbackData("netEaseExec") val stepButton = InlineKeyboardButton("刷步数").callbackData("stepExec") val weiboButton = InlineKeyboardButton("微博").callbackData("weiboExec") val douYuButton = InlineKeyboardButton("斗鱼").callbackData("douYuExec") val smZdmButton = InlineKeyboardButton("什么值得买").callbackData("smZdmExec") - val aliDrive = inlineKeyboardButton("阿里云盘", "aliDriveExec") val nodeSeek = inlineKeyboardButton("NodeSeek", "nodeSeekExec") - val glaDos = inlineKeyboardButton("GlaDos", "glaDosExec") - val iqy = inlineKeyboardButton("爱奇艺", "iqyExec") val eCloud = inlineKeyboardButton("天翼云盘", "eCloudExec") return InlineKeyboardMarkup( arrayOf(baiduButton, biliBiliButton), arrayOf(hostLocButton, kuGouButton), - arrayOf(miHoYoButton, netEaseButton), + arrayOf(miHoYoButton), arrayOf(stepButton, weiboButton), arrayOf(douYuButton, smZdmButton), - arrayOf(aliDrive, nodeSeek), - arrayOf(glaDos, iqy), + arrayOf(nodeSeek), arrayOf(eCloud) ) } @@ -177,58 +168,6 @@ class ExecExtension( } } - fun TelegramSubscribe.netEaseExec() { - before { set(netEaseService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定网易云音乐账号")) } - callback("netEaseExec") { - val netEaseSignButton = InlineKeyboardButton("签到").callbackData("netEaseSign") - val sign1 = InlineKeyboardButton("音乐人签到(推荐任务)").callbackData("netEaseMusicianSign1") - val sign2 = inlineKeyboardButton("音乐人签到(每日任务)", "netEaseMusicianSign2") - val sign3 = inlineKeyboardButton("其他", "netEaseMusicianSign3") - val vipSign = inlineKeyboardButton("vip签到", "netEaseVipSign") - val markup = InlineKeyboardMarkup( - arrayOf(netEaseSignButton), - arrayOf(sign1), - arrayOf(sign2), - arrayOf(sign3), - arrayOf(vipSign) - ) - editMessageText("网易云音乐", markup) - } - callback("netEaseSign") { - val netEaseEntity = firstArg() - NetEaseLogic.sign(netEaseEntity) - delay(3000) - NetEaseLogic.listenMusic(netEaseEntity) - editMessageText("网易云音乐签到成功") - } - callback("netEaseMusicianSign1") { - val netEaseEntity = firstArg() - NetEaseLogic.publish(netEaseEntity) - delay(3000) -// NetEaseLogic.myMusicComment(netEaseEntity) - editMessageText("网易云音乐人推荐任务完成成功") - } - callback("netEaseMusicianSign2") { - val netEaseEntity = firstArg() - NetEaseLogic.musicianSign(netEaseEntity) - delay(3000) - NetEaseLogic.publishAndShareMySongAndComment(netEaseEntity) - editMessageText("网易云音乐人每日任务完成成功") - } - callback("netEaseMusicianSign3") { - val netEaseEntity = firstArg() - NetEaseLogic.publishMLog(netEaseEntity) - delay(3000) - NetEaseLogic.publishMLog(netEaseEntity) - editMessageText("网易云音乐执行成功") - } - callback("netEaseVipSign") { - NetEaseLogic.vipSign(firstArg()) - NetEaseLogic.receiveTaskReward(firstArg()) - editMessageText("网易云音乐vip签到成功") - } - } - fun TelegramSubscribe.stepExec() { before { set(stepService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定任何刷步数账号")) } callback("stepExec") { @@ -300,74 +239,6 @@ class ExecExtension( } } - fun TelegramSubscribe.aliDrive() { - before { set(aliDriveService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定阿里云盘账号")) } - callback("aliDriveExec") { - val signButton = inlineKeyboardButton("签到", "aliDriveSign") - val receive = inlineKeyboardButton("领取", "aliDriveReceive") - val task = inlineKeyboardButton("完成任务", "aliDriveTask") - val receiveTask = inlineKeyboardButton("领取任务奖励", "aliDriveReceiveTask") - val deviceRoom = inlineKeyboardButton("时光设备间", "aliDriveDeviceRoom") - val card = inlineKeyboardButton("领取补签卡", "aliDriveCard") - val inlineKeyboardMarkup = InlineKeyboardMarkup( - arrayOf(signButton), arrayOf(receive), arrayOf(task), arrayOf(receiveTask), arrayOf(deviceRoom), - arrayOf(card) - ) - editMessageText(""" - 阿里云盘 - 完成任务会在你的云盘上上传图片、视频、新建文件夹等,介意勿用 - 完成任务如出现device offline错误,请找到阿里云盘的登录设备管理,下线一些设备即可 - """.trimIndent(), inlineKeyboardMarkup) - } - callback("aliDriveSign") { - val entity: AliDriveEntity = firstArg() - val res = aliDriveLogic.sign(entity) - editMessageText(res.customMessage) - } - callback("aliDriveReceive") { - editMessageText("请发送领取哪天的奖励") - val day = nextMessage().text().toIntOrNull() ?: error("错误,不为数字") - val result = aliDriveLogic.receive(firstArg(), day) - editMessageText(result) - } - callback("aliDriveTask") { - editMessageText("完成阿里云盘每日任务,程序正在后台为您完成任务,任务完成时间会很长") - kotlin.runCatching { - aliDriveLogic.finishTask(firstArg()) - sendMessage("#手动执行结果\n阿里云盘完成任务成功") - }.onFailure { - sendMessage("#手动执行结果\n阿里云盘完成任务失败,失败原因:${it.message}") - } - } - callback("aliDriveReceiveTask") { - editMessageText("请发送领取哪天的奖励") - val day = nextMessage().text().toIntOrNull() ?: error("错误,不为数字") - aliDriveLogic.signInInfo(firstArg()) - val result = aliDriveLogic.receiveTask(firstArg(), day) - editMessageText(result) - } - callback("aliDriveDeviceRoom") { - editMessageText("完成阿里云盘时光设备间,程序正在后台为您完成任务,任务完成时间会很长") - kotlin.runCatching { - aliDriveLogic.finishDeviceRoom(firstArg()) - sendMessage("#手动执行结果\n阿里云盘完成时光设备间成功") - }.onFailure { - sendMessage("#手动执行结果\n阿里云盘完成时光设备间失败,失败原因:${it.message}") - } - } - callback("aliDriveCard") { - editMessageText("领取阿里云盘补签卡,程序正在后台为您完成任务,任务完成时间会很长") - kotlin.runCatching { - aliDriveLogic.finishCard(firstArg()) - delay(3000) - aliDriveLogic.receiveCard(firstArg()) - sendMessage("#手动执行结果\n阿里云盘领取补签卡成功") - }.onFailure { - sendMessage("#手动执行结果\n阿里云盘领取补签卡失败,失败原因:${it.message}") - } - } - } - fun TelegramSubscribe.nodeSeekExec() { before { set(nodeSeekService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定NodeSeek账号")) } callback("nodeSeekExec") { @@ -392,41 +263,6 @@ class ExecExtension( } } - fun TelegramSubscribe.glaDosExec() { - before { set(glaDosService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定GlaDos账号")) } - callback("glaDosExec") { - editMessageText("GlaDos", InlineKeyboardMarkup( - arrayOf( - inlineKeyboardButton("签到", "glaDosSign"), - ) - )) - } - callback("glaDosSign") { - val message = GlaDosLogic.sign(firstArg()) - editMessageText(message) - } - } - - fun TelegramSubscribe.iqyExec() { - before { iqyService.findByTgId(tgId).set("未绑定爱奇艺账号") } - callback("iqyExec") { - editMessageText("爱奇艺", InlineKeyboardMarkup( - arrayOf( - inlineKeyboardButton("签到", "iqySign"), - inlineKeyboardButton("观看任务", "iqyWatch") - ) - )) - } - callback("iqySign") { - IqyLogic.taskSign(firstArg()) - editMessageText("爱奇艺签到成功") - } - callback("iqyWatch") { - IqyLogic.finishTaskWatch(firstArg()) - editMessageText("爱奇艺观看任务完成成功") - } - } - fun TelegramSubscribe.eCloudExec() { before { eCloudService.findByTgId(tgId).set("未绑定天翼云盘账号") } callback("eCloudExec") { diff --git a/src/main/kotlin/me/kuku/telegram/extension/LoginExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/LoginExtension.kt index c273abd..b4dad86 100644 --- a/src/main/kotlin/me/kuku/telegram/extension/LoginExtension.kt +++ b/src/main/kotlin/me/kuku/telegram/extension/LoginExtension.kt @@ -16,7 +16,6 @@ import me.kuku.telegram.logic.* import me.kuku.telegram.utils.* import me.kuku.utils.* import org.springframework.stereotype.Service -import java.util.UUID @Service class LoginExtension( @@ -28,18 +27,12 @@ class LoginExtension( private val hostLocService: HostLocService, private val huYaLogic: HuYaLogic, private val huYaService: HuYaService, private val kuGouService: KuGouService, private val kuGouLogic: KuGouLogic, - private val netEaseService: NetEaseService, private val stepService: StepService, private val weiboService: WeiboService, private val miHoYoService: MiHoYoService, private val miHoYoLogic: MiHoYoLogic, - private val twitterService: TwitterService, - private val pixivService: PixivService, private val smZdmService: SmZdmService, private val smZdmLogic: SmZdmLogic, - private val aliDriveLogic: AliDriveLogic, private val aliDriveService: AliDriveService, private val leiShenService: LeiShenService, private val nodeSeekService: NodeSeekService, - private val glaDosService: GlaDosService, - private val iqyService: IqyService, private val eCloudService: ECloudService, private val eCloudLogic: ECloudLogic, private val linuxDoService: LinuxDoService ) { @@ -52,29 +45,21 @@ class LoginExtension( val huYaButton = InlineKeyboardButton("虎牙").callbackData("huYaLogin") val kuGouButton = InlineKeyboardButton("酷狗").callbackData("kuGouLogin") val miHoYoButton = InlineKeyboardButton("米哈游").callbackData("miHoYoLogin") - val netEaseButton = InlineKeyboardButton("网易云音乐").callbackData("netEaseLogin") val stepButton = InlineKeyboardButton("刷步数").callbackData("stepLogin") val weiboStepButton = InlineKeyboardButton("微博").callbackData("weiboLogin") - val twitterButton = InlineKeyboardButton("twitter").callbackData("twitterLogin") - val pixivButton = InlineKeyboardButton("pixiv").callbackData("pixivLogin") val smZdmButton = inlineKeyboardButton("什么值得买", "smZdmLogin") - val aliDriveButton = inlineKeyboardButton("阿里云盘", "aliDriveLogin") val leiShenButton = inlineKeyboardButton("雷神加速器", "leiShenLogin") val nodeSeekButton = inlineKeyboardButton("NodeSeek", "nodeSeekLogin") - val gloDos = inlineKeyboardButton("GloDos", "gloDosLogin") - val iqy = inlineKeyboardButton("爱奇艺", "iqyLogin") val eCloud = inlineKeyboardButton("天翼云盘", "eCloudLogin") val linuxDo = inlineKeyboardButton("LinuxDo", "linuxDoLogin") return InlineKeyboardMarkup( arrayOf(baiduButton, biliBiliButton), arrayOf(douYuButton, hostLocButton), arrayOf(huYaButton, kuGouButton), - arrayOf(miHoYoButton, netEaseButton), + arrayOf(miHoYoButton), arrayOf(stepButton, weiboStepButton), - arrayOf(twitterButton, pixivButton), - arrayOf(smZdmButton, aliDriveButton), + arrayOf(smZdmButton), arrayOf(leiShenButton, nodeSeekButton), - arrayOf(gloDos, iqy), arrayOf(eCloud, linuxDo) ) } @@ -405,72 +390,6 @@ class LoginExtension( } } - - fun TelegramSubscribe.netEase() { - callback("netEaseLogin") { - val qrcodeButton = inlineKeyboardButton("扫码登录", "netEaseQrcodeLogin") - val passwordButton = inlineKeyboardButton("手机密码登录", "netEasePasswordLogin") - editMessageText("网易云登录", InlineKeyboardMarkup(arrayOf(qrcodeButton), arrayOf(passwordButton))) - } - callback("netEaseQrcodeLogin") { - val key = NetEaseLogic.qrcode() - val url = "http://music.163.com/login?codekey=$key" - var photoMessage: Message? - qrcode(url).let { - val photo = SendPhoto(chatId, it) - photoMessage = bot.asyncExecute(photo).message() - editMessageText("请使用网易云音乐App扫描下面二维码登录", returnButton = false) - } - var scan = true - var i = 0 - while (true) { - if (i++ > 20) { - editMessageText("网易云二维码已过期") - break - } - delay(3000) - val result = NetEaseLogic.checkQrcode(key) - when (result.code) { - 200 -> { - val netEaseEntity = result.data() - val newEntity = netEaseService.findByTgId(tgId) ?: NetEaseEntity().init() - newEntity.csrf = netEaseEntity.csrf - newEntity.musicU = netEaseEntity.musicU - netEaseService.save(newEntity) - editMessageText("绑定网易云音乐成功") - break - } - 500 -> { - editMessageText("网易云音乐登录失败,${result.message}") - break - } - 1 -> { - if (scan) { - editMessageText(result.message) - scan = false - } - } - } - } - photoMessage?.delete() - } - callback("netEasePasswordLogin") { - editMessageText("请发送网易云音乐登录的手机号") - val phone = nextMessage().text() - editMessageText("请发送网易云音乐登录的密码") - val password = nextMessage().text() - val result = NetEaseLogic.login(phone, password) - if (result.success()) { - val entity = netEaseService.findByTgId(tgId) ?: NetEaseEntity().init() - val newEntity = result.data() - entity.csrf = newEntity.csrf - entity.musicU = newEntity.musicU - netEaseService.save(entity) - editMessageText("绑定网易云音乐成功") - } else editMessageText("绑定网易云音乐失败,${result.message}") - } - } - fun TelegramSubscribe.xiaomiStepLogin() { callback("stepLogin") { editMessageText(""" @@ -563,71 +482,6 @@ class LoginExtension( } } - fun TelegramSubscribe.twitterLogin() { - callback("twitterLogin") { - val loginButton = inlineKeyboardButton("模拟登录", "twitterLoginByUsername") - val cookieButton = inlineKeyboardButton("cookie登录", "twitterCookieLogin") - val markup = InlineKeyboardMarkup( - arrayOf(loginButton), - arrayOf(cookieButton) - ) - editMessageText("请选择twitter登录方式", markup) - } - callback("twitterLoginByUsername") { - editMessageText("请发送twitter的用户名") - val username = nextMessage().text() - editMessageText("请发送twitter的密码") - val password = nextMessage().text() - val twitterEntity = TwitterLogic.login(username, password) - val queryEntity = twitterService.findByTgId(tgId) ?: TwitterEntity().init() - queryEntity.cookie = twitterEntity.cookie - queryEntity.csrf = twitterEntity.csrf - queryEntity.tId = twitterEntity.tId - queryEntity.tRestId = twitterEntity.tRestId - twitterService.save(queryEntity) - editMessageText("绑定twitter成功") - } - callback("twitterCookieLogin") { - editMessageText("请发送twitter的cookie") - val cookie = nextMessage().text() - val ct0 = OkUtils.cookie(cookie, "ct0") ?: error("cookie中必须包含ct0") - val entity = TwitterEntity().also { entity -> - entity.cookie = cookie - entity.csrf = ct0 - } - TwitterLogic.friendTweet(entity) - val queryEntity = twitterService.findByTgId(tgId) ?: TwitterEntity().init() - queryEntity.cookie = cookie - queryEntity.csrf = ct0 - twitterService.save(queryEntity) - editMessageText("绑定twitter成功") - } - } - - fun TelegramSubscribe.pixivLogin() { - callback("pixivLogin") { - val loginButton = inlineKeyboardButton("使用微博app扫码登陆", "pixivLoginByWeibo") - val cookieButton = inlineKeyboardButton("cookie登录", "pixivCookieLogin") - val markup = InlineKeyboardMarkup( - arrayOf(loginButton), - arrayOf(cookieButton) - ) - editMessageText("请选择pixiv登录方式", markup) - } - callback("pixivLoginByWeibo") { - answerCallbackQuery("没写") - } - callback("pixivCookieLogin") { - editMessageText("请发送pixiv的cookie") - val cookie = nextMessage().text() - PixivLogic.followImage(PixivEntity().also { ii -> ii.cookie = cookie }) - val pixivEntity = pixivService.findByTgId(tgId) ?: PixivEntity().init() - pixivEntity.cookie = cookie - pixivService.save(pixivEntity) - editMessageText("绑定pixiv成功") - } - } - fun TelegramSubscribe.smZdm() { callback("smZdmLogin") { val loginButton = inlineKeyboardButton("使用手机验证码登陆", "smZdmLoginByPhoneCode") @@ -724,59 +578,6 @@ class LoginExtension( } } - fun TelegramSubscribe.aliDrive() { - callback("aliDriveLogin") { - editMessageText(""" - 请选择阿里云盘登录方式 - 登陆成功之后账号可能会用于完成加入共享相册的任务 - """.trimIndent(), InlineKeyboardMarkup( - arrayOf(inlineKeyboardButton("使用阿里云盘app扫码登录", "aliDriveQrcodeLogin")), - arrayOf(inlineKeyboardButton("使用阿里云盘RefreshToken登录", "aliDriveTokenLogin")) - )) - } - callback("aliDriveQrcodeLogin") { - val qrcode = aliDriveLogic.login1() - var photoMessage: Message? - qrcode(qrcode.qrcodeUrl).let { - val sendPhoto = SendPhoto(chatId, it) - photoMessage = bot.asyncExecute(sendPhoto).message() - editMessageText("请使用阿里云盘app扫码登陆", returnButton = false) - } - var i = 0 - while (true) { - if (++i > 20) { - editMessageText("阿里云盘登陆二维码已过期") - break - } - delay(3000) - val commonResult = aliDriveLogic.login2(qrcode) - if (commonResult.success()) { - val data = commonResult.data() - val refreshToken = data.refreshToken - val aliDriveEntity = aliDriveService.findByTgId(tgId) ?: AliDriveEntity().init() - aliDriveEntity.refreshToken = refreshToken - if (aliDriveEntity.deviceId.isEmpty()) aliDriveEntity.deviceId = UUID.randomUUID().toString() - aliDriveService.save(aliDriveEntity) - editMessageText("绑定阿里云盘成功") - break - } else if (commonResult.code != 0) { - editMessageText(commonResult.message) - break - } - } - photoMessage?.delete() - } - callback("aliDriveTokenLogin") { - editMessageText("请发送阿里云盘的RefreshToken") - val refreshToken = nextMessage().text() - val aliDriveEntity = aliDriveService.findByTgId(tgId) ?: AliDriveEntity().init() - aliDriveEntity.refreshToken = refreshToken - if (aliDriveEntity.deviceId.isEmpty()) aliDriveEntity.deviceId = UUID.randomUUID().toString() - aliDriveService.save(aliDriveEntity) - editMessageText("绑定阿里云盘成功") - } - } - fun TelegramSubscribe.leiShenLogin() { callback("leiShenLogin") { editMessageText("请选择雷神加速器登录方式\n使用账号密码登录会记录账号密码以自动更新cookie", InlineKeyboardMarkup( @@ -816,77 +617,6 @@ class LoginExtension( } } - fun TelegramSubscribe.gloDosSign() { - callback("gloDosLogin") { - editMessageText("请选择Glodos的登陆方式", InlineKeyboardMarkup( - arrayOf(inlineKeyboardButton("使用cookie登陆", "glaDosCookieLogin")), - arrayOf(inlineKeyboardButton("使用邮箱验证码登录", "glaDosPasswordLogin")), - )) - } - callback("glaDosCookieLogin") { - editMessageText("请发送Glados的cookie") - val text = nextMessage().text() - val entity = glaDosService.findByTgId(tgId) ?: GlaDosEntity().init() - entity.cookie = text - glaDosService.save(entity) - editMessageText("绑定Glados成功") - } - callback("glaDosPasswordLogin") { - editMessageText("请发送Glados的登录邮箱") - val email = nextMessage().text() - GlaDosLogic.sendCode(email) - editMessageText("请发送Glados登录邮箱${email}的验证码") - val code = nextMessage().text() - val cookie = GlaDosLogic.verifyCode(email, code) - val entity = glaDosService.findByTgId(tgId) ?: GlaDosEntity().init() - entity.cookie = cookie - glaDosService.save(entity) - editMessageText("绑定Glados成功") - } - } - - fun TelegramSubscribe.iqyLogin() { - callback("iqyLogin") { - editMessageText("请选择爱奇艺的登陆方式", InlineKeyboardMarkup( - arrayOf(inlineKeyboardButton("扫码登陆", "iqyQrcodeLogin")), - )) - } - callback("iqyQrcodeLogin") { - val qrcode = IqyLogic.login1() - var photoMessage: Message? - qrcode.imageUrl.let { - val sendPhoto = SendPhoto(chatId, it) - photoMessage = bot.asyncExecute(sendPhoto).message() - editMessageText("请使用爱奇艺App扫码登陆", returnButton = false) - } - var i = 0 - while (true) { - if (++i > 20) { - editMessageText("爱奇艺登陆二维码已过期") - break - } - delay(3000) - val newIqyEntity = try { - IqyLogic.login2(qrcode) - } catch (_: QrcodeScanException) { - continue - } - val iqyEntity = iqyService.findByTgId(tgId) ?: IqyEntity().init() - iqyEntity.authCookie = newIqyEntity.authCookie - iqyEntity.userid = newIqyEntity.userid - iqyEntity.platform = newIqyEntity.platform - iqyEntity.deviceId = newIqyEntity.deviceId - iqyEntity.qyId = newIqyEntity.qyId - iqyEntity.cookie = newIqyEntity.cookie - iqyEntity.p00001 = newIqyEntity.p00001 - iqyService.save(iqyEntity) - editMessageText("绑定爱奇艺成功") - break - } - photoMessage?.delete() - } - } - fun TelegramSubscribe.eCloudLogin() { callback("eCloudLogin") { editMessageText("请选择天翼云盘的登陆方式", InlineKeyboardMarkup( diff --git a/src/main/kotlin/me/kuku/telegram/extension/ManagerExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/ManagerExtension.kt index d3f1a1e..7d77c52 100644 --- a/src/main/kotlin/me/kuku/telegram/extension/ManagerExtension.kt +++ b/src/main/kotlin/me/kuku/telegram/extension/ManagerExtension.kt @@ -19,17 +19,11 @@ class ManagerExtension( private val huYaService: HuYaService, private val kuGouService: KuGouService, private val miHoYoService: MiHoYoService, - private val netEaseService: NetEaseService, private val stepService: StepService, private val weiboService: WeiboService, - private val twitterService: TwitterService, - private val pixivService: PixivService, private val smZdmService: SmZdmService, - private val aliDriveService: AliDriveService, private val leiShenService: LeiShenService, private val nodeSeekService: NodeSeekService, - private val glaDosService: GlaDosService, - private val iqyService: IqyService, private val eCloudService: ECloudService, private val linuxDoService: LinuxDoService ) { @@ -42,29 +36,21 @@ class ManagerExtension( val huYaButton = InlineKeyboardButton("虎牙").callbackData("huYaManager") val kuGouButton = InlineKeyboardButton("酷狗").callbackData("kuGouManager") val miHoYoButton = InlineKeyboardButton("米哈游").callbackData("miHoYoManager") - val netEaseButton = InlineKeyboardButton("网易云音乐").callbackData("netEaseManager") val xiaomiStepButton = InlineKeyboardButton("刷步数").callbackData("stepManager") val weiboButton = InlineKeyboardButton("微博").callbackData("weiboManager") - val twitterButton = InlineKeyboardButton("twitter").callbackData("twitterManager") - val pixivButton = InlineKeyboardButton("pixiv").callbackData("pixivManager") val smZdmButton = InlineKeyboardButton("什么值得买").callbackData("smZdmManager") - val aliDrive = inlineKeyboardButton("阿里云盘", "aliDriveManager") val leiShen = inlineKeyboardButton("雷神加速器", "leiShenManager") val nodeSeek = inlineKeyboardButton("NodeSeek", "nodeSeekManager") - val glaDos = inlineKeyboardButton("Glados", "glaDosManager") - val iqy = inlineKeyboardButton("爱奇艺", "iqyManager") val eCloud = inlineKeyboardButton("天翼云盘", "eCloudManager") val linuxDo = inlineKeyboardButton("LinuxDo", "linuxDoManager") return InlineKeyboardMarkup( arrayOf(baiduButton, biliBiliButton), arrayOf(douYuButton, hostLocButton), arrayOf(huYaButton, kuGouButton), - arrayOf(miHoYoButton, netEaseButton), + arrayOf(miHoYoButton), arrayOf(xiaomiStepButton, weiboButton), - arrayOf(twitterButton, pixivButton), - arrayOf(smZdmButton, aliDrive), + arrayOf(smZdmButton), arrayOf(leiShen, nodeSeek), - arrayOf(glaDos, iqy), arrayOf(eCloud, linuxDo) ) } @@ -232,33 +218,6 @@ class ManagerExtension( } } - fun TelegramSubscribe.netEaseManager() { - before { set(netEaseService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定网易云音乐账号")) } - callback("netEaseManager") {} - callback("netEaseSignSwitch") { firstArg().also { it.sign = !it.sign } } - callback("netEaseMusicianSignSwitch") { firstArg().also { it.musicianSign = !it.musicianSign } } - callback("netEaseVipSignSwitch") { firstArg().also { it.vipSign = !it.vipSign } } - callback("netEaseListenSwitch") { firstArg().also { it.listen = !it.listen } } - after { - val netEaseEntity = firstArg() - netEaseService.save(netEaseEntity) - val signButton = InlineKeyboardButton("${netEaseEntity.sign}自动签到") - .callbackData("netEaseSignSwitch") - val musicianSignButton = InlineKeyboardButton("${netEaseEntity.musicianSign}音乐人自动签到") - .callbackData("netEaseMusicianSignSwitch") - val vipSign = inlineKeyboardButton("${netEaseEntity.vipSign}vip自动签到", "netEaseVipSignSwitch") - val listen = inlineKeyboardButton("${netEaseEntity.listen}刷歌曲播放", "netEaseListenSwitch") - val inlineKeyboardMarkup = InlineKeyboardMarkup( - arrayOf(signButton), - arrayOf(musicianSignButton), - arrayOf(vipSign), - arrayOf(listen) - ) - editMessageText(""" - 网易云签到管理 - """.trimIndent(), inlineKeyboardMarkup, top = true) - } - } fun TelegramSubscribe.stepManager() { before { set(stepService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定刷步数的账号")) } @@ -309,42 +268,6 @@ class ManagerExtension( } } - fun TelegramSubscribe.twitterManager() { - before { set(twitterService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定Twitter账号")) } - callback("twitterManager") {} - callback("twitterPushSwitch") { firstArg().also { it.push = !it.push } } - after { - val twitterEntity = firstArg() - twitterService.save(twitterEntity) - val pushButton = InlineKeyboardButton("${twitterEntity.push}推文推送") - .callbackData("twitterPushSwitch") - val inlineKeyboardMarkup = InlineKeyboardMarkup( - arrayOf(pushButton) - ) - editMessageText(""" - 推特管理 - """.trimIndent(), inlineKeyboardMarkup, top = true) - } - } - - fun TelegramSubscribe.pixivManager() { - before { set(pixivService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定pixiv")) } - callback("pixivManager") {} - callback("pixivPushSwitch") { firstArg().also { it.push = !it.push } } - after { - val pixivEntity = firstArg() - pixivService.save(pixivEntity) - val pushButton = InlineKeyboardButton("${pixivEntity.push}插画推送") - .callbackData("pixivPushSwitch") - val inlineKeyboardMarkup = InlineKeyboardMarkup( - arrayOf(pushButton) - ) - editMessageText(""" - pixiv管理 - """.trimIndent(), inlineKeyboardMarkup, top = true) - } - } - fun TelegramSubscribe.smZdmManager() { before { set(smZdmService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定什么值得买账号")) } callback("smZdmManager") {} @@ -361,41 +284,6 @@ class ManagerExtension( } } - fun TelegramSubscribe.aliDriveManager() { - before { set(aliDriveService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定阿里云盘账号")) } - callback("aliDriveManager") {} - callback("aliDriveSignSwitch") { firstArg().also { it.sign = !it.sign } } - callback("aliDriveReceiveSwitch") { firstArg().also { it.receive = !it.receive } } - callback("aliDriveTaskSwitch") { firstArg().also { it.task = !it.task } } - callback("aliDriveReceiveTaskSwitch") { firstArg().also { it.receiveTask = !it.receiveTask } } - callback("aliDriveDeviceRoomTurn") { firstArg().also { it.deviceRoom = !it.deviceRoom } } - callback("aliDriveCardSwitch") { firstArg().also { it.card = !it.card } } - after { - val aliDriveEntity = firstArg() - aliDriveService.save(aliDriveEntity) - val signButton = inlineKeyboardButton("${aliDriveEntity.sign}自动签到", - "aliDriveSignSwitch") - val receiveButton = inlineKeyboardButton("${aliDriveEntity.receive}自动领取", - "aliDriveReceiveSwitch") - val task = inlineKeyboardButton("${aliDriveEntity.task}完成任务", - "aliDriveTaskSwitch") - val receiveTask = inlineKeyboardButton("${aliDriveEntity.receiveTask}领取任务奖励", - "aliDriveReceiveTaskSwitch") - val deviceRoom = InlineKeyboardButton("${aliDriveEntity.deviceRoom}时光设备间") - .callbackData("aliDriveDeviceRoomTurn") - val card = inlineKeyboardButton("${aliDriveEntity.card}领取补签卡", - "aliDriveCardSwitch") - val markup = InlineKeyboardMarkup(arrayOf(signButton), arrayOf(receiveButton), - arrayOf(task), arrayOf(receiveTask), arrayOf(deviceRoom), arrayOf(card) - ) - editMessageText(""" - 阿里云盘,如自动签到为关,自动领取不生效 - 完成任务会在你的云盘上上传图片、视频、新建文件夹等,介意勿用 - 完成任务如出现device offline错误,请找到阿里云盘的登录设备管理,下线一些设备即可 - """.trimIndent(), markup, top = true) - } - } - fun TelegramSubscribe.leiShenManager() { before { set(leiShenService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定雷神加速器账号")) } callback("leiShenManager") {} @@ -463,42 +351,6 @@ class ManagerExtension( } } - fun TelegramSubscribe.glaDosManager() { - before { set(glaDosService.findByTgId(tgId) ?: errorAnswerCallbackQuery("未绑定GlaDos账号")) } - callback("glaDosManager") {} - callback("glaDosSignSwitch") { firstArg().also { it.sign = !it.sign } } - after { - val glaDosEntity: GlaDosEntity = firstArg() - glaDosService.save(glaDosEntity) - val markup = InlineKeyboardMarkup( - arrayOf( - inlineKeyboardButton("${glaDosEntity.sign}自动签到", "glaDosSignSwitch"), - ) - ) - editMessageText(""" - GlaDos - """.trimIndent(), markup, top = true) - } - } - - fun TelegramSubscribe.iqyManager() { - before { iqyService.findByTgId(tgId).set("未绑定爱奇艺账号") } - callback("iqyManager") {} - callback("iqySignSwitch") { firstArg().also { it.sign = !it.sign } } - after { - val entity: IqyEntity = firstArg() - iqyService.save(entity) - val markup = InlineKeyboardMarkup( - arrayOf( - inlineKeyboardButton("${entity.sign}自动签到", "iqySignSwitch"), - ) - ) - editMessageText(""" - 爱奇艺 - """.trimIndent(), markup, top = true) - } - } - fun TelegramSubscribe.eCloudManager() { before { eCloudService.findByTgId(tgId).set("未绑定天翼云盘账号") } callback("eCloudManager") {} diff --git a/src/main/kotlin/me/kuku/telegram/extension/NetEaseSmallExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/NetEaseSmallExtension.kt deleted file mode 100644 index f42ecc4..0000000 --- a/src/main/kotlin/me/kuku/telegram/extension/NetEaseSmallExtension.kt +++ /dev/null @@ -1,41 +0,0 @@ -package me.kuku.telegram.extension - -import me.kuku.telegram.context.AbilitySubscriber -import me.kuku.telegram.context.Privacy -import me.kuku.telegram.context.nextMessage -import me.kuku.telegram.entity.NetEaseSmallEntity -import me.kuku.telegram.entity.NetEaseSmallService -import me.kuku.telegram.logic.NetEaseSmallLogic -import org.springframework.stereotype.Service - -@Service -class NetEaseSmallExtension( - private val netEaseSmallService: NetEaseSmallService, - private val netEaseSmallLogic: NetEaseSmallLogic -) { - - fun AbilitySubscriber.netEaseSmall() { - sub(name = "neteasesmall", privacy = Privacy.CREATOR) { - sendMessage(""" - 请发送网易云小号,格式为:用户名----密码,一行一个 - """.trimIndent()) - val text = nextMessage().text() - val firstArr = text.split("\n") - for (line in firstArr) { - val lineSplit = line.split("----") - val username = lineSplit[0] - var password = lineSplit[1] - password.indexOf('-').takeIf { it > 0 }?.let { - password = password.substring(0, it) - } - val netEaseSmallEntity = netEaseSmallService.findByUsername(username) ?: NetEaseSmallEntity() - netEaseSmallEntity.username = username - netEaseSmallEntity.password = password - netEaseSmallService.save(netEaseSmallEntity) - } - sendMessage("保存网易云小号成功") - netEaseSmallLogic.check() - } - } - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/extension/OtherPushExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/OtherPushExtension.kt deleted file mode 100644 index b69680b..0000000 --- a/src/main/kotlin/me/kuku/telegram/extension/OtherPushExtension.kt +++ /dev/null @@ -1,82 +0,0 @@ -package me.kuku.telegram.extension - -import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup -import me.kuku.telegram.context.* -import me.kuku.telegram.entity.OtherPushEntity -import me.kuku.telegram.entity.OtherPushService -import org.springframework.stereotype.Component - -@Component -class OtherPushExtension( - private val otherPushService: OtherPushService -) { - - private fun Boolean.toStr() = if (this) "√" else "x" - - private suspend fun Context.otherPush() { - val entity = otherPushService.findByTgId(tgId) - val pushTypes = entity.pushTypes - val switchEmail = inlineKeyboardButton("${pushTypes.contains(OtherPushEntity.OtherPushType.Email).toStr()}邮件推送" , "switchEmail") - val keyboardMarkup = InlineKeyboardMarkup( - arrayOf(switchEmail) - ) - val text = """ - 第三方推送,为了防止某些人fcm不正常,收不到telegram的推送,所以可以选择开启第三方推送,请切换推送开关 - """.trimIndent() - if (this is AbilityContext) { - sendMessage(text, keyboardMarkup) - } else if (this is TelegramContext) { - editMessageText(text, keyboardMarkup, returnButton = false) - } - } - - fun AbilitySubscriber.otherPush() { - sub("otherpush") { - otherPush() - } - } - - fun TelegramSubscribe.otherPush() { - before { set(otherPushService.findByTgId(tgId)) } - callback("switchEmail") { - val otherPushEntity = firstArg() - val pushTypes = otherPushEntity.pushTypes - if (pushTypes.contains(OtherPushEntity.OtherPushType.Email)) { - pushTypes.remove(OtherPushEntity.OtherPushType.Email) - otherPushService.save(otherPushEntity) - otherPush() - } else { - val receiveEmail = otherPushEntity.complex.receiveEmail - if (receiveEmail.isNotEmpty()) { - editMessageText("您即将启用邮箱推送,请选择以下选项", InlineKeyboardMarkup( - arrayOf(inlineKeyboardButton("${receiveEmail}为接收邮箱", "switchEmail2")), - arrayOf(inlineKeyboardButton("更换新邮箱", "switchEmail3")) - )) - } else { - editMessageText("请发送您接收的邮箱") - val email = nextMessage().text() - otherPushEntity.complex.receiveEmail = email - otherPushEntity.pushTypes.add(OtherPushEntity.OtherPushType.Email) - otherPushService.save(otherPushEntity) - otherPush() - } - } - } - callback("switchEmail2") { - val otherPushEntity = firstArg() - otherPushEntity.pushTypes.add(OtherPushEntity.OtherPushType.Email) - otherPushService.save(otherPushEntity) - otherPush() - } - callback("switchEmail3") { - val otherPushEntity = firstArg() - editMessageText("请发送您接收的邮箱") - val email = nextMessage().text() - otherPushEntity.complex.receiveEmail = email - otherPushEntity.pushTypes.add(OtherPushEntity.OtherPushType.Email) - otherPushService.save(otherPushEntity) - otherPush() - } - } - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/extension/ToolExtension.kt b/src/main/kotlin/me/kuku/telegram/extension/ToolExtension.kt index 7234d8e..174fbe4 100644 --- a/src/main/kotlin/me/kuku/telegram/extension/ToolExtension.kt +++ b/src/main/kotlin/me/kuku/telegram/extension/ToolExtension.kt @@ -15,7 +15,6 @@ import me.kuku.telegram.context.* import me.kuku.telegram.entity.BiliBiliService import me.kuku.telegram.logic.BiliBiliLogic import me.kuku.telegram.logic.ToolLogic -import me.kuku.telegram.logic.TwitterLogic import me.kuku.telegram.logic.YgoLogic import me.kuku.telegram.utils.githubCommit import me.kuku.utils.* @@ -154,35 +153,7 @@ class ToolExtension( file.delete() } } - sub("x", 1, locality = Locality.ALL) { - mutex.withLock { - val id = try { - firstArg().toLong() - } catch (e: NumberFormatException) { - MyUtils.regex("(?<=/status/)[0-9]*", firstArg())?.toLong() ?: error("错误的x链接") - } - val twitterPojo = TwitterLogic.tweet(id) - val text = TwitterLogic.convertStr(twitterPojo) - val videoUrl = if (twitterPojo.videoList.isNotEmpty()) twitterPojo.videoList[0] - else "" - try { - if (videoUrl.isNotEmpty()) { - client.get(videoUrl).body().let { - val sendVideo = SendVideo(chatId, it).fileName("${twitterPojo.id}.mp4") - .caption(text) - messageThreadId?.let { id -> sendVideo.messageThreadId(id) } - bot.asyncExecute(sendVideo) - } - } else if (twitterPojo.photoList.isNotEmpty() || twitterPojo.forwardPhotoList.isNotEmpty()) { - val imageList = twitterPojo.photoList - imageList.addAll(twitterPojo.forwardPhotoList) - bot.sendPic(chatId, text, imageList, messageThreadId) - } else bot.sendTextMessage(chatId, text, messageThreadId) - } catch (e: Exception) { - bot.sendTextMessage(chatId, text, messageThreadId) - } - } - } + sub("dy", 1, locality = Locality.ALL) { mutex.withLock { val urlArg = firstArg() diff --git a/src/main/kotlin/me/kuku/telegram/logic/AliDriveLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/AliDriveLogic.kt deleted file mode 100644 index b9c5ab4..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/AliDriveLogic.kt +++ /dev/null @@ -1,1493 +0,0 @@ -package me.kuku.telegram.logic - -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.JsonNode -import io.ktor.client.call.* -import io.ktor.client.request.* -import kotlinx.coroutines.delay -import me.kuku.pojo.CommonResult -import me.kuku.pojo.UA -import me.kuku.telegram.entity.AliDriveEntity -import me.kuku.telegram.entity.AliDriveService -import me.kuku.utils.* -import net.consensys.cava.bytes.Bytes32 -import net.consensys.cava.crypto.Hash -import net.consensys.cava.crypto.SECP256K1 -import okhttp3.RequestBody.Companion.toRequestBody -import org.bouncycastle.jce.provider.BouncyCastleProvider -import org.bouncycastle.util.encoders.Hex -import org.springframework.stereotype.Service -import java.io.ByteArrayInputStream -import java.io.File -import java.nio.charset.StandardCharsets -import java.security.Security -import java.time.LocalDate -import java.util.* -import javax.imageio.ImageIO - -@Service -class AliDriveLogic( - private val aliDriveService: AliDriveService -) { - - init { - if (Security.getProvider("BC") == null) { - Security.addProvider(BouncyCastleProvider()) - } - } - - private val cache = mutableMapOf() - private val signatureCache = mutableMapOf() - - suspend fun login1(): AliDriveQrcode { - val url = "https://passport.aliyundrive.com/mini_login.htm?lang=zh_cn&appName=aliyun_drive&appEntrance=web_default&styleType=auto&bizParams=¬LoadSsoView=false¬KeepLogin=false&isMobile=false&ad__pass__q__rememberLogin=true&ad__pass__q__rememberLoginDefaultValue=true&ad__pass__q__forgotPassword=true&ad__pass__q__licenseMargin=true&ad__pass__q__loginType=normal&hidePhoneCode=true&rnd=0.${MyUtils.randomNum(17)}" - val html = OkHttpKtUtils.getStr(url, - mapOf("user-agent" to UA.PC.value, "referer" to "https://auth.aliyundrive.com/")) - val jsonStr = MyUtils.regex("window.viewData = ", ";", html)!! - val jsonNode = Jackson.parse(jsonStr) - val loginJsonNode = jsonNode["loginFormData"] - val csrfToken = loginJsonNode["_csrf_token"].asText() - val idToken = loginJsonNode["umidToken"].asText() - val hs = loginJsonNode["hsiz"].asText() - val qrcodeJsonNode = OkHttpKtUtils.getJson("https://passport.aliyundrive.com/newlogin/qrcode/generate.do?appName=aliyun_drive&appName=aliyun_drive&fromSite=52&fromSite=52&appEntrance=web&_csrf_token=$csrfToken&umidToken=$idToken&isMobile=false&lang=zh_CN&returnUrl=&hsiz=$hs&bizParams=&_bx-v=2.0.31", - OkUtils.headers("", url, UA.PC)) - val contentJsonNode = qrcodeJsonNode["content"] - val contentDataJsonNode = contentJsonNode["data"] - return if (!contentJsonNode["success"].asBoolean()) error(contentDataJsonNode["titleMsg"].asText()) - else { - val qrcodeUrl = contentDataJsonNode["codeContent"].asText() - val t = contentDataJsonNode["t"].asLong() - val ck = contentDataJsonNode["ck"].asText() - AliDriveQrcode(qrcodeUrl, ck, csrfToken, idToken, hs, t) - } - } - - suspend fun login2(aliDriveQrcode: AliDriveQrcode): CommonResult { - val jsonNode = OkHttpKtUtils.postJson("https://passport.aliyundrive.com/newlogin/qrcode/query.do?appName=aliyun_drive&fromSite=52&_bx-v=2.0.50", - mapOf("t" to aliDriveQrcode.t.toString(), "ck" to aliDriveQrcode.ck, "ua" to "null", "appName" to "aliyun_drive", - "appEntrance" to "web", "_csrf_token" to aliDriveQrcode.csrfToken, "umidToken" to aliDriveQrcode.idToken, - "isMobile" to "false", "lang" to "zh_CN", "returnUrl" to "", "hsiz" to aliDriveQrcode.hs, "fromSite" to "52", - "bizParams" to "", "navlanguage" to "zh-CN", "navUserAgent" to "null", - "navPlatform" to "win32", "deviceId" to ""), OkUtils.headers("", "", UA.PC) - ) - val contentJsonNode = jsonNode["content"] - val contentDataJsonNode = contentJsonNode["data"] - return if (!contentJsonNode["success"].asBoolean()) CommonResult.failure(contentDataJsonNode["titleMsg"].asText(), null) - else { - when (contentDataJsonNode["qrCodeStatus"].asText()) { - "NEW" -> CommonResult.failure("二维码未扫描", null, 0) - "EXPIRED" -> CommonResult.failure("二维码已失效", null, 505) - "SCANED" -> CommonResult.failure("二维码已扫描", null, 0) - "CANCELED" -> CommonResult.failure("二维码已失效", null, 505) - "CONFIRMED" -> { - val bizExt = contentDataJsonNode["bizExt"].asText() - val jsonStr = Base64.getDecoder().decode(bizExt).toString(StandardCharsets.UTF_8) - val loginJsonNode = Jackson.parse(jsonStr) - val refreshToken = loginJsonNode["pds_login_result"]["refreshToken"].asText() - CommonResult.success(AliDriveEntity().also { - it.refreshToken = refreshToken - }) - } - else -> CommonResult.failure("未知的状态码", null) - } - } - } - - private suspend fun accessToken(aliDriveEntity: AliDriveEntity): String { - val accessToken = cache[aliDriveEntity.tgId] - return if (accessToken == null || accessToken.isExpire()) { - val jsonNode = client.post("https://auth.aliyundrive.com/v2/account/token") { - setJsonBody("""{"refresh_token": "${aliDriveEntity.refreshToken}", "grant_type": "refresh_token"}"}""") - }.body() - if (jsonNode.has("code")) error(jsonNode["message"].asText()) - val token = "${jsonNode["token_type"].asText()} ${jsonNode["access_token"].asText()}" - cache[aliDriveEntity.tgId] = AliDriveAccessToken(token, System.currentTimeMillis() + jsonNode["expires_in"].asLong() * 1000) - val newRefreshToken = jsonNode["refresh_token"].asText() - val newEntity = aliDriveService.findById(aliDriveEntity.id!!)!! - newEntity.refreshToken = newRefreshToken - aliDriveService.save(newEntity) - token - } else accessToken.accessToken - } - - suspend fun sign(aliDriveEntity: AliDriveEntity): AliDriveSign { - val accessToken = accessToken(aliDriveEntity) - val jsonNode = client.post("https://member.aliyundrive.com/v1/activity/sign_in_list") { - setJsonBody("{}") - headers { - append("Authorization", accessToken) - } - }.body() - jsonNode.check() - val result = jsonNode["result"] - val sign = AliDriveSign() - sign.subject = result["subject"].asText() - sign.customMessage = "签到成功,本月已签到${jsonNode["result"]["signInCount"].asInt()}次" - sign.title = result["title"].asText() - sign.isReward = result["isReward"].asBoolean() - sign.blessing = result["blessing"].asText() - sign.signInCount = result["signInCount"].asInt() - for (node in result["signInLogs"]) { - val signInLog = AliDriveSign.SignInLog() - signInLog.day = node["day"].asInt() - signInLog.status = node["status"].asText() - signInLog.type = node["type"].asText() - signInLog.rewardAmount = node["rewardAmount"].asInt() - signInLog.themes = node["themes"].asText() - signInLog.calendarChinese = node["calendarChinese"].asText() - signInLog.calendarDay = node["calendarDay"].asInt() - signInLog.calendarMonth = node["calendarMonth"].asText() - signInLog.isReward = node["isReward"].asBoolean() - sign.signInLogs.add(signInLog) - } - return sign - } - - context(HttpRequestBuilder) - private suspend fun AliDriveEntity.appendAuth() { - val accessToken = accessToken(this@AliDriveEntity) - headers { - append("Authorization", accessToken) - append("user-agent", "AliApp(AYSD/4.9.15.4) com.alicloud.databox/32886297 Channel/36176727979800@rimet_android_4.9.15.4 language/zh-CN /Android Mobile/Redmi M2007J3SC") - } - } - - context(HttpRequestBuilder) - private suspend fun AliDriveEntity.appendEncrypt(device: AliDriveDevice = AliDriveDevice()) { - val entity = this@AliDriveEntity - val deviceId = device.deviceId.ifEmpty { - device.deviceId = entity.deviceId - device.deviceId - } - val key = "${entity.tgId}$deviceId" - val aliDriveSignature = if (signatureCache.containsKey(key)) { - val aliDriveSignature = signatureCache[key]!! - if (aliDriveSignature.isExpire()) { - val encrypt = encrypt(entity, aliDriveSignature.key, aliDriveSignature.userid, - aliDriveSignature.nonce, device) - aliDriveSignature.signature = encrypt.signature - aliDriveSignature.expireRefresh() - aliDriveSignature - } else aliDriveSignature - } else { - val userGet = userGet(entity) - if (entity.deviceId.isEmpty()) { - entity.deviceId = UUID.randomUUID().toString() - aliDriveService.save(entity) - } - val encryptKey = encryptKey() - val encrypt = - encrypt(entity, encryptKey, userGet.userid, 0, device) - val aliDriveSignature = AliDriveSignature(encryptKey) - aliDriveSignature.deviceId = deviceId - aliDriveSignature.signature = encrypt.signature - aliDriveSignature.userid = userGet.userid - signatureCache[key] = aliDriveSignature - aliDriveSignature - } - headers { - append("x-device-id", aliDriveSignature.deviceId) - append("x-signature", aliDriveSignature.signature) - if (device.desktop) { - append("X-Canary", "client=windows,app=adrive,version=v4.9.14") - } else { - if (device.phone()) { - append("X-Canary", "client=Android,app=adrive,version=v4.9.15.4") - } else { - append("X-Canary", "client=web,app=other,version=v0.1.0") - } - } - } - } - - context(HttpRequestBuilder) - private suspend fun AliDriveEntity.appendBackupDeviceEncrypt() { - val device = findDevice(this@AliDriveEntity) - appendEncrypt(device) - } - - private fun JsonNode.check() { - if (this["success"]?.asBoolean() != true) error("${this["code"].asText()}-${this["message"]?.asText()}") - } - - private fun JsonNode.check2() { - if (this.has("code")) error(this["message"].asText()) - } - - private fun JsonNode.check3() { - if (this["code"].asInt() != 200) error(this["message"].asText()) - } - - private fun addZero(day: Int): String { - val dayString = day.toString() - return if (dayString.length == 1 && !dayString.startsWith("0")) "0$dayString" else dayString - } - - private suspend fun reallyDay(aliDriveEntity: AliDriveEntity, day: Int): String { - val signInList = signInList(aliDriveEntity) - val dayString = addZero(day) - return signInList.signInInfos.find { it.date == dayString }?.day ?: error("您没有完成这天的任务") - } - - suspend fun receive(aliDriveEntity: AliDriveEntity, day: Int = LocalDate.now().dayOfMonth): String { - val accessToken = accessToken(aliDriveEntity) - val newDay = reallyDay(aliDriveEntity, day) - val jsonNode = client.post("https://member.aliyundrive.com/v1/activity/sign_in_reward?_rx-s=mobile") { - setJsonBody("""{"signInDay": $newDay}""") - headers { - append("Authorization", accessToken) - } - }.body() - return if (jsonNode["success"]?.asBoolean() == true) { - "领取成功,${jsonNode["result"]["notice"].asText()}" - } else error(jsonNode["code"].asText()) - } - - suspend fun receiveTask(aliDriveEntity: AliDriveEntity, day: Int = LocalDate.now().dayOfMonth): String { - val accessToken = accessToken(aliDriveEntity) - val newDay = reallyDay(aliDriveEntity, day) - val jsonNode = client.post("https://member.aliyundrive.com/v2/activity/sign_in_task_reward?_rx-s=mobile") { - setJsonBody("""{"signInDay": $newDay}""") - headers { - append("Authorization", accessToken) - } - aliDriveEntity.appendBackupDeviceEncrypt() - }.body() - jsonNode.check() - return if (jsonNode["success"]?.asBoolean() == true) { - "领取成功,${jsonNode["result"]["notice"].asText()}" - } else error(jsonNode["code"].asText()) - } - - suspend fun signInInfo(aliDriveEntity: AliDriveEntity, aliDriveDevice: AliDriveDevice? = null): AliDriveSignInInfo { - val jsonNode = client.post("https://member.aliyundrive.com/v2/activity/sign_in_info") { - setJsonBody("{}") - aliDriveEntity.appendAuth() - if (aliDriveDevice == null) - aliDriveEntity.appendBackupDeviceEncrypt() - else - aliDriveEntity.appendEncrypt(aliDriveDevice) - }.body() - jsonNode.check() - return jsonNode["result"].convertValue() - } - - private suspend fun albumsDriveId(aliDriveEntity: AliDriveEntity): Int { - // code = 200 - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/user/albums_info") { - aliDriveEntity.appendAuth() - setJsonBody("{}") - }.body() - jsonNode.check3() - return jsonNode["data"]["driveId"].asInt() - } - - @Suppress("DuplicatedCode") - private suspend fun uploadFileToAlbums(aliDriveEntity: AliDriveEntity, driveId: Int, fileName: String, byteArray: ByteArray, - scene: AliDriveScene = AliDriveScene.ManualBackup, deviceName: String = "", - aliDriveDevice: AliDriveDevice? = null): AliDriveUploadComplete { - val newDevice = aliDriveDevice ?: findDevice(aliDriveEntity) - val suffix = fileName.substring(fileName.lastIndexOf('.') + 1) - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/biz/albums/file/create") { - setJsonBody(""" - {"drive_id":"$driveId","part_info_list":[{"part_number":1}],"parent_file_id":"root","name":"$fileName","type":"file","check_name_mode":"auto_rename","size":${byteArray.size},"create_scene":"${scene.value}","device_name":"$deviceName","hidden":false,"content_type":"image/$suffix"} - """.trimIndent()) - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt(newDevice) - }.body() - jsonNode.check2() - val fileId = jsonNode["file_id"].asText() - val uploadId = jsonNode["upload_id"].asText() - val uploadUrl = jsonNode["part_info_list"][0]["upload_url"].asText() - OkHttpKtUtils.putStr( - uploadUrl, byteArray.toRequestBody(), mapOf( - "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36", - "Origin" to "https://www.aliyundrive.com", - "Referer" to "https://www.aliyundrive.com" - ) - ) - val complete = client.post("https://api.aliyundrive.com/v2/file/complete") { - setJsonBody(""" - {"drive_id":"$driveId","upload_id":"$uploadId","file_id":"$fileId"} - """.trimIndent()) - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt(newDevice) - }.body() - val aliDriveUploadComplete = complete.convertValue() - aliDriveEntity.uploads.add(AliDriveEntity.Upload(driveId, aliDriveUploadComplete.fileId)) - aliDriveService.save(aliDriveEntity) - return aliDriveUploadComplete - } - - private suspend fun albumList(aliDriveEntity: AliDriveEntity): List { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/album/list") { - setJsonBody("""{"limit":20,"order_by":"created_at","order_direction":"ASC"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - val list = mutableListOf() - for (node in jsonNode["items"]) { - list.add(AliDriveAlbum().also { - it.id = node["album_id"].asText() - it.name = node["name"].asText() - }) - } - return list - } - - private suspend fun albumFileList(aliDriveEntity: AliDriveEntity, albumId: String): AliDriveFileList { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/album/list_files") { - setJsonBody(""" - {"album_id":"$albumId","image_thumbnail_process":"image/resize,w_480/format,avif","image_url_process":"image/resize,w_1920/format,avif","video_thumbnail_process":"video/snapshot,t_0,f_jpg,ar_auto,w_480","filter":"","fields":"*","limit":20,"order_by":"joined_at","order_direction":"DESC"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun createAlbum(aliDriveEntity: AliDriveEntity, name: String): AliDriveAlbum { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/album/create") { - setJsonBody("""{"name":"$name","description":""}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return AliDriveAlbum().also { - it.id = jsonNode["album_id"].asText() - it.name = jsonNode["name"].asText() - } - } - - private suspend fun deleteAlbum(aliDriveEntity: AliDriveEntity, id: String) { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/album/delete") { - setJsonBody("""{"album_id":"$id"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - } - - private suspend fun addFileToAlbum(aliDriveEntity: AliDriveEntity, driveId: Int, fileId: String, albumId: String) { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/album/add_files") { - setJsonBody("""{"drive_file_list":[{"drive_id":"$driveId","file_id":"$fileId"}],"album_id":"$albumId"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - } - - @Suppress("DuplicatedCode") - private suspend fun uploadFileToBackupDrive(aliDriveEntity: AliDriveEntity, driveId: Int, fileName: String, byteArray: ByteArray, parentId: String = "root", scene: AliDriveScene = AliDriveScene.Upload): AliDriveUploadComplete { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v2/file/createWithFolders") { - setJsonBody(""" - {"drive_id":"$driveId","part_info_list":[{"part_number":1}],"parent_file_id":"$parentId","name":"$fileName","type":"file","check_name_mode":"auto_rename","size":${byteArray.size},"create_scene":"${scene.value}","device_name":""} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - val fileId = jsonNode["file_id"].asText() - val uploadId = jsonNode["upload_id"].asText() - val uploadUrl = jsonNode["part_info_list"][0]["upload_url"].asText() - OkHttpKtUtils.putStr( - uploadUrl, byteArray.toRequestBody(), mapOf( - "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36", - "Origin" to "https://www.aliyundrive.com", - "Referer" to "https://www.aliyundrive.com" - ) - ) - val complete = client.post("https://api.aliyundrive.com/v2/file/complete") { - setJsonBody(""" - {"drive_id":"$driveId","upload_id":"$uploadId","file_id":"$fileId"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - val aliDriveUploadComplete = complete.convertValue() - aliDriveEntity.uploads.add(AliDriveEntity.Upload(driveId, aliDriveUploadComplete.fileId)) - aliDriveService.save(aliDriveEntity) - return aliDriveUploadComplete - } - - private suspend fun createFolder(aliDriveEntity: AliDriveEntity, driveId: Int, name: String, parentId: String = "root"): AliDriveFolder { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v2/file/createWithFolders") { - setJsonBody("""{"drive_id":"$driveId","parent_file_id":"$parentId","name":"$name","check_name_mode":"refuse","type":"folder"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun fileList(aliDriveEntity: AliDriveEntity, driveId: Int, parentId: String = "root"): AliDriveFileList { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v3/file/list?jsonmask=next_marker%2Citems(name%2Cfile_id%2Cdrive_id%2Ctype%2Csize%2Ccreated_at%2Cupdated_at%2Ccategory%2Cfile_extension%2Cparent_file_id%2Cmime_type%2Cstarred%2Cthumbnail%2Curl%2Cstreams_info%2Ccontent_hash%2Cuser_tags%2Cuser_meta%2Ctrashed%2Cvideo_media_metadata%2Cvideo_preview_metadata%2Csync_meta%2Csync_device_flag%2Csync_flag%2Cpunish_flag)") { - setJsonBody(""" - {"drive_id":"$driveId","parent_file_id":"$parentId","limit":20,"all":false,"url_expire_sec":14400,"image_thumbnail_process":"image/resize,w_256/format,avif","image_url_process":"image/resize,w_1920/format,avif","video_thumbnail_process":"video/snapshot,t_1000,f_jpg,ar_auto,w_256","fields":"*","order_by":"updated_at","order_direction":"DESC"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun batch(aliDriveEntity: AliDriveEntity, aliDriveBatch: AliDriveBatch, header: Map = mapOf()) { - val jsonNode = client.post("https://api.aliyundrive.com/v2/batch") { - setJsonBody(aliDriveBatch) - aliDriveEntity.appendAuth() - headers { - header.forEach { (k, u) -> append(k, u) } - } - }.body() - jsonNode.check2() -// val responses = jsonNode["responses"] -// for (node in responses) { -// val status = node["status"] -// -// } - } - - suspend fun batchDeleteFile(aliDriveEntity: AliDriveEntity, list: List) { - if (list.isEmpty()) return - val batch = AliDriveBatch() - for (deleteFileBody in list) { - val request = AliDriveBatch.Request() - request.id = deleteFileBody.fileId - request.url = "/recyclebin/trash" - request.body = deleteFileBody - batch.requests.add(request) - } - batch(aliDriveEntity, batch) - } - - private suspend fun batchDeleteFile2(aliDriveEntity: AliDriveEntity, list: List) { - if (list.isEmpty()) return - list.forEach { it.permanently = true } - val batch = AliDriveBatch() - for (deleteFileBody in list) { - val request = AliDriveBatch.Request() - request.id = deleteFileBody.fileId - request.url = "/file/delete" - request.body = deleteFileBody - batch.requests.add(request) - } - batch(aliDriveEntity, batch) - } - - private suspend fun searchFile(aliDriveEntity: AliDriveEntity, name: String, driveId: List): List { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v3/file/search") { - setJsonBody(""" - {"limit":20,"query":"name match \"$name\"","image_thumbnail_process":"image/resize,w_256/format,avif","image_url_process":"image/resize,w_1920/format,avif","video_thumbnail_process":"video/snapshot,t_1000,f_jpg,ar_auto,w_256","order_by":"updated_at DESC","drive_id_list":[${driveId.joinToString(",", prefix = "\"", postfix = "\"")}]} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode["items"].convertValue() - } - - private suspend fun userGet(aliDriveEntity: AliDriveEntity): AliDriveUser { - val jsonNode = client.post("https://user.aliyundrive.com/v2/user/get") { - aliDriveEntity.appendAuth() - setJsonBody("{}") - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun videoInfo(aliDriveEntity: AliDriveEntity, driveId: Int, fileId: String): AliDriveVideo { - val jsonNode = client.post("https://api.aliyundrive.com/v2/file/get_video_preview_play_info") { - setJsonBody(""" - {"drive_id":"$driveId","file_id":"$fileId","category":"live_transcoding","template_id":"","get_subtitle_info":true} - """.trimIndent()) - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun videoUpdate(aliDriveEntity: AliDriveEntity, driveId: Int, fileId: String, duration: Double, play: Double) { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v2/video/update") { - setJsonBody(""" - {"drive_id":"$driveId","file_id":"$fileId","play_cursor":"$play","duration":"$duration"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - } - - private suspend fun shareAlbum(aliDriveEntity: AliDriveEntity): List { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbum/list") { - setJsonBody("{}") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode["items"].convertValue() - } - - private suspend fun deleteShareAlbum(aliDriveEntity: AliDriveEntity, id: String) { - val jsonNode = client.post("https://api.alipan.com/adrive/v1/sharedAlbum/delete") { - setJsonBody("""{"sharedAlbumId":"$id"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - } - - private suspend fun createShareAlbum(aliDriveEntity: AliDriveEntity, name: String): String { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbum/create") { - setJsonBody("""{"name":"$name","description":""}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode["sharedAlbumId"].asText() - } - - private suspend fun uploadFileToShareAlbum(aliDriveEntity: AliDriveEntity, id: String, name: String, byteArray: ByteArray) { - val activityJsonNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbum/createActivity") { - setJsonBody("""{"sharedAlbumId":"$id"}""") - aliDriveEntity.appendAuth() - }.body() - activityJsonNode.check2() - val activityId = activityJsonNode["activityId"].asText() - val time = System.currentTimeMillis() - val width: Int - val height: Int - ByteArrayInputStream(byteArray).use { - val image = ImageIO.read(it) - width = image.width - height = image.height - } - val phoneId = MyUtils.randomInt(1000, 9999) - val createFileJsonNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbum/createFile") { - setJsonBody(""" - {"boundId":"$id","check_name_mode":"auto_rename","device_name":"Redmi M2007J3SC","drive_id":"","hidden":false,"image_media_metadata":{"width":$width,"time":$time,"height":$height},"name":"$name","parent_file_id":"root","part_info_list":[{"part_number":1,"part_size":${byteArray.size}}],"size":${byteArray.size},"type":"file","user_meta":"{\"size\":${byteArray.size},\"android_local_file_path\":\"/storage/emulated/0/DCIM/Screenshots/$name\",\"device_meta\":[{\"identifier\":\"${phoneId}_/storage/emulated/0/DCIM/Screenshots/${name}\",\"utd_id\":\"${MyUtils.random(24)}\",\"platform\":\"android\"}],\"android_identify_id\":\"$phoneId\",\"time\":$time}"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - val fileId = createFileJsonNode["file_id"].asText() - val uploadId = createFileJsonNode["upload_id"].asText() - val driveId = createFileJsonNode["drive_id"].asText() - val uploadUrl = createFileJsonNode["part_info_list"][0]["upload_url"].asText() - OkHttpKtUtils.putStr( - uploadUrl, byteArray.toRequestBody(), mapOf( - "Referer" to "https://www.aliyundrive.com" - ) - ) - client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbum/completeFile") { - setJsonBody(""" - {"boundId":"$id","drive_id":"$driveId","file_id":"$fileId","upload_id":"$uploadId"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbum/addFilesToActivity") { - setJsonBody("""{"activityId":"$activityId","files":[{"drive_id":"$driveId","file_id":"$fileId"}],"sharedAlbumId":"$id"}""") - aliDriveEntity.appendAuth() - }.body() - } - - private suspend fun shareAlbumInvite(aliDriveEntity: AliDriveEntity, id: String): AliDriveShareAlbumInvite { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbumMember/invite") { - setJsonBody(""" - {"sharedAlbumId":"$id"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun albumIdByCode(aliDriveEntity: AliDriveEntity, code: String): String { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbumMember/invitePage") { - setJsonBody("""{"code":"$code"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode["sharedAlbumId"].asText() - } - - private suspend fun joinShareAlbum(aliDriveEntity: AliDriveEntity, code: String) { - val shareAlbumId = albumIdByCode(aliDriveEntity, code) - val joinNode = client.post("https://api.aliyundrive.com/adrive/v1/sharedAlbumMember/join") { - setJsonBody(""" - {"code":"$code","sharedAlbumId":"$shareAlbumId"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - joinNode.check2() - // https://api.alipan.com/adrive/v1/sharedAlbumMember/quit {"sharedAlbumId":""} - } - - private suspend fun quitShareAlbum(aliDriveEntity: AliDriveEntity, id: String) { - val jsonNode = client.post("https://api.alipan.com/adrive/v1/sharedAlbumMember/quit") { - setJsonBody(""" - {"sharedAlbumId":"$id"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - } - - suspend fun quitShareAlbumByCode(aliDriveEntity: AliDriveEntity, code: String) { - val shareAlbumId = albumIdByCode(aliDriveEntity, code) - quitShareAlbum(aliDriveEntity, shareAlbumId) - } - - suspend fun bottleFish(aliDriveEntity: AliDriveEntity): AliDriveBottle { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/bottle/fish") { - setJsonBody(""" - {} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - private suspend fun saveTo(aliDriveEntity: AliDriveEntity, shareId: String) { - val tokenNode = client.post("https://api.aliyundrive.com/v2/share_link/get_share_token") { - setJsonBody(""" - {"share_id":"$shareId","share_pwd":""} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - tokenNode.check2() - val shareToken = tokenNode["share_token"].asText() - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v2/file/list_by_share") { - setJsonBody(""" - {"share_id":"$shareId","parent_file_id":"root","limit":20,"image_thumbnail_process":"image/resize,w_256/format,jpeg","image_url_process":"image/resize,w_1920/format,jpeg/interlace,1","video_thumbnail_process":"video/snapshot,t_1000,f_jpg,ar_auto,w_256","order_by":"name","order_direction":"DESC"} - """.trimIndent()) - aliDriveEntity.appendAuth() - headers { append("X-Share-Token", shareToken) } - }.body() - val page = jsonNode.convertValue>() - val file = page.items.random() - val fileId = file.fileId -// val jsonNode = client.post("https://api.aliyundrive.com/adrive/v3/share_link/get_share_by_anonymous?share_id=$shareId") { -// setJsonBody("""{"share_id":"$shareId"}""") -// aliDriveEntity.appendAuth() -// }.body() -// jsonNode.check2() -// val fileId = jsonNode["file_infos"][0]["file_id"].asText() - val batch = AliDriveBatch() - val request = AliDriveBatch.Request() - request.id = "0" - request.url = "/file/copy" - val body = AliDriveBatch.SaveShareFileBody() - body.fileId = fileId - body.shareId = shareId - val userGet = userGet(aliDriveEntity) - body.toDriveId = userGet.resourceDriveId.toString() - request.body = body - batch.requests.add(request) - batch(aliDriveEntity, batch, mapOf("X-Share-Token" to shareToken)) - } - - private fun encryptKey(): AliDriveKey { - val byteArray = ByteArray(32) - Random().nextBytes(byteArray) - val privateKey = HexUtils.byteArrayToHex(byteArray) - val publicKey = generatePublicKey(privateKey) - return AliDriveKey(privateKey, publicKey) - } - - private fun generatePublicKey(privateKey: String): String { - val fromBytes = SECP256K1.SecretKey.fromBytes(Bytes32.wrap(Hex.decode(privateKey))) - val keyPair = SECP256K1.KeyPair.fromSecretKey(fromBytes) - return Hex.toHexString(keyPair.publicKey().bytesArray()) - } - - private suspend fun encrypt(aliDriveEntity: AliDriveEntity, encryptKey: AliDriveKey, userid: String, nonce: Int = 0, - device: AliDriveDevice): AliDriveEncrypt { - val deviceName = device.deviceName - val modelName = device.deviceModel - val deviceId = device.deviceId - val phone = device.phone() - val privateKey = encryptKey.privateKey - val publicKey = encryptKey.publicKey - val appId = if (!phone) "5dde4e1bdf9e4966b387ba58f4b3fdc3" - else "81c38d8c0d224d5d981f5f4e6db2d587" - val data = "$appId:$deviceId:$userid:$nonce".toByteArray() - val fromBytes = SECP256K1.SecretKey.fromBytes(Bytes32.wrap(Hex.decode(privateKey))) - val keyPair = SECP256K1.KeyPair.fromSecretKey(fromBytes) - val signature = Hex.toHexString(SECP256K1.signHashed(Hash.sha2_256(data), keyPair).bytes().toArray()) - val accessToken = accessToken(aliDriveEntity) - val jsonNode = /*if (nonce == 0) {*/ - client.post("https://api.aliyundrive.com/users/v1/users/device/create_session") { - setJsonBody(""" - {"deviceName":"$deviceName","modelName":"$modelName","nonce":"0","pubKey":"$publicKey","refreshToken":"${aliDriveEntity.refreshToken}"} - """.trimIndent()) - headers { - append("x-device-id", deviceId) - append("x-signature", signature) - append("authorization", accessToken) - if (device.desktop) { - append("X-Canary", "client=windows,app=adrive,version=v4.9.14") - } else { - if (phone) { - append("X-Canary", "client=Android,app=adrive,version=v4.9.15.4") - } - } - } - }.body() - /*} else { - client.post("https://api.aliyundrive.com/users/v1/users/device/renew_session") { - setJsonBody("{}") - headers { - append("x-device-id", deviceId) - append("x-signature", signature) - append("authorization", accessToken) - if (phone) { - append("X-Canary", "client=Android,app=adrive,version=v4.1.0") - } - } - }.body() - }*/ - jsonNode.check() - return AliDriveEncrypt(deviceId, signature) - } - - @Suppress("DuplicatedCode") - suspend fun finishTask(aliDriveEntity: AliDriveEntity) { - val signInInfo = signInInfo(aliDriveEntity) - val reward = signInInfo.rewards[1] - when (reward.remind) { - "创建一个手工相册即可领取奖励" -> { - val aliDriveAlbums = albumList(aliDriveEntity).filter { it.name.contains("kuku的") } - aliDriveAlbums.forEach { - val fileList = albumFileList(aliDriveEntity, it.id) - val bodies = fileList.items.map { item -> AliDriveBatch.DeleteFileBody(item.driveId.toString(), item.fileId) } - batchDeleteFile(aliDriveEntity, bodies) - deleteAlbum(aliDriveEntity, it.id) - } - createAlbum(aliDriveEntity, "kuku的创建相册任务") - } - "上传10个文件到备份盘即可领取奖励" -> { - val info = createAutoFile(aliDriveEntity) - val backupDriveId = info.backupDriveId - val fileId = info.fileId - val fileList = fileList(aliDriveEntity, backupDriveId, fileId) - val bodies = fileList.items.map { AliDriveBatch.DeleteFileBody(it.driveId.toString(), it.fileId) } - batchDeleteFile(aliDriveEntity, bodies) - repeat(12) { - delay(3000) - val bytes = picture(it) - uploadFileToBackupDrive(aliDriveEntity, backupDriveId, - "${MyUtils.random(10)}.jpg", bytes, fileId) - } - } - "备份10张照片到相册即可领取奖励" -> { - finishBackupPhoto(aliDriveEntity, 12) - } - "接3次好运瓶即可领取奖励" -> { - repeat(3) { - delay(3000) - bottleFish(aliDriveEntity) - } - } - "播放1个视频30秒即可领取奖励" -> { - watchVideo(aliDriveEntity, 50.123) - } - "创建共享相簿邀请成员加入并上传10张照片" -> { - val albumList = shareAlbum(aliDriveEntity) - albumList.filter { it.name == "kuku的共享相册任务" }.forEach { - deleteShareAlbum(aliDriveEntity, it.shareAlbumId) - } - val id = createShareAlbum(aliDriveEntity, "kuku的共享相册任务") - val shareAlbumInvite = shareAlbumInvite(aliDriveEntity, id) - val filterEntity = aliDriveService.findAll().filter { it.id != aliDriveEntity.id }.randomOrNull() - ?: error("数据库中未拥有其他阿里云盘账号,无法邀请成员加入共享相簿") - joinShareAlbum(filterEntity, shareAlbumInvite.code()) - repeat(12) { - delay(3000) - val bytes = picture(it) - uploadFileToShareAlbum(aliDriveEntity, id, "${MyUtils.random(6)}.jpg", bytes) - } - } - "使用快传功能传输任意1个文件即可领取奖励" -> { - finishQuickShare(aliDriveEntity) - } - "分享好运口令(点击分享-> 今日好运卡)" -> { - shareGoodLuckCard(aliDriveEntity) - } - "接好运瓶并转存任意1个文件" -> { - val bottleFish = bottleFish(aliDriveEntity) - val shareId = bottleFish.shareId - saveTo(aliDriveEntity, shareId) - } - "创建1个共享相簿即可领取奖励" -> { - val albumList = shareAlbum(aliDriveEntity) - albumList.filter { it.name == "kuku的共享相册任务" }.forEach { - deleteShareAlbum(aliDriveEntity, it.shareAlbumId) - } - createShareAlbum(aliDriveEntity, "kuku的共享相册任务") - } - "开启自动备份并备份满10个文件" -> { - backup(aliDriveEntity, "kuku", "Android 12") - val driveId = albumsDriveId(aliDriveEntity) - repeat(12) { - delay(3000) - val bytes = picture(it) - uploadFileToAlbums(aliDriveEntity, driveId, - "${MyUtils.random(10)}.jpg", bytes, scene = AliDriveScene.AutoBackup, deviceName = "ku ku") - } - } - "开启手机自动备份并持续至少一小时" -> { - backup(aliDriveEntity, "kuku", "Android 12") - signInInfo(aliDriveEntity) - } - "开启「自动同步电脑文件夹至少一小时」" -> { - backupDesktop(aliDriveEntity) - signInInfo(aliDriveEntity, backupDesktopDevice(aliDriveEntity)) - } - else -> error("不支持的任务,${reward.remind}") - } - } - - private fun picture(i: Int): ByteArray { - val num = i + 1 - return this::class.java.classLoader.getResourceAsStream("image" + File.separator + "$num.jpg") - ?.readAllBytes() ?: error("图片不存在") - } - - suspend fun signInList(aliDriveEntity: AliDriveEntity): AliDriveSignIn { - val jsonNode = client.post("https://member.aliyundrive.com/v2/activity/sign_in_list?_rx-s=mobile") { - setJsonBody("{}") - aliDriveEntity.appendAuth() - aliDriveEntity.appendBackupDeviceEncrypt() - }.body() - jsonNode.check() - return jsonNode["result"].convertValue() - } - - private suspend fun quickShare(aliDriveEntity: AliDriveEntity, driveId: Int, fileId: String) { - val jsonNode = client.post("https://api.aliyundrive.com/adrive/v1/share/create") { - setJsonBody("""{"drive_file_list":[{"drive_id":"$driveId","file_id":"$fileId"}]}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - } - - private suspend fun shareGoodLuckCard(aliDriveEntity: AliDriveEntity) { - val jsonNode = client.post("https://member.aliyundrive.com/v1/activity/behave?_rx-s=mobile") { - setJsonBody("""{"behave":"share-signIn-code"}""") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check() - } - - suspend fun backup(aliDriveEntity: AliDriveEntity, brand: String, systemVersion: String, status: Boolean = true, - aliDriveDevice: AliDriveDevice? = null) { - var backupDeviceId = aliDriveEntity.backupDeviceId - if (backupDeviceId.isEmpty()) backupDeviceId = UUID.randomUUID().toString() - aliDriveEntity.backupDeviceId = backupDeviceId - aliDriveService.save(aliDriveEntity) - val newAliDriveDevice = aliDriveDevice ?: run { - val device = AliDriveDevice() - device.deviceId = backupDeviceId - device.deviceName = "kuku" - device.deviceModel = "kuku" - device - } - val jsonNode = client.post("https://api.alipan.com/users/v1/users/update_device_extras") { - setJsonBody(""" - {"albumAccessAuthority":true,"albumBackupLeftFileTotal":0,"albumBackupLeftFileTotalSize":0,"albumFile":0,"autoBackupStatus":$status,"brand":"${brand.lowercase()}","systemVersion":"$systemVersion","totalSize":242965508096,"umid":"ZDYBtYRLPNE6gwKLFDrYBaGJ8Q/r8p58","useSize":122042286080,"utdid":"Y90sZAck9L8DAO5WYKs2lFge"} - """.trimIndent()) - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt(newAliDriveDevice) - }.body() - jsonNode.check() - } - - fun backupDesktopDevice(aliDriveEntity: AliDriveEntity): AliDriveDevice { - return AliDriveDevice().also { - it.deviceId = aliDriveEntity.backupDesktopDeviceId - it.deviceName = "kuku's PC" - it.deviceModel = "Windows客户端" - it.desktop = true - } - } - - suspend fun backupDesktop(aliDriveEntity: AliDriveEntity, status: Boolean = true) { - var backupDesktopDeviceId = aliDriveEntity.backupDesktopDeviceId - if (backupDesktopDeviceId.isEmpty()) backupDesktopDeviceId = UUID.randomUUID().toString() - aliDriveEntity.backupDesktopDeviceId = backupDesktopDeviceId - aliDriveService.save(aliDriveEntity) - val aliDriveDevice = backupDesktopDevice(aliDriveEntity) - val jsonNode = client.post("https://api.aliyundrive.com/users/v1/users/update_device_extras") { - setJsonBody(""" - {"autoBackupStatus":$status} - """.trimIndent()) - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt(aliDriveDevice) - }.body() - jsonNode.check() - } - - private suspend fun deviceList(aliDriveEntity: AliDriveEntity): List { - val newEntity = aliDriveService.findById(aliDriveEntity.id!!)!! - val jsonNode = client.post("https://api.alipan.com/adrive/v2/backup/device_applet_list_summary") { - setJsonBody("{}") - newEntity.appendAuth() - newEntity.appendEncrypt() - }.body() - jsonNode.check2() - return jsonNode["deviceItems"].convertValue() - } - - private suspend fun findDevice(aliDriveEntity: AliDriveEntity, deviceId: String? = null): AliDriveDevice { - val list = deviceList(aliDriveEntity) - val matchDeviceId = deviceId ?: aliDriveEntity.backupDeviceId.ifEmpty { aliDriveEntity.deviceId } - return list.find { it.deviceId == matchDeviceId } ?: AliDriveDevice() - } - - private suspend fun deviceFileList(aliDriveEntity: AliDriveEntity, deviceId: String? = null): AliDrivePage { - val driveId = albumsDriveId(aliDriveEntity) - val jsonNode = client.post("https://api.alipan.com/adrive/v2/backup/device/file_list") { - setJsonBody(""" - {"backupView":"album","deviceId":"$deviceId","deviceType":"Android","driveId":"$driveId","limit":50} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode.convertValue() - } - - suspend fun deviceRoom(aliDriveEntity: AliDriveEntity): List { - val jsonNode = client.post("https://user.aliyundrive.com/v1/deviceRoom/listDevice") { - setJsonBody("{}") - aliDriveEntity.appendAuth() - }.body() - jsonNode.check2() - return jsonNode["items"].convertValue() - } - - suspend fun receiveDeviceRoom(aliDriveEntity: AliDriveEntity, deviceId: String): String { - val jsonNode = client.post("https://member.aliyundrive.com/v1/deviceRoom/rewardEnergy") { - setJsonBody(""" - {"deviceId":"$deviceId"} - """.trimIndent()) - aliDriveEntity.appendAuth() - }.body() - jsonNode.check() - return "已领取${jsonNode["result"]["size"].asInt()}M空间" - } - - suspend fun finishDeviceRoom(aliDriveEntity: AliDriveEntity): String { - var deviceList = deviceList(aliDriveEntity) - if (deviceList.size < 5) { - for (i in 0 until 5 - deviceList.size) { - delay(3000) - val aliDriveDevice = AliDriveDevice() - val deviceId = UUID.randomUUID().toString() - aliDriveDevice.deviceName = "kuku" - aliDriveDevice.deviceModel = MyUtils.randomLetterLower(2) - aliDriveDevice.deviceId = deviceId - backup(aliDriveEntity, "kuku", "Android 12", true, - aliDriveDevice - ) - } - } - deviceList = deviceList(aliDriveEntity) - val driveId = albumsDriveId(aliDriveEntity) - for (aliDriveDevice in deviceList) { - repeat(2) { - delay(3000) - val bytes = picture(it) - aliDriveEntity.backupDeviceId = aliDriveDevice.deviceId - uploadFileToAlbums(aliDriveEntity, driveId, - "${MyUtils.random(10)}.jpg", bytes, scene = AliDriveScene.AutoBackup, - deviceName = "ku ku", aliDriveDevice) - } - } - val deviceRoom = deviceRoom(aliDriveEntity).stream().limit(5).toList() - val sb = StringBuilder() - for (aliDriveDeviceRoom in deviceRoom) { - delay(1000) - if (aliDriveDeviceRoom.canCollectEnergy) - sb.append(receiveDeviceRoom(aliDriveEntity, aliDriveDeviceRoom.id)).append(",") - } - return sb.toString().ifEmpty { "领取容量成功" } - } - - private suspend fun receiveCard(aliDriveEntity: AliDriveEntity, position: Int) { - val jsonNode = client.post("https://member.aliyundrive.com/v2/activity/complement_task?_rx-s=mobile") { - setJsonBody("""{"position":$position}""") - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt() - }.body() - jsonNode.check() - } - - private suspend fun cardDetail(aliDriveEntity: AliDriveEntity): AliDriveCard { - val jsonNode = client.post("https://member.aliyundrive.com/v2/activity/complement_task_detail?_rx-s=mobile") { - setJsonBody("{}") - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt() - }.body() - jsonNode.check() - return jsonNode["result"].convertValue() - } - - private suspend fun cardAward(aliDriveEntity: AliDriveEntity, period: String, taskId: Int) { - val jsonNode = client.post("https://member.aliyundrive.com/v2/activity/complement_task_reward?_rx-s=mobile") { - setJsonBody(""" - {"period":"$period","taskId":$taskId} - """.trimIndent()) - aliDriveEntity.appendAuth() - aliDriveEntity.appendEncrypt() - }.body() - jsonNode.check() - } - - private suspend fun finishBackupPhoto(aliDriveEntity: AliDriveEntity, count: Int = 20) { - val albumsDriveId = albumsDriveId(aliDriveEntity) - val albumList = albumList(aliDriveEntity) - val findAlbum = albumList.find { it.name == "kuku的上传图片任务" } - val id = findAlbum?.id ?: createAlbum(aliDriveEntity, "kuku的上传图片任务").id - val fileList = albumFileList(aliDriveEntity, id) - val bodies = fileList.items.map { AliDriveBatch.DeleteFileBody(it.driveId.toString(), it.fileId) } - batchDeleteFile(aliDriveEntity, bodies) - repeat(count) { - delay(3000) - val bytes = picture(it) - val complete = uploadFileToAlbums( - aliDriveEntity, - albumsDriveId, - "${MyUtils.random(10)}.jpg", - bytes - ) - addFileToAlbum(aliDriveEntity, albumsDriveId, complete.fileId, id) - } - } - - private suspend fun createAutoFile(aliDriveEntity: AliDriveEntity): AutoInfo { - val userGet = userGet(aliDriveEntity) - val backupDriveId = userGet.backupDriveId - val searchFile = searchFile(aliDriveEntity, "kuku的上传文件任务", listOf(backupDriveId.toString())) - val fileId = if (searchFile.isEmpty()) - createFolder(aliDriveEntity, backupDriveId, "kuku的上传文件任务").fileId - else searchFile[0].fileId - return AutoInfo(backupDriveId, fileId) - } - - data class AutoInfo(val backupDriveId: Int, val fileId: String) - - private suspend fun finishQuickShare(aliDriveEntity: AliDriveEntity) { - val info = createAutoFile(aliDriveEntity) - val bytes = picture(5) - val complete = uploadFileToBackupDrive( - aliDriveEntity, info.backupDriveId, - "${MyUtils.random(10)}.jpg", bytes, info.fileId - ) - quickShare(aliDriveEntity, info.backupDriveId, complete.fileId) - } - - private suspend fun watchVideo(aliDriveEntity: AliDriveEntity, play: Double) { - val userGet = userGet(aliDriveEntity) - val backupDriveId = userGet.backupDriveId - val searchFile = searchFile(aliDriveEntity, "kuku的视频", listOf(backupDriveId.toString())) - val fileId = if (searchFile.isEmpty()) - createFolder(aliDriveEntity, backupDriveId, "kuku的视频").fileId - else searchFile[0].fileId - val fileList = fileList(aliDriveEntity, backupDriveId, fileId) - val bodies = fileList.items.map { AliDriveBatch.DeleteFileBody(it.driveId.toString(), it.fileId) } - batchDeleteFile(aliDriveEntity, bodies) - val bytes = client.get("https://minio.kuku.me/kuku/BV14s4y1Z7ZAoutput.mp4").body() - val uploadComplete = uploadFileToBackupDrive( - aliDriveEntity, backupDriveId, - "BV14s4y1Z7ZAoutput.mp4", bytes, fileId - ) - val uploadFileId = uploadComplete.fileId - val uploadDriveId = uploadComplete.driveId - val videoInfo = videoInfo(aliDriveEntity, uploadDriveId, uploadFileId) - videoUpdate(aliDriveEntity, uploadDriveId, uploadFileId, videoInfo.videoPreviewPlayInfo.meta.duration, - play) - } - - suspend fun finishCard(aliDriveEntity: AliDriveEntity) { - runCatching { - repeat(3) { - receiveCard(aliDriveEntity, it + 1) - } - } - val cardDetail = cardDetail(aliDriveEntity) - val map = mutableMapOf Unit>() - map["当周使用快传发送文件给好友"] = { - finishQuickShare(aliDriveEntity) - } - map["当周使用好运瓶翻3次"] = { - repeat(3) { - delay(3000) - bottleFish(aliDriveEntity) - } - } - map["当周备份照片满20张"] = { - finishBackupPhoto(aliDriveEntity, 22) - } - map["当周观看任意一个电影时间满3分钟"] = { - watchVideo(aliDriveEntity, 190.123) - } - val task = cardDetail.tasks.find { map[it.taskName] != null } - ?: error("不支持的任务,${cardDetail.tasks.joinToString(",") { it.taskName }}") - map[task.taskName]!!.invoke(aliDriveEntity) - } - - suspend fun receiveCard(aliDriveEntity: AliDriveEntity) { - val cardDetail = cardDetail(aliDriveEntity) - val task = cardDetail.tasks.find { it.status == "finished" } ?: error("未完成补签卡任务,领取补签卡失败") - cardAward(aliDriveEntity, cardDetail.period, task.taskId) - } - - -} - - -data class AliDriveQrcode( - var qrcodeUrl: String = "", - var ck: String = "", - var csrfToken: String = "", - var idToken: String = "", - var hs: String = "", - var t: Long = 0 -) - -data class AliDriveAccessToken(val accessToken: String, val expire: Long) { - fun isExpire() = System.currentTimeMillis() > expire -} - -data class AliDriveTeam(val id: Int, val period: String, val title: String, val subTitle: String, - val joinTeam: String, val joinCount: Int, val endTime: Long) - -class AliDriveSign { - var subject: String = "" - var customMessage: String = "" - var title: String = "" - var isReward: Boolean = false - var blessing: String = "" - var signInCount: Int = 0 - var signInLogs: MutableList = mutableListOf() - - class SignInLog { - var day: Int = 0 - var status: String = "" - var type: String = "" - var rewardAmount: Int = 0 - var themes: String = "" - var calendarChinese: String = "" - var calendarDay: Int = 0 - var calendarMonth: String = "" - var isReward: Boolean = false - } -} - -class AliDriveAlbum { - var id: String = "" - var name: String = "" -} - -class AliDriveUploadComplete { - @JsonProperty("drive_id") - var driveId: Int = 0 - @JsonProperty("file_id") - var fileId: String = "" - var name: String = "" -} - -class AliDriveFolder { - @JsonProperty("parent_file_id") - var parentFileId: String = "" - var type: String = "" - @JsonProperty("file_id") - var fileId: String = "" - @JsonProperty("domain_id") - var domainId: String = "" - @JsonProperty("drive_id") - var driveId: Int = 0 - @JsonProperty("file_name") - var fileName: String = "" -} - -class AliDriveUser { - @JsonProperty("backup_drive_id") - var backupDriveId: Int = 0 - @JsonProperty("resource_drive_id") - var resourceDriveId: Int = 0 - @JsonProperty("default_drive_id") - var defaultDriveId: Int = 0 - @JsonProperty("user_id") - var userid: String = "" -} - -class AliDriveSignInInfo { - var isSignIn: Boolean = false - var month: String = "" - var day: Int = 0 - var signInDay: Int = 0 - var rewards: MutableList = mutableListOf() - - class Reward { - var name: String = "" - var type: String = "" - var remind: String = "" - var status: String = "" - var position: Int = 0 - } -} - -class AliDriveSearch { - @JsonProperty("drive_id") - var driveId: Int = 0 - @JsonProperty("domain_id") - var domainId: String = "" - @JsonProperty("file_id") - var fileId: String = "" - var name: String = "" - var type: String = "" -} - -class AliDriveVideo { - @JsonProperty("domain_id") - var domainId: String = "" - @JsonProperty("drive_id") - var driveId: Int = 0 - @JsonProperty("file_id") - var fileId: String = "" - var category: String = "" - @JsonProperty("video_preview_play_info") - var videoPreviewPlayInfo: VideoPreviewPlayInfo = VideoPreviewPlayInfo() - - class VideoPreviewPlayInfo { - var category: String = "" - var meta: Meta = Meta() - - class Meta { - var duration: Double = 0.0 - var width: Int = 0 - var height: Int = 0 - } - } -} - -class AliDriveShareAlbum { - @JsonProperty("sharedAlbumId") - var shareAlbumId: String = "" - var name: String = "" - var description: String = "" -} - -class AliDriveBottle { - var bottleId: Long = 0 - var bottleName: String = "" - var shareId: String = "" -} - -data class AliDriveEncrypt(val deviceId: String, val signature: String) - -data class AliDriveKey(val privateKey: String, val publicKey: String) - -class AliDriveSignature(val key: AliDriveKey) { - var nonce: Int = 0 - var deviceId: String = "" - var signature: String = "" - var userid: String = "" - private var expire: Long = System.currentTimeMillis() + 1000 * 60 * 60 - - fun isExpire() = System.currentTimeMillis() > expire - - fun expireRefresh() { - expire = System.currentTimeMillis() + 1000 * 60 * 30 - } -} - -class AliDriveSignIn { - var month: String = "" - var signInCount: Int = 0 - var signInInfos: MutableList = mutableListOf() - - class SignInInfo { - var day: String = "0" - var date: String? = null - var blessing: String = "" - var status: String = "" - var subtitle: String? = null - var theme: String? = null - var rewards: MutableList = mutableListOf() - - class Reward { - var name: String = "" - var type: String = "" - var status: String = "" - var remind: String = "" - } - } - - -} - -class AliDriveFileList { - var items: MutableList = mutableListOf() - @JsonProperty("next_marker") - var nextMarker: String = "" -} - -class AliDriveFile { - var category: String = "" - @JsonProperty("content_hash") - var contentHash: String = "" - @JsonProperty("created_at") - var createdAt: String = "" - @JsonProperty("drive_id") - var driveId: Int = 0 - @JsonProperty("file_extension") - var fileExtension: String = "" - @JsonProperty("file_id") - var fileId: String = "" - @JsonProperty("mime_type") - var mimeType: String = "" - var name: String = "" - @JsonProperty("parent_file_id") - var parentFileId: String = "" - @JsonProperty("punish_flag") - var punishFlag: Int = 0 - var size: Long = 0 - var starred: Boolean = false - var thumbnail: String = "" - var type: String = "" - @JsonProperty("updated_at") - var updatedAt: String = "" - var url: String = "" - @JsonProperty("user_meta") - var userMeta: String = "" -} - -class AliDriveBatch { - var requests: MutableList = mutableListOf() - var resource: String = "file" - - class Request { - var body: Any = Any() - var headers: MutableMap = mutableMapOf("Content-Type" to "application/json") - var id: String = "" - var method: String = "POST" - var url: String = "" - } - - data class DeleteFileBody( - @JsonProperty("drive_id") - var driveId: String = "", - @JsonProperty("file_id") - var fileId: String = "", - var permanently: Boolean? = null - ) - - data class SaveShareFileBody( - @JsonProperty("file_id") - var fileId: String = "", - @JsonProperty("share_id") - var shareId: String = "", - @JsonProperty("auto_rename") - var autoRename: Boolean = true, - @JsonProperty("to_parent_file_id") - var toParentFileId: String = "root", - @JsonProperty("to_drive_id") - var toDriveId: String = "" - ) -} - -class AliDriveShareAlbumInvite { - - var message: String = "" - var url: String = "" - var shareMode: String = "" - var shareTitle: String = "" - var shareSubTitle: String = "" - var shareImageUrl: String = "" - - fun code(): String { - return MyUtils.regex("(?<=album/).*", url) ?: error("找不到共享相册code") - } - -} - -class AliDrivePage { - var items: MutableList = mutableListOf() - @JsonProperty("next_marker") - var nextMarker: String = "" -} - -class AliDriveShareFile { - @JsonProperty("drive_id") - var driveId: String = "" - @JsonProperty("domain_id") - var domainId: String = "" - @JsonProperty("file_id") - var fileId: String = "" - @JsonProperty("share_id") - var shareId: String = "" - var name: String = "" - var type: String = "" - @JsonProperty("parent_file_id") - var parentFileId: String = "" -} - -enum class AliDriveScene(val value: String) { - Upload("file_upload"), - AutoBackup("album_autobackup"), - ManualBackup("album_manualbackup") -} - -class AliDriveDevice { - var fileCount: Int = 0 - var totalSize: String = "" - var latestBackupTime: Long = 0 - var earlyBackupTime: Long = 0 - var enable: Boolean = false - var defaultDriveFileCount: Int = 0 - var albumDriveFileCount: Int = 0 - var defaultDriveFileSize: String = "" - var albumDriveFileSize: String = "" - var deviceId: String = "" - var deviceName: String = "Chrome浏览器" - var deviceModel: String = "Windows网页版" - var deviceType: String = "" - var deviceSystemVersion: String = "" - var deviceRegisterDay: Int = 0 - var updateTime: Long = 0 - var desktop: Boolean = false - - fun phone() = deviceName != "Chrome浏览器" -} - -class AliDriveDeviceRoom { - var gmtCollectEnergy: String? = null - var gmtGenerateEnergy: String? = "" - var deviceNameInfo: DeviceNameInfo? = null - var new: Boolean = false - var order: Int = 0 - @JsonProperty("isNew") - var repeatNew: Boolean = false - var canCollectEnergy: Boolean = false - var type: String = "" - var name: String = "" - var icon: String = "" - var id: String = "" - var gmCreate: String = "" - var gmtModified: String? = null - - class DeviceNameInfo { - var deviceType: String = "" - var deviceName: String = "" - var deviceModel: String = "" - var displayName: String = "" - } -} - -class AliDriveCard { - var period: String = "" - var tasks: MutableList = mutableListOf() - - class Task { - var taskId: Int = 0 - var taskName: String = "" - var description: String = "" - var action: String = "" - var category: String = "" - var status: String = "" - var process: String = "" - var position: Int = 0 - } -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/logic/GlaDosLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/GlaDosLogic.kt deleted file mode 100644 index ebabdfa..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/GlaDosLogic.kt +++ /dev/null @@ -1,42 +0,0 @@ -package me.kuku.telegram.logic - -import com.fasterxml.jackson.databind.JsonNode -import io.ktor.client.call.* -import io.ktor.client.request.* -import io.ktor.client.statement.* -import me.kuku.telegram.entity.GlaDosEntity -import me.kuku.utils.* - -object GlaDosLogic { - - private fun JsonNode.check() { - if (this["code"].asInt() != 0) error(this["message"].asText()) - } - - suspend fun sendCode(email: String) { - val jsonNode = client.post("https://glados.space/api/authorization") { - setJsonBody("""{"address":"$email","site":"glados.network"}""") - }.body() - jsonNode.check() - } - - suspend fun verifyCode(email: String, code: String): String { - val response = client.post("https://glados.space/api/login") { - setJsonBody("""{"method":"email","site":"glados.network","email":"$email","mailcode":"$code"}""") - } - val jsonNode = response.body() - jsonNode.check() - return response.cookie() - } - - suspend fun sign(entity: GlaDosEntity): String { - val jsonNode = client.post("https://glados.space/api/user/checkin") { - setJsonBody("""{"token":"glados.one"}""") - cookieString(entity.cookie) - }.bodyAsText().toJsonNode() - jsonNode.check() - return jsonNode["message"].asText() - } - - -} diff --git a/src/main/kotlin/me/kuku/telegram/logic/HostLocLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/HostLocLogic.kt index 0e0744d..a7a548b 100644 --- a/src/main/kotlin/me/kuku/telegram/logic/HostLocLogic.kt +++ b/src/main/kotlin/me/kuku/telegram/logic/HostLocLogic.kt @@ -31,8 +31,10 @@ object HostLocLogic { } private suspend fun checkLogin(cookie: String) { + val prepareCookie = prepareCookie() + val newCookie = prepareCookie + cookie val html = client.get("https://hostloc.com/home.php?mod=spacecp") { - cookieString(cookie) + cookieString(newCookie) }.bodyAsText() val text = Jsoup.parse(html).getElementsByTag("title").first()!!.text() val b = text.contains("个人资料") @@ -124,7 +126,8 @@ object HostLocLogic { } private suspend fun prepareCookie(): String { - val html = client.get("https://hostloc.com/forum.php").bodyAsText() + val html = client.get("https://hostloc.com/forum.php") { + }.bodyAsText() val group = MyUtils.regexGroup("(?<=toNumbers\\(\").*?(?=\"\\))", html) if (group.isEmpty()) return "" val a = intArrToByteArr(toNumbers(group[0])) diff --git a/src/main/kotlin/me/kuku/telegram/logic/IqyLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/IqyLogic.kt deleted file mode 100644 index 450f425..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/IqyLogic.kt +++ /dev/null @@ -1,170 +0,0 @@ -package me.kuku.telegram.logic - -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.JsonNode -import io.ktor.client.call.* -import io.ktor.client.request.* -import me.kuku.telegram.entity.IqyEntity -import me.kuku.telegram.exception.qrcodeNotScanned -import me.kuku.telegram.exception.qrcodeScanned -import me.kuku.utils.* - -object IqyLogic { - - suspend fun login1(): IqyQrcode { - val response = client.post("https://passport.iqiyi.com/apis/qrcode/gen_login_token.action") { - setFormDataContent { - append("agenttype", "1") - append("app_version", "") - append("device_id", "") - append("device_name", "网页端") - append("fromSDK", "1") - append("ptid", "01010021010000000000") - append("sdk_version", "1.0.0") - append("surl", "1") - append("device_auth_uid", "") - append("new_device_auth", "") - } - } - val jsonNode = response.body() - jsonNode.check() - val data = jsonNode["data"] - val token = data["token"].asText() - val url = data["url"].asText() - val enUrl = url.toUrlEncode() - val salt = "35f4223bb8f6c8638dc91d94e9b16f5$enUrl".md5() - val cookie = response.cookie() - return IqyQrcode(token, url, "https://qrcode.iqiyipic.com/login/?data=$enUrl&property=0&salt=$salt&width=162&_=0.${MyUtils.randomNum(16)}", - cookie) - } - - suspend fun login2(qrcode: IqyQrcode): IqyEntity { - val response = client.post("https://passport.iqiyi.com/apis/qrcode/is_token_login.action") { - setFormDataContent { - append("agenttype", "1") - append("app_version", "") - append("device_id", "") - append("fromSDK", "1") - append("ptid", "01010021010000000000") - append("sdk_version", "1.0.0") - append("token", qrcode.token) - append("dfp", "a17fefafa0ba5e426c96ffc2a0e9d1516066b7e9eebfbc3ce429d53c05e305085e") - } - } - val jsonNode = response.body() - // {"msg":"找不到用户登录信息,可能手机端尚未确认","code":"A00001"} - val code = jsonNode["code"].asText() - return when (code) { - "A00001" -> qrcodeNotScanned() - "P01006" -> qrcodeScanned() - "A00000" -> { - val data = jsonNode["data"] - val authCookie = data["authcookie"].asText() - val userid = data["userinfo"]["uid"].asLong() - val platform = MyUtils.randomLetterLowerNum(16) - val deviceId = MyUtils.randomLetterLowerNum(32) - val cookie = response.cookie() - val iqyEntity = IqyEntity() - iqyEntity.authCookie = authCookie - iqyEntity.userid = userid - iqyEntity.platform = platform - iqyEntity.deviceId = deviceId - iqyEntity.qyId = deviceId - iqyEntity.cookie = cookie - iqyEntity.p00001 = OkUtils.cookie(cookie, "P00001") ?: error("没有找到P00001的cookie") - iqyEntity - } - else -> error("未知错误") - } - } - - - private fun JsonNode.check() { - if (this["code"].asText() !in listOf("A00000", "Q00504")) error(this["msg"]?.asText() ?: this["message"].asText()) - } - - private fun messageId() = (System.currentTimeMillis() + MyUtils.randomNum(9).toLong()).toString().md5() - - private fun sign(iqyEntity: IqyEntity, taskCode: String, timestamp: Long): String { - val str = "agentType=1|agentversion=1.0|appKey=basic_pcw|authCookie=${iqyEntity.authCookie}|qyid=${iqyEntity.qyId}|task_code=$taskCode|timestamp=$timestamp|typeCode=point|userId=${iqyEntity.userid}|UKobMjDMsDoScuWOfp6F" - return str.md5() - } - - private suspend fun receiveTask(iqyEntity: IqyEntity, taskCode: String) { - val jsonNode = client.get("https://tc.vip.iqiyi.com/taskCenter/task/joinTask?P00001=${iqyEntity.p00001}&taskCode=${taskCode}&platform=${iqyEntity.platform}&lang=zh_CN&app_lm=cn") - .body() - jsonNode.check() - } - - private suspend fun receiveTaskAward(iqyEntity: IqyEntity, taskCode: String) { - val jsonNode = client.get("https://tc.vip.iqiyi.com/taskCenter/task/getTaskRewards?P00001=${iqyEntity.p00001}&taskCode=$taskCode&dfp=&platform=${iqyEntity.platform}&lang=zh_CN&app_lm=cn&deviceID=${iqyEntity.deviceId}&token=&multiReward=1&fv=bed99b2cf5722bfe") - .body() - jsonNode.check() - } - - private suspend fun watchPage(iqyEntity: IqyEntity, taskCode: String) { - val jsonNode = client.get("https://tc.vip.iqiyi.com/taskCenter/task/notify?taskCode=$taskCode&P00001=${iqyEntity.p00001}&platform=${iqyEntity.platform}&lang=cn&bizSource=component_browse_timing_tasks&_=${System.currentTimeMillis()}") - .body() - jsonNode.check() - } - - suspend fun task(iqyEntity: IqyEntity): IqyTask { - val jsonNode = client.get("https://tc.vip.iqiyi.com/taskCenter/task/getTaskStatus?appname=PCW&messageId=${messageId()}&version=2.0&invokeType=outer_http&lang=zh_cn&P00001=${iqyEntity.p00001}&taskCode=8a2186bb5f7bedd4,b6e688905d4e7184,acf8adbb5870eb29,843376c6b3e2bf00,8ba31f70013989a8,CHANGE_SKIN&newH5=1&fv=bed99b2cf5722bfe") - .body() - jsonNode.check() - return jsonNode["data"].convertValue() - } - - private suspend fun taskSign(iqyEntity: IqyEntity, taskCode: String) { - val timestamp = System.currentTimeMillis() - val sign = sign(iqyEntity, taskCode, timestamp) - val jsonNode = client.post("https://community.iqiyi.com/openApi/task/execute?agentType=1&agentversion=1.0&appKey=basic_pcw&authCookie=${iqyEntity.authCookie}&qyid=${iqyEntity.qyId}&task_code=$taskCode×tamp=$timestamp&typeCode=point&userId=${iqyEntity.userid}&sign=$sign") { - setJsonBody(""" - {"$taskCode":{"agentType":1,"agentversion":1,"authCookie":"${iqyEntity.authCookie}","dfp":"","qyid":"${iqyEntity.qyId}","verticalCode":"iQIYI","taskCode":"iQIYI_mofhr"}} - """.trimIndent()) - }.body() - jsonNode.check() - } - - suspend fun taskSign(iqyEntity: IqyEntity) { - taskSign(iqyEntity, "natural_month_sign") - taskSign(iqyEntity, "natural_month_sign_process") - } - - private suspend fun taskWatch(iqyEntity: IqyEntity, taskCode: String) { - receiveTask(iqyEntity, taskCode) - watchPage(iqyEntity, taskCode) - receiveTaskAward(iqyEntity, taskCode) - } - - suspend fun finishTaskWatch(iqyEntity: IqyEntity) { - taskWatch(iqyEntity, "b6e688905d4e7184") - taskWatch(iqyEntity, "a7f02e895ccbf416") - taskWatch(iqyEntity, "GetReward") - } - -} - -class IqyTask { - var finishedCount: Int = 0 - var count: Int = 0 - var tasks: List = mutableListOf() - class Task { - var name: String = "" - var taskCode: String = "" - var priority: Int = 0 - var status: Int = 0 - var belong: String = "" - var group: String = "" - var joinTime: String = "" - var rewardTime: String = "" - var taskGiftValue: Int = 0 - var taskTitle: String = "" - @JsonProperty("taskDescrip") - var taskDescription: String = "" - var androidUrl: String = "" - var bonusDes: String = "" - } -} - -data class IqyQrcode(val token: String, val url: String, val imageUrl: String, val cookie: String) \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/logic/MiHoYoLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/MiHoYoLogic.kt index bc87a4e..c33c8fb 100644 --- a/src/main/kotlin/me/kuku/telegram/logic/MiHoYoLogic.kt +++ b/src/main/kotlin/me/kuku/telegram/logic/MiHoYoLogic.kt @@ -6,7 +6,6 @@ import io.ktor.client.call.* import io.ktor.client.request.* import kotlinx.coroutines.delay import me.kuku.pojo.CommonResult -import me.kuku.pojo.UA import me.kuku.telegram.entity.MiHoYoEntity import me.kuku.utils.* import org.springframework.stereotype.Service @@ -356,7 +355,7 @@ class MiHoYoLogic( when (jsonNode.getInteger("retcode")) { 0, -5003 -> { val data = jsonNode["data"] - val gt = data["gt"].asText() + val gt = data["gt"]?.asText() ?: "" if (gt.isNotEmpty()) { val challenge = data["challenge"].asText() val rr = twoCaptchaLogic.geeTest(gt, challenge, "https://webstatic.mihoyo.com/", tgId = tgId) diff --git a/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt deleted file mode 100644 index 7065bcb..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt +++ /dev/null @@ -1,613 +0,0 @@ -package me.kuku.telegram.logic - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ObjectNode -import io.ktor.client.call.* -import io.ktor.client.request.* -import io.ktor.http.* -import kotlinx.coroutines.delay -import me.kuku.pojo.CommonResult -import me.kuku.pojo.UA -import me.kuku.telegram.config.api -import me.kuku.telegram.entity.NetEaseBaseEntity -import me.kuku.telegram.entity.NetEaseEntity -import me.kuku.telegram.entity.NetEaseSmallEntity -import me.kuku.utils.* -import okhttp3.internal.toHexString -import java.time.Duration -import kotlin.time.Duration.Companion.seconds - -object NetEaseLogic { - - private const val domain = "https://music.163.com" - - private const val ua = "NeteaseMusic/8.7.22.220331222744(8007022);Dalvik/2.1.0 (Linux; U; Android 12; M2007J3SC Build/SKQ1.211006.001)" - - private fun aesEncode(secretData: String, secret: String): String { - val vi = "0102030405060708" - return AESUtils.encrypt(secretData, secret, vi)!! - } - - private fun prepare(map: Map, netEaseEntity: NetEaseEntity? = null): Map { - return prepare(Jackson.toJsonString(map), netEaseEntity) - } - - private fun HttpRequestBuilder.setParams(map: Map, netEaseEntity: NetEaseEntity? = null) { - setFormDataContent { - prepare(Jackson.toJsonString(map), netEaseEntity).forEach { (k, v) -> - append(k, v) - } - } - } - - context(HttpRequestBuilder) - fun NetEaseBaseEntity?.encrypt(map: Map) { - encrypt(Jackson.toJsonString(map)) - } - - context(HttpRequestBuilder) - fun NetEaseBaseEntity?.encrypt(json: String) { - val nonce = "0CoJUm6Qyw8W8jud" - val secretKey = "TA3YiYCfY2dDJQgg" - val encSecKey = - "84ca47bca10bad09a6b04c5c927ef077d9b9f1e37098aa3eac6ea70eb59df0aa28b691b7e75e4f1f9831754919ea784c8f74fbfadf2898b0be17849fd656060162857830e241aba44991601f137624094c114ea8d17bce815b0cd4e5b8e2fbaba978c6d1d14dc3d1faf852bdd28818031ccdaaa13a6018e1024e2aae98844210" - val jsonNode = json.toJsonNode() - this?.let { - (jsonNode as ObjectNode).put("csrf_token", it.csrf) - } - var param = aesEncode(jsonNode.toString(), nonce) - param = aesEncode(param, secretKey) - setFormDataContent { - append("params", param) - append("encSecKey", encSecKey) - } - io.ktor.http.headers { - userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36") - this@encrypt?.pcCookie()?.let { - cookieString(it) - } - referer("https://music.163.com") - origin("https://music.163.com") - } - } - - private fun prepare(json: String, netEaseEntity: NetEaseEntity? = null, netEaseSmallEntity: NetEaseSmallEntity? = null): Map { - val nonce = "0CoJUm6Qyw8W8jud" - val secretKey = "TA3YiYCfY2dDJQgg" - val encSecKey = - "84ca47bca10bad09a6b04c5c927ef077d9b9f1e37098aa3eac6ea70eb59df0aa28b691b7e75e4f1f9831754919ea784c8f74fbfadf2898b0be17849fd656060162857830e241aba44991601f137624094c114ea8d17bce815b0cd4e5b8e2fbaba978c6d1d14dc3d1faf852bdd28818031ccdaaa13a6018e1024e2aae98844210" - val jsonNode = json.toJsonNode() - netEaseEntity?.let { - (jsonNode as ObjectNode).put("csrf_token", it.csrf) - } - netEaseSmallEntity?.let { - (jsonNode as ObjectNode).put("csrf_token", it.csrf) - } - var param = aesEncode(jsonNode.toString(), nonce) - param = aesEncode(param, secretKey) - return mapOf("params" to param, "encSecKey" to encSecKey) -// val nonce = "0CoJUm6Qyw8W8jud" -// val secretKey = MyUtils.randomLetterLowerNum(16).toByteArray().hex().substring(0, 16) -// val ss = BigInteger(HexUtils.byteArrayToHex(secretKey.reversed().toByteArray()), 16) -// .pow("010001".toInt(16)) -// val sss = BigInteger("00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7", 16) -// val d = ss.divideAndRemainder(sss)[1] -// val encSecKey = d.toString(16) -// val jsonNode = JSON.parseObject(json) -// netEaseEntity?.let { -// jsonNode["csrf_token"] = netEaseEntity.csrf -// } -// var param = aesEncode(jsonNode.toString(), nonce) -// param = aesEncode(param, secretKey) -// return mapOf("params" to param, "encSecKey" to encSecKey) - } - - suspend fun login(phone: String, password: String): CommonResult { - val map = mapOf("countrycode" to "86", "password" to if (password.length == 32) password else password.md5(), "phone" to phone, - "rememberLogin" to "true") - val response = OkHttpKtUtils.post("$domain/weapi/login/cellphone", prepare(map), - mapOf("Referer" to "https://music.163.com", "User-Agent" to "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36", - "cookie" to "os=ios; appver=8.7.01; __remember_me=true; ")) - val jsonNode = OkUtils.json(response) - return if (jsonNode["code"].asInt() == 200) { - val cookie = OkUtils.cookie(response) - val csrf = OkUtils.cookie(cookie, "__csrf")!! - val musicU = OkUtils.cookie(cookie, "MUSIC_U")!! - CommonResult.success(NetEaseEntity().also { - it.csrf = csrf - it.musicU = musicU - }) - } else CommonResult.failure(jsonNode.getString("message")) - } - - suspend fun qrcode(): String { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/login/qrcode/unikey", prepare("""{"type": 1}""")) - return jsonNode.getString("unikey") - } - - suspend fun checkQrcode(key: String): CommonResult { - val response = OkHttpKtUtils.post("https://music.163.com/weapi/login/qrcode/client/login", prepare("""{"type":1,"key":"$key"}"""), mapOf("crypto" to "weapi")) - val jsonNode = OkUtils.json(response) - return when (jsonNode.getInteger("code")) { - 803 -> { - val cookie = OkUtils.cookie(response) - val csrf = OkUtils.cookie(cookie, "__csrf") - val musicU = OkUtils.cookie(cookie, "MUSIC_U") - CommonResult.success(NetEaseEntity().also { - it.csrf = csrf!! - it.musicU = musicU!! - }) - } - 801 -> CommonResult.failure(code = 0, message = "等待扫码") - 802 -> CommonResult.failure(code = 1, message = "${jsonNode.getString("nickname")}已扫码,等待确认登陆") - 800 -> CommonResult.failure("二维码已过期") - else -> CommonResult.failure(jsonNode.getString("message")) - } - } - - suspend fun sign(netEaseEntity: NetEaseEntity) { - val map = mapOf("type" to "0") - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/point/dailyTask", prepare(map), - mapOf("cookie" to netEaseEntity.cookie(), "crypto" to "webapi", "referer" to "https://music.163.com/discover", - "user-agent" to UA.PC.value, "origin" to "https://music.163.com") - ) - val code = jsonNode.getInteger("code") - if (code != 200 && code != -2) error(jsonNode.getString("message")) - } - - private suspend fun recommend(netEaseEntity: NetEaseEntity): MutableList { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/v1/discovery/recommend/resource", - prepare(mapOf("csrf_token" to netEaseEntity.csrf)), OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC) - ) - return when (jsonNode.getInteger("code")) { - 200 -> { - val jsonArray = jsonNode["recommend"] - val list = mutableListOf() - jsonArray.forEach { list.add(it.getString("id")) } - list - } - 301 -> error("您的网易云音乐cookie已失效") - else -> error(jsonNode.getString("message")) - } - } - - - private suspend fun songId(playListId: String): JsonNode { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/v3/playlist/detail", - prepare(mapOf("id" to playListId, "total" to "true", "limit" to "1000", "n" to "1000")) - ) - return jsonNode["playlist"]["trackIds"] - } - - @Suppress("DuplicatedCode") - suspend fun listenMusic(netEaseEntity: NetEaseEntity) { - val playList = recommend(netEaseEntity) - val ids = Jackson.createArrayNode() - while (ids.size() < 310) { - val songIds = songId(playList.random()) - var k = 0 - while (ids.size() < 310 && k < songIds.size()) { - val jsonNode = Jackson.createObjectNode() - jsonNode.put("download", 0) - jsonNode.put("end", "playend") - jsonNode.put("id", songIds[k].getInteger("id")) - jsonNode.put("sourceId", "") - jsonNode.put("time", 240) - jsonNode.put("type", "song") - jsonNode.put("wifi", "0") - val totalJsonNode = Jackson.createObjectNode() - totalJsonNode.set("json", jsonNode) - totalJsonNode.put("action", "play") - ids.add(totalJsonNode) - k++ - } - } - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/feedback/weblog", prepare(mapOf("logs" to ids.toString())), - OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC)) - if (jsonNode.getInteger("code") != 200) error(jsonNode.getString("message")) - } - - suspend fun listenMusic0(netEaseSmallEntity: NetEaseSmallEntity, id: Long) { - - // 歌曲详情请求 - val songDetailResult = client.post("$domain/weapi/v3/song/detail") { - netEaseSmallEntity.encrypt(""" - {"c": "[{\"id\": $id}]", "id": "$id"} - """.trimIndent()) - }.body() - songDetailResult.check() - - // 歌词请求 - val lyricResult = client.post("$domain/weapi/song/lyric") { - netEaseSmallEntity.encrypt(""" - {"id":$id,"lv":-1,"tv":-1} - """.trimIndent()) - }.body() - lyricResult.check() - - // 歌曲URL请求 - val songUrlResult = client.post("$domain/weapi/song/enhance/player/url/v1") { - netEaseSmallEntity.encrypt(mapOf( - "ids" to "[$id]", - "level" to "standard", - "encodeType" to "aac" - )) - }.body() - songUrlResult.check() - val songUrl = songUrlResult["data"][0]["url"].asText() - val logUrl = "$domain/weapi/feedback/weblog" - - client.get(songUrl).body() - - // 反馈日志请求 - val log2 = client.post(logUrl) { - netEaseSmallEntity.encrypt(mapOf("logs" to """ - [{"action":"play","json":{"id":"$id","type":"song","source":"search","sourceid":"kuku","mainsite":"1","content":"s=kuku&type=1"}}] - """.trimIndent())) - }.body() - log2.check() - - val log3 = client.post(logUrl) { - netEaseSmallEntity.encrypt(mapOf("logs" to """ - [{"action":"play","json":{"type":"song","wifi":0,"download":0,"id":$id,"time":297,"end":"ui","source":"search","sourceId":"kuku","mainsite":"1","content":"s=kuku&type=1"}}] - """.trimIndent())) - }.body() - log3.check() - - val log1 = client.post(logUrl) { - netEaseSmallEntity.encrypt(mapOf("logs" to """ - [{"action":"startplay","json":{"id":$id,"type":"song","content":"s=kuku&type=1","mainsite":"1"}}] - """.trimIndent())) - }.body() - log1.check() - - val log4 = client.post(logUrl) { - netEaseSmallEntity.encrypt(mapOf("logs" to """ - [{"action":"mobile_monitor","json":{"meta._ver":2,"meta._dataName":"pip_lyric_monitor","action":"render","userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36","chromeVersion":128,"resourceId":$id,"resourceType":"song","mainsite":"1"}}] - """.trimIndent())) - }.body() - log4.check() - - val log5 = client.post(logUrl) { - netEaseSmallEntity.encrypt(mapOf("logs" to """ - [{"action":"sysaction","json":{"dataType":"cdnCompare","cdnType":"NetEase","loadeddataTime":15791,"resourceType":"audiom4a","resourceId":$id,"resourceUrl":"$songUrl","xySupport":true,"error":false,"errorType":"","ua":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36","mainsite":"1"}}] - """.trimIndent())) - }.body() - log5.check() - - } - - suspend fun listenMusic(netEaseSmallEntity: NetEaseSmallEntity, id: Long) { - val jsonNode = client.get("http://192.168.1.177:8000/neteasemusic/listen?music_id=${id}&cookie=${netEaseSmallEntity.cookie().toUrlEncode()}") - .body() - val sleep = jsonNode["sleep"].asLong() + 30 - delay(sleep.seconds) - } - - private suspend fun musicianStageMission(netEaseEntity: NetEaseEntity): MutableList { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/nmusician/workbench/mission/stage/list", prepare(mapOf()), - OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC)) - return if (jsonNode.getInteger("code") == 200) { - val jsonArray = jsonNode["data"]["list"] - val list = mutableListOf() - jsonArray.forEach { - list.add(Mission(it["userStageTargetList"][0]["userMissionId"]?.asLong(), it.getInteger("period"), it.getInteger("type"), it.getString("description"))) - } - list - } else error(jsonNode.getString("message")) - } - - private suspend fun musicianCycleMission(netEaseEntity: NetEaseEntity): List { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/nmusician/workbench/mission/cycle/list", - prepare(mapOf("actionType" to "", "platform" to "")), - OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC)) - return if (jsonNode.getInteger("code") == 200) { - val jsonArray = jsonNode["data"]["list"] - val list = mutableListOf() - jsonArray.forEach { - list.add(Mission(it.get("userMissionId")?.asLong(), it.getInteger("period"), it.getInteger("type"), it.getString("description"))) - } - list - } else error(jsonNode.getString("message")) - } - - private suspend fun musicianReceive(netEaseEntity: NetEaseEntity, mission: Mission) { - val missionId = mission.userMissionId?.toString() ?: error("userMissionId为空") - val jsonNode = OkHttpKtUtils.postJson("https://interface.music.163.com/weapi/nmusician/workbench/mission/reward/obtain/new", - prepare(mapOf("userMissionId" to missionId, "period" to mission.period.toString())), - OkUtils.headers(netEaseEntity.androidCookie(), domain, "Mozilla/5.0 (Linux; Android 12; M2007J3SC Build/SKQ1.211006.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/120.0.6099.210 Mobile Safari/537.36 CloudMusic/0.1.2 NeteaseMusic/9.0.10") - ) - val code = jsonNode.getInteger("code") - if (code != 200 && code != -2) error(jsonNode.getString("message")) - } - - private suspend fun userAccess(netEaseEntity: NetEaseEntity) { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/creator/user/access", prepare(mapOf()), OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC)) - if (jsonNode.getInteger("code") != 200) error(jsonNode.getString("message")) - } - - suspend fun musicianSign(netEaseEntity: NetEaseEntity) { - userAccess(netEaseEntity) - val list = musicianCycleMission(netEaseEntity) - for (mission in list) { - if (mission.description == "音乐人中心签到") { -// if (mission.type != 100) { -// userAccess(netEaseEntity) -// } - return musicianReceive(netEaseEntity, mission) - } - } - error("没有找到音乐人签到任务") - } - - suspend fun myMusic(netEaseEntity: NetEaseEntity): List { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/nmusician/production/common/artist/song/item/list/get?csrf_token=${netEaseEntity.csrf}", - prepare(mapOf("fromBackend" to "0", "limit" to "10", "offset" to "0", "online" to "1")), - mapOf("user-agent" to UA.PC.value, "cookie" to netEaseEntity.cookie(), "referer" to "https://music.163.com/nmusician/web/albums/work/actor/song/self/pub")) - return if (jsonNode.getInteger("code") == 200) { - val list = mutableListOf() - jsonNode["data"]["list"].forEach { - list.add(NetEaseSong(it.getString("songName"), it.getLong("songId"), it.getLong("albumId"), it.getString("albumName"))) - } - list - } else error(jsonNode.getString("message")) - } - - private suspend fun personalizedPlaylist(netEaseEntity: NetEaseEntity): List { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/personalized/playlist", - prepare(mapOf("limit" to "9")), OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC) - ) - return if (jsonNode.getInteger("code") == 200) { - val list = mutableListOf() - jsonNode["result"].forEach { - list.add(Play(it.getString("name"), it.getLong("id"), it.getLong("playCount"))) - } - list - } else error(jsonNode["message"]?.asText() ?: "获取失败") - } - - private suspend fun shareResource(netEaseEntity: NetEaseEntity, id: Long, message: String = "每日分享"): Long { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/share/friends/resource", - prepare(mapOf("type" to "playlist", "id" to id.toString(), "message" to message)), - mapOf("cookie" to netEaseEntity.cookie(), "referer" to domain, "user-agent" to UA.PC.value) - ) - return if (jsonNode.getInteger("code") == 200) - jsonNode.getLong("id") - else error(jsonNode.getString("message")) - } - - private suspend fun removeDy(netEaseEntity: NetEaseEntity, id: Long) { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/event/delete", - prepare(mapOf("id" to id.toString())), - OkUtils.headers(netEaseEntity.pcCookie(), domain, UA.PC) - ) - if (jsonNode.getInteger("code") != 200) error(jsonNode["message"]?.asText() ?: "删除动态失败") - } - - private suspend fun finishCycleMission(netEaseEntity: NetEaseEntity, name: String) { - val list = musicianCycleMission(netEaseEntity) - for (mission in list) { - if (mission.description == name) { - if (mission.type != 100) { - userAccess(netEaseEntity) - } - return musicianReceive(netEaseEntity, mission) - } - } - error("没有找到音乐人签到任务:$name") - } - - private suspend fun finishStageMission(netEaseEntity: NetEaseEntity, name: String) { - val list = musicianStageMission(netEaseEntity) - for (mission in list) { - if (mission.description == name) { - if (mission.type != 100) { - userAccess(netEaseEntity) - } - return musicianReceive(netEaseEntity, mission) - } - } - error("没有找到音乐人签到任务:$name") - } - - suspend fun publish(netEaseEntity: NetEaseEntity) { - val list = myMusic(netEaseEntity) - val netEaseSong = list.random() - val commentId = shareMySong(netEaseEntity, netEaseSong.songId) - removeDy(netEaseEntity, commentId) - finishStageMission(netEaseEntity, "发布动态") - } - - private suspend fun mLogNosToken(netEaseEntity: NetEaseEntity, url: String): MLogInfo { - val bizKey = StringBuilder() - for (i in 0..8) { - bizKey.append(MyUtils.randomInt(0, 15).toHexString().replace("0x", "")) - } - val fileName = "album.jpg" - val bytes = - OkHttpKtUtils.getBytes(url) - val size = bytes.size - val md5 = bytes.md5() - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/nos/token/whalealloc", - prepare(mapOf("bizKey" to bizKey.toString(), "filename" to fileName, "bucket" to "yyimgs", - "md5" to md5, "type" to "image", "fileSize" to size.toString())), - OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC) - ) - return if (jsonNode.getInteger("code") == 200) { - val dataJsonNode = jsonNode["data"] - MLogInfo(dataJsonNode.getLong("resourceId"), dataJsonNode.getString("objectKey"), dataJsonNode.getString("token"), - dataJsonNode.getString("bucket"), bytes) - } else error(jsonNode.getString("message")) - } - - private suspend fun uploadFile(netEaseEntity: NetEaseEntity, mLogInfo: MLogInfo): UploadFileInfo { - val url = "http://45.127.129.8/${mLogInfo.bucket}/${mLogInfo.objectKey}?offset=0&complete=true&version=1.0" - val contentType = "image/jpg" - val jsonNode = OkHttpKtUtils.postJson(url, OkUtils.streamBody(mLogInfo.byteArray, contentType), - mapOf("x-nos-token" to mLogInfo.token, "cookie" to netEaseEntity.cookie(), "referer" to domain)) - return Jackson.parseObject(Jackson.toJsonString(jsonNode)) - } - - private suspend fun songDetail(netEaseEntity: NetEaseEntity, id: Long): SongDetail { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/v3/song/detail", - prepare(""" - {"c": "[{\"id\": $id}]", "ids": "[$id]"} - """.trimIndent(), netEaseEntity), - OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC) - ) - return if (jsonNode.getInteger("code") == 200) { - val songJsonNode = jsonNode["songs"][0] - SongDetail(songJsonNode.getString("name"), songJsonNode["ar"][0].getString("name"), - songJsonNode["al"].getString("picUrl") + "?param=500y500") - } else error(jsonNode.getString("message")) - } - - suspend fun publishMLog(netEaseEntity: NetEaseEntity) { - val list = myMusic(netEaseEntity) - val songId = list.random().songId - val songDetail = songDetail(netEaseEntity, songId) - val mLogInfo = mLogNosToken(netEaseEntity, songDetail.pic) - uploadFile(netEaseEntity, mLogInfo) - val songName = songDetail.name - val text = "分享${songDetail.artistName}的歌曲: ${songDetail.name}" - val jsonStr = """ - {"type":1,"mlog":"{\"content\": {\"image\": [{\"height\": 500, \"width\": 500, \"more\": false, \"nosKey\": \"${mLogInfo.bucket}/${mLogInfo.objectKey}\", \"picKey\": ${mLogInfo.resourceId}}], \"needAudio\": false, \"song\": {\"endTime\": 0, \"name\": \"${songName}\", \"songId\": $songId, \"startTime\": 30000}, \"text\": \"$text\"}, \"from\": 0, \"type\": 1}"} - """.trimIndent() - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/mlog/publish/v1", prepare(jsonStr), OkUtils.headers(netEaseEntity.cookie(), domain, UA.PC)) - return if (jsonNode.getInteger("code") == 200) { - val resourceId = jsonNode["data"]["event"]["info"].getLong("resourceId") - removeDy(netEaseEntity, resourceId) -// finishCycleMission(netEaseEntity, "发布mlog") - } else error(jsonNode.getString("message")) - } - - private suspend fun musicComment(netEaseEntity: NetEaseEntity, id: Long, comment: String = "欢迎大家收听"): Long { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/v1/resource/comments/add", - prepare(mapOf("threadId" to "R_SO_4_$id", "content" to comment)), - OkUtils.headers(netEaseEntity.cookie().replace("os=pc; ", "") + "os=android; ", domain, ua) - ) - jsonNode.check() - return jsonNode["comment"].getLong("commentId") - } - - private suspend fun userid(netEaseEntity: NetEaseEntity): String { - val html = client.get("https://music.163.com/discover") { - cookieString(netEaseEntity.cookie()) - userAgent(UA.PC.value) - }.body() - return MyUtils.regex("\\{userId:", ",", html) ?: error("获取userid失败") - } - - private suspend fun dynamicComment(netEaseEntity: NetEaseEntity, id: Long, comment: String = "评论"): Long { - val userid = userid(netEaseEntity) - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/resource/comments/add", - prepare(mapOf("threadId" to "A_EV_2_${id}_$userid", "content" to comment)), - OkUtils.headers(netEaseEntity.cookie().replace("os=pc; ", "") + "os=android; ", domain, ua) - ) - return if (jsonNode.getInteger("code") == 200) { - jsonNode["comment"].getLong("commentId") - } else error(jsonNode.getString("message")) - } - - private suspend fun deleteMusicComment(netEaseEntity: NetEaseEntity, id: Long, commentId: Long) { - val jsonNode = OkHttpKtUtils.postJson("$domain/weapi/resource/comments/delete", - prepare(mapOf("commentId" to commentId.toString(), "threadId" to "R_SO_4_$id")), - OkUtils.headers(netEaseEntity.pcCookie(), domain, UA.PC) - ) - if (jsonNode.getInteger("code") != 200) error(jsonNode.getString("message")) - } - - // /api/nmusician/workbench/upgrade/production/song/publish/list - // {"limit":10,"offset":0,"publishStatus":200,"operations":"[\\"MANAGE_SONG\\",\\"EDIT_SONG\\",\\"OFFLINE_SONG\\",\\"SET_SCHEDULE_TIME\\"]","onlyBeat":false} - - suspend fun myMusicComment(netEaseEntity: NetEaseEntity) { - val list = myMusic(netEaseEntity) - val netEaseSong = list.random() - val commentId1 = musicComment(netEaseEntity, netEaseSong.songId) - delay(2000) - deleteMusicComment(netEaseEntity, netEaseSong.songId, commentId1) - val commentId2 = musicComment(netEaseEntity, netEaseSong.songId) - delay(2000) - deleteMusicComment(netEaseEntity, netEaseSong.songId, commentId2) -// finishStageMission(netEaseEntity, "发表主创说") - } - - private fun JsonNode.check() { - if (this["code"].asInt() != 200) error(this["message"].asText()) - } - - /** - * https://interface.music.163.com/api/vipnewcenter/app/level/task/reward/getall - * https://interface.music.163.com/weapi/batch?csrf_token=b04a98c9c484bba93a1bcc16147ac6e7 - * {"/api/vipnewcenter/app/level/myvip":"","/api/vipnewcenter/app/vipcenter/level/privilege/guide":"","/api/music-vip-membership/front/vip/info":"","/api/vip-center-bff/task/list":"","/api/vipnewcenter/app/user/max/score":""} - */ - suspend fun vipSign(netEaseEntity: NetEaseEntity) { - val jsonNode = client.post("https://interface.music.163.com/weapi/vip-center-bff/task/sign?csrf_token=${netEaseEntity.csrf}") { - setParams(mapOf()) - cookieString(netEaseEntity.cookie()) - }.body() - jsonNode.check() - } - - suspend fun receiveTaskReward(netEaseEntity: NetEaseEntity) { - val jsonNode = client.post("https://interface.music.163.com/api/vipnewcenter/app/level/task/reward/getall") { - setParams(mapOf()) - cookieString(netEaseEntity.cookie()) - }.body() - jsonNode.check() - } - - private suspend fun shareMySong(netEaseEntity: NetEaseEntity, songId: Long, msg: String = "每日分享"): Long { - val checkTokenNode = client.post("$api/exec/netEase/checkToken").body() - val checkToken = checkTokenNode["checkToken"]?.asText() ?: error("获取checkToken失败,请重试或检查api") - val jsonNode = client.post("$domain/weapi/share/friends/resource") { - setParams(mapOf("type" to "song", "id" to songId.toString(), "msg" to msg, - "uuid" to "publish-${System.currentTimeMillis()}${MyUtils.randomNum(5)}", "checkToken" to checkToken)) - cookieString(netEaseEntity.cookie()) - }.body() - jsonNode.check() - return jsonNode["id"].asLong() - } - - suspend fun shareMySong(netEaseEntity: NetEaseEntity) { - val list = myMusic(netEaseEntity) - val netEaseSong = list.random() - val commentId = shareMySong(netEaseEntity, netEaseSong.songId) - removeDy(netEaseEntity, commentId) - finishCycleMission(netEaseEntity, "在动态分享歌曲") - } - - suspend fun commentMyDy(netEaseEntity: NetEaseEntity) { - val list = myMusic(netEaseEntity) - val netEaseSong = list.random() - val commentId = shareMySong(netEaseEntity, netEaseSong.songId) - dynamicComment(netEaseEntity, commentId) - removeDy(netEaseEntity, commentId) - finishCycleMission(netEaseEntity, "在自己动态下发布评论") - } - - suspend fun publishAndShareMySongAndComment(netEaseEntity: NetEaseEntity) { - val list = myMusic(netEaseEntity) - val netEaseSong = list.random() - val commentId = shareMySong(netEaseEntity, netEaseSong.songId) - dynamicComment(netEaseEntity, commentId) - removeDy(netEaseEntity, commentId) - delay(5000) - finishStageMission(netEaseEntity, "发布动态") -// finishCycleMission(netEaseEntity, "在动态分享歌曲") -// finishCycleMission(netEaseEntity, "在自己动态下发布评论") - } - -} - -data class Mission(val userMissionId: Long?, val period: Int, val type: Int, val description: String = "") - -data class NetEaseSong(val songName: String, val songId: Long, val albumId: Long, val albumName: String) - -data class Play(val name: String, val id: Long, val playCount: Long) - -data class MLogInfo(val resourceId: Long, val objectKey: String, val token: String, val bucket: String, val byteArray: ByteArray) - -data class UploadFileInfo(var callbackRetmessage: String = "", var offset: Long = 0, var requestId: String = "", var context: String = "", var callbackRetMsg: String = "") - -data class SongDetail(val name: String, val artistName: String, val pic: String) diff --git a/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt deleted file mode 100644 index ac996c0..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt +++ /dev/null @@ -1,61 +0,0 @@ -package me.kuku.telegram.logic - -import com.fasterxml.jackson.databind.JsonNode -import io.ktor.client.call.* -import io.ktor.client.request.* -import kotlinx.coroutines.delay -import me.kuku.telegram.entity.NetEaseSmallService -import me.kuku.telegram.entity.Status -import me.kuku.utils.client -import org.springframework.stereotype.Service - -@Service -class NetEaseSmallLogic( - private val netEaseSmallService: NetEaseSmallService -) { - - suspend fun check() { - val list = netEaseSmallService.findAll() - for (netEaseSmallEntity in list) { - if (netEaseSmallEntity.status == Status.ON && !netEaseSmallEntity.oneDayAgo()) continue - val loginResult = NetEaseLogic.login(netEaseSmallEntity.username, netEaseSmallEntity.password) - delay(2000) - if (loginResult.success()) { - val newEntity = loginResult.data() - netEaseSmallEntity.csrf = newEntity.csrf - netEaseSmallEntity.musicU = newEntity.musicU - netEaseSmallEntity.reason = "" - netEaseSmallEntity.status = Status.ON - netEaseSmallService.save(netEaseSmallEntity) - } else { - kotlin.runCatching { - val jsonNode = client.get("http://192.168.1.177:8000/neteasemusic/login?phone=${netEaseSmallEntity.username}&password=${netEaseSmallEntity.password}") - .body() - val musicU = jsonNode["musicU"].asText() - val csrf = jsonNode["csrf"].asText() - netEaseSmallEntity.csrf = csrf - netEaseSmallEntity.musicU = musicU - netEaseSmallEntity.status = Status.ON - netEaseSmallEntity.reason = "" - netEaseSmallService.save(netEaseSmallEntity) - }.onFailure { - netEaseSmallEntity.status = Status.OFF - netEaseSmallEntity.reason = loginResult.message - netEaseSmallService.save(netEaseSmallEntity) - } - - } - } - } - - suspend fun listenMusic(id: Long) { - val list = netEaseSmallService.findByStatus(Status.ON) - for (netEaseSmallEntity in list) { - if (netEaseSmallEntity.csrf.isNotEmpty()) { - NetEaseLogic.listenMusic0(netEaseSmallEntity, id) - } - } - } - - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/logic/PixivLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/PixivLogic.kt deleted file mode 100644 index 256d63b..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/PixivLogic.kt +++ /dev/null @@ -1,73 +0,0 @@ -package me.kuku.telegram.logic - -import me.kuku.telegram.entity.PixivEntity -import me.kuku.utils.OkHttpKtUtils -import me.kuku.utils.OkUtils -import java.io.InputStream - -object PixivLogic { - - fun loginByWeibo() { - - } - - - suspend fun followImage(pixivEntity: PixivEntity): List { - val jsonNode = OkHttpKtUtils.getJson("https://www.pixiv.net/ajax/follow_latest/illust?p=1&mode=all&lang=zh", - OkUtils.headers(pixivEntity.cookie, "https://www.pixiv.net/bookmark_new_illust.php")) - if (jsonNode["error"].asBoolean()) error(jsonNode["message"].asText()) - val list = mutableListOf() - for (node in jsonNode["body"]["thumbnails"]["illust"]) { - val id = node["id"].asLong() - val userid = node["userId"].asLong() - val username = node["userName"].asText() - val title = node["title"].asText() - val alt = node["alt"].asText() - val createDate = node["createDate"].asText() - val updateDate = node["updateDate"].asText() - val pojo = PixivPojo(id, userid, username, title, alt, createDate, updateDate) - node["tags"].forEach { - pojo.tags.add(it.asText()) - } - list.add(pojo) - } - return list - } - - suspend fun imageById(id: Long): List { - val jsonNode = OkHttpKtUtils.getJson("https://www.pixiv.net/ajax/illust/$id/pages?lang=zh", - OkUtils.referer("https://www.pixiv.net/artworks/101070399")) - if (jsonNode["error"].asBoolean()) error(jsonNode["message"].asText()) - val list = mutableListOf() - val body = jsonNode["body"] - for (node in body) { - val url = node["urls"]["original"].asText() - list.add(url) - } - return list - } - - fun convertStr(pixivPojo: PixivPojo): String { - val sb = StringBuilder() - sb.appendLine("#${pixivPojo.username}") - .appendLine("标题:${pixivPojo.title}") - .appendLine("描述:${pixivPojo.alt}") - .appendLine("创建时间:${pixivPojo.createDate}") - .appendLine("更新时间:${pixivPojo.updateDate}") - .append("tag:") - pixivPojo.tags.forEach { - sb.append("$it ") - } - return sb.toString() - } - - suspend fun imageIs(url: String): InputStream { - return OkHttpKtUtils.getByteStream(url, OkUtils.referer("https://www.pixiv.net")) - } - - -} - -data class PixivPojo(val id: Long, val userid: Long, val username: String, val title: String, val alt: String, - val createDate: String, val updateDate: String, - val tags: MutableList = mutableListOf()) diff --git a/src/main/kotlin/me/kuku/telegram/logic/TwitterLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/TwitterLogic.kt deleted file mode 100644 index c274b00..0000000 --- a/src/main/kotlin/me/kuku/telegram/logic/TwitterLogic.kt +++ /dev/null @@ -1,251 +0,0 @@ -@file:Suppress("DuplicatedCode") - -package me.kuku.telegram.logic - -import com.fasterxml.jackson.databind.JsonNode -import io.ktor.client.call.* -import io.ktor.client.request.* -import io.ktor.client.statement.* -import io.ktor.http.* -import me.kuku.telegram.entity.TwitterEntity -import me.kuku.utils.* -import org.jsoup.Jsoup - -object TwitterLogic { - - private var guestToken: String? = null - - private fun Map.auth(): MutableMap { - val map = this.toMutableMap() - map["authorization"] = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA" - map["accept-language"] = "zh-CN,zh;q=0.9" - return map - } - - suspend fun login(username: String, password: String): TwitterEntity { - val guestJsonNode = OkHttpKtUtils.postJson("https://api.twitter.com/1.1/guest/activate.json", mapOf(), - mapOf().auth()) - val guestToken = guestJsonNode["guest_token"].asText() - val headers = mapOf("x-guest-token" to guestToken).auth() - val flowJsonNode = OkHttpKtUtils.postJson("https://twitter.com/i/api/1.1/onboarding/task.json?flow_name=login", OkUtils.json(""" - {"input_flow_data":{"flow_context":{"debug_overrides":{},"start_location":{"location":"unknown"}}},"subtask_versions":{"action_list":2,"alert_dialog":1,"app_download_cta":1,"check_logged_in_account":1,"choice_selection":3,"contacts_live_sync_permission_prompt":0,"cta":7,"email_verification":2,"end_flow":1,"enter_date":1,"enter_email":2,"enter_password":5,"enter_phone":2,"enter_recaptcha":1,"enter_text":5,"enter_username":2,"generic_urt":3,"in_app_notification":1,"interest_picker":3,"js_instrumentation":1,"menu_dialog":1,"notifications_permission_prompt":2,"open_account":2,"open_home_timeline":1,"open_link":1,"phone_verification":4,"privacy_options":1,"security_key":3,"select_avatar":4,"select_banner":2,"settings_list":7,"show_code":1,"sign_up":2,"sign_up_review":4,"tweet_selection_urt":1,"update_users":1,"upload_media":1,"user_recommendations_list":4,"user_recommendations_urt":1,"wait_spinner":3,"web_modal":1}} - """.trimIndent()), headers) - var flowToken = flowJsonNode["flow_token"].asText() - val str = OkHttpKtUtils.getStr("https://twitter.com/i/js_inst?c_name=ui_metrics") - val json = "{" + MyUtils.regex("return \\{", ";\\};", str) - val taskNode = OkHttpKtUtils.postJson("https://twitter.com/i/api/1.1/onboarding/task.json", OkUtils.json(""" - {"flow_token":"$flowToken","subtask_inputs":[{"subtask_id":"LoginJsInstrumentationSubtask","js_instrumentation":{"response":"$json","link":"next_link"}}]} - """.trimIndent()), headers) - flowToken = taskNode["flow_token"].asText() - val usernameJsonNode = OkHttpKtUtils.postJson("https://twitter.com/i/api/1.1/onboarding/task.json", OkUtils.json(""" - {"flow_token":"$flowToken","subtask_inputs":[{"subtask_id":"LoginEnterUserIdentifierSSO","settings_list":{"setting_responses":[{"key":"user_identifier","response_data":{"text_data":{"result":"$username"}}}],"link":"next_link"}}]} - """.trimIndent()), headers) - flowToken = usernameJsonNode["flow_token"].asText() - val loginJsonNode = OkHttpKtUtils.postJson("https://twitter.com/i/api/1.1/onboarding/task.json", OkUtils.json(""" - {"flow_token":"$flowToken","subtask_inputs":[{"subtask_id":"LoginEnterPassword","enter_password":{"password":"$password","link":"next_link"}}]} - """.trimIndent()), headers) - return if (loginJsonNode["status"]?.asText() == "success") { - flowToken = loginJsonNode["flow_token"].asText() - val response = OkHttpKtUtils.post("https://twitter.com/i/api/1.1/onboarding/task.json", OkUtils.json(""" - {"flow_token":"$flowToken","subtask_inputs":[{"subtask_id":"AccountDuplicationCheck","check_logged_in_account":{"link":"AccountDuplicationCheck_false"}}]} - """.trimIndent()), headers) - response.close() - val cookie = OkUtils.cookie(response) - val ct = OkUtils.cookie(cookie, "ct0")!! - val checkResponse = OkHttpKtUtils.get("https://twitter.com/i/api/graphql/4jeP7HyKpQUitFUTWedrqA/Viewer?variables=%7B%22withCommunitiesMemberships%22%3Atrue%2C%22withCommunitiesCreation%22%3Atrue%2C%22withSuperFollowsUserFields%22%3Atrue%7D&features=%7B%22responsive_web_graphql_timeline_navigation_enabled%22%3Afalse%7D", - headers.also { - it["cookie"] = cookie - it["x-csrf-token"] = ct - }) - val checkJsonNode = OkUtils.json(checkResponse) - val resultJsonNode = checkJsonNode["data"]["viewer"]["user_results"]["result"] - val id = resultJsonNode["id"].asText() - val restId = resultJsonNode["rest_id"].asText() - val ctCookie = OkUtils.cookie(checkResponse) - val ct0 = OkUtils.cookie(ctCookie, "ct0")!! - val resCookie = cookie.replace("ct0=$ct;", "ct0=$ct0;") - TwitterEntity().also { - it.cookie = resCookie - it.tId = id - it.tRestId = restId - it.csrf = ct0 - } - } else error(loginJsonNode["errors"][0]["message"].asText()) - } - - private fun Map.auth(twitterEntity: TwitterEntity): MutableMap { - val map = auth() - map["cookie"] = twitterEntity.cookie - map["x-csrf-token"] = twitterEntity.csrf - return map - } - - private fun convert(jsonNode: JsonNode): TwitterPojo? { - val content = jsonNode["content"]["itemContent"] - if (content?.get("socialContext") != null) return null - val result = content?.get("tweet_results")?.get("result") ?: return null - val legacy = result["legacy"] ?: return null - val createdAt = legacy["created_at"].asText() - val text = legacy["full_text"].asText() - val userid = legacy["user_id_str"].asLong() - val userResult = result["core"]["user_results"]["result"] - val userLegacy = userResult["legacy"] - val username = userLegacy["name"].asText() - val screenName = userLegacy["screen_name"].asText() - val source = Jsoup.parse(legacy["source"]?.asText() ?: "").text() - val id = legacy["id_str"].asLong() - val pojo = TwitterPojo(id, createdAt, text, userid, username, screenName, source) - legacy["extended_entities"]?.get("media")?.let { - for (node in it) { - val type = node["type"].asText() - if (type == "photo") { - pojo.photoList.add(node["media_url_https"].asText()) - } - if (type == "video") { - val url = node["video_info"]["variants"][0]["url"].asText() - pojo.videoList.add(url) - } - } - } - result["quoted_status_result"]?.let { - pojo.forward = true - val quotedResult = it["result"] - val forwardId = quotedResult["rest_id"].asLong() - val forwardUserResult = quotedResult["core"]["user_results"]["result"] - val forwardUserid = forwardUserResult["rest_id"].asLong() - val forwardUserLegacy = forwardUserResult["legacy"] - val forwardUsername = forwardUserLegacy["name"].asText() - val forwardScreenName = forwardUserLegacy["screen_name"].asText() - val quotedLegacy = quotedResult["legacy"] - val forwardText = quotedLegacy["full_text"].asText() - val forwardCreatedAt = quotedLegacy["created_at"].asText() - val forwardSource = Jsoup.parse(quotedLegacy["source"]?.asText() ?: "").text() - pojo.forwardId = forwardId - pojo.forwardCreatedAt = forwardCreatedAt - pojo.forwardText = forwardText - pojo.forwardUserid = forwardUserid - pojo.forwardUsername = forwardUsername - pojo.forwardScreenName = forwardScreenName - pojo.forwardSource = forwardSource - quotedLegacy["extended_entities"]?.get("media")?.let { media -> - for (node in media) { - val type = node["type"].asText() - if (type == "photo") { - pojo.forwardPhotoList.add(node["media_url_https"].asText()) - } - if (type == "video") { - val url = node["video_info"]["variants"][0]["url"].asText() - pojo.forwardVideoList.add(url) - } - } - } - } - return pojo - } - - private suspend fun guestToken(): String { - return if (guestToken == null || !checkGuest(guestToken!!)) { - val url = "https://twitter.com/home" - val response = client.get(url) - val cookie = response.cookie() - val text = client.get(url) { - headers { cookieString(cookie) } - }.bodyAsText() - guestToken = MyUtils.regex("gt=", ";", text) ?: error("未获取到guest-token") - guestToken!! - } else guestToken!! - } - - private suspend fun checkGuest(token: String): Boolean { - val response = client.get("https://twitter.com/i/api/1.1/hashflags.json") { - headers { - append("Authorization", "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA") - append("X-Guest-Token", token) - } - } - return response.status != HttpStatusCode.Forbidden - } - - suspend fun tweet(id: Long): TwitterPojo { - val guestToken = guestToken() - val jsonNode = client.get("https://twitter.com/i/api/graphql/0hWvDhmW8YQ-S_ib3azIrw/TweetResultByRestId?variables=%7B%22tweetId%22%3A%22${id}%22%2C%22withCommunity%22%3Afalse%2C%22includePromotedContent%22%3Afalse%2C%22withVoice%22%3Afalse%7D&features=%7B%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticleRichContentState%22%3Afalse%2C%22withAuxiliaryUserLabels%22%3Afalse%7D") { - headers { - append("Authorization", "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA") - append("X-Guest-Token", guestToken) - } - }.body() - val result = jsonNode["data"]["tweetResult"]["result"] - val restId = result["rest_id"].asLong() - val userResult = result["core"]["user_results"]["result"] - val userLegacy = userResult["legacy"] - val createAt = userLegacy["created_at"].asText() - val username = userLegacy["name"].asText() - val screenName = userLegacy["screen_name"].asText() - val userid = userResult["rest_id"].asLong() - val legacy = result["legacy"] - val source = Jsoup.parse(result["source"].asText()).text() - val text = legacy["full_text"].asText() - val pojo = TwitterPojo(restId, createAt, text, userid, username, screenName, source) - legacy["extended_entities"]?.get("media")?.let { - for (node in it) { - val type = node["type"].asText() - if (type == "photo") { - pojo.photoList.add(node["media_url_https"].asText()) - } - if (type == "video") { - val url = node["video_info"]["variants"] - .filter { va -> va["content_type"].asText() == "video/mp4" } - .maxBy { va -> va["bitrate"].asInt() }["url"].asText() - pojo.videoList.add(url) - } - } - } - return pojo - } - - suspend fun friendTweet(twitterEntity: TwitterEntity): List { - val response = OkHttpKtUtils.get("https://twitter.com/i/api/graphql/xDH0v9kM5QTSTNtbAke9TQ/HomeTimeline?variables=%7B%22count%22%3A20%2C%22includePromotedContent%22%3Afalse%2C%22latestControlAvailable%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withSuperFollowsUserFields%22%3Atrue%2C%22withDownvotePerspective%22%3Afalse%2C%22withReactionsMetadata%22%3Afalse%2C%22withReactionsPerspective%22%3Afalse%2C%22withSuperFollowsTweetFields%22%3Atrue%7D&features=%7B%22responsive_web_graphql_timeline_navigation_enabled%22%3Afalse%2C%22unified_cards_ad_metadata_container_dynamic_card_content_query_enabled%22%3Afalse%2C%22dont_mention_me_view_api_enabled%22%3Atrue%2C%22responsive_web_uc_gql_enabled%22%3Atrue%2C%22vibe_api_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Afalse%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Afalse%2C%22interactive_text_enabled%22%3Atrue%2C%22responsive_web_text_conversations_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Atrue%7D", - mapOf().auth(twitterEntity) - ) - if (response.code != 200) error("cookie已失效") - val jsonNode = OkUtils.json(response) - val list = mutableListOf() - val arrayNode = jsonNode["data"]["home"]["home_timeline_urt"]["instructions"][0]["entries"] - for (node in arrayNode) { - convert(node)?.let { - list.add(it) - } - } - return list - } - - fun convertStr(twitterPojo: TwitterPojo): String { - val sb = StringBuilder() - sb.appendLine("#${twitterPojo.username}") - .appendLine("发布时间:${twitterPojo.createdAt}") - .appendLine("内容:${twitterPojo.text}") - .append("链接:${twitterPojo.url()}") - if (twitterPojo.forward) { - sb.appendLine() - .appendLine("转发自:#${twitterPojo.forwardUsername}") - .appendLine("发布时间:${twitterPojo.forwardCreatedAt}") - .appendLine("内容:${twitterPojo.forwardText}") - .append("链接:${twitterPojo.forwardUrl()}") - } - return sb.toString() - } - -} - -data class TwitterPojo(val id: Long, val createdAt: String, val text: String, val userid: Long, val username: String, val screenName: String, val source: String, - var forward: Boolean = false, var forwardId: Long = 0, var forwardCreatedAt: String = "", var forwardText: String = "", - var forwardUserid: Long = 0, var forwardUsername: String = "", var forwardScreenName: String = "", var forwardSource: String = "") { - val photoList = mutableListOf() - val videoList = mutableListOf() - val forwardPhotoList = mutableListOf() - val forwardVideoList = mutableListOf() - - fun url() = "https://twitter.com/$screenName/status/$id" - - fun forwardUrl() = "https://twitter.com/$forwardScreenName/status/$forwardId" -} diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/AliDriveScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/AliDriveScheduled.kt deleted file mode 100644 index 3e5f1c9..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/AliDriveScheduled.kt +++ /dev/null @@ -1,186 +0,0 @@ -package me.kuku.telegram.scheduled - -import com.pengrad.telegrambot.TelegramBot -import kotlinx.coroutines.delay -import me.kuku.telegram.context.sendTextMessage -import me.kuku.telegram.entity.* -import me.kuku.telegram.logic.AliDriveBatch -import me.kuku.telegram.logic.AliDriveLogic -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.time.DayOfWeek -import java.time.LocalDate - -@Component -class AliDriveScheduled( - private val aliDriveLogic: AliDriveLogic, - private val aliDriveService: AliDriveService, - private val logService: LogService, - private val telegramBot: TelegramBot -) { - - @Scheduled(cron = "13 9 2 * * ?") - suspend fun sign() { - val list = aliDriveService.findBySign(Status.ON) - for (aliDriveEntity in list) { - logService.log(aliDriveEntity, LogType.AliDrive) { - delay(3000) - aliDriveLogic.sign(aliDriveEntity) - if (aliDriveEntity.receive == Status.ON) { - show = aliDriveLogic.receive(aliDriveEntity) - } - } - } - } - - @Scheduled(cron = "10 4 5 * * ?") - suspend fun lastDayReceive() { - val now = LocalDate.now() - val nextMonth = now.plusMonths(1) - val lastDay = LocalDate.of(nextMonth.year, nextMonth.month, 1).minusDays(1) - if (now.dayOfMonth == lastDay.dayOfMonth) { - val list = aliDriveService.findBySign(Status.ON) - for (aliDriveEntity in list) { - logService.log(aliDriveEntity, LogType.ALiDriveReceive) { - val signList = aliDriveLogic.sign(aliDriveEntity) - for (signInLog in signList.signInLogs) { - if (!signInLog.isReward) { - delay(3000) - kotlin.runCatching { - aliDriveLogic.receive(aliDriveEntity, signInLog.day) - } - } - } - } - } - val taskList = aliDriveService.findByTask(Status.ON) - for (aliDriveEntity in taskList) { - logService.log(aliDriveEntity, LogType.ALiDriveReceiveTask) { - val signList = aliDriveLogic.signInList(aliDriveEntity) - for (signInInfo in signList.signInInfos) { - signInInfo.rewards.getOrNull(1)?.let { reward -> - if (reward.status == "finished") { - delay(3000) - kotlin.runCatching { - aliDriveLogic.receiveTask(aliDriveEntity, signInInfo.day.toInt()) - } - } - } - } - } - } - } - } - - @Scheduled(cron = "43 1 3 * * ?") - suspend fun task() { - val list = aliDriveService.findByTask(Status.ON) - for (aliDriveEntity in list) { - logService.log(aliDriveEntity, LogType.AliDriveTask) { - aliDriveLogic.finishTask(aliDriveEntity) - delay(3000) - } - - } - } - - @Scheduled(cron = "43 30 5 * * ?") - suspend fun receiveTodayTask() { - val list = aliDriveService.findByTask(Status.ON) - for (aliDriveEntity in list) { - kotlin.runCatching { - delay(3000) - var signInInfo = aliDriveLogic.signInInfo(aliDriveEntity) - var reward = signInInfo.rewards[1] - if (reward.remind == "开启「自动同步电脑文件夹至少一小时」") { - signInInfo = aliDriveLogic.signInInfo(aliDriveEntity, aliDriveLogic.backupDesktopDevice(aliDriveEntity)) - reward = signInInfo.rewards[1] - } - if (reward.status !in listOf("finished", "verification")) { - error("阿里云盘任务完成失败,任务名称:${reward.remind}") - } - }.onSuccess { - if (aliDriveEntity.receiveTask == Status.ON) { - logService.log(aliDriveEntity, LogType.AliDriveReceiveTaskToday) { - aliDriveLogic.signInList(aliDriveEntity) - show = aliDriveLogic.receiveTask(aliDriveEntity) - } - } - }.onFailure { - telegramBot.sendTextMessage(aliDriveEntity.tgId, - "#阿里云盘任务检测\n${it.message}") - } - } - } - - @Scheduled(cron = "32 50 4 * * ?") - suspend fun finishDeviceRoom() { - val list = aliDriveService.findByDeviceRoom(Status.ON) - for (aliDriveEntity in list) { - logService.log(aliDriveEntity, LogType.AliDriveDeviceRoom) { - delay(3000) - show = aliDriveLogic.finishDeviceRoom(aliDriveEntity) - } - } - } - - @Scheduled(cron = "32 51 5 * * ?") - suspend fun receiveDeviceRoom() { - val list = aliDriveService.findByDeviceRoom(Status.ON) - for (aliDriveEntity in list) { - delay(3000) - val deviceRoom = aliDriveLogic.deviceRoom(aliDriveEntity).stream().limit(5).toList() - for (aliDriveDeviceRoom in deviceRoom) { - if (aliDriveDeviceRoom.canCollectEnergy) { - aliDriveLogic.receiveDeviceRoom(aliDriveEntity, aliDriveDeviceRoom.id) - } - } - } - } - - @Scheduled(cron = "1 23 3 * * ?") - suspend fun finishCard() { - val now = LocalDate.now() - val dayOfWeek = now.dayOfWeek - if (dayOfWeek != DayOfWeek.MONDAY) return - val list = aliDriveService.findByCard(Status.ON) - for (aliDriveEntity in list) { - delay(3000) - kotlin.runCatching { - aliDriveLogic.finishCard(aliDriveEntity) - }.onFailure { - telegramBot.sendTextMessage(aliDriveEntity.tgId, - "#自动签到失败提醒\n阿里云盘完成补签卡任务失败,\n${it.message}") - } - } - } - - @Scheduled(cron = "1 43 3 * * ?") - suspend fun receiveCard() { - val now = LocalDate.now() - val dayOfWeek = now.dayOfWeek - if (dayOfWeek != DayOfWeek.MONDAY) return - val list = aliDriveService.findByCard(Status.ON) - for (aliDriveEntity in list) { - delay(3000) - logService.log(aliDriveEntity, LogType.AliDriveCard) { - aliDriveLogic.receiveCard(aliDriveEntity) - } - } - } - - @Scheduled(cron = "10 21 1 * * ?") - suspend fun clearRubbish() { - val list = aliDriveService.findAll().filter { it.uploads.isNotEmpty() } - for (aliDriveEntity in list) { - delay(3000) - runCatching { - aliDriveLogic.batchDeleteFile(aliDriveEntity, aliDriveEntity.uploads - .map { AliDriveBatch.DeleteFileBody(it.driveId.toString(), it.fileId) }) - aliDriveEntity.uploads.clear() - aliDriveService.save(aliDriveEntity) - } - } - } - -} diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/GlaDosScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/GlaDosScheduled.kt deleted file mode 100644 index a97deca..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/GlaDosScheduled.kt +++ /dev/null @@ -1,30 +0,0 @@ -package me.kuku.telegram.scheduled - -import kotlinx.coroutines.delay -import me.kuku.telegram.entity.GlaDosService -import me.kuku.telegram.entity.LogService -import me.kuku.telegram.entity.LogType -import me.kuku.telegram.entity.Status -import me.kuku.telegram.logic.GlaDosLogic -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component - -@Component -class GlaDosScheduled( - private val glaDosService: GlaDosService, - private val logService: LogService -) { - - @Scheduled(cron = "1 51 5 * * ?") - suspend fun sign() { - val list = glaDosService.findBySign(Status.ON) - for (glaDosEntity in list) { - logService.log(glaDosEntity, LogType.GlaDos) { - delay(3000) - GlaDosLogic.sign(glaDosEntity) - } - } - } - - -} diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/IqyScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/IqyScheduled.kt deleted file mode 100644 index d2837fe..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/IqyScheduled.kt +++ /dev/null @@ -1,30 +0,0 @@ -package me.kuku.telegram.scheduled - -import me.kuku.telegram.entity.IqyService -import me.kuku.telegram.entity.LogService -import me.kuku.telegram.entity.LogType -import me.kuku.telegram.entity.Status -import me.kuku.telegram.logic.IqyLogic -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component - -@Component -class IqyScheduled( - private val iqyService: IqyService, - private val logService: LogService -) { - - @Scheduled(cron = "8 41 5 * * ?") - suspend fun sign() { - val list = iqyService.findBySign(Status.ON) - for (entity in list) { - logService.log(entity, LogType.Iqy) { - IqyLogic.taskSign(entity) - IqyLogic.finishTaskWatch(entity) - } - } - } - - - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseScheduled.kt deleted file mode 100644 index a6b53e5..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseScheduled.kt +++ /dev/null @@ -1,64 +0,0 @@ -package me.kuku.telegram.scheduled - -import kotlinx.coroutines.delay -import me.kuku.telegram.entity.* -import me.kuku.telegram.logic.NetEaseLogic -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component - -@Component -class NetEaseScheduled( - private val netEaseService: NetEaseService, - private val logService: LogService -) { - - @Scheduled(cron = "0 12 7 * * ?") - suspend fun sign() { - val list = netEaseService.findBySign(Status.ON) - for (netEaseEntity in list) { - logService.log(netEaseEntity, LogType.NetEase) { - delay(3000) - NetEaseLogic.listenMusic(netEaseEntity) - delay(3000) - NetEaseLogic.sign(netEaseEntity) - } - } - } - - private suspend fun execMusicianSign(netEaseEntity: NetEaseEntity) { - NetEaseLogic.musicianSign(netEaseEntity) - delay(3000) - NetEaseLogic.myMusicComment(netEaseEntity) - delay(3000) - NetEaseLogic.publishAndShareMySongAndComment(netEaseEntity) - delay(1000 * 60) - NetEaseLogic.publishMLog(netEaseEntity) - } - - @Scheduled(cron = "0 32 8 * * ?") - suspend fun musicianSign() { - val list = netEaseService.findByMusicianSign(Status.ON) - for (netEaseEntity in list) { - logService.log(netEaseEntity, LogType.NetEaseMusician) { - try { - execMusicianSign(netEaseEntity) - } catch (e: Exception) { - execMusicianSign(netEaseEntity) - } - } - } - } - - @Scheduled(cron = "0 40 8 * * ?") - suspend fun vipSign() { - val list = netEaseService.findByVipSign(Status.ON) - for (netEaseEntity in list.reversed()) { - logService.log(netEaseEntity, LogType.NetEaseVip) { - delay(3000) - NetEaseLogic.vipSign(netEaseEntity) - NetEaseLogic.receiveTaskReward(netEaseEntity) - } - } - } - -} diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt deleted file mode 100644 index 3ed21f7..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt +++ /dev/null @@ -1,35 +0,0 @@ -package me.kuku.telegram.scheduled - -import kotlinx.coroutines.delay -import me.kuku.telegram.entity.NetEaseService -import me.kuku.telegram.entity.Status -import me.kuku.telegram.logic.NetEaseLogic -import me.kuku.telegram.logic.NetEaseSmallLogic -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.util.concurrent.TimeUnit - -@Component -class NetEaseSmallScheduled( - private val netEaseSmallLogic: NetEaseSmallLogic, - private val netEaseService: NetEaseService -) { - -// @Scheduled(fixedDelay = 12, initialDelay = 0, timeUnit = TimeUnit.HOURS) - suspend fun listenMusic() { - netEaseSmallLogic.check() - val list = netEaseService.findByListen(Status.ON) - for (netEaseEntity in list) { - val myMusicList = try { - NetEaseLogic.myMusic(netEaseEntity) - } catch (e: Exception) { - continue - } - for (netEaseSong in myMusicList) { - netEaseSmallLogic.listenMusic(netEaseSong.songId) - delay(2000) - } - } - } - -} \ No newline at end of file diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt deleted file mode 100644 index 2baf3a0..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt +++ /dev/null @@ -1,95 +0,0 @@ -@file:Suppress("SpellCheckingInspection") - -package me.kuku.telegram.scheduled - -import com.pengrad.telegrambot.TelegramBot -import com.pengrad.telegrambot.model.request.InputMediaPhoto -import com.pengrad.telegrambot.request.SendMediaGroup -import com.pengrad.telegrambot.request.SendPhoto -import io.ktor.util.logging.* -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.withContext -import me.kuku.telegram.context.asyncExecute -import me.kuku.telegram.entity.PixivService -import me.kuku.telegram.entity.Status -import me.kuku.telegram.logic.PixivLogic -import me.kuku.telegram.logic.PixivPojo -import org.slf4j.LoggerFactory -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.util.concurrent.TimeUnit - -@Component -class PixivScheduled( - private val pixivService: PixivService, - private val telegramBot: TelegramBot -) { - - private val logger = LoggerFactory.getLogger(PixivScheduled::class.java) - - private val userMap = mutableMapOf() - - @Scheduled(fixedDelay = 2, timeUnit = TimeUnit.MINUTES) - suspend fun push() { - val entityList = pixivService.findByPush(Status.ON) - for (pixivEntity in entityList) { - kotlin.runCatching { - val tgId = pixivEntity.tgId - val list = PixivLogic.followImage(pixivEntity) - delay(3000) - val newList = mutableListOf() - if (userMap.containsKey(tgId)) { - val oldId = userMap[tgId]!! - for (pixivPojo in list) { - if (pixivPojo.id <= oldId) break - newList.add(pixivPojo) - } - for (pixivPojo in newList) { - val text = "#pixiv推送\n${PixivLogic.convertStr(pixivPojo)}" - val imageList = kotlin.runCatching { - PixivLogic.imageById(pixivPojo.id) - }.getOrNull() ?: continue - val sendList = mutableListOf>() - for (i in imageList.indices) { - val uu = imageList[i] - if ((i + 1) % 10 == 1) sendList.add(mutableListOf()) - sendList.last().add(uu) - } - for (innerList in sendList) { - if (innerList.size == 1) { - val url = imageList[0] - val name = url.substring(url.lastIndexOf('/') + 1) - withContext(Dispatchers.IO) { - PixivLogic.imageIs(url).readAllBytes() - }.let { - val sendPhoto = SendPhoto(tgId, it).fileName("$name.jpg") - .caption(text) - telegramBot.asyncExecute(sendPhoto) - } - } else { - val inputMediaList = mutableListOf() - for (imageUrl in innerList) { - val iis = PixivLogic.imageIs(imageUrl) - val name = imageUrl.substring(imageUrl.lastIndexOf('/') + 1) - val mediaPhoto = InputMediaPhoto(withContext(Dispatchers.IO) { - iis.readAllBytes() - }) - .fileName(name).caption(text) - inputMediaList.add(mediaPhoto) - } - val sendMediaGroup = SendMediaGroup(tgId, *inputMediaList.toTypedArray()) - telegramBot.asyncExecute(sendMediaGroup) - } - } - - } - } - userMap[tgId] = list[0].id - }.onFailure { - logger.error(it) - } - } - } - -} diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt deleted file mode 100644 index fb16d27..0000000 --- a/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt +++ /dev/null @@ -1,76 +0,0 @@ -package me.kuku.telegram.scheduled - -import com.pengrad.telegrambot.TelegramBot -import com.pengrad.telegrambot.request.SendVideo -import io.ktor.util.logging.* -import kotlinx.coroutines.delay -import me.kuku.telegram.context.asyncExecute -import me.kuku.telegram.entity.Status -import me.kuku.telegram.entity.TwitterService -import me.kuku.telegram.logic.TwitterLogic -import me.kuku.telegram.logic.TwitterPojo -import me.kuku.telegram.context.sendPic -import me.kuku.telegram.context.sendTextMessage -import me.kuku.utils.OkHttpKtUtils -import org.slf4j.LoggerFactory -import org.springframework.scheduling.annotation.Scheduled -import org.springframework.stereotype.Component -import java.lang.Long.max -import java.util.concurrent.TimeUnit - -@Component -class TwitterScheduled( - private val twitterService: TwitterService, - private val telegramBot: TelegramBot -) { - - private val logger = LoggerFactory.getLogger(TwitterScheduled::class.java) - - private val userMap = mutableMapOf() - - @Scheduled(fixedDelay = 2, timeUnit = TimeUnit.MINUTES) - suspend fun push() { - val entityList = twitterService.findByPush(Status.ON) - for (entity in entityList) { - kotlin.runCatching { - val tgId = entity.tgId - val list = TwitterLogic.friendTweet(entity).sortedBy { -it.id } - delay(3000) - if (list.isEmpty()) return@runCatching - val newList = mutableListOf() - if (userMap.containsKey(tgId)) { - val oldId = userMap[tgId]!! - for (twitterPojo in list) { - if (twitterPojo.id <= oldId) break - newList.add(twitterPojo) - } - for (twitterPojo in newList) { - val text = "#Twitter新推推送\n${TwitterLogic.convertStr(twitterPojo)}" - val videoUrl = if (twitterPojo.videoList.isNotEmpty()) twitterPojo.videoList[0] - else if (twitterPojo.forwardVideoList.isNotEmpty()) twitterPojo.forwardVideoList[0] - else "" - try { - if (videoUrl.isNotEmpty()) { - OkHttpKtUtils.getBytes(videoUrl).let { - val sendVideo = SendVideo(tgId, it).fileName("${twitterPojo.id}.mp4") - .caption(text) - telegramBot.asyncExecute(sendVideo) - } - } else if (twitterPojo.photoList.isNotEmpty() || twitterPojo.forwardPhotoList.isNotEmpty()) { - val imageList = twitterPojo.photoList - imageList.addAll(twitterPojo.forwardPhotoList) - telegramBot.sendPic(tgId, text, imageList) - } else telegramBot.sendTextMessage(tgId, text) - } catch (e: Exception) { - telegramBot.sendTextMessage(tgId, text) - } - } - } - userMap[tgId] = max(list[0].id, userMap[tgId] ?: 0) - }.onFailure { - logger.error(it) - } - } - } - -}