From 62475fde46d0774d2ebb97e1d318d1e2e9c8b924 Mon Sep 17 00:00:00 2001 From: lunaticbum <> Date: Wed, 2 Oct 2024 18:15:35 +0900 Subject: [PATCH 1/3] .. --- Dockerfile | 17 ++- build.gradle.kts | 2 +- .../kr/lunaticbum/back/lun/LunApplication.kt | 63 +++++---- .../lunaticbum/back/lun/configs/AppConfig.kt | 10 ++ .../back/lun/configs/GlobalEnvironment.kt | 30 +++++ .../back/lun/configs/RootAppContext.kt | 25 ++++ .../back/lun/controllers/Telegram.kt | 126 +++++++++++++++++- .../back/lun/model/TelegramUpdate.kt | 112 ++++++++++++++++ src/main/resources/application.properties | 21 ++- 9 files changed, 367 insertions(+), 39 deletions(-) create mode 100644 src/main/kotlin/kr/lunaticbum/back/lun/configs/GlobalEnvironment.kt create mode 100644 src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt diff --git a/Dockerfile b/Dockerfile index 74c125e..66ec882 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,18 @@ 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 " +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 EXPOSE 8080 -ENTRYPOINT ["java","-jar","app.jar"] \ No newline at end of file +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}"] \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 9e98a10..6ab7def 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -6,7 +6,7 @@ plugins { } group = "kr.lunaticbum.back" -version = "0.0.1-SNAPSHOT" +version = "0.0.4-SNAPSHOT" java { toolchain { diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/LunApplication.kt b/src/main/kotlin/kr/lunaticbum/back/lun/LunApplication.kt index fbd7c63..66b9be6 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/LunApplication.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/LunApplication.kt @@ -1,45 +1,52 @@ package kr.lunaticbum.back.lun -import com.google.gson.Gson -import kr.lunaticbum.back.lun.model.CurrentWeather -import org.springframework.boot.CommandLineRunner -import org.springframework.boot.SpringApplication +import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.SpringBootApplication 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.Scheduled -import org.springframework.web.reactive.function.client.WebClient -import java.time.LocalDateTime -import java.util.* +import org.springframework.stereotype.Component + @EnableScheduling // 추가 @SpringBootApplication -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(result,CurrentWeather::class.java) +class LunApplication() { + - 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) { +// 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(*args) } // diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt index 598da80..b283a57 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt @@ -1,5 +1,6 @@ package kr.lunaticbum.back.lun.configs +import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.EnableWebMvc @@ -8,6 +9,15 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc @Configuration @EnableWebMvc class AppConfig { + +// @Bean +// fun getProperty() : Map{ +// println("telegramBotKey >>>> $telegramBotKey") +// println("telegramMyId >>>> $telegramMyId") +// println("weatherApiKey >>>> $weatherApiKey") +// +// return hashMapOf(Pair("telegramMyId",telegramMyId)) +// } // @Bean // fun memberRepository(): MemberRepository { // return MemoryMemberRepository() diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/GlobalEnvironment.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/GlobalEnvironment.kt new file mode 100644 index 0000000..ee74148 --- /dev/null +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/GlobalEnvironment.kt @@ -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") + } + +} \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/RootAppContext.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/RootAppContext.kt index b567afe..2656e32 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/RootAppContext.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/RootAppContext.kt @@ -1,7 +1,32 @@ 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.data.mongodb.core.MongoTemplate +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories +import org.springframework.scheduling.annotation.EnableAsync + @Configuration +@EnableMongoRepositories( basePackages = arrayOf("kr.lunaticbum.back.lun")) +@EnableAsync 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() +// } } \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt index d539441..b0f4850 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt @@ -1,11 +1,36 @@ 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.reactive.function.client.WebClient +import java.util.* + @RestController @RequestMapping("tlg") class Telegram { + + @Autowired + lateinit var globalEvv : GlobalEnvironment + + @Autowired + lateinit var telegramService: TelegramMsgService + @Autowired + lateinit var logService: LogService + @ResponseBody @GetMapping("/hello") fun hello(): String { @@ -18,7 +43,7 @@ class Telegram { println("path >>> $path") val client = WebClient.create() client.get() - .uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/getUpdates") + .uri("https://api.telegram.org/${globalEvv.telegramBotKey}/getUpdates") .retrieve() .bodyToMono(String::class.java).block() ?: "FAIL" @@ -36,4 +61,101 @@ class Telegram { // // } -} \ No newline at end of file + + @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(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(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 +} diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt b/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt new file mode 100644 index 0000000..fbbeb52 --- /dev/null +++ b/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt @@ -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? = 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? = null +} + +@Repository +interface TelegramRepository : ReactiveMongoRepository { + @Query("{id :?0}") + override fun findById(id: String): Mono + + @Query("{id :?0}") + fun count(id: Int): Mono +} +interface MsgService { + fun findById(id: String): Mono? +} + +@Service +class TelegramMsgService : MsgService { + @Autowired + private lateinit var logService: LogService + + @Autowired + private lateinit var telegramRepository: TelegramRepository + + + + override fun findById(id: String): Mono? { + return telegramRepository.findById(id) + } + + + fun has(id: Int): Mono? { + return telegramRepository.count(id) + } + + fun save(msg: Message) { + telegramRepository.save(msg) + logService.log("saved msg ${msg}") + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 64b48f2..49ecd75 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,15 +1,24 @@ 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.username=lun_admin spring.datasource.password=VioPup*383 spring.datasource.driver-class-name=org.mariadb.jdbc.Driver -spring.data.mongodb.host=nas.lunaticbum.kr -#spring.data.mongodb.host=localhost -spring.data.mongodb.port=27017 -spring.data.mongodb.database=lun_db +#spring.data.mongodb.host=mongodb://127.0.0.1 +spring.datasource.url=jdbc:mariadb://127.0.0.1:3307/lun_db +spring.data.mongodb.host=mongo.sbspace.synology.me/?authSource=admin +#///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 #logging.level.org.springframework.boot.autoconfigure=ERROR #spring.mvc.view.prefix=/templates #spring.mvc.view.suffix=.html -#server.servlet.register-default-servlet=true \ No newline at end of file +#server.servlet.register-default-servlet=true +telegram.bot.key=1 +telegram.my.id=2 +telegram.target.id=3 +weather.api.key=3 \ No newline at end of file From 7df54a521ce95ba498bd86ca7bb97e1590c9a37f Mon Sep 17 00:00:00 2001 From: lunaticbum <> Date: Fri, 4 Oct 2024 14:53:37 +0900 Subject: [PATCH 2/3] ... --- Dockerfile | 9 +- build.gradle.kts | 4 +- src/main/kotlin/WebConfig.kt | 124 ++++++++++++++++++ .../lunaticbum/back/lun/configs/AppConfig.kt | 1 - .../back/lun/configs/AutoAppConfig.kt | 1 - .../back/lun/configs/ServletAppContext.kt | 64 +++++---- .../lunaticbum/back/lun/configs/WebConfig.kt | 120 ----------------- .../back/lun/controllers/Telegram.kt | 41 +++--- .../lunaticbum/back/lun/controllers/User.kt | 6 +- .../back/lun/model/TelegramUpdate.kt | 11 +- .../back/lun/utils/WebClientUtil.kt | 1 - src/main/resources/application.properties | 49 ++++--- .../resources/templates/{ => user}/join.html | 5 +- 13 files changed, 240 insertions(+), 196 deletions(-) create mode 100644 src/main/kotlin/WebConfig.kt delete mode 100644 src/main/kotlin/kr/lunaticbum/back/lun/configs/WebConfig.kt rename src/main/resources/templates/{ => user}/join.html (97%) diff --git a/Dockerfile b/Dockerfile index 66ec882..42ebea3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,14 +5,17 @@ ENV WEATHER_KEY=default ENV BOT_KEY=default ENV DATASOURCE_URL=default ENV MONGODB_HOST=default +ENV MONGODB_NAME=default +ENV MRA_ADMIN=default +ENV MRA_PW=default LABEL maintainer="lunaticbum " LABEL version="0.0.4" LABEL description="Spring Boot Jar Test" -ARG JAR_FILE=build/libs/lun-0.0.4-SNAPSHOT.jar +ARG JAR_FILE=build/libs/lun-0.0.5-SNAPSHOT.jar COPY ${JAR_FILE} app.jar -EXPOSE 8080 +EXPOSE 443 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","-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.uri=${MONGODB_HOST}","-Dspring.data.mongodb.database=${MONGODB_NAME}","-Dspring.datasource.username=${MRA_ADMIN}","-Dspring.datasource.password=${MRA_PW}","-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}"] \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 6ab7def..1fe0718 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -6,7 +6,7 @@ plugins { } group = "kr.lunaticbum.back" -version = "0.0.4-SNAPSHOT" +version = "0.0.5-SNAPSHOT" java { toolchain { @@ -40,6 +40,8 @@ dependencies { implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") implementation("org.jetbrains.kotlin:kotlin-reflect") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") + implementation("org.springframework.boot:spring-boot-starter-thymeleaf") + compileOnly("org.projectlombok:lombok") runtimeOnly("org.mariadb.jdbc:mariadb-java-client") annotationProcessor("org.projectlombok:lombok") diff --git a/src/main/kotlin/WebConfig.kt b/src/main/kotlin/WebConfig.kt new file mode 100644 index 0000000..69b051d --- /dev/null +++ b/src/main/kotlin/WebConfig.kt @@ -0,0 +1,124 @@ +//package kr.lunaticbum.back.lun.configs +// +//import io.netty.channel.ChannelOption +//import io.netty.handler.timeout.ReadTimeoutHandler +//import io.netty.handler.timeout.WriteTimeoutHandler +//import jakarta.servlet.ServletContext +//import jakarta.servlet.ServletException +//import kr.lunaticbum.back.lun.utils.LogService +//import lombok.RequiredArgsConstructor +//import org.springframework.beans.factory.annotation.Autowired +//import org.springframework.beans.factory.annotation.Qualifier +//import org.springframework.context.annotation.Bean +//import org.springframework.http.client.reactive.ReactorClientHttpConnector +//import org.springframework.web.WebApplicationInitializer +//import org.springframework.web.context.ContextLoaderListener +//import org.springframework.web.context.support.AnnotationConfigWebApplicationContext +//import org.springframework.web.reactive.function.client.ClientRequest +//import org.springframework.web.reactive.function.client.ClientResponse +//import org.springframework.web.reactive.function.client.ExchangeFilterFunction +//import org.springframework.web.reactive.function.client.WebClient +//import org.springframework.web.servlet.DispatcherServlet +//import org.springframework.web.servlet.HandlerInterceptor +//import org.springframework.web.servlet.config.annotation.InterceptorRegistry +//import org.springframework.web.util.DefaultUriBuilderFactory +//import reactor.core.publisher.Mono +//import reactor.netty.Connection +//import reactor.netty.http.client.HttpClient +//import java.time.Duration +//import java.util.concurrent.TimeUnit +//import java.util.function.Consumer +// +// +//@RequiredArgsConstructor +//class WebConfig : WebApplicationInitializer { +// +// lateinit var logService : LogService +// +// var factory: DefaultUriBuilderFactory = DefaultUriBuilderFactory() +// +// var httpClient: HttpClient = HttpClient.create() +// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) // 10초 +// +// +// @Throws(ServletException::class) +// override fun onStartup(servletContext: ServletContext) { +// // Spring MVC 프로젝트 설정을 위해 작성하는 클래스의 객체를 생성한다. +// val servletAppContext = AnnotationConfigWebApplicationContext() +//// servletAppContext.register(ServletAppContext::class.java) +// +// // 요청 발생 시 요청을 처리하는 서블릿을 DispatcherServlet으로 설정해준다. +//// val dispatcherServlet = DispatcherServlet(servletAppContext) +//// val servlet = servletContext.addServlet("dispatcher", dispatcherServlet) +//// +//// // 부가 설정 +//// servlet.setLoadOnStartup(1) +//// servlet.addMapping("/") +// +// // Bean을 정의하는 클래스를 지정한다. +// val rootAppContext = AnnotationConfigWebApplicationContext() +// rootAppContext.register(RootAppContext::class.java) +// +// val listener = ContextLoaderListener(rootAppContext) +// servletContext.addListener(listener) +// } +// +// +// +// +// @Bean +// fun webClient(): WebClient { +// /** +// * 통신시 timeout 세팅 +// * - connect, read, write 를 모두 5000ms +// */ +// +// val httpClient = HttpClient.create() +// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) +// .responseTimeout(Duration.ofMillis(5000)) +// .doOnConnected { conn: Connection -> +// conn.addHandlerLast(ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS)) +// .addHandlerLast(WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS)) +// } +// +// val webClient = WebClient.builder() +// .baseUrl("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w") +// .clientConnector(ReactorClientHttpConnector(httpClient)) //생성한 HttpClient 연결 +// //Request Header 로깅 필터 +// .filter( +// ExchangeFilterFunction.ofRequestProcessor { clientRequest: ClientRequest -> +// logService.log(">>>>>>>>> REQUEST <<<<<<<<<<") +// logService.log("Request: ${clientRequest.method()} ${clientRequest.url()}") +// clientRequest.headers() +// .forEach { (name: String?, values: MutableList?) -> +// values.forEach( +// Consumer { value: String? -> +// logService.log( +// "${name} : ${value}" +// ) +// }) +// } +// Mono.just(clientRequest) +// } +// ) //Response Header 로깅 필터 +// .filter( +// ExchangeFilterFunction.ofResponseProcessor { clientResponse: ClientResponse -> +// logService.log(">>>>>>>>>> RESPONSE <<<<<<<<<<") +// clientResponse.headers().asHttpHeaders() +// .forEach { (name: String?, values: MutableList?) -> +// values.forEach( +// Consumer { value: String? -> +// logService.log( +// "${name} ${value}" +// ) +// }) +// } +// Mono.just(clientResponse) +// } +// ) +// .defaultHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8") //기본 헤더설정 +// .build() +// +// return webClient +// } +//} \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt index b283a57..76e6f8d 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/AppConfig.kt @@ -7,7 +7,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc @Configuration -@EnableWebMvc class AppConfig { // @Bean diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/AutoAppConfig.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/AutoAppConfig.kt index a141e8c..035df93 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/AutoAppConfig.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/AutoAppConfig.kt @@ -7,7 +7,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc @Configuration -@EnableWebMvc @ComponentScan(excludeFilters = [ComponentScan.Filter(type = FilterType.ANNOTATION, classes = arrayOf(Configuration::class))]) class AutoAppConfig { diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/ServletAppContext.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/ServletAppContext.kt index 98ecee8..e6a1c62 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/ServletAppContext.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/configs/ServletAppContext.kt @@ -1,30 +1,46 @@ package kr.lunaticbum.back.lun.configs +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration -import org.springframework.web.servlet.config.annotation.EnableWebMvc -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry -import org.springframework.web.servlet.config.annotation.ViewResolverRegistry -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer +import org.springframework.http.CacheControl +import org.springframework.web.servlet.HandlerInterceptor +import org.springframework.web.servlet.config.annotation.* +import java.util.concurrent.TimeUnit -// Spring MVC 프로젝트에 관련된 설정을 하는 클래스 -@Configuration // Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다. -@EnableWebMvc // 스캔할 패키지를 지정한다. -@ComponentScan("kr.lunaticbum.back.lun.controllers") -internal class ServletAppContext : WebMvcConfigurer { - // Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다. - override fun configureViewResolvers(registry: ViewResolverRegistry) { - // TODO Auto-generated method stub - super.configureViewResolvers(registry) -// registry.viewResolver { viewName, locale -> } -// registry.jsp("/WEB-INF/views/", ".jsp") - } - - // 정적 파일의 경로를 매핑한다. - override fun addResourceHandlers(registry: ResourceHandlerRegistry) { - // TODO Auto-generated method stub - super.addResourceHandlers(registry) - registry.addResourceHandler("/**").addResourceLocations("/resources/") - } -} \ No newline at end of file +//// Spring MVC 프로젝트에 관련된 설정을 하는 클래스 +//@Configuration // Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다. +////@ComponentScan("kr.lunaticbum.back.lun.controllers") +//internal class ServletAppContext : WebMvcConfigurer { +// // // Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다. +//// override fun configureViewResolvers(registry: ViewResolverRegistry) { +//// // TODO Auto-generated method stub +//// super.configureViewResolvers(registry) +////// registry.viewResolver { viewName, locale -> } +////// registry.jsp("/WEB-INF/views/", ".jsp") +//// } +//// +//// // 정적 파일의 경로를 매핑한다. +// override fun addResourceHandlers(registry: ResourceHandlerRegistry) { +// // TODO Auto-generated method stub +//// super.addResourceHandlers(registry) +// registry +// .addResourceHandler("/") +//// .addResourceHandler("/**") +// .addResourceLocations("classpath:/META-INF/resources/") +// .addResourceLocations("classpath:/static/") +// .addResourceLocations("classpath:/templates/") +// .addResourceLocations("classpath:/templates/user/") +// .setCacheControl(CacheControl.maxAge(10,TimeUnit.SECONDS)) +// super.addResourceHandlers(registry) +// } +//// @Autowired +//// @Qualifier(value = "authInterceptor") +//// private val authInterceptor: HandlerInterceptor? = null +//// +//// override fun addInterceptors(registry: InterceptorRegistry) { +//// registry.addInterceptor(authInterceptor).addPathPatterns("/**") +//// } +//} \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/configs/WebConfig.kt b/src/main/kotlin/kr/lunaticbum/back/lun/configs/WebConfig.kt deleted file mode 100644 index 9f4cd5f..0000000 --- a/src/main/kotlin/kr/lunaticbum/back/lun/configs/WebConfig.kt +++ /dev/null @@ -1,120 +0,0 @@ -package kr.lunaticbum.back.lun.configs - -import io.netty.channel.ChannelOption -import io.netty.handler.timeout.ReadTimeoutHandler -import io.netty.handler.timeout.WriteTimeoutHandler -import jakarta.servlet.ServletContext -import jakarta.servlet.ServletException -import kr.lunaticbum.back.lun.utils.LogService -import kr.lunaticbum.back.lun.utils.Logger -import lombok.RequiredArgsConstructor -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.annotation.Bean -import org.springframework.http.client.reactive.ReactorClientHttpConnector -import org.springframework.web.WebApplicationInitializer -import org.springframework.web.context.ContextLoaderListener -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext -import org.springframework.web.reactive.function.client.ClientRequest -import org.springframework.web.reactive.function.client.ClientResponse -import org.springframework.web.reactive.function.client.ExchangeFilterFunction -import org.springframework.web.reactive.function.client.WebClient -import org.springframework.web.servlet.DispatcherServlet -import org.springframework.web.util.DefaultUriBuilderFactory -import reactor.core.publisher.Mono -import reactor.netty.Connection -import reactor.netty.http.client.HttpClient -import java.time.Duration -import java.util.concurrent.TimeUnit -import java.util.function.Consumer - -@RequiredArgsConstructor -class WebConfig : WebApplicationInitializer { - - lateinit var logService : LogService - - var factory: DefaultUriBuilderFactory = DefaultUriBuilderFactory() - - var httpClient: HttpClient = HttpClient.create() - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) // 10초 - - - @Throws(ServletException::class) - override fun onStartup(servletContext: ServletContext) { - // Spring MVC 프로젝트 설정을 위해 작성하는 클래스의 객체를 생성한다. - val servletAppContext = AnnotationConfigWebApplicationContext() - servletAppContext.register(ServletAppContext::class.java) - - // 요청 발생 시 요청을 처리하는 서블릿을 DispatcherServlet으로 설정해준다. - val dispatcherServlet = DispatcherServlet(servletAppContext) - val servlet = servletContext.addServlet("dispatcher", dispatcherServlet) - - // 부가 설정 - servlet.setLoadOnStartup(1) - servlet.addMapping("/") - - // Bean을 정의하는 클래스를 지정한다. - val rootAppContext = AnnotationConfigWebApplicationContext() - rootAppContext.register(RootAppContext::class.java) - - val listener = ContextLoaderListener(rootAppContext) - servletContext.addListener(listener) - } - - - - @Bean - fun webClient(): WebClient { - /** - * 통신시 timeout 세팅 - * - connect, read, write 를 모두 5000ms - */ - - val httpClient = HttpClient.create() - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) - .responseTimeout(Duration.ofMillis(5000)) - .doOnConnected { conn: Connection -> - conn.addHandlerLast(ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS)) - .addHandlerLast(WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS)) - } - - val webClient = WebClient.builder() - .baseUrl("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w") - .clientConnector(ReactorClientHttpConnector(httpClient)) //생성한 HttpClient 연결 - //Request Header 로깅 필터 - .filter( - ExchangeFilterFunction.ofRequestProcessor { clientRequest: ClientRequest -> - logService.log(">>>>>>>>> REQUEST <<<<<<<<<<") - logService.log("Request: ${clientRequest.method()} ${clientRequest.url()}") - clientRequest.headers() - .forEach { (name: String?, values: MutableList?) -> - values.forEach( - Consumer { value: String? -> - logService.log( - "${name} : ${value}" - ) - }) - } - Mono.just(clientRequest) - } - ) //Response Header 로깅 필터 - .filter( - ExchangeFilterFunction.ofResponseProcessor { clientResponse: ClientResponse -> - logService.log(">>>>>>>>>> RESPONSE <<<<<<<<<<") - clientResponse.headers().asHttpHeaders() - .forEach { (name: String?, values: MutableList?) -> - values.forEach( - Consumer { value: String? -> - logService.log( - "${name} ${value}" - ) - }) - } - Mono.just(clientResponse) - } - ) - .defaultHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8") //기본 헤더설정 - .build() - - return webClient - } -} \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt index b0f4850..0447e70 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt @@ -38,14 +38,14 @@ class Telegram { } @ResponseBody - @GetMapping("webhook") - fun test(@PathVariable path : String) { - println("path >>> $path") - val client = WebClient.create() - client.get() - .uri("https://api.telegram.org/${globalEvv.telegramBotKey}/getUpdates") - .retrieve() - .bodyToMono(String::class.java).block() ?: "FAIL" + @PostMapping("webhook") + fun test(@RequestBody str : String) { + println("path >>> $str") +// val client = WebClient.create() +// client.get() +// .uri("https://api.telegram.org/${globalEvv.telegramBotKey}/getUpdates") +// .retrieve() +// .bodyToMono(String::class.java).block() ?: "FAIL" } @@ -63,7 +63,7 @@ class Telegram { @Bean - @Scheduled(cron = "0 0 0/2 * * *") // + @Scheduled(cron = "0 0 0/1 * * *") // fun runJob() { try { println("telegramBotKey >>>> ${globalEvv.telegramBotKey}") @@ -125,21 +125,28 @@ class Telegram { } } - fun qns(it : Int, msg : Message) { - - telegramService.has(it)?.subscribe { m -> + fun qns(it : String, msg : Message) { + var doSave = true + telegramService.findById(it)?.subscribe( { m -> println("pollingTelegramUpdate doOnSuccess m >>>> $m") - if (m == 0L) { + if (m != null) { if (msg.text?.contains("어디") == true) { - sendMsg() + } else { logService.log(msg.text ?: "NONE") } - telegramService.save(msg) } else { - + doSave = false } - } + },{ e -> + e.printStackTrace() + },{ + if (doSave) { + telegramService.save(msg) + sendMsg() + } + println("pollingTelegramUpdate doOnSuccess comp ") + }) } fun sendMsg() { val client = WebClient.create() diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/User.kt b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/User.kt index f0a93fe..1618a3f 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/controllers/User.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/controllers/User.kt @@ -8,13 +8,13 @@ import org.springframework.web.servlet.view.ContentNegotiatingViewResolver @RestController -@RequestMapping("/user") +@RequestMapping("user") class User { - @GetMapping("join") + @GetMapping("/join") fun hello(httpServletRequest: HttpServletRequest): ModelAndView { println("onJoin") - val vm = ModelAndView("join") + val vm = ModelAndView() vm.modelMap.put("ddd","asdas") println("${vm.toString()}") return vm diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt b/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt index fbbeb52..5482435 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt @@ -49,7 +49,7 @@ class From { @Document(collection = "TelegramMessage") class Message { @Id - var message_id: Int = 0 + var message_id: String = "" @BsonIgnore var from: From? = null @@ -81,6 +81,8 @@ interface TelegramRepository : ReactiveMongoRepository { @Query("{id :?0}") fun count(id: Int): Mono + + fun save(message: Message): Mono } interface MsgService { fun findById(id: String): Mono? @@ -106,7 +108,10 @@ class TelegramMsgService : MsgService { } fun save(msg: Message) { - telegramRepository.save(msg) - logService.log("saved msg ${msg}") + println("saved msg before ${msg}") + telegramRepository.save(msg).subscribe( { println("saved msg after ${it}") },{e -> e.printStackTrace()},{ + println("saved msg comp") + }) + } } \ No newline at end of file diff --git a/src/main/kotlin/kr/lunaticbum/back/lun/utils/WebClientUtil.kt b/src/main/kotlin/kr/lunaticbum/back/lun/utils/WebClientUtil.kt index 0dca0f5..e5a672d 100644 --- a/src/main/kotlin/kr/lunaticbum/back/lun/utils/WebClientUtil.kt +++ b/src/main/kotlin/kr/lunaticbum/back/lun/utils/WebClientUtil.kt @@ -1,6 +1,5 @@ package kr.lunaticbum.back.lun.utils -import kr.lunaticbum.back.lun.configs.WebConfig import lombok.RequiredArgsConstructor import org.apache.logging.log4j.util.InternalException import org.springframework.http.HttpMethod diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 49ecd75..301df4e 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,24 +1,35 @@ spring.application.name=lun - -#spring.datasource.url=jdbc:mariadb://localhost:3307/lun_db -spring.datasource.username=lun_admin -spring.datasource.password=VioPup*383 +server.port=443 +spring.datasource.username=c +spring.datasource.password=c spring.datasource.driver-class-name=org.mariadb.jdbc.Driver -#spring.data.mongodb.host=mongodb://127.0.0.1 -spring.datasource.url=jdbc:mariadb://127.0.0.1:3307/lun_db -spring.data.mongodb.host=mongo.sbspace.synology.me/?authSource=admin -#///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 -#logging.level.org.springframework.boot.autoconfigure=ERROR -#spring.mvc.view.prefix=/templates -#spring.mvc.view.suffix=.html -#server.servlet.register-default-servlet=true +spring.datasource.url=b +spring.data.mongodb.uri=a +spring.data.mongodb.authentication-database=admin +spring.data.mongodb.database=l +spring.thymeleaf.prefix=classpath:/templates/ +spring.thymeleaf.suffix=.html telegram.bot.key=1 telegram.my.id=2 telegram.target.id=3 -weather.api.key=3 \ No newline at end of file +weather.api.key=3 +spring.data.mongodb.option.min-connection-per-host=0 +spring.data.mongodb.option.max-connection-per-host=100 +spring.data.mongodb.option.threads-allowed-to-block-for-connection-multiplier=5 +spring.data.mongodb.option.server-selection-timeout=30000 +spring.data.mongodb.option.max-wait-time=120000 +spring.data.mongodb.option.max-connection-idle-time=0 +spring.data.mongodb.option.max-connection-life-time=0 +spring.data.mongodb.option.connect-timeout=10000 +spring.data.mongodb.option.socket-timeout=0 + +spring.data.mongodb.option.socket-keep-alive=false +spring.data.mongodb.option.ssl-enabled=false +spring.data.mongodb.option.ssl-invalid-host-name-allowed=false +spring.data.mongodb.option.always-use-m-beans=false + +spring.data.mongodb.option.heartbeat-socket-timeout=20000 +spring.data.mongodb.option.heartbeat-connect-timeout=20000 +spring.data.mongodb.option.min-heartbeat-frequency=500 +spring.data.mongodb.option.heartbeat-frequency=10000 +spring.data.mongodb.option.local-threshold=15 \ No newline at end of file diff --git a/src/main/resources/templates/join.html b/src/main/resources/templates/user/join.html similarity index 97% rename from src/main/resources/templates/join.html rename to src/main/resources/templates/user/join.html index afcfbf5..4ef1c80 100644 --- a/src/main/resources/templates/join.html +++ b/src/main/resources/templates/user/join.html @@ -1,6 +1,5 @@ -<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> + - @@ -8,7 +7,7 @@ -
+ @@ -135,6 +149,6 @@

회원가입

-
+ \ No newline at end of file