From 1d89ee2167ab04172b7d11bdc6f139097ada680b Mon Sep 17 00:00:00 2001 From: kuku Date: Tue, 29 Oct 2024 20:25:32 +0800 Subject: [PATCH] fix bugs --- gradle/wrapper/gradle-wrapper.properties | 2 +- .../me/kuku/telegram/entity/NetEaseEntity.kt | 19 ++- .../telegram/entity/NetEaseSmallEntity.kt | 14 +- .../me/kuku/telegram/logic/LeiShenLogic.kt | 24 ++- .../me/kuku/telegram/logic/NetEaseLogic.kt | 134 +++++++++++++--- .../kuku/telegram/logic/NetEaseSmallLogic.kt | 46 ++++-- .../telegram/scheduled/BiliBilliScheduled.kt | 129 +++++++++------- .../kuku/telegram/scheduled/DouYuScheduled.kt | 144 ++++++++++-------- .../kuku/telegram/scheduled/EpicScheduled.kt | 14 +- .../telegram/scheduled/HostLocScheduled.kt | 12 +- .../kuku/telegram/scheduled/HuYaScheduled.kt | 56 ++++--- .../telegram/scheduled/LeiShenScheduled.kt | 54 ++++--- .../scheduled/NetEaseSmallScheduled.kt | 10 +- .../kuku/telegram/scheduled/PixivScheduled.kt | 98 ++++++------ .../telegram/scheduled/TwitterScheduled.kt | 70 +++++---- .../kuku/telegram/scheduled/V2exScheduled.kt | 12 +- .../kuku/telegram/scheduled/WeiboScheduled.kt | 70 +++++---- 17 files changed, 570 insertions(+), 338 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e1adfb4..1e2fbf0 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt index 8990a06..a8955ef 100644 --- a/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt +++ b/src/main/kotlin/me/kuku/telegram/entity/NetEaseEntity.kt @@ -7,22 +7,27 @@ 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: BaseEntity() { +class NetEaseEntity: NetEaseBaseEntity() { @Id var id: String? = null - var musicU: String = "" - var csrf: String = "" var sign: Status = Status.OFF var musicianSign: Status = Status.OFF var vipSign: Status = Status.OFF var listen: Status = Status.OFF - fun cookie() = "channel=netease; __remember_me=true; MUSIC_U=$musicU; __csrf=$csrf; " - - fun pcCookie() = "os=pc; ${cookie()}" - fun androidCookie() = "os=android; ${cookie()}" } interface NetEaseRepository: CoroutineCrudRepository { diff --git a/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt b/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt index 11e6787..5f91b35 100644 --- a/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt +++ b/src/main/kotlin/me/kuku/telegram/entity/NetEaseSmallEntity.kt @@ -5,21 +5,25 @@ 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 { +class NetEaseSmallEntity: NetEaseBaseEntity() { @Id var id: String? = null var username: String = "" var password: String = "" - var musicU: String = "" - var csrf: String = "" + var status: Status = Status.OFF + var reason: String = "" - fun cookie() = "channel=netease; __remember_me=true; MUSIC_U=$musicU; __csrf=$csrf; " + 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 @@ -33,4 +37,6 @@ class NetEaseSmallService( 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/logic/LeiShenLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/LeiShenLogic.kt index 7a6c6c1..1463f19 100644 --- a/src/main/kotlin/me/kuku/telegram/logic/LeiShenLogic.kt +++ b/src/main/kotlin/me/kuku/telegram/logic/LeiShenLogic.kt @@ -2,19 +2,33 @@ package me.kuku.telegram.logic import com.fasterxml.jackson.annotation.JsonProperty 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.client.statement.* import me.kuku.telegram.entity.LeiShenEntity import me.kuku.utils.* +import java.net.URLEncoder object LeiShenLogic { suspend fun login(phone: String, password: String): LeiShenEntity { - val jsonNode = client.post("https://webapi.leigod.com/wap/login/bind") { - setJsonBody(""" - {"username":"$phone","password":"$password","user_type":"0","src_channel":"guanwang","code":"","country_code":86,"lang":"zh_CN"} - """.trimIndent()) - }.body() + val params = """ + {"os_type":4,"password":"$password","mobile_num":"$phone","src_channel":"guanwang","country_code":86,"username":"$phone","lang":"zh_CN","region_code":1,"ts":"${System.currentTimeMillis() / 1000}"} + """.trimIndent().toJsonNode() as ObjectNode + val sortedFields = params.fields().asSequence() + .sortedBy { it.key } // 对字段进行排序 + .map { entry -> + val key = URLEncoder.encode(entry.key, "UTF-8") + val value = URLEncoder.encode(entry.value.asText(), "UTF-8") + "$key=$value" + } + val convert = sortedFields.joinToString("&") + "&key=5C5A639C20665313622F51E93E3F2783" + val md5 = MD5Utils.toMD5(convert) + params.put("sign", md5) + val jsonNode = client.post("https://webapi.leigod.com/api/auth/login/v1") { + setJsonBody(params) + }.bodyAsText().toJsonNode() if (jsonNode["code"].asInt() != 0) error(jsonNode["msg"].asText()) val data = jsonNode["data"] val info = data["login_info"] diff --git a/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt index 04233a8..7065bcb 100644 --- a/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt +++ b/src/main/kotlin/me/kuku/telegram/logic/NetEaseLogic.kt @@ -9,10 +9,13 @@ 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 { @@ -37,14 +40,48 @@ object NetEaseLogic { } } - private fun prepare(json: String, netEaseEntity: NetEaseEntity? = null): Map { + 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", netEaseEntity.csrf) + (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) @@ -170,24 +207,81 @@ object NetEaseLogic { if (jsonNode.getInteger("code") != 200) error(jsonNode.getString("message")) } - @Suppress("DuplicatedCode") - suspend fun listenMusic(netEaseSmallEntity: NetEaseSmallEntity, id: Int) { - val ids = Jackson.createArrayNode() - val jsonNode = Jackson.createObjectNode() - jsonNode.put("download", 0) - jsonNode.put("end", "playend") - jsonNode.put("id", 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) - val resultJsonNode = OkHttpKtUtils.postJson("$domain/weapi/feedback/weblog", prepare(mapOf("logs" to ids.toString())), - OkUtils.headers(netEaseSmallEntity.cookie(), domain, UA.PC)) - if (resultJsonNode.getInteger("code") != 200) error(resultJsonNode.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 { diff --git a/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt b/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt index 3e3dab7..ac996c0 100644 --- a/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt +++ b/src/main/kotlin/me/kuku/telegram/logic/NetEaseSmallLogic.kt @@ -1,7 +1,12 @@ 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 @@ -12,27 +17,42 @@ class NetEaseSmallLogic( suspend fun check() { val list = netEaseSmallService.findAll() for (netEaseSmallEntity in list) { - if (netEaseSmallEntity.csrf.isEmpty()) { - 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 + 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) - } else { - netEaseSmallService.delete(netEaseSmallEntity) } + } } } - suspend fun listenMusic(id: Int) { - val list = netEaseSmallService.findAll() + suspend fun listenMusic(id: Long) { + val list = netEaseSmallService.findByStatus(Status.ON) for (netEaseSmallEntity in list) { if (netEaseSmallEntity.csrf.isNotEmpty()) { - NetEaseLogic.listenMusic(netEaseSmallEntity, id) - delay(2000) + NetEaseLogic.listenMusic0(netEaseSmallEntity, id) } } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/BiliBilliScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/BiliBilliScheduled.kt index a7e4903..720d563 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/BiliBilliScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/BiliBilliScheduled.kt @@ -6,6 +6,7 @@ import com.pengrad.telegrambot.request.SendPhoto import com.pengrad.telegrambot.request.SendVideo import io.ktor.client.call.* import io.ktor.client.request.* +import io.ktor.util.logging.* import kotlinx.coroutines.delay import me.kuku.telegram.config.TelegramConfig import me.kuku.telegram.context.asyncExecute @@ -14,6 +15,7 @@ import me.kuku.telegram.logic.BiliBiliLogic import me.kuku.telegram.logic.BiliBiliPojo import me.kuku.telegram.context.sendPic import me.kuku.utils.client +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.io.File @@ -29,6 +31,7 @@ class BiliBilliScheduled( private val liveMap = mutableMapOf>() private val userMap = mutableMapOf() + private val logger = LoggerFactory.getLogger(BiliBilliScheduled::class.java) @Scheduled(cron = "0 23 3 * * ?") @@ -52,31 +55,35 @@ class BiliBilliScheduled( suspend fun liveMonitor() { val list = biliBiliService.findByLive(Status.ON) for (biliBiliEntity in list) { - delay(3000) - val tgId = biliBiliEntity.tgId - if (!liveMap.containsKey(tgId)) liveMap[tgId] = mutableMapOf() - val map = liveMap[tgId]!! - val liveList = BiliBiliLogic.live(biliBiliEntity) - for (live in liveList) { - val userid = live.id.toLong() - val b = live.status - val name = live.uname - if (map.containsKey(userid)) { - if (map[userid] != b) { - map[userid] = b - val msg = if (b) "直播啦!!" else "下播了!!" - val text = "#哔哩哔哩开播提醒\n#$name $msg\n标题:${live.title}\n链接:${live.url}" - val imageUrl = live.imageUrl - if (imageUrl.isEmpty()) - telegramBot.asyncExecute(SendMessage(tgId, text)) - else { - client.get(imageUrl).body().let { - val sendPhoto = SendPhoto(tgId, it).caption(text).fileName("live.jpg") - telegramBot.asyncExecute(sendPhoto) + kotlin.runCatching { + delay(3000) + val tgId = biliBiliEntity.tgId + if (!liveMap.containsKey(tgId)) liveMap[tgId] = mutableMapOf() + val map = liveMap[tgId]!! + val liveList = BiliBiliLogic.live(biliBiliEntity) + for (live in liveList) { + val userid = live.id.toLong() + val b = live.status + val name = live.uname + if (map.containsKey(userid)) { + if (map[userid] != b) { + map[userid] = b + val msg = if (b) "直播啦!!" else "下播了!!" + val text = "#哔哩哔哩开播提醒\n#$name $msg\n标题:${live.title}\n链接:${live.url}" + val imageUrl = live.imageUrl + if (imageUrl.isEmpty()) + telegramBot.asyncExecute(SendMessage(tgId, text)) + else { + client.get(imageUrl).body().let { + val sendPhoto = SendPhoto(tgId, it).caption(text).fileName("live.jpg") + telegramBot.asyncExecute(sendPhoto) + } } } - } - } else map[userid] = live.status + } else map[userid] = live.status + } + }.onFailure { + logger.error(it) } } } @@ -85,45 +92,49 @@ class BiliBilliScheduled( suspend fun userMonitor() { val biliBiliList = biliBiliService.findByPush(Status.ON) for (biliBiliEntity in biliBiliList) { - val tgId = biliBiliEntity.tgId - delay(3000) - val result = BiliBiliLogic.friendDynamic(biliBiliEntity) - val list = result.data ?: continue - val newList = mutableListOf() - if (userMap.containsKey(tgId)) { - val oldId = userMap[tgId]!! - for (biliBiliPojo in list) { - if (biliBiliPojo.id.toLong() <= oldId) break - newList.add(biliBiliPojo) - } - for (biliBiliPojo in newList) { - val text = "#哔哩哔哩动态推送\n${BiliBiliLogic.convertStr(biliBiliPojo)}" - val bvId = if (biliBiliPojo.bvId.isNotEmpty()) biliBiliPojo.bvId - else if (biliBiliPojo.forwardBvId.isNotEmpty()) biliBiliPojo.forwardBvId - else "" - try { - if (bvId.isNotEmpty() && telegramConfig.url.isNotEmpty()) { - var file: File? = null - try { - delay(3000) - file = BiliBiliLogic.videoByBvId(biliBiliEntity, biliBiliPojo.bvId) - val sendVideo = - SendVideo(tgId, file).caption(text) - telegramBot.asyncExecute(sendVideo) - } finally { - file?.delete() - } - } else if (biliBiliPojo.picList.isNotEmpty() || biliBiliPojo.forwardPicList.isNotEmpty()) { - val picList = biliBiliPojo.picList - picList.addAll(biliBiliPojo.forwardPicList) - telegramBot.sendPic(tgId, text, picList) - } else telegramBot.asyncExecute(SendMessage(tgId, text)) - } catch (e: Exception) { - telegramBot.asyncExecute(SendMessage(tgId, text)) + kotlin.runCatching { + val tgId = biliBiliEntity.tgId + delay(3000) + val result = BiliBiliLogic.friendDynamic(biliBiliEntity) + val list = result.data ?: return@runCatching + val newList = mutableListOf() + if (userMap.containsKey(tgId)) { + val oldId = userMap[tgId]!! + for (biliBiliPojo in list) { + if (biliBiliPojo.id.toLong() <= oldId) break + newList.add(biliBiliPojo) + } + for (biliBiliPojo in newList) { + val text = "#哔哩哔哩动态推送\n${BiliBiliLogic.convertStr(biliBiliPojo)}" + val bvId = if (biliBiliPojo.bvId.isNotEmpty()) biliBiliPojo.bvId + else if (biliBiliPojo.forwardBvId.isNotEmpty()) biliBiliPojo.forwardBvId + else "" + try { + if (bvId.isNotEmpty() && telegramConfig.url.isNotEmpty()) { + var file: File? = null + try { + delay(3000) + file = BiliBiliLogic.videoByBvId(biliBiliEntity, biliBiliPojo.bvId) + val sendVideo = + SendVideo(tgId, file).caption(text) + telegramBot.asyncExecute(sendVideo) + } finally { + file?.delete() + } + } else if (biliBiliPojo.picList.isNotEmpty() || biliBiliPojo.forwardPicList.isNotEmpty()) { + val picList = biliBiliPojo.picList + picList.addAll(biliBiliPojo.forwardPicList) + telegramBot.sendPic(tgId, text, picList) + } else telegramBot.asyncExecute(SendMessage(tgId, text)) + } catch (e: Exception) { + telegramBot.asyncExecute(SendMessage(tgId, text)) + } } } + userMap[tgId] = list[0].id.toLong() + }.onFailure { + logger.error(it) } - userMap[tgId] = list[0].id.toLong() } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/DouYuScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/DouYuScheduled.kt index 63828da..576f4b6 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/DouYuScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/DouYuScheduled.kt @@ -5,6 +5,7 @@ import com.pengrad.telegrambot.request.SendMessage import com.pengrad.telegrambot.request.SendPhoto import io.ktor.client.call.* import io.ktor.client.request.* +import io.ktor.util.logging.* import kotlinx.coroutines.delay import me.kuku.telegram.context.asyncExecute import me.kuku.telegram.entity.* @@ -14,6 +15,7 @@ import me.kuku.telegram.context.sendPic import me.kuku.telegram.context.sendTextMessage import me.kuku.utils.JobManager import me.kuku.utils.client +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit @@ -32,35 +34,41 @@ class DouYuScheduled( private val douYuTitleMap = mutableMapOf>() + private val logger = LoggerFactory.getLogger(DouYuScheduled::class.java) + @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.MINUTES) suspend fun douYu() { val list = douYuService.findByLive(Status.ON) for (douYuEntity in list) { - val baseResult = douYuLogic.room(douYuEntity) - delay(3000) - if (baseResult.failure()) continue - val rooms = baseResult.data() - val tgId = douYuEntity.tgId - if (!douYuLiveMap.containsKey(tgId)) douYuLiveMap[tgId] = mutableMapOf() - val map = douYuLiveMap[tgId]!! - for (room in rooms) { - val id = room.roomId - val b = room.showStatus - if (map.containsKey(id)) { - if (map[id] != b) { - map[id] = b - val msg = if (b) "直播啦!!" else "下播啦" - val text = "#斗鱼开播提醒\n#${room.nickName} $msg\n标题:${room.name}\n分类:${room.gameName}\n在线:${room.online}\n链接:${room.url}" - val imageUrl = room.imageUrl - if (imageUrl.isNotEmpty()) { - client.get(imageUrl).body().let { - val sendPhoto = SendPhoto(tgId, it) - .caption(text).fileName("douYuRoom.jpg") - telegramBot.asyncExecute(sendPhoto) - } - } else telegramBot.asyncExecute(SendMessage(tgId, text)) - } - } else map[id] = b + kotlin.runCatching { + val baseResult = douYuLogic.room(douYuEntity) + delay(3000) + if (baseResult.failure()) return@runCatching + val rooms = baseResult.data() + val tgId = douYuEntity.tgId + if (!douYuLiveMap.containsKey(tgId)) douYuLiveMap[tgId] = mutableMapOf() + val map = douYuLiveMap[tgId]!! + for (room in rooms) { + val id = room.roomId + val b = room.showStatus + if (map.containsKey(id)) { + if (map[id] != b) { + map[id] = b + val msg = if (b) "直播啦!!" else "下播啦" + val text = "#斗鱼开播提醒\n#${room.nickName} $msg\n标题:${room.name}\n分类:${room.gameName}\n在线:${room.online}\n链接:${room.url}" + val imageUrl = room.imageUrl + if (imageUrl.isNotEmpty()) { + client.get(imageUrl).body().let { + val sendPhoto = SendPhoto(tgId, it) + .caption(text).fileName("douYuRoom.jpg") + telegramBot.asyncExecute(sendPhoto) + } + } else telegramBot.asyncExecute(SendMessage(tgId, text)) + } + } else map[id] = b + } + }.onFailure { + logger.error(it) } } } @@ -69,28 +77,32 @@ class DouYuScheduled( suspend fun titleChange() { val list = douYuService.findByTitleChange(Status.ON) for (douYuEntity in list) { - val baseResult = douYuLogic.room(douYuEntity) - delay(3000) - if (baseResult.failure()) continue - val tgId = douYuEntity.tgId - if (!douYuTitleMap.containsKey(tgId)) douYuTitleMap[tgId] = mutableMapOf() - val map = douYuTitleMap[tgId]!! - for (room in baseResult.data()) { - val name = room.name - val roomId = room.roomId - val value = map[roomId] - if (value != null && value != name) { - val text = "#斗鱼标题更新提醒\n${room.nickName}\n旧标题:${value}\n新标题:${name}\n链接:${room.url}" - val imageUrl = room.imageUrl - if (imageUrl.isNotEmpty()) { - client.get(imageUrl).body().let { - val sendPhoto = SendPhoto(tgId.toString(), it).fileName("douYuRoom.jpg") - .caption(text) - telegramBot.asyncExecute(sendPhoto) - } - } else telegramBot.sendTextMessage(tgId, text) + kotlin.runCatching { + val baseResult = douYuLogic.room(douYuEntity) + delay(3000) + if (baseResult.failure()) return@runCatching + val tgId = douYuEntity.tgId + if (!douYuTitleMap.containsKey(tgId)) douYuTitleMap[tgId] = mutableMapOf() + val map = douYuTitleMap[tgId]!! + for (room in baseResult.data()) { + val name = room.name + val roomId = room.roomId + val value = map[roomId] + if (value != null && value != name) { + val text = "#斗鱼标题更新提醒\n${room.nickName}\n旧标题:${value}\n新标题:${name}\n链接:${room.url}" + val imageUrl = room.imageUrl + if (imageUrl.isNotEmpty()) { + client.get(imageUrl).body().let { + val sendPhoto = SendPhoto(tgId.toString(), it).fileName("douYuRoom.jpg") + .caption(text) + telegramBot.asyncExecute(sendPhoto) + } + } else telegramBot.sendTextMessage(tgId, text) + } + map[roomId] = name } - map[roomId] = name + }.onFailure { + logger.error(it) } } } @@ -111,29 +123,31 @@ class DouYuScheduled( suspend fun douYuPush() { val entityList = douYuService.findByPush(Status.ON) for (douYuEntity in entityList) { - val tgId = douYuEntity.tgId - val list = try { - douYuLogic.focusFishGroup(douYuEntity) - } catch (e: Exception) {continue} - val newList = mutableListOf() - if (douYuPushMap.containsKey(tgId)) { - val oldId = douYuPushMap[tgId]!! - for (biliBiliPojo in list) { - if (biliBiliPojo.id <= oldId) break - newList.add(biliBiliPojo) - } - for (douYuFish in newList) { - val text = "#斗鱼鱼吧动态推送\n#${douYuFish.nickname}\n标题:${douYuFish.title}\n内容:${douYuFish.content}\n链接:${douYuFish.url}" - if (douYuFish.image.isNotEmpty()) { - JobManager.delay(1000 * 60) { - telegramBot.sendPic(tgId, text, douYuFish.image) + kotlin.runCatching { + val tgId = douYuEntity.tgId + val list = douYuLogic.focusFishGroup(douYuEntity) + val newList = mutableListOf() + if (douYuPushMap.containsKey(tgId)) { + val oldId = douYuPushMap[tgId]!! + for (biliBiliPojo in list) { + if (biliBiliPojo.id <= oldId) break + newList.add(biliBiliPojo) + } + for (douYuFish in newList) { + val text = "#斗鱼鱼吧动态推送\n#${douYuFish.nickname}\n标题:${douYuFish.title}\n内容:${douYuFish.content}\n链接:${douYuFish.url}" + if (douYuFish.image.isNotEmpty()) { + JobManager.delay(1000 * 60) { + telegramBot.sendPic(tgId, text, douYuFish.image) + } + } else { + telegramBot.asyncExecute(SendMessage(tgId, text)) } - } else { - telegramBot.asyncExecute(SendMessage(tgId, text)) } } + douYuPushMap[tgId] = list[0].id + }.onFailure { + logger.error(it) } - douYuPushMap[tgId] = list[0].id } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/EpicScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/EpicScheduled.kt index f1ddd86..fb202a7 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/EpicScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/EpicScheduled.kt @@ -6,6 +6,7 @@ import com.pengrad.telegrambot.TelegramBot import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* +import io.ktor.util.logging.* import me.kuku.telegram.context.sendPic import me.kuku.telegram.entity.ConfigService import me.kuku.telegram.entity.Status @@ -13,6 +14,7 @@ import me.kuku.utils.DateTimeFormatterUtils import me.kuku.utils.MyUtils import me.kuku.utils.client import me.kuku.utils.toJsonNode +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.time.ZoneOffset @@ -24,6 +26,8 @@ class EpicScheduled( private val configService: ConfigService ) { + private val logger = LoggerFactory.getLogger(EpicScheduled::class.java) + @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.HOURS) suspend fun pushFreeGame() { val list = configService.findByEpicFreeGamePush(Status.ON) @@ -63,9 +67,13 @@ class EpicScheduled( val discountPrice = fmtPrice["discountPrice"].asText() val url = "https://store.epicgames.com/purchase?highlightColor=0078f2&offers=1-$namespace-$id&showNavigation=true#/purchase/payment-methods" for (configEntity in list) { - telegramBot.sendPic(configEntity.tgId, - "#Epic免费游戏推送\n游戏名称: $title\n游戏内部名称: $innerTitle\n游戏描述: $description\n游戏长描述: $longDescription\n原价: $originalPrice\n折扣价: $discountPrice\n订单地址:$url", - listOf(imageUrl)) + kotlin.runCatching { + telegramBot.sendPic(configEntity.tgId, + "#Epic免费游戏推送\n游戏名称: $title\n游戏内部名称: $innerTitle\n游戏描述: $description\n游戏长描述: $longDescription\n原价: $originalPrice\n折扣价: $discountPrice\n订单地址:$url", + listOf(imageUrl)) + }.onFailure { + logger.error(it) + } } } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/HostLocScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/HostLocScheduled.kt index fd0d3c3..f809573 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/HostLocScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/HostLocScheduled.kt @@ -2,11 +2,13 @@ package me.kuku.telegram.scheduled import com.pengrad.telegrambot.TelegramBot import com.pengrad.telegrambot.request.SendMessage +import io.ktor.util.logging.* import kotlinx.coroutines.delay import me.kuku.telegram.context.asyncExecute import me.kuku.telegram.entity.* import me.kuku.telegram.logic.HostLocLogic import me.kuku.telegram.logic.HostLocPost +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.net.ConnectException @@ -20,6 +22,8 @@ class HostLocScheduled( ) { private var locId = 0 + private val logger = LoggerFactory.getLogger(HostLocScheduled::class.java) + @Scheduled(fixedDelay = 2, timeUnit = TimeUnit.MINUTES) suspend fun locPush() { val list = try { @@ -47,8 +51,12 @@ class HostLocScheduled( 链接:${hostLocPost.url} 内容:${HostLocLogic.postContent(hostLocPost.url, hostLocEntity.cookie)} """.trimIndent() - val sendMessage = SendMessage(hostLocEntity.tgId, str) - telegramBot.asyncExecute(sendMessage) + kotlin.runCatching { + val sendMessage = SendMessage(hostLocEntity.tgId, str) + telegramBot.asyncExecute(sendMessage) + }.onFailure { + logger.error(it) + } } } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/HuYaScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/HuYaScheduled.kt index 0330262..230b478 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/HuYaScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/HuYaScheduled.kt @@ -4,12 +4,14 @@ import com.pengrad.telegrambot.TelegramBot import com.pengrad.telegrambot.request.SendPhoto import io.ktor.client.call.* import io.ktor.client.request.* +import io.ktor.util.logging.* import kotlinx.coroutines.delay import me.kuku.telegram.context.asyncExecute import me.kuku.telegram.entity.* import me.kuku.telegram.logic.HuYaLogic import me.kuku.telegram.context.sendTextMessage import me.kuku.utils.client +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit @@ -21,38 +23,44 @@ class HuYaScheduled( private val telegramBot: TelegramBot ) { + private val logger = LoggerFactory.getLogger(HuYaScheduled::class.java) + private val huYaLiveMap = mutableMapOf>() @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.MINUTES) suspend fun huYa() { val list = huYaService.findByLive(Status.ON) for (huYaEntity in list) { - delay(3000) - val baseResult = huYaLogic.live(huYaEntity) - if (baseResult.failure()) continue - val lives = baseResult.data() - val tgId = huYaEntity.tgId - if (!huYaLiveMap.containsKey(tgId)) huYaLiveMap[tgId] = mutableMapOf() - val map = huYaLiveMap[tgId]!! - for (room in lives) { - val id = room.roomId - val b = room.isLive - if (map.containsKey(id)) { - if (map[id] != b) { - map[id] = b - val msg = if (b) "直播啦!!" else "下播啦" - val text = "#虎牙开播提醒\n#${room.nick} $msg\n标题:${room.liveDesc}\n分类:${room.gameName}\n链接:${room.url}" - val videoCaptureUrl = room.videoCaptureUrl - if (videoCaptureUrl.isEmpty()) telegramBot.sendTextMessage(tgId, text) - else { - client.get(videoCaptureUrl).body().let { - val sendPhoto = - SendPhoto(tgId, text).caption(text).fileName("huYa.jpg") - telegramBot.asyncExecute(sendPhoto) + kotlin.runCatching { + delay(3000) + val baseResult = huYaLogic.live(huYaEntity) + if (baseResult.failure()) return@runCatching + val lives = baseResult.data() + val tgId = huYaEntity.tgId + if (!huYaLiveMap.containsKey(tgId)) huYaLiveMap[tgId] = mutableMapOf() + val map = huYaLiveMap[tgId]!! + for (room in lives) { + val id = room.roomId + val b = room.isLive + if (map.containsKey(id)) { + if (map[id] != b) { + map[id] = b + val msg = if (b) "直播啦!!" else "下播啦" + val text = "#虎牙开播提醒\n#${room.nick} $msg\n标题:${room.liveDesc}\n分类:${room.gameName}\n链接:${room.url}" + val videoCaptureUrl = room.videoCaptureUrl + if (videoCaptureUrl.isEmpty()) telegramBot.sendTextMessage(tgId, text) + else { + client.get(videoCaptureUrl).body().let { + val sendPhoto = + SendPhoto(tgId, text).caption(text).fileName("huYa.jpg") + telegramBot.asyncExecute(sendPhoto) + } } } - } - } else map[id] = b + } else map[id] = b + } + }.onFailure { + logger.error(it) } } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/LeiShenScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/LeiShenScheduled.kt index e783312..8f2c777 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/LeiShenScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/LeiShenScheduled.kt @@ -3,12 +3,14 @@ package me.kuku.telegram.scheduled import com.pengrad.telegrambot.TelegramBot import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup import com.pengrad.telegrambot.request.SendMessage +import io.ktor.util.logging.* import me.kuku.telegram.context.asyncExecute import me.kuku.telegram.entity.LeiShenService import me.kuku.telegram.entity.Status import me.kuku.telegram.logic.LeiShenLogic import me.kuku.telegram.context.inlineKeyboardButton import me.kuku.telegram.context.sendTextMessage +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit @@ -19,40 +21,46 @@ class LeiShenScheduled( private val telegramBot: TelegramBot ) { + private val logger = LoggerFactory.getLogger(LeiShenScheduled::class.java) + @Scheduled(fixedDelay = 2, timeUnit = TimeUnit.HOURS) suspend fun leiShenRemind() { val entities = leiShenService.findByStatus(Status.ON) for (entity in entities) { - val expiryTime = entity.expiryTime - try { - if (System.currentTimeMillis() > expiryTime) { - val newEntity = LeiShenLogic.login(entity.username, entity.password) - entity.accountToken = newEntity.accountToken - entity.nnToken = newEntity.nnToken - entity.expiryTime = newEntity.expiryTime - leiShenService.save(entity) - } - } catch (e: Exception) { - telegramBot.sendTextMessage(entity.tgId, """ + kotlin.runCatching { + val expiryTime = entity.expiryTime + try { + if (System.currentTimeMillis() > expiryTime) { + val newEntity = LeiShenLogic.login(entity.username, entity.password) + entity.accountToken = newEntity.accountToken + entity.nnToken = newEntity.nnToken + entity.expiryTime = newEntity.expiryTime + leiShenService.save(entity) + } + } catch (e: Exception) { + telegramBot.sendTextMessage(entity.tgId, """ #雷神加速器登录失败提醒 您的雷神加速器cookie已失效,重新登录失败,原因:${e.message} """.trimIndent()) - continue - } - val userInfo = try { - LeiShenLogic.userInfo(entity) - } catch (e: Exception) { - entity.expiryTime = 0 - leiShenService.save(entity) - continue - } - if (userInfo.pauseStatusId == 0) { - val sendMessage = SendMessage(entity.tgId, """ + return@runCatching + } + val userInfo = try { + LeiShenLogic.userInfo(entity) + } catch (e: Exception) { + entity.expiryTime = 0 + leiShenService.save(entity) + return@runCatching + } + if (userInfo.pauseStatusId == 0) { + val sendMessage = SendMessage(entity.tgId, """ #雷神加速器未暂停时间提醒 2小时提醒一次 您的雷神加速器未暂停时间,如果您未在玩游戏,请尽快暂停 """.trimIndent()).replyMarkup(InlineKeyboardMarkup(inlineKeyboardButton("暂停时间", "leiShenPause"))) - telegramBot.asyncExecute(sendMessage) + telegramBot.asyncExecute(sendMessage) + } + }.onFailure { + logger.error(it) } } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt index c6b60a5..3ed21f7 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/NetEaseSmallScheduled.kt @@ -15,14 +15,18 @@ class NetEaseSmallScheduled( private val netEaseService: NetEaseService ) { - @Scheduled(fixedDelay = 12, initialDelay = 1, timeUnit = TimeUnit.HOURS) +// @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 = NetEaseLogic.myMusic(netEaseEntity) + val myMusicList = try { + NetEaseLogic.myMusic(netEaseEntity) + } catch (e: Exception) { + continue + } for (netEaseSong in myMusicList) { - netEaseSmallLogic.listenMusic(netEaseSong.songId.toInt()) + netEaseSmallLogic.listenMusic(netEaseSong.songId) delay(2000) } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt index 3a2739a..2baf3a0 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/PixivScheduled.kt @@ -6,6 +6,7 @@ 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 @@ -14,6 +15,7 @@ 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 @@ -24,63 +26,69 @@ class PixivScheduled( 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) { - 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) + 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 (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) + 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) } - val sendMediaGroup = SendMediaGroup(tgId, *inputMediaList.toTypedArray()) - telegramBot.asyncExecute(sendMediaGroup) } - } + } } + userMap[tgId] = list[0].id + }.onFailure { + logger.error(it) } - userMap[tgId] = list[0].id } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt index def0b22..fb16d27 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/TwitterScheduled.kt @@ -2,6 +2,7 @@ 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 @@ -11,6 +12,7 @@ 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 @@ -22,46 +24,52 @@ class TwitterScheduled( 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) { - val tgId = entity.tgId - val list = TwitterLogic.friendTweet(entity).sortedBy { -it.id } - delay(3000) - if (list.isEmpty()) continue - 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) + 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) } - userMap[tgId] = max(list[0].id, userMap[tgId] ?: 0) } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/V2exScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/V2exScheduled.kt index 79feacb..ec81b5c 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/V2exScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/V2exScheduled.kt @@ -2,11 +2,13 @@ package me.kuku.telegram.scheduled import com.pengrad.telegrambot.TelegramBot import com.pengrad.telegrambot.request.SendMessage +import io.ktor.util.logging.* import me.kuku.telegram.context.asyncExecute import me.kuku.telegram.entity.ConfigService import me.kuku.telegram.entity.Status import me.kuku.telegram.logic.V2exLogic import me.kuku.telegram.logic.V2exTopic +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.net.ConnectException @@ -18,6 +20,8 @@ class V2exScheduled( private val telegramBot: TelegramBot ) { + private val logger = LoggerFactory.getLogger(V2exScheduled::class.java) + private var v2exId = 0 @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.MINUTES) @@ -44,8 +48,12 @@ class V2exScheduled( 标题:${v2exTopic.title} 链接:${v2exTopic.url} """.trimIndent() - val sendMessage = SendMessage(configEntity.tgId, str) - telegramBot.asyncExecute(sendMessage) + kotlin.runCatching { + val sendMessage = SendMessage(configEntity.tgId, str) + telegramBot.asyncExecute(sendMessage) + }.onFailure { + logger.error(it) + } } } } diff --git a/src/main/kotlin/me/kuku/telegram/scheduled/WeiboScheduled.kt b/src/main/kotlin/me/kuku/telegram/scheduled/WeiboScheduled.kt index 296ec98..f8022f2 100644 --- a/src/main/kotlin/me/kuku/telegram/scheduled/WeiboScheduled.kt +++ b/src/main/kotlin/me/kuku/telegram/scheduled/WeiboScheduled.kt @@ -4,6 +4,7 @@ import com.pengrad.telegrambot.TelegramBot import com.pengrad.telegrambot.request.SendVideo import io.ktor.client.call.* import io.ktor.client.request.* +import io.ktor.util.logging.* import kotlinx.coroutines.delay import me.kuku.telegram.context.asyncExecute import me.kuku.telegram.entity.* @@ -12,6 +13,7 @@ import me.kuku.telegram.logic.WeiboPojo import me.kuku.telegram.context.sendPic import me.kuku.telegram.context.sendTextMessage import me.kuku.utils.client +import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit @@ -23,6 +25,8 @@ class WeiboScheduled( private val logService: LogService ) { + private val logger = LoggerFactory.getLogger(WeiboScheduled::class.java) + private val userMap = mutableMapOf() @Scheduled(cron = "0 51 4 * * ?") @@ -40,40 +44,44 @@ class WeiboScheduled( suspend fun userMonitor() { val weiboList = weiboService.findByPush(Status.ON) for (weiboEntity in weiboList) { - val tgId = weiboEntity.tgId - delay(3000) - val list = WeiboLogic.followWeibo(weiboEntity) - val newList = mutableListOf() - if (userMap.containsKey(tgId)) { - for (weiboPojo in list) { - if (weiboPojo.id <= userMap[tgId]!!) break - newList.add(weiboPojo) - } - for (weiboPojo in newList) { - val ownText = if (weiboPojo.longText) WeiboLogic.longText(weiboEntity, weiboPojo.bid) else weiboPojo.text - val forwardText = if (weiboPojo.forwardLongText) WeiboLogic.longText(weiboEntity, weiboPojo.forwardBid) else weiboPojo.forwardText - val text = "#微博动态推送\n${WeiboLogic.convert(weiboPojo, ownText, forwardText)}" - val videoUrl = if (weiboPojo.videoUrl.isNotEmpty()) weiboPojo.videoUrl - else if (weiboPojo.forwardVideoUrl.isNotEmpty()) weiboPojo.forwardVideoUrl - else "" - try { - if (videoUrl.isNotEmpty()) { - client.get(videoUrl).body().let { - val sendVideo = SendVideo(tgId, it).caption(text) - .fileName("${weiboPojo.bid}.mp4") - telegramBot.asyncExecute(sendVideo) - } - } else if (weiboPojo.imageUrl.isNotEmpty() || weiboPojo.forwardImageUrl.isNotEmpty()) { - val imageList = weiboPojo.imageUrl - imageList.addAll(weiboPojo.forwardImageUrl) - telegramBot.sendPic(tgId, text, imageList) - } else telegramBot.sendTextMessage(tgId, text) - } catch (e: Exception) { - telegramBot.sendTextMessage(tgId, text) + kotlin.runCatching { + val tgId = weiboEntity.tgId + delay(3000) + val list = WeiboLogic.followWeibo(weiboEntity) + val newList = mutableListOf() + if (userMap.containsKey(tgId)) { + for (weiboPojo in list) { + if (weiboPojo.id <= userMap[tgId]!!) break + newList.add(weiboPojo) + } + for (weiboPojo in newList) { + val ownText = if (weiboPojo.longText) WeiboLogic.longText(weiboEntity, weiboPojo.bid) else weiboPojo.text + val forwardText = if (weiboPojo.forwardLongText) WeiboLogic.longText(weiboEntity, weiboPojo.forwardBid) else weiboPojo.forwardText + val text = "#微博动态推送\n${WeiboLogic.convert(weiboPojo, ownText, forwardText)}" + val videoUrl = if (weiboPojo.videoUrl.isNotEmpty()) weiboPojo.videoUrl + else if (weiboPojo.forwardVideoUrl.isNotEmpty()) weiboPojo.forwardVideoUrl + else "" + try { + if (videoUrl.isNotEmpty()) { + client.get(videoUrl).body().let { + val sendVideo = SendVideo(tgId, it).caption(text) + .fileName("${weiboPojo.bid}.mp4") + telegramBot.asyncExecute(sendVideo) + } + } else if (weiboPojo.imageUrl.isNotEmpty() || weiboPojo.forwardImageUrl.isNotEmpty()) { + val imageList = weiboPojo.imageUrl + imageList.addAll(weiboPojo.forwardImageUrl) + telegramBot.sendPic(tgId, text, imageList) + } else telegramBot.sendTextMessage(tgId, text) + } catch (e: Exception) { + telegramBot.sendTextMessage(tgId, text) + } } } + userMap[tgId] = list[0].id + }.onFailure { + logger.error(it) } - userMap[tgId] = list[0].id } }