# Conflicts:
#	src/main/kotlin/kr/lunaticbum/back/lun/LunApplication.kt
#	src/main/kotlin/kr/lunaticbum/back/lun/controllers/Telegram.kt
#	src/main/kotlin/kr/lunaticbum/back/lun/model/TelegramUpdate.kt
#	src/main/resources/application.properties
This commit is contained in:
lunaticbum 2024-10-05 17:18:43 +09:00
commit dfa6b28a66
20 changed files with 793 additions and 305 deletions

View File

@ -1,5 +1,21 @@
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
ENV MONGODB_NAME=default
ENV MRA_ADMIN=default
ENV MRA_PW=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.5-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar COPY ${JAR_FILE} app.jar
EXPOSE 8080 EXPOSE 443
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.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}"]

View File

@ -6,7 +6,7 @@ plugins {
} }
group = "kr.lunaticbum.back" group = "kr.lunaticbum.back"
version = "0.0.1-SNAPSHOT" version = "0.0.5-SNAPSHOT"
java { java {
toolchain { toolchain {
@ -40,6 +40,8 @@ dependencies {
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
implementation("org.jetbrains.kotlin:kotlin-reflect") implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
compileOnly("org.projectlombok:lombok") compileOnly("org.projectlombok:lombok")
runtimeOnly("org.mariadb.jdbc:mariadb-java-client") runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
annotationProcessor("org.projectlombok:lombok") annotationProcessor("org.projectlombok:lombok")

View File

@ -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<String?>?) ->
// values.forEach(
// Consumer<String> { value: String? ->
// logService.log(
// "${name} : ${value}"
// )
// })
// }
// Mono.just<ClientRequest>(clientRequest)
// }
// ) //Response Header 로깅 필터
// .filter(
// ExchangeFilterFunction.ofResponseProcessor { clientResponse: ClientResponse ->
// logService.log(">>>>>>>>>> RESPONSE <<<<<<<<<<")
// clientResponse.headers().asHttpHeaders()
// .forEach { (name: String?, values: MutableList<String?>?) ->
// values.forEach(
// Consumer<String> { value: String? ->
// logService.log(
// "${name} ${value}"
// )
// })
// }
// Mono.just<ClientResponse>(clientResponse)
// }
// )
// .defaultHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8") //기본 헤더설정
// .build()
//
// return webClient
// }
//}

View File

@ -1,17 +1,14 @@
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 org.springframework.web.reactive.function.client.WebClient
import java.time.LocalDateTime
import java.util.*
@EnableScheduling // 추가 @EnableScheduling // 추가
@SpringBootApplication @SpringBootApplication
@ -24,51 +21,15 @@ class LunApplication {
.bodyToMono(String::class.java).block() ?: "FAIL" .bodyToMono(String::class.java).block() ?: "FAIL"
} }
@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()
}
}
} }
fun main(args: Array<String>) { fun main(args: Array<String>) {
args.forEach {
println("main ARG >> $it")
}
runApplication<LunApplication>(*args) runApplication<LunApplication>(*args)
} }
//
//@SpringBootApplication
//class Application {
// @Bean
// fun commandLineRunner(ctx: ApplicationContext): CommandLineRunner {
// return CommandLineRunner { args: Array<String?>? ->
// println("Let's inspect the beans provided by Spring Boot:")
// val beanNames: Array<String> = ctx.getBeanDefinitionNames()
// Arrays.sort(beanNames)
// for (beanName in beanNames) {
// println(beanName)
// }
// }
// }
//
// companion object {
// @JvmStatic
// fun main(args: Array<String>) {
// SpringApplication.run(Application::class.java, *args)
// }
// }
//}

View File

@ -1,13 +1,22 @@
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
@Configuration @Configuration
@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

@ -7,7 +7,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc
@Configuration @Configuration
@EnableWebMvc
@ComponentScan(excludeFilters = [ComponentScan.Filter(type = FilterType.ANNOTATION, classes = arrayOf(Configuration::class))]) @ComponentScan(excludeFilters = [ComponentScan.Filter(type = FilterType.ANNOTATION, classes = arrayOf(Configuration::class))])
class AutoAppConfig { class AutoAppConfig {

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,30 +1,46 @@
package kr.lunaticbum.back.lun.configs 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.ComponentScan
import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.http.CacheControl
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry import org.springframework.web.servlet.config.annotation.*
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import java.util.concurrent.TimeUnit
// Spring MVC 프로젝트에 관련된 설정을 하는 클래스 //// Spring MVC 프로젝트에 관련된 설정을 하는 클래스
@Configuration // Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다. //@Configuration // Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다.
@EnableWebMvc // 스캔할 패키지를 지정한다. ////@ComponentScan("kr.lunaticbum.back.lun.controllers")
@ComponentScan("kr.lunaticbum.back.lun.controllers") //internal class ServletAppContext : WebMvcConfigurer {
internal class ServletAppContext : WebMvcConfigurer { // // // Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다.
// Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다. //// override fun configureViewResolvers(registry: ViewResolverRegistry) {
override fun configureViewResolvers(registry: ViewResolverRegistry) { //// // TODO Auto-generated method stub
// TODO Auto-generated method stub //// super.configureViewResolvers(registry)
super.configureViewResolvers(registry) ////// registry.viewResolver { viewName, locale -> }
// registry.viewResolver { viewName, locale -> } ////// registry.jsp("/WEB-INF/views/", ".jsp")
// registry.jsp("/WEB-INF/views/", ".jsp") //// }
} ////
//// // 정적 파일의 경로를 매핑한다.
// 정적 파일의 경로를 매핑한다. // override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
override fun addResourceHandlers(registry: ResourceHandlerRegistry) { // // TODO Auto-generated method stub
// TODO Auto-generated method stub //// super.addResourceHandlers(registry)
super.addResourceHandlers(registry) // registry
registry.addResourceHandler("/**").addResourceLocations("/resources/") // .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("/**")
//// }
//}

View File

@ -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<String?>?) ->
values.forEach(
Consumer<String> { value: String? ->
logService.log(
"${name} : ${value}"
)
})
}
Mono.just<ClientRequest>(clientRequest)
}
) //Response Header 로깅 필터
.filter(
ExchangeFilterFunction.ofResponseProcessor { clientResponse: ClientResponse ->
logService.log(">>>>>>>>>> RESPONSE <<<<<<<<<<")
clientResponse.headers().asHttpHeaders()
.forEach { (name: String?, values: MutableList<String?>?) ->
values.forEach(
Consumer<String> { value: String? ->
logService.log(
"${name} ${value}"
)
})
}
Mono.just<ClientResponse>(clientResponse)
}
)
.defaultHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8") //기본 헤더설정
.build()
return webClient
}
}

View File

@ -1,11 +1,37 @@
package kr.lunaticbum.back.lun.controllers package kr.lunaticbum.back.lun.controllers
import com.google.gson.Gson
import jakarta.servlet.http.HttpServletRequest
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 {
@ -16,14 +42,14 @@ class Telegram {
@PostMapping("webhook") @PostMapping("webhook")
fun test(httpServletRequest: HttpServletRequest, @RequestBody update : TelegramUpdate?) { fun test(httpServletRequest: HttpServletRequest, @RequestBody update : TelegramUpdate?) {
try { try {
logger.log("test strat ${update}") logService.log("test strat ${update}")
logger.log("test strat ${httpServletRequest.requestURI}") logService.log("test strat ${httpServletRequest.requestURI}")
// val client0 = WebClient.create() // val client0 = WebClient.create()
// client0.get() // client0.get()
// .uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/getUpdates") // .uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/getUpdates")
// .retrieve() // .retrieve()
// .bodyToMono(String::class.java).subscribe { result -> // .bodyToMono(String::class.java).subscribe { result ->
logger.log("test $httpServletRequest.requestURI") logService.log("test $httpServletRequest.requestURI")
// var sss = Gson().fromJson<TelegramUpdate>(jsonString, TelegramUpdate::class.java) // var sss = Gson().fromJson<TelegramUpdate>(jsonString, TelegramUpdate::class.java)
// if (sss.ok) { // if (sss.ok) {
// var doSend = false // var doSend = false
@ -41,20 +67,128 @@ class Telegram {
// } // }
// } // }
} catch (e : Exception) { } catch (e : Exception) {
//=======
// fun test(@RequestBody str : String) {
// println("path >>> $str")
//>>>>>>> ab915d0a416c69708f1df1ad76d7a14c779c1f59
} }
} }
// @ResponseBody
// @GetMapping("webhook")
// fun test(@PathVariable path : String) {
// println("path >>> $path")
// val client = WebClient.create()
// client.get()
// .uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/getUpdates")
// .retrieve()
// .bodyToMono(String::class.java).block() ?: "FAIL"
//
// }
}
@Bean
@Scheduled(cron = "0 0 0/1 * * *") //
fun runJob() {
try {
logService.log("telegramBotKey >>>> ${globalEvv.telegramBotKey}")
logService.log("telegramMyId >>>> ${globalEvv.telegramMyId}")
logService.log("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"
Gson().fromJson(result, CurrentWeather::class.java)?.let { sss ->
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 {
logService.log("pollingTelegramUpdate telegramBotKey >>>> ${globalEvv.telegramBotKey}")
logService.log("pollingTelegramUpdate telegramMyId >>>> ${globalEvv.telegramMyId}")
logService.log("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"
logService.log("pollingTelegramUpdate result >>>> $result")
Gson().fromJson(result, TelegramUpdate::class.java)?.let { sss ->
logService.log("pollingTelegramUpdate sss >>>> $sss")
if (sss.isSucces()) {
sss.result?.filter {
((it.message?.date ?: 0L) * 1000L) > before5Min()
}?.forEach {
logService.log("pollingTelegramUpdate before Query doOnSuccess m >>>> ${it}")
it.message?.let { msg ->
logService.log("pollingTelegramUpdate before Query doOnSuccess m >>>> ${msg.message_id}")
qns(msg.message_id,msg)
}
}
}
}
}
}catch (e : Exception) {
e.printStackTrace()
}
}
fun qns(it : String, msg : Message) {
var doSave = true
telegramService.findById(it)?.subscribe( { m ->
logService.log("pollingTelegramUpdate doOnSuccess m >>>> $m")
if (m != null) {
if (msg.text?.contains("어디") == true) {
} else {
logService.log(msg.text ?: "NONE")
}
} else {
doSave = false
}
},{ e ->
e.printStackTrace()
},{
if (doSave) {
telegramService.save(msg)
if (msg.text?.contains("어디") == true || msg.text?.startsWith("\"") == true) {
sendMsg()
}
}
logService.log("pollingTelegramUpdate doOnSuccess comp")
})
}
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

@ -1,45 +0,0 @@
package kr.lunaticbum.back.lun.controllers
import jakarta.servlet.http.HttpServletRequest
import org.springframework.web.bind.annotation.*
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver
@RestController
@RequestMapping("/user")
class User {
@GetMapping("join")
fun hello(httpServletRequest: HttpServletRequest): ModelAndView {
println("onJoin")
val vm = ModelAndView("join")
vm.modelMap.put("ddd","asdas")
println("${vm.toString()}")
return vm
}
@ResponseBody
@PostMapping("joinUser.api")
fun joinUser(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : String {
println("${httpServletRequest.requestURI}")
val reqString = jsonString
println(reqString)
return "1234"
}
@ResponseBody
@GetMapping("test/{path}")
fun test(@PathVariable path : String): String {
println("path >>> $path")
val client = WebClient.create()
return client.get()
.uri("https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=71476436&text=${path}")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
}
}

View File

@ -0,0 +1,96 @@
package kr.lunaticbum.back.lun.controllers
import com.google.gson.Gson
import jakarta.servlet.http.HttpServletRequest
import kr.lunaticbum.back.lun.configs.GlobalEnvironment
import kr.lunaticbum.back.lun.model.ResponceResult
import kr.lunaticbum.back.lun.model.User
import kr.lunaticbum.back.lun.model.UserManager
import kr.lunaticbum.back.lun.utils.LogService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.annotation.AccessType
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.function.ServerResponse
import reactor.core.publisher.Mono
@RestController
@RequestMapping("user")
class UserController {
@Autowired
lateinit var globalEvv : GlobalEnvironment
@Autowired
lateinit var logService: LogService
@Autowired
lateinit var userManager: UserManager
@GetMapping("/join")
fun hello(httpServletRequest: HttpServletRequest): ModelAndView {
logService.log("onJoin")
val vm = ModelAndView()
vm.modelMap.put("ddd","asdas")
logService.log("${vm.toString()}")
return vm
}
@ResponseBody
@PostMapping("joinUser.api")
fun joinUser(httpServletRequest: HttpServletRequest, @RequestBody jsonString: String) : ResponseEntity<ResponceResult> {
logService.log("${httpServletRequest.requestURI}")
logService.log(jsonString)
val reqString = jsonString.split("_||L_")
var nb = arrayListOf<String>()
(reqString[0].replace("_||L_","").split("")).toList().let {
nb.addAll(it)
}
logService.log(nb.toString())
var na = arrayListOf<String>()
reqString[1].replace("_||L_","").split("").toList().let {
na.addAll(it)
}
logService.log(na.toString())
var max = nb.size + na.size
var fullData = arrayListOf<String>()
for (idx in 0..max) {
if (idx % 2 == 0) {
if (nb.size > 0) {
fullData.add(nb.removeLast())
}
} else {
if (na.size > 0) {
fullData.add(na.removeLast())
}
}
}
logService.log(fullData.joinToString(""))
var user = Gson().fromJson(fullData.joinToString(""), User::class.java)
var u = userManager.save(user).block()
val responce = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(ResponceResult().apply {
resultCode = if (u != null) 0 else 8245
resultMsg = if (u != null) "OK" else "User Insert Fail"
})
return responce
}
@ResponseBody
@GetMapping("test/{path}")
fun test(@PathVariable path : String): String {
logService.log("path >>> $path")
val client = WebClient.create()
return client.get()
.uri("https://api.telegram.org/${globalEvv.telegramBotKey}/sendMessage?chat_id=${globalEvv.telegramMyId}&text=${path}")
.retrieve()
.bodyToMono(String::class.java).block() ?: "FAIL"
}
}

View File

@ -0,0 +1,10 @@
package kr.lunaticbum.back.lun.model
import lombok.Getter
@Getter
class ResponceResult {
var resultCode: Int = 0
var resultMsg: String? = null
}

View File

@ -1,4 +1,117 @@
package kr.lunaticbum.back.lun.model 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: String = ""
@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 { 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>
fun save(message: Message): Mono<Message>
}
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) {
println("saved msg before ${msg}")
telegramRepository.save(msg).subscribe( { println("saved msg after ${it}") },{e -> e.printStackTrace()},{
println("saved msg comp")
})
}
} }

View File

@ -0,0 +1,73 @@
package kr.lunaticbum.back.lun.model
import kr.lunaticbum.back.lun.utils.LogService
import lombok.AllArgsConstructor
import lombok.Data
import lombok.NoArgsConstructor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Primary
import org.springframework.data.annotation.CreatedDate
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
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "User")
class User {
@Id
var user_id: String? = null
var user_pw: String? = null
var user_pw_check: String? = null
var user_email: String? = null
@CreatedDate
var user_join: Long = 0L
var user_name: String? = null
var isAccept : String? = null
var isAdmin : String? = null
}
@Repository
interface UserRepository : ReactiveMongoRepository<User, String> {
@Query("{id :?0}")
override fun findById(id: String): Mono<User>
fun save(user: User): Mono<User>
}
interface UserService {
fun findById(id: String): Mono<User>?
}
@Service
class UserManager : UserService {
@Autowired
private lateinit var logService: LogService
@Autowired
private lateinit var userRepository: UserRepository
override fun findById(id: String): Mono<User>? {
return userRepository.findById(id)
}
fun save(user: User): Mono<User> {
println("saved user before ${user}")
return userRepository.save(user)
// .subscribe( { println("saved user after ${it}") },{e -> e.printStackTrace()},{
// println("saved user comp")
// })
}
}

View File

@ -44,12 +44,13 @@ class Logger {
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
class LogService { class LogService {
private val myLogger: Logger? = null
fun logic(id: String) { fun logic(id: String) {
myLogger?.log("service id = $id") println("service id = $id")
} }
fun log(id: String) { fun log(id: String) {
myLogger?.log("log = $id") println("log = $id")
} }
} }

View File

@ -1,6 +1,5 @@
package kr.lunaticbum.back.lun.utils package kr.lunaticbum.back.lun.utils
import kr.lunaticbum.back.lun.configs.WebConfig
import lombok.RequiredArgsConstructor import lombok.RequiredArgsConstructor
import org.apache.logging.log4j.util.InternalException import org.apache.logging.log4j.util.InternalException
import org.springframework.http.HttpMethod import org.springframework.http.HttpMethod

View File

@ -1,13 +1,13 @@
spring.application.name=lun spring.application.name=lun
spring.datasource.url=jdbc:mariadb://lunaticbum.kr:3307/lun_db server.port=443
#spring.datasource.url=jdbc:mariadb://localhost:3307/lun_db spring.datasource.username=c
spring.datasource.username=lun_admin spring.datasource.password=c
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 #<<<<<<< HEAD
#spring.data.mongodb.host=nas.lunaticbum.kr
#spring.data.mongodb.host=localhost #spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017 #spring.data.mongodb.port=27017
spring.data.mongodb.database=lun_db #spring.data.mongodb.database=lun_db
#SSL #SSL
server.ssl.key-store=classpath:prv.p12 server.ssl.key-store=classpath:prv.p12
server.ssl.key-store-type=PKCS12 server.ssl.key-store-type=PKCS12
@ -17,4 +17,36 @@ server.http2.enabled=true
#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
#=======
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
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
#>>>>>>> ab915d0a416c69708f1df1ad76d7a14c779c1f59

View File

@ -1,6 +1,5 @@
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <html lang="ko" xmlns:th="http://www.thymeleaf.org">
<html lang="ko">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
@ -8,7 +7,7 @@
<style> <style>
table { table {
width: 280px; width: 280px;
height: 550px; height: 850px;
margin: auto; margin: auto;
} }
@ -65,50 +64,64 @@
} }
</style> </style>
<script> <script>
function getDivder() {
return "_||L_"
}
function mergeData(a , b) {
return a.join("") + getDivder() + b.join("")
}
function userJoin() { function userJoin() {
var httpRequest; var httpRequest;
var user_id = document.getElementById("user_id").value; var user_id = document.getElementById("user_id").value;
var user_pw = document.getElementById("user_pw").value; var user_pw = document.getElementById("user_pw").value;
var user_pw_check = document.getElementById("user_pw_check").value; var user_pw_check = document.getElementById("user_pw_check").value;
var user_email = document.getElementById("user_email").value; if (user_pw === user_pw_check) {
var user_birth = document.getElementById("user_birth").value; var user_email = document.getElementById("user_email").value;
var user_name = document.getElementById("user_name").value; var user_birth = document.getElementById("user_birth").value;
var user_name = document.getElementById("user_name").value;
/* 통신에 사용 될 XMLHttpRequest 객체 정의 */ /* 통신에 사용 될 XMLHttpRequest 객체 정의 */
httpRequest = new XMLHttpRequest(); httpRequest = new XMLHttpRequest();
/* httpRequest의 readyState가 변화했을때 함수 실행 */ /* httpRequest의 readyState가 변화했을때 함수 실행 */
httpRequest.onreadystatechange = () => { httpRequest.onreadystatechange = () => {
/* readyState가 Done이고 응답 값이 200일 때, 받아온 response로 name과 age를 그려줌 */ /* readyState가 Done이고 응답 값이 200일 때, 받아온 response로 name과 age를 그려줌 */
if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) { if (httpRequest.status === 200) {
var result = httpRequest.response; var result = httpRequest.response;
document.getElementById("name").innerText = result.name; console.log(result)
document.getElementById("age").innerText = result.age; alert('Request OK!' + result);
} else { // document.getElementById("name").innerText = result.name;
alert('Request Error!'); // document.getElementById("age").innerText = result.age;
} else {
alert('Request Error!');
}
} }
};
/* Get 방식으로 name 파라미터와 함께 요청 */
httpRequest.open('POST', 'joinUser.api', true);
httpRequest.setRequestHeader("Content-Type", "text/plain");
let data = {
'user_id': user_id,
'user_pw': user_pw,
'user_pw_check': user_pw_check,
'user_email': user_email,
'user_birth': user_birth,
'user_name': user_name
} }
}; var odd = []
/* Get 방식으로 name 파라미터와 함께 요청 */ var even = []
httpRequest.open('POST', 'joinUser.api', true); var dataStr = JSON.stringify(data)
httpRequest.setRequestHeader("Content-Type", "application/json"); var src = dataStr.split("")
src.forEach(function (s,i,a) {if (i % 2 === 0) {even.push(s)} else {odd.push(s)}})
let data = { httpRequest.send(mergeData(even.reverse(),odd.reverse()));
'user_id': user_id,
'user_pw': user_pw,
'user_pw_check': user_pw_check,
'user_email': user_email,
'user_birth': user_birth,
'user_name': user_name
} }
httpRequest.send(JSON.stringify(data));
} }
</script> </script>
</head> </head>
<body> <body>
<form >
<table> <table>
<tr> <tr>
<td><h2>회원가입</h2></td> <td><h2>회원가입</h2></td>
@ -136,6 +149,6 @@
</tr> </tr>
<tr><td><input type="submit" value="가입하기" class="btn" onclick="userJoin()"></td></tr> <tr><td><input type="submit" value="가입하기" class="btn" onclick="userJoin()"></td></tr>
</table> </table>
</form>
</body> </body>
</html> </html>