diff --git a/.gitignore b/.gitignore deleted file mode 100644 index d938789..0000000 --- a/.gitignore +++ /dev/null @@ -1,45 +0,0 @@ -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/**/build/ -!**/src/test/**/build/ - -### IntelliJ IDEA ### -.idea/modules.xml -.idea/jarRepositories.xml -.idea/compiler.xml -.idea/libraries/ -*.iws -*.iml -*.ipr -out/ -!**/src/main/**/out/ -!**/src/test/**/out/ - -### Eclipse ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache -bin/ -!**/src/main/**/bin/ -!**/src/test/**/bin/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ - -### Mac OS ### -.DS_Store - -/src/main/resources/ -/.env diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b8..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/discord.xml b/.idea/discord.xml deleted file mode 100644 index 8cf359d..0000000 --- a/.idea/discord.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml deleted file mode 100644 index 67033f8..0000000 --- a/.idea/gradle.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 1ebc6b1..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index 2b63946..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/README.md b/README.md index 9980c5b..4205173 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ # automata A github bot for automating github related stuff + +a javascript rewrite by @SrIzan10 +ty seren for giving me dev access to the organization :D \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts deleted file mode 100644 index 9392f5a..0000000 --- a/build.gradle.kts +++ /dev/null @@ -1,52 +0,0 @@ -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile -val jwt_version : String by project -val coroutine_version : String by project -val gh_version : String by project -val arrow_fx_version : String by project -val fuel_version : String by project -plugins { - kotlin("jvm") version "1.7.10" - application - kotlin("plugin.serialization") version "1.7.10" -} - -group = "org.example" -version = "1.0-SNAPSHOT" - -repositories { - mavenCentral() -} - -dependencies { - implementation(platform("io.arrow-kt:arrow-stack:$arrow_fx_version")) - implementation("io.ktor:ktor-server-content-negotiation-jvm:2.1.0") - implementation("io.ktor:ktor-serialization-gson-jvm:2.1.0") - testImplementation(kotlin("test")) - - implementation("io.ktor:ktor-client-core:2.1.0") - implementation("io.ktor:ktor-client-cio:2.1.0") - implementation("io.ktor:ktor-client-content-negotiation:2.1.0") - implementation("io.ktor:ktor-client-json:2.1.0") - implementation("io.ktor:ktor-client-serialization:2.0.3") - implementation("io.ktor:ktor-serialization-kotlinx-json:2.1.0") - // Use JSON serialization - implementation("io.ktor:ktor-server-core-jvm:2.0.3") - implementation("io.ktor:ktor-server-netty-jvm:2.0.3") - implementation("com.auth0:java-jwt:$jwt_version") - - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutine_version") - implementation("io.github.cdimascio:dotenv-kotlin:6.3.1") - implementation("io.arrow-kt:arrow-core") -} - -tasks.test { - useJUnitPlatform() -} - -tasks.withType { - kotlinOptions.jvmTarget = "1.8" -} - -application { - mainClass.set("MainKt") -} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index 6f90f8d..0000000 --- a/gradle.properties +++ /dev/null @@ -1,6 +0,0 @@ -kotlin.code.style=official -jwt_version=4.0.0 -coroutine_version= 1.6.4 -gh_version=1.307 -arrow_fx_version=1.0.1 -fuel_version=4.6.4 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 7454180..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 60c76b3..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists \ No newline at end of file diff --git a/gradlew b/gradlew deleted file mode 100644 index 1b6c787..0000000 --- a/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 107acd3..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/settings.gradle.kts b/settings.gradle.kts deleted file mode 100644 index ca0dc38..0000000 --- a/settings.gradle.kts +++ /dev/null @@ -1,3 +0,0 @@ - -rootProject.name = "sern-automata" - diff --git a/src/main/kotlin/Client.kt b/src/main/kotlin/Client.kt deleted file mode 100644 index f608a00..0000000 --- a/src/main/kotlin/Client.kt +++ /dev/null @@ -1,76 +0,0 @@ -import io.github.cdimascio.dotenv.dotenv -import io.ktor.serialization.kotlinx.json.* -import io.ktor.server.application.* -import io.ktor.server.engine.* -import io.ktor.server.netty.* -import io.ktor.server.plugins.contentnegotiation.* -import kotlinx.coroutines.* -import kotlinx.serialization.json.Json -import structures.HttpProvider -import structures.api.account.OrgAccount -import structures.api.account.TokenData -import structures.wrapped.Base -import kotlin.coroutines.CoroutineContext - -object Globals { - val eventEmitter = EventEmitter() - val serializer = Json { - ignoreUnknownKeys = true - prettyPrint = true - explicitNulls = false - } -} - -class Client : CoroutineScope { - val api = HttpProvider(this) - private var parentJob = Job() - lateinit var application : structures.api.application.Application - lateinit var orgAccount: OrgAccount - lateinit var tokenData : TokenData - override val coroutineContext: CoroutineContext - get() = Dispatchers.Default + parentJob - init { - dotenv { - systemProperties = true - } - } - inline fun on( - eventName: String, - crossinline fn: suspend (T) -> Unit - ) { - launch { - Globals.eventEmitter.events.collect { - when (eventName) { - "pull_request" -> { - fn(it as T) - } - } - } - } - } - suspend fun loginAsync() { - coroutineScope { - withContext(Dispatchers.Default) { - application = api.loginIntoApplicationAsync().await() - orgAccount = api.loginIntoOrgAsync().await() - tokenData = api.getInstallationTokenAsync(orgAccount).await() - } - } - } - /** - * This should start last in order to prevent blocking of thread and listeners - */ - fun startWebhookListener() { - embeddedServer( - Netty, - port = 8000, - host = "localhost", - parentCoroutineContext = coroutineContext - ) { - configureRouting(this@Client) - install(ContentNegotiation) { - json(Globals.serializer) - } - }.start(wait = true).also { println("Started server") } - } -} \ No newline at end of file diff --git a/src/main/kotlin/EventEmitter.kt b/src/main/kotlin/EventEmitter.kt deleted file mode 100644 index 1c5177c..0000000 --- a/src/main/kotlin/EventEmitter.kt +++ /dev/null @@ -1,13 +0,0 @@ -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.asSharedFlow -import structures.api.Response -import structures.wrapped.Base - -class EventEmitter { - private val _events = MutableSharedFlow() // private mutable shared flow - val events = _events.asSharedFlow() // publicly exposed as read-only shared flow - - suspend fun produceEvent(event: T) { - _events.emit(event) // suspends until all subscribers receive it - } -} \ No newline at end of file diff --git a/src/main/kotlin/HttpClientExtensions.kt b/src/main/kotlin/HttpClientExtensions.kt deleted file mode 100644 index 6be2af3..0000000 --- a/src/main/kotlin/HttpClientExtensions.kt +++ /dev/null @@ -1,88 +0,0 @@ -import HashUtils.verifySignature -import arrow.core.Either -import io.ktor.http.* -import io.ktor.server.application.* -import io.ktor.server.request.* -import io.ktor.server.response.* -import io.ktor.server.routing.* -import io.ktor.util.pipeline.* -import kotlinx.coroutines.* -import kotlinx.serialization.decodeFromString -import javax.crypto.Mac -import javax.crypto.spec.SecretKeySpec -import kotlin.experimental.xor - - -fun Application.configureRouting(client: Client) { - routing { - - pullRequests(client) - } - -} - -fun Routing.pullRequests(client: Client) { - post("/pulls") { - val secret = call.request.headers["X-Hub-Signature-256"]!! - val event = call.request.headers["X-Github-Event"]!! - val respText = call.receiveText() - when(val resp = verifySignature(secret, respText)) { - is Either.Left -> { - launch(Dispatchers.Default) { - when(event) { - "pull_request" -> { - Globals.eventEmitter.produceEvent( - structures.wrapped.PullRequestsManager(client, - Globals.serializer.decodeFromString(resp.value) - ) - ) - } - } - call.respond(HttpStatusCode.OK) - }.join() - } - is Either.Right -> resp.value - } - - } -} - -object HashUtils { - private fun ByteArray.toHex(): String = joinToString(separator = "") { eachByte -> "%02x".format(eachByte) } - - //https://security.stackexchange.com/questions/239054/timing-attacks-in-password-hash-comparisons - fun secureCompare(secret : String, hash: String) : Boolean { - val digesta = secret.toByteArray(); val digestb = hash.toByteArray() - - if (digesta.size and digestb.size == 0) return false - var difference = 0 - for (i in digesta.indices) difference = difference.or(digesta[i].xor(digestb[i]).toInt()) - return difference == 0 - } - /** - * Supported algorithms on Android: - * - * Algorithm Supported API Levels - * MD5 1+ - * SHA-1 1+ - * SHA-224 1-8,22+ - * SHA-256 1+ - * SHA-384 1+ - * SHA-512 1+ - */ - fun sha256(body: String): String { - val key = System.getProperty("WEBHOOK_TOKEN") - val hasher: Mac = Mac.getInstance("HmacSHA256") - hasher.init(SecretKeySpec(key.toByteArray(), "HmacSHA256")) - - val hash: ByteArray = hasher.doFinal(body.toByteArray()) - return "sha256=${hash.toHex()}" - } - - suspend inline fun PipelineContext.verifySignature(secret: String, resp: String) : Either { - if(secureCompare(secret, sha256(resp))) { - return Either.Left(resp) - } - return Either.Right(call.respond(HttpStatusCode.Unauthorized, "Nice try")) - } -} diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt deleted file mode 100644 index d8dae0d..0000000 --- a/src/main/kotlin/Main.kt +++ /dev/null @@ -1,23 +0,0 @@ - -import kotlinx.coroutines.* -import structures.api.application.PullRequestAction -import structures.options.PullRequestCreateOptions -import structures.wrapped.PullRequestsManager - -fun main() = runBlocking { - val sernClient = Client() - sernClient.loginAsync() - - sernClient.on("pull_request") { pr_event -> - when(pr_event.action) { - PullRequestAction.Opened -> { - println("new pull request opened") - } - else -> Unit - } - } - sernClient.startWebhookListener() -} - - - diff --git a/src/main/kotlin/structures/HttpProvider.kt b/src/main/kotlin/structures/HttpProvider.kt deleted file mode 100644 index 813072b..0000000 --- a/src/main/kotlin/structures/HttpProvider.kt +++ /dev/null @@ -1,91 +0,0 @@ -package structures -import Client -import io.ktor.client.* -import io.ktor.client.call.* -import io.ktor.client.engine.cio.* -import io.ktor.client.plugins.contentnegotiation.* -import io.ktor.client.request.* -import io.ktor.client.statement.* -import io.ktor.http.* -import io.ktor.serialization.kotlinx.json.* -import kotlinx.coroutines.* -import kotlinx.serialization.encodeToString -import structures.api.Response -import structures.api.account.OrgAccount -import structures.api.account.TokenData -import structures.api.application.Application -import structures.options.PostOptions -import kotlin.coroutines.CoroutineContext - -class HttpProvider(private val client: Client) : CoroutineScope { - val httpClient = HttpClient(CIO) { - install(ContentNegotiation) { - json(Globals.serializer) - } - } - enum class ApiType { - Rest, - App - } - val orgName = "sern-handler" - val baseLink = "https://api.github.com" - - fun authHeader(type: ApiType): Pair { - return HttpHeaders.Authorization to when(type) { - ApiType.App -> "Bearer ${JWTProvider.jwt}" - ApiType.Rest -> "Bearer ${client.tokenData.token}" - } - } - val contentTypeHeader = HttpHeaders.Accept to "application/vnd.github+json" - inline fun postAsync(path: String, body: V) : Deferred { - return async { - httpClient.post("$baseLink/$path") { - headers { - append(HttpHeaders.ContentType, "application/json") - append(contentTypeHeader) - append(authHeader(ApiType.Rest)) - } - setBody(body) - }.body() - } - } - - fun loginIntoApplicationAsync() : Deferred { - return async { - httpClient.request("$baseLink/app") { - headers { - append(contentTypeHeader) - append(authHeader(ApiType.App)) - } - }.body() - } - } - fun loginIntoOrgAsync(): Deferred { - return async { - // GHAppInstallation - httpClient.request("$baseLink/orgs/$orgName/installation") { - headers { - append(contentTypeHeader) - append(authHeader(ApiType.App)) - } - }.body() - } - } - - fun getInstallationTokenAsync(orgAccount: OrgAccount): Deferred { - return async { - httpClient.post("$baseLink/app/installations/${orgAccount.id}/access_tokens") { - headers { - append(contentTypeHeader) - append(authHeader(ApiType.App)) - } - }.body() - } - } - override val coroutineContext: CoroutineContext - get() = Dispatchers.Default + Job() -} - -fun HeadersBuilder.append(name: Pair) { - append(name.first, name.second) -} diff --git a/src/main/kotlin/structures/JWTProvider.kt b/src/main/kotlin/structures/JWTProvider.kt deleted file mode 100644 index 0f440a5..0000000 --- a/src/main/kotlin/structures/JWTProvider.kt +++ /dev/null @@ -1,38 +0,0 @@ -package structures - -import com.auth0.jwt.JWT -import com.auth0.jwt.algorithms.Algorithm -import java.security.KeyFactory -import java.security.interfaces.RSAPrivateKey -import java.security.spec.PKCS8EncodedKeySpec -import java.time.Instant -import java.util.* - -/** - * Thank you hub4j/githubapi - */ -object JWTProvider { - private val validUntil = Instant.MIN - private val privateKey: RSAPrivateKey? = - javaClass.getResourceAsStream("/private_key.pem") - ?.bufferedReader() - ?.useLines { br -> - val privateKey = br.filter { str -> - str != "-----BEGIN PRIVATE KEY-----" && str != "-----END PRIVATE KEY-----" - } - val seq = privateKey.joinToString("") - val encoded = Base64.getDecoder().decode(seq) - val kf = KeyFactory.getInstance("RSA") - val keySpec = PKCS8EncodedKeySpec(encoded) - (kf.generatePrivate(keySpec) as RSAPrivateKey) - } - val jwt : String = JWT.create() - .withIssuer(System.getProperty("APP_ID")) - .withIssuedAt(Instant.now().minusMillis(6_000)) - .withExpiresAt(Instant.now().plusMillis(600000)) - .sign(Algorithm.RSA256(privateKey)) - - fun isNotValid(): Boolean { - return Instant.now().isAfter(validUntil) - } -} \ No newline at end of file diff --git a/src/main/kotlin/structures/api/AutoMerge.kt b/src/main/kotlin/structures/api/AutoMerge.kt deleted file mode 100644 index 2c5b39d..0000000 --- a/src/main/kotlin/structures/api/AutoMerge.kt +++ /dev/null @@ -1,9 +0,0 @@ -package structures.api - -@kotlinx.serialization.Serializable -data class AutoMerge( - val commit_message: String?, - val commit_title: String?, - val enabled_by: EnabledBy, - val merge_method: String -) : Response() \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Base.kt b/src/main/kotlin/structures/api/Base.kt deleted file mode 100644 index a2e377f..0000000 --- a/src/main/kotlin/structures/api/Base.kt +++ /dev/null @@ -1,11 +0,0 @@ -package structures.api - -@kotlinx.serialization.Serializable -data class Base( - - val label: String, - val ref: String, - val repo: Repo, - val sha: String, - val user: User -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Comments.kt b/src/main/kotlin/structures/api/Comments.kt deleted file mode 100644 index 8438441..0000000 --- a/src/main/kotlin/structures/api/Comments.kt +++ /dev/null @@ -1,5 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Comments( - val href: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Commits.kt b/src/main/kotlin/structures/api/Commits.kt deleted file mode 100644 index b6793b0..0000000 --- a/src/main/kotlin/structures/api/Commits.kt +++ /dev/null @@ -1,5 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Commits( - val href: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/EnabledBy.kt b/src/main/kotlin/structures/api/EnabledBy.kt deleted file mode 100644 index fc14bcc..0000000 --- a/src/main/kotlin/structures/api/EnabledBy.kt +++ /dev/null @@ -1,22 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class EnabledBy( - val avatar_url: String, - val events_url: String, - val followers_url: String, - val following_url: String, - val gists_url: String, - val gravatar_id: String, - val html_url: String, - val id: Int, - val login: String, - val node_id: String, - val organizations_url: String, - val received_events_url: String, - val repos_url: String, - val site_admin: Boolean, - val starred_url: String, - val subscriptions_url: String, - val type: String, - val url: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Head.kt b/src/main/kotlin/structures/api/Head.kt deleted file mode 100644 index 4a1f101..0000000 --- a/src/main/kotlin/structures/api/Head.kt +++ /dev/null @@ -1,9 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Head( - val label: String, - val ref: String, - val repo: Repo, - val sha: String, - val user: User -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Html.kt b/src/main/kotlin/structures/api/Html.kt deleted file mode 100644 index df4f961..0000000 --- a/src/main/kotlin/structures/api/Html.kt +++ /dev/null @@ -1,5 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Html( - val href: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Issue.kt b/src/main/kotlin/structures/api/Issue.kt deleted file mode 100644 index 9b6a95d..0000000 --- a/src/main/kotlin/structures/api/Issue.kt +++ /dev/null @@ -1,5 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Issue( - val href: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Label.kt b/src/main/kotlin/structures/api/Label.kt deleted file mode 100644 index fc38627..0000000 --- a/src/main/kotlin/structures/api/Label.kt +++ /dev/null @@ -1,11 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Label( - val color: String, - val default: Boolean, - val description: String, - val id: Long, - val name: String, - val node_id: String, - val url: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Links.kt b/src/main/kotlin/structures/api/Links.kt deleted file mode 100644 index 631a618..0000000 --- a/src/main/kotlin/structures/api/Links.kt +++ /dev/null @@ -1,12 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Links( - val comments: Comments, - val commits: Commits, - val html: Html, - val issue: Issue, - val review_comment: ReviewComment, - val review_comments: ReviewComments, - val self: Self, - val statuses: Statuses -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Milestone.kt b/src/main/kotlin/structures/api/Milestone.kt deleted file mode 100644 index 59a1540..0000000 --- a/src/main/kotlin/structures/api/Milestone.kt +++ /dev/null @@ -1,13 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Milestone( - val creator: User, - val description: String, - val html_url: String, - val id: Int, - val labels_url: String, - val node_id: String, - val number: Int, - val title: String, - val url: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/Organization.kt b/src/main/kotlin/structures/api/Organization.kt deleted file mode 100644 index 01beca0..0000000 --- a/src/main/kotlin/structures/api/Organization.kt +++ /dev/null @@ -1,16 +0,0 @@ -package structures.api -@kotlinx.serialization.Serializable -data class Organization( - val avatar_url: String, - val description: String, - val events_url: String, - val hooks_url: String, - val id: Int, - val issues_url: String, - val login: String, - val members_url: String, - val node_id: String, - val public_members_url: String, - val repos_url: String, - val url: String -) \ No newline at end of file diff --git a/src/main/kotlin/structures/api/PullRequest.kt b/src/main/kotlin/structures/api/PullRequest.kt deleted file mode 100644 index d303b96..0000000 --- a/src/main/kotlin/structures/api/PullRequest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package structures.api - - -@kotlinx.serialization.Serializable -data class PullRequest( - val _links: Links, - val active_lock_reason: String?, - val additions: Int, - val assignee: User?, - val assignees: List, - val author_association: String, - val auto_merge: AutoMerge?, - val base: Base, - val body: String?, - val changed_files: Int, - val closed_at: String?, - val comments: Int, - val comments_url: String, - val commits: Int, - val commits_url: String, - val created_at: String, - val deletions: Int, - val diff_url: String, - val draft: Boolean, - val head: Head, - val html_url: String, - val id: Int, - val issue_url: String, - val labels: List