This commit is contained in:
lunaticbum 2024-10-02 18:15:35 +09:00
parent 829ea04d0c
commit 62475fde46
9 changed files with 367 additions and 39 deletions

View File

@ -1,5 +1,18 @@
FROM openjdk:17 FROM openjdk:17
ARG JAR_FILE=build/libs/lun-0.0.1-SNAPSHOT.jar ENV TG_TARGET_ID=default
ENV TG_MINE=default
ENV WEATHER_KEY=default
ENV BOT_KEY=default
ENV DATASOURCE_URL=default
ENV MONGODB_HOST=default
LABEL maintainer="lunaticbum <lunaticbum@gmail.com>"
LABEL version="0.0.4"
LABEL description="Spring Boot Jar Test"
ARG JAR_FILE=build/libs/lun-0.0.4-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar COPY ${JAR_FILE} app.jar
EXPOSE 8080 EXPOSE 8080
ENTRYPOINT ["java","-jar","app.jar"] EXPOSE 27012
EXPOSE 3307
ENTRYPOINT ["java","-Dtelegram.bot.key=${BOT_KEY}","-Dtelegram.my.id=${TG_MINE}","-Dtelegram.target.id=${TG_TARGET_ID}","-Dweather.api.key=${WEATHER_KEY}","-Dspring.datasource.url=${DATASOURCE_URL}" ,"-Dspring.data.mongodb.host=${MONGODB_HOST}" ,"-jar","app.jar"]
#ENTRYPOINT ["java","-jar","app.jar","-Dspring-boot.run.arguments=--telegram.bot.key=${BOT_KEY}, --telegram.my.id=${TG_MINE}, --telegram.target.id=${TG_TARGET_ID}, --weather.api.key=${WEATHER_KEY}"]

View File

@ -6,7 +6,7 @@ plugins {
} }
group = "kr.lunaticbum.back" group = "kr.lunaticbum.back"
version = "0.0.1-SNAPSHOT" version = "0.0.4-SNAPSHOT"
java { java {
toolchain { toolchain {

View File

@ -1,45 +1,52 @@
package kr.lunaticbum.back.lun package kr.lunaticbum.back.lun
import com.google.gson.Gson import org.springframework.beans.factory.annotation.Value
import kr.lunaticbum.back.lun.model.CurrentWeather
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.client.WebClient
import java.time.LocalDateTime
import java.util.*
@EnableScheduling // 추가 @EnableScheduling // 추가
@SpringBootApplication @SpringBootApplication
class LunApplication { class LunApplication() {
@Scheduled(cron = "0 0 0/4 * * *") //
fun runJob() {
try {
val client0 = WebClient.create()
val result = client0.get()
.uri("http://api.weatherapi.com/v1/current.json?key=de574a260b1f474d99955729241909&q=seoul&aqi=no")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
var sss = Gson().fromJson<CurrentWeather>(result,CurrentWeather::class.java)
val client = WebClient.create()
client.get()
.uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=71476436&text=온도${sss.current?.temp_c}")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
}catch (e : Exception) {
e.printStackTrace()
}
}
} }
//@Component
//class GEnv : EnvironmentAware {
// @Value("\${telegram.bot.key}")
// var telegramBotKey: String? = ""
//
// @Value("\${telegram.my.id}")
// var telegramMyId: String? = ""
//
// @Value("\${weather.api.key}")
// var weatherApiKey: String? = ""
//
//
// override fun setEnvironment(environment: Environment) {
// println ("telegramBotKey $telegramBotKey")
// println("telegramMyId $telegramMyId")
// println("weatherApiKey $weatherApiKey")
// }
//}
fun main(args: Array<String>) { fun main(args: Array<String>) {
// val props = System.getProperties()
// val enumerator = props.keys()
// while (enumerator.hasMoreElements()) {
// val ele = enumerator.nextElement()
// val key = ele.toString()
// println(key + ": " + System.getProperty(key))
// }
args.forEach {
println("main ARG >> $it")
}
runApplication<LunApplication>(*args) runApplication<LunApplication>(*args)
} }
// //

View File

@ -1,5 +1,6 @@
package kr.lunaticbum.back.lun.configs package kr.lunaticbum.back.lun.configs
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.EnableWebMvc
@ -8,6 +9,15 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
class AppConfig { class AppConfig {
// @Bean
// fun getProperty() : Map<String,String>{
// println("telegramBotKey >>>> $telegramBotKey")
// println("telegramMyId >>>> $telegramMyId")
// println("weatherApiKey >>>> $weatherApiKey")
//
// return hashMapOf(Pair("telegramMyId",telegramMyId))
// }
// @Bean // @Bean
// fun memberRepository(): MemberRepository { // fun memberRepository(): MemberRepository {
// return MemoryMemberRepository() // return MemoryMemberRepository()

View File

@ -0,0 +1,30 @@
package kr.lunaticbum.back.lun.configs
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.stereotype.Component
@Component
class GlobalEnvironment : EnvironmentAware {
@Value("\${telegram.bot.key}")
var telegramBotKey: String? = ""
@Value("\${telegram.my.id}")
var telegramMyId: String? = ""
@Value("\${telegram.target.id}")
var telegramTargetId: String? = ""
@Value("\${weather.api.key}")
var weatherApiKey: String? = ""
override fun setEnvironment(environment: Environment) {
println ("telegramBotKey $telegramBotKey")
println("telegramMyId $telegramMyId")
println("telegramMyId $telegramTargetId")
println("weatherApiKey $weatherApiKey")
}
}

View File

@ -1,7 +1,32 @@
package kr.lunaticbum.back.lun.configs package kr.lunaticbum.back.lun.configs
import com.mongodb.reactivestreams.client.MongoClient
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Configuration
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories
import org.springframework.scheduling.annotation.EnableAsync
@Configuration @Configuration
@EnableMongoRepositories( basePackages = arrayOf("kr.lunaticbum.back.lun"))
@EnableAsync
class RootAppContext { class RootAppContext {
// @Bean
// fun mongoClient(): MongoClient {
// return MongoClient("localhost")
// }
// fun mongoDbFactory(): MongoDbFactory {
// return SimpleMongoDbFactory(mongoClient(), "test")
// }
// @Bean
// fun mongoTemplate(): MongoTemplate {
// return MongoTemplate(mongoDbFactory())
// }
// fun mongoTemplate() :MongoTemplate {
// return MongoTemplate()
// }
} }

View File

@ -1,11 +1,36 @@
package kr.lunaticbum.back.lun.controllers package kr.lunaticbum.back.lun.controllers
import com.google.gson.Gson
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch
import kr.lunaticbum.back.lun.configs.GlobalEnvironment
import kr.lunaticbum.back.lun.model.CurrentWeather
import kr.lunaticbum.back.lun.model.Message
import kr.lunaticbum.back.lun.model.TelegramMsgService
import kr.lunaticbum.back.lun.model.TelegramUpdate
import kr.lunaticbum.back.lun.utils.LogService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient
import java.util.*
@RestController @RestController
@RequestMapping("tlg") @RequestMapping("tlg")
class Telegram { class Telegram {
@Autowired
lateinit var globalEvv : GlobalEnvironment
@Autowired
lateinit var telegramService: TelegramMsgService
@Autowired
lateinit var logService: LogService
@ResponseBody @ResponseBody
@GetMapping("/hello") @GetMapping("/hello")
fun hello(): String { fun hello(): String {
@ -18,7 +43,7 @@ class Telegram {
println("path >>> $path") println("path >>> $path")
val client = WebClient.create() val client = WebClient.create()
client.get() client.get()
.uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/getUpdates") .uri("https://api.telegram.org/${globalEvv.telegramBotKey}/getUpdates")
.retrieve() .retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL" .bodyToMono(String::class.java).block() ?: "FAIL"
@ -36,4 +61,101 @@ class Telegram {
// //
// } // }
@Bean
@Scheduled(cron = "0 0 0/2 * * *") //
fun runJob() {
try {
println("telegramBotKey >>>> ${globalEvv.telegramBotKey}")
println("telegramMyId >>>> ${globalEvv.telegramMyId}")
println("weatherApiKey >>>> ${globalEvv.weatherApiKey}")
if (globalEvv.weatherApiKey?.length ?: 0 > 3 && globalEvv.telegramBotKey?.length ?: 0 > 3 && globalEvv.telegramMyId?.length ?: 0 > 3) {
val client0 = WebClient.create()
val result = client0.get()
.uri("http://api.weatherapi.com/v1/current.json?key=${globalEvv.weatherApiKey}&q=seoul&aqi=no")
.retrieve()
.bodyToMono(String::class.java)
.block() ?: "FAIL"
var sss = Gson().fromJson<CurrentWeather>(result, CurrentWeather::class.java)
val client = WebClient.create()
client.get()
.uri("https://api.telegram.org/${globalEvv.telegramBotKey}/sendMessage?chat_id=${globalEvv.telegramMyId}&text=온도${sss.current?.temp_c}")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
}
}catch (e : Exception) {
e.printStackTrace()
}
}
@Bean
@Scheduled(cron = "0 0/2 * * * *") //
fun pollingTelegramUpdate() {
try {
println("pollingTelegramUpdate telegramBotKey >>>> ${globalEvv.telegramBotKey}")
println("pollingTelegramUpdate telegramMyId >>>> ${globalEvv.telegramMyId}")
println("pollingTelegramUpdate weatherApiKey >>>> ${globalEvv.weatherApiKey}")
if (globalEvv.weatherApiKey?.length ?: 0 > 3 && globalEvv.telegramBotKey?.length ?: 0 > 3 && globalEvv.telegramMyId?.length ?: 0 > 3) {
val client0 = WebClient.create()
val result = client0.get()
.uri("https://api.telegram.org/${globalEvv.telegramBotKey}/getUpdates")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
println("pollingTelegramUpdate result >>>> $result")
var sss = Gson().fromJson<TelegramUpdate>(result, TelegramUpdate::class.java)
println("pollingTelegramUpdate sss >>>> $sss")
if (sss.isSucces()) {
sss.result?.filter {
// println("${(it.message?.date ?: 0L).times(1000L) } > ${before5Min()} ${(it.message?.date ?: 0L).times(1000L) - before5Min()} ")
((it.message?.date ?: 0L) * 1000L) > before5Min()
}?.forEach {
println("pollingTelegramUpdate before Query doOnSuccess m >>>> ${it}")
it.message?.let { msg ->
println("pollingTelegramUpdate before Query doOnSuccess m >>>> ${msg.message_id}")
qns(msg.message_id,msg)
}
}
}
}
}catch (e : Exception) {
e.printStackTrace()
}
}
fun qns(it : Int, msg : Message) {
telegramService.has(it)?.subscribe { m ->
println("pollingTelegramUpdate doOnSuccess m >>>> $m")
if (m == 0L) {
if (msg.text?.contains("어디") == true) {
sendMsg()
} else {
logService.log(msg.text ?: "NONE")
}
telegramService.save(msg)
} else {
}
}
}
fun sendMsg() {
val client = WebClient.create()
client.get()
.uri("https://api.telegram.org/${globalEvv.telegramBotKey}/sendMessage?chat_id=${globalEvv.telegramMyId}&text=/g_mustShareLocation")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
}
}
fun before5Min(): Long {
val cal: Calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"))
cal.setTime(Date(System.currentTimeMillis()))
cal.timeZone = TimeZone.getDefault()
cal.add(Calendar.MINUTE, -10)
return cal.timeInMillis
} }

View File

@ -0,0 +1,112 @@
package kr.lunaticbum.back.lun.model
import kr.lunaticbum.back.lun.utils.LogService
import lombok.AllArgsConstructor
import lombok.Data
import lombok.NoArgsConstructor
import org.bson.codecs.pojo.annotations.BsonIgnore
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.repository.Query
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import java.util.*
// import com.fasterxml.jackson.databind.ObjectMapper; // version 2.11.1
// import com.fasterxml.jackson.annotation.JsonProperty; // version 2.11.1
/* ObjectMapper om = new ObjectMapper();
Root root = om.readValue(myJsonString, Root.class); */
class Chat {
var id: Int = 0
var first_name: String? = null
var last_name: String? = null
var username: String? = null
var type: String? = null
}
class Entity {
var offset: Int = 0
var length: Int = 0
var type: String? = null
}
class From {
var id: Int = 0
var is_bot: Boolean = false
var first_name: String? = null
var last_name: String? = null
var username: String? = null
var language_code: String? = null
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "TelegramMessage")
class Message {
@Id
var message_id: Int = 0
@BsonIgnore
var from: From? = null
@BsonIgnore
var chat: Chat? = null
var date: Long = 0
var text: String? = null
@BsonIgnore
var entities: ArrayList<Entity>? = null
}
class Result {
var update_id: Int = 0
var message: Message? = null
}
class TelegramUpdate {
fun isSucces() = ok == true
var ok: Boolean = false
var result: ArrayList<Result>? = null
}
@Repository
interface TelegramRepository : ReactiveMongoRepository<Message,String> {
@Query("{id :?0}")
override fun findById(id: String): Mono<Message>
@Query("{id :?0}")
fun count(id: Int): Mono<Long>
}
interface MsgService {
fun findById(id: String): Mono<Message>?
}
@Service
class TelegramMsgService : MsgService {
@Autowired
private lateinit var logService: LogService
@Autowired
private lateinit var telegramRepository: TelegramRepository
override fun findById(id: String): Mono<Message>? {
return telegramRepository.findById(id)
}
fun has(id: Int): Mono<Long>? {
return telegramRepository.count(id)
}
fun save(msg: Message) {
telegramRepository.save(msg)
logService.log("saved msg ${msg}")
}
}

View File

@ -1,15 +1,24 @@
spring.application.name=lun spring.application.name=lun
spring.datasource.url=jdbc:mariadb://lunaticbum.kr:3307/lun_db
#spring.datasource.url=jdbc:mariadb://localhost:3307/lun_db #spring.datasource.url=jdbc:mariadb://localhost:3307/lun_db
spring.datasource.username=lun_admin spring.datasource.username=lun_admin
spring.datasource.password=VioPup*383 spring.datasource.password=VioPup*383
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.data.mongodb.host=nas.lunaticbum.kr #spring.data.mongodb.host=mongodb://127.0.0.1
#spring.data.mongodb.host=localhost spring.datasource.url=jdbc:mariadb://127.0.0.1:3307/lun_db
spring.data.mongodb.port=27017 spring.data.mongodb.host=mongo.sbspace.synology.me/?authSource=admin
spring.data.mongodb.database=lun_db #///mogodb://mongo.sbspace.synology.me
#spring.data.mongodb.host=mongo.sbspace.synology.me
#spring.data.mongodb.port=443
spring.data.mongodb.username=lun_admin
spring.data.mongodb.password=VioPup*383
spring.data.mongodb.database=Telegram
#spring.main.web-application-type=SERVLET #spring.main.web-application-type=SERVLET
#logging.level.org.springframework.boot.autoconfigure=ERROR #logging.level.org.springframework.boot.autoconfigure=ERROR
#spring.mvc.view.prefix=/templates #spring.mvc.view.prefix=/templates
#spring.mvc.view.suffix=.html #spring.mvc.view.suffix=.html
#server.servlet.register-default-servlet=true #server.servlet.register-default-servlet=true
telegram.bot.key=1
telegram.my.id=2
telegram.target.id=3
weather.api.key=3