mirror of
https://github.com/LamGC/oracle-manager.git
synced 2025-04-29 14:17:33 +00:00
initial: 初步完成了账号管理功能.
This commit is contained in:
commit
5df02ab5be
44
.gitignore
vendored
Normal file
44
.gitignore
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
.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
|
||||
|
||||
run/
|
8
.idea/.gitignore
vendored
Normal file
8
.idea/.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
18
.idea/gradle.xml
Normal file
18
.idea/gradle.xml
Normal file
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="distributionType" value="WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleHome" value="$PROJECT_DIR$/../../Gradle/gradle-7.3.3" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
18
.idea/misc.xml
Normal file
18
.idea/misc.xml
Normal file
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="FrameworkDetectionExcludesConfiguration">
|
||||
<file type="web" url="file://$PROJECT_DIR$" />
|
||||
</component>
|
||||
<component name="KotlinMultiplatform">
|
||||
<allAvailableExecutables />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="OpenJdk-11" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
<component name="SwUserDefinedSpecifications">
|
||||
<option name="specTypeByUrl">
|
||||
<map />
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
6
.idea/vcs.xml
Normal file
6
.idea/vcs.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
60
build.gradle.kts
Normal file
60
build.gradle.kts
Normal file
@ -0,0 +1,60 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
kotlin("jvm") version "1.6.20"
|
||||
`maven-publish`
|
||||
}
|
||||
|
||||
group = "net.lamgc.scext"
|
||||
version = "1.0-SNAPSHOT"
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("io.github.microutils:kotlin-logging:2.1.21")
|
||||
compileOnly("net.lamgc:scalabot-extension:0.1.0")
|
||||
|
||||
val ociSdkVer = "2.22.0"
|
||||
implementation("com.oracle.oci.sdk:oci-java-sdk-core:$ociSdkVer")
|
||||
implementation("com.oracle.oci.sdk:oci-java-sdk-identity:$ociSdkVer")
|
||||
implementation("com.oracle.oci.sdk:oci-java-sdk-objectstorage:$ociSdkVer")
|
||||
|
||||
implementation("org.apache.httpcomponents.client5:httpclient5:5.1.3")
|
||||
|
||||
implementation("org.ktorm:ktorm-core:3.4.1")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.20")
|
||||
implementation("org.xerial:sqlite-jdbc:3.36.0.3")
|
||||
|
||||
implementation("com.google.code.gson:gson:2.9.0")
|
||||
|
||||
testImplementation(kotlin("test"))
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions.jvmTarget = "1.8"
|
||||
}
|
||||
|
||||
publishing {
|
||||
repositories {
|
||||
mavenLocal()
|
||||
}
|
||||
|
||||
publications {
|
||||
create<MavenPublication>("maven") {
|
||||
from(components["java"])
|
||||
|
||||
pom {
|
||||
name.set("Oracle-manager")
|
||||
description.set("在 Telegram 管理你的 Oracle.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
1
gradle.properties
Normal file
1
gradle.properties
Normal file
@ -0,0 +1 @@
|
||||
kotlin.code.style=official
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
234
gradlew
vendored
Normal file
234
gradlew
vendored
Normal file
@ -0,0 +1,234 @@
|
||||
#!/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" "$@"
|
89
gradlew.bat
vendored
Normal file
89
gradlew.bat
vendored
Normal file
@ -0,0 +1,89 @@
|
||||
@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
|
2
settings.gradle.kts
Normal file
2
settings.gradle.kts
Normal file
@ -0,0 +1,2 @@
|
||||
rootProject.name = "oracle-manager"
|
||||
|
1
src/main/kotlin/CachingUtils.kt
Normal file
1
src/main/kotlin/CachingUtils.kt
Normal file
@ -0,0 +1 @@
|
||||
package net.lamgc.scext.oraclemanager
|
167
src/main/kotlin/Databases.kt
Normal file
167
src/main/kotlin/Databases.kt
Normal file
@ -0,0 +1,167 @@
|
||||
package net.lamgc.scext.oraclemanager
|
||||
|
||||
import org.ktorm.database.Database
|
||||
import org.ktorm.entity.Entity
|
||||
import org.ktorm.entity.sequenceOf
|
||||
import org.ktorm.schema.*
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot
|
||||
import java.io.File
|
||||
import java.sql.DriverManager
|
||||
import java.sql.PreparedStatement
|
||||
import java.sql.ResultSet
|
||||
import java.sql.Types
|
||||
|
||||
val database = DatabaseManager.doInitialDatabase(File("${dataDirectory.canonicalPath}/db/oracle.db"))
|
||||
|
||||
val <T : BaseAbilityBot> T.database: Database
|
||||
get() = DatabaseManager.getDatabaseByBot(this)
|
||||
|
||||
/**
|
||||
* 原本是想弄一个机器人一个数据库的。
|
||||
* 想了想,太麻烦了。
|
||||
*/
|
||||
object DatabaseManager {
|
||||
private val databaseMapping = hashMapOf<BaseAbilityBot, Database>()
|
||||
|
||||
@Synchronized
|
||||
fun initialDatabase(bot: BaseAbilityBot, dataFolder: File) {
|
||||
if (databaseMapping.containsKey(bot)) {
|
||||
return
|
||||
}
|
||||
val database = doInitialDatabase(
|
||||
File(
|
||||
dataFolder,
|
||||
"${bot.botToken.substringBefore(":")}/oracle.db"
|
||||
)
|
||||
)
|
||||
databaseMapping[bot] = database
|
||||
}
|
||||
|
||||
fun getDatabaseByBot(bot: BaseAbilityBot): Database {
|
||||
return databaseMapping[bot]
|
||||
?: throw IllegalStateException("The database has not been initialized. (bot: `${bot.botUsername}`)")
|
||||
}
|
||||
|
||||
fun doInitialDatabase(dbFile: File): Database {
|
||||
return Database.connect(generateSqlInUpperCase = true) {
|
||||
val dbFolder = dbFile.parentFile
|
||||
if (!dbFolder.exists()) {
|
||||
dbFolder.mkdirs()
|
||||
}
|
||||
|
||||
Class.forName("org.sqlite.JDBC")
|
||||
val connection = DriverManager.getConnection("jdbc:sqlite:${dbFile.canonicalPath}")
|
||||
connection.prepareStatement(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ${OracleAccountTable.tableName} (
|
||||
user_id VARCHAR(128) PRIMARY KEY NOT NULL,
|
||||
tenancy_id VARCHAR(128) NOT NULL ,
|
||||
region_id VARCHAR(64) NOT NULL ,
|
||||
key_fingerprint CHAR(32) NOT NULL ,
|
||||
tg_user_id BIGINT NOT NULL,
|
||||
name VARCHAR(64) NOT NULL
|
||||
);
|
||||
""".trimIndent()
|
||||
).execute()
|
||||
connection.prepareStatement(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ${AccessKeyPairTable.tableName} (
|
||||
key_fingerprint CHAR(32) PRIMARY KEY NOT NULL,
|
||||
private_key TEXT NOT NULL
|
||||
)
|
||||
""".trimIndent()
|
||||
).execute()
|
||||
connection
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CharSqlType(private val maxLength: Int) : SqlType<String>(Types.CHAR, "char") {
|
||||
override fun doGetResult(rs: ResultSet, index: Int): String? {
|
||||
return rs.getString(index)
|
||||
}
|
||||
|
||||
override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: String) {
|
||||
if (parameter.length > maxLength) {
|
||||
throw IllegalArgumentException(
|
||||
"The passed in parameter exceeds the maximum allowed value. " +
|
||||
"(expect: $maxLength, actual: ${parameter.length})"
|
||||
)
|
||||
}
|
||||
ps.setString(index, parameter)
|
||||
}
|
||||
}
|
||||
|
||||
fun Table<*>.char(name: String, maxLength: Int): Column<String> {
|
||||
return registerColumn(name, CharSqlType(maxLength))
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
object OracleAccountTable : Table<OracleAccountProfilePO>("oracle_accounts") {
|
||||
val userId = varchar("user_id").primaryKey().bindTo { it.userId }
|
||||
val tenantId = varchar("tenancy_id").bindTo { it.tenantId }
|
||||
val regionId = varchar("region_id").bindTo { it.regionId }
|
||||
val keyFingerprint = char("key_fingerprint", 32).bindTo { it.keyFingerprint }
|
||||
val tgUserId = long("tg_user_id").bindTo { it.telegramUserId }
|
||||
val name = varchar("name").bindTo { it.name }
|
||||
}
|
||||
|
||||
val Database.OracleAccounts get() = this.sequenceOf(OracleAccountTable)
|
||||
|
||||
@Suppress("unused")
|
||||
object AccessKeyPairTable : Table<OracleAccessKeyPO>("access_keys") {
|
||||
val keyFingerprint = char("key_fingerprint", 32).primaryKey().bindTo { it.fingerprint }
|
||||
val privateKey = text("private_key").bindTo { it.privateKeyContent }
|
||||
}
|
||||
|
||||
val Database.OracleAccessKeys get() = this.sequenceOf(AccessKeyPairTable)
|
||||
|
||||
interface OracleAccountProfilePO : Entity<OracleAccountProfilePO> {
|
||||
var userId: String
|
||||
var name: String
|
||||
var tenantId: String
|
||||
var regionId: String
|
||||
var keyFingerprint: String
|
||||
var telegramUserId: Long
|
||||
|
||||
companion object : Entity.Factory<OracleAccountProfilePO>() {
|
||||
@JvmStatic
|
||||
fun fromDataClass(dataClass: OracleAccountProfile): OracleAccountProfilePO {
|
||||
return OracleAccountProfilePO {
|
||||
userId = dataClass.userId
|
||||
name = dataClass.name
|
||||
tenantId = dataClass.tenantId
|
||||
regionId = dataClass.regionId
|
||||
keyFingerprint = dataClass.keyFingerprint.replace(":", "")
|
||||
telegramUserId = dataClass.telegramUserId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun <T : OracleAccountProfilePO> T.toDataClass(): OracleAccountProfile {
|
||||
return OracleAccountProfile(userId, tenantId, regionId, keyFingerprint, telegramUserId, name)
|
||||
}
|
||||
|
||||
interface OracleAccessKeyPO : Entity<OracleAccessKeyPO> {
|
||||
|
||||
var fingerprint: String
|
||||
var privateKeyContent: String
|
||||
|
||||
companion object : Entity.Factory<OracleAccessKeyPO>() {
|
||||
fun fromDataClass(dataClass: OracleAccessKey): OracleAccessKeyPO {
|
||||
return OracleAccessKeyPO {
|
||||
fingerprint = dataClass.fingerprint
|
||||
privateKeyContent = dataClass.privateKeyContent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun <T : OracleAccessKeyPO> T.toDataClass(): OracleAccessKey {
|
||||
return OracleAccessKey(
|
||||
fingerprint = fingerprint,
|
||||
privateKeyContent = privateKeyContent
|
||||
)
|
||||
}
|
404
src/main/kotlin/OracleAccountExtension.kt
Normal file
404
src/main/kotlin/OracleAccountExtension.kt
Normal file
@ -0,0 +1,404 @@
|
||||
package net.lamgc.scext.oraclemanager
|
||||
|
||||
import com.oracle.bmc.ConfigFileReader
|
||||
import com.oracle.bmc.identity.IdentityClient
|
||||
import com.oracle.bmc.model.BmcException
|
||||
import mu.KotlinLogging
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients
|
||||
import org.apache.hc.core5.http.HttpHost
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot
|
||||
import org.telegram.abilitybots.api.objects.*
|
||||
import org.telegram.abilitybots.api.util.AbilityExtension
|
||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage
|
||||
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageReplyMarkup
|
||||
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.security.interfaces.RSAPrivateCrtKey
|
||||
|
||||
private val httpClient = HttpClients.custom()
|
||||
.setProxy(HttpHost("127.0.0.1", 1080))
|
||||
.build()
|
||||
|
||||
@Suppress("unused")
|
||||
class OracleAccountManagerExtension(private val bot: BaseAbilityBot) : AbilityExtension {
|
||||
|
||||
/**
|
||||
* 添加 Oracle 租户并关联 Telegram 账号.
|
||||
*/
|
||||
fun addAccount(): Ability = Ability.builder()
|
||||
.name("oc_account_add")
|
||||
.info("关联新的 Oracle 账号")
|
||||
.locality(Locality.USER)
|
||||
.privacy(Privacy.PUBLIC)
|
||||
.enableStats()
|
||||
.action {
|
||||
it.bot().silent().send("发送 API 配置文件,或复制配置文件内容直接发送。", it.chatId())
|
||||
}
|
||||
.reply(ReplyFlow.builder(bot.db())
|
||||
.action { bot, upd ->
|
||||
val configFile = if (upd.message.hasDocument()) {
|
||||
val configUrl = bot.getFileUrl(upd.message.document.fileId)
|
||||
val httpResponse = httpClient.execute(HttpGet(configUrl))
|
||||
ConfigFileReader.parse(httpResponse.entity.content, "DEFAULT")
|
||||
} else if (upd.message.hasText()) {
|
||||
ConfigFileReader.parse(ByteArrayInputStream(upd.message.text.toByteArray()), "DEFAULT")
|
||||
} else {
|
||||
bot.silent().send("上传的配置不包括 DEFAULT 节。", upd.message.chatId)
|
||||
return@action
|
||||
}
|
||||
if (!configFile.validate()) {
|
||||
bot.silent().send("配置文件无效,请重新发送。", upd.message.chatId)
|
||||
return@action
|
||||
}
|
||||
|
||||
|
||||
val profile = configFile.toOracleAccountProfile(upd.message.from.id)
|
||||
val existProfile = OracleAccountManage.getOracleAccountByOracleUserId(profile.userId)
|
||||
if (existProfile != null) {
|
||||
bot.silent().send(
|
||||
"Oracle 账号已经被${
|
||||
if (existProfile.telegramUserId == upd.message.chatId) "你" else "其他人"
|
||||
}绑定,请重新上传其他账号的 Oracle。", upd.message.chatId
|
||||
)
|
||||
return@action
|
||||
}
|
||||
|
||||
if (!OracleAccessKeyManager.accessKeyContains(profile.keyFingerprint)) {
|
||||
bot.db().getVar<String>("oc_account_add::${upd.message.chatId}::profile").set(
|
||||
profile.toJson()
|
||||
)
|
||||
bot.silent().send(
|
||||
"OK,配置文件检查通过,现在需要发送相应的私钥(机器人的所有人将对密钥的安全性负责)," +
|
||||
"所需密钥的指纹是:\n${configFile["fingerprint"]}", upd.message.chatId
|
||||
)
|
||||
} else {
|
||||
OracleAccountManage.addOracleAccount(profile)
|
||||
bot.silent().execute(
|
||||
createSuccessfulMsgWithChangeName(
|
||||
"密钥已存在,Oracle 账号绑定成功!\n" +
|
||||
"账号名称:${profile.name}",
|
||||
upd.message.chatId, profile
|
||||
)
|
||||
)
|
||||
}
|
||||
}.onlyIf {
|
||||
it.hasMessage() && (
|
||||
it.message.hasDocument() &&
|
||||
it.message.document.fileName.endsWith(".ini", ignoreCase = true)
|
||||
||
|
||||
it.message.hasText() && it.message.text.trim().startsWith(
|
||||
"[DEFAULT]"
|
||||
))
|
||||
}
|
||||
.enableStats(getStatsName("oc_account_add", "add_profile"))
|
||||
.next(
|
||||
ReplyFlow.builder(bot.db())
|
||||
.action { bot, upd ->
|
||||
try {
|
||||
val privateKey = try {
|
||||
val keyUrl = bot.getFileUrl(upd.message.document.fileId)
|
||||
val response = httpClient.execute(HttpGet(keyUrl))
|
||||
loadPkcs8PrivateKeyFromStream(response.entity.content)
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "接收密钥文件时发生错误." }
|
||||
bot.silent().send("接收密钥时发生错误,请重试一次。", upd.message.chatId)
|
||||
return@action
|
||||
}
|
||||
if (privateKey !is RSAPrivateCrtKey) {
|
||||
logger.warn { "用户上传的密钥不符合要求." }
|
||||
bot.silent().send("密钥不符合要求,请重新生成密钥后重新添加 Oracle 账号。", upd.message.chatId)
|
||||
return@action
|
||||
}
|
||||
|
||||
val profileEntry = bot.db().getVar<String>("oc_account_add::${upd.message.chatId}::profile")
|
||||
val profile = OracleAccountProfile.fromJson(profileEntry.get())
|
||||
val uploadedKeyFingerprint = try {
|
||||
getKeyPairFingerprint(privateKey)
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "计算密钥指纹时发生错误." }
|
||||
bot.silent().send("密钥指纹计算失败,请确保上传了正确的密钥。", upd.message.chatId)
|
||||
return@action
|
||||
}
|
||||
if (!profile.keyFingerprint.contentEquals(uploadedKeyFingerprint, ignoreCase = true)) {
|
||||
bot.silent().send("上传的私钥与认证配置的密钥指纹不符。", upd.message.chatId)
|
||||
return@action
|
||||
}
|
||||
|
||||
OracleAccessKeyManager.addAccessKey(privateKey)
|
||||
OracleAccountManage.addOracleAccount(profile)
|
||||
bot.silent().execute(
|
||||
createSuccessfulMsgWithChangeName(
|
||||
"密钥已确定,Oracle 账号绑定成功!\n" +
|
||||
"账号名称:${profile.name}", upd.message.chatId, profile
|
||||
)
|
||||
)
|
||||
profileEntry.set(null)
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "处理密钥时发生错误." }
|
||||
bot.silent().send("处理密钥时出现未知错误!请联系机器人管理员。", upd.message.chatId)
|
||||
}
|
||||
}
|
||||
.onlyIf {
|
||||
it.hasMessage() && bot.db().getVar<String>("oc_account_add::${it.message.chatId}::profile")
|
||||
.get() != null &&
|
||||
it.message.hasDocument() &&
|
||||
it.message.document.fileName.endsWith(".pem", ignoreCase = true)
|
||||
}
|
||||
.enableStats(getStatsName("oc_account_add", "add_private_key"))
|
||||
.build())
|
||||
.build())
|
||||
.build()
|
||||
|
||||
fun listOracleAccount(): Ability = Ability.builder()
|
||||
.name("oc_account_list")
|
||||
.info("列出关联的 Oracle 账号")
|
||||
.privacy(Privacy.PUBLIC)
|
||||
.locality(Locality.USER)
|
||||
.action {
|
||||
doListOracleAccount(it.bot(), it.chatId(), it.user().id)
|
||||
}
|
||||
.build()
|
||||
|
||||
private fun createSuccessfulMsgWithChangeName(
|
||||
msg: String,
|
||||
chatId: Long,
|
||||
profile: OracleAccountProfile,
|
||||
changeNameMsg: String = "点此更改机器人的名称"
|
||||
): SendMessage {
|
||||
val markup = InlineKeyboardGroupBuilder()
|
||||
.configure {
|
||||
}
|
||||
.newRow()
|
||||
.addButton {
|
||||
text(changeNameMsg)
|
||||
callbackData(action = "oc_account_change_name", profile.toJson())
|
||||
}
|
||||
.build()
|
||||
return SendMessage.builder()
|
||||
.chatId(chatId.toString())
|
||||
.text(msg)
|
||||
.replyMarkup(markup)
|
||||
.build()
|
||||
}
|
||||
|
||||
fun listOracleAccountReply(): Reply = Reply.of({ bot, upd ->
|
||||
doListOracleAccount(bot, upd.callbackQuery.message.chatId, upd.callbackQuery.from.id)
|
||||
}, callbackQueryAt("oc_account_list"))
|
||||
|
||||
private fun doListOracleAccount(bot: BaseAbilityBot, chatId: Long, userId: Long) {
|
||||
val accounts = OracleAccountManage.getOracleAccountsByTelegramUserId(userId)
|
||||
if (accounts.isEmpty()) {
|
||||
bot.silent().send("你还没有绑定任何 Oracle 账号,请使用【/oc_account_add】绑定一个 Oracle 账号。", chatId)
|
||||
return
|
||||
}
|
||||
// TODO: 要弄个页面, 防止账号太多刷爆了
|
||||
val msgBuilder = SendMessage.builder()
|
||||
.chatId(chatId.toString())
|
||||
.text(
|
||||
"""
|
||||
当前 Telegram 用户已绑定以下 Oracle 账号
|
||||
(账号没有名字只有邮箱是因为通过 API 获取名字失败)
|
||||
""".trimIndent()
|
||||
)
|
||||
val keyboardGroup = InlineKeyboardMarkup.builder()
|
||||
for (account in accounts) {
|
||||
val provider = account.getAuthenticationDetailsProvider()
|
||||
val identityClient = IdentityClient(provider)
|
||||
val text = try {
|
||||
val user = identityClient.getUser(provider.userId)
|
||||
"${account.name} / ${user.name}(${user.email})【${account.regionId}】"
|
||||
} catch (e: BmcException) {
|
||||
"${account.name} / null 【${account.regionId}】"
|
||||
}
|
||||
keyboardGroup.keyboardRow(
|
||||
listOf(
|
||||
InlineKeyboardButton.builder()
|
||||
.text(text)
|
||||
.callbackData(
|
||||
action = "oc_account_manager",
|
||||
extraData = account.toJson()
|
||||
)
|
||||
.build()
|
||||
)
|
||||
)
|
||||
}
|
||||
msgBuilder.replyMarkup(keyboardGroup.build())
|
||||
bot.silent().execute(msgBuilder.build())
|
||||
}
|
||||
|
||||
fun manageOracleAccount(): Reply = Reply.of({ bot, upd ->
|
||||
val keyboardCallback = upd.callbackQuery.callbackData
|
||||
val profile = OracleAccountProfile.fromJson(keyboardCallback.extraData!!)
|
||||
val identityClient = IdentityClient(profile.getAuthenticationDetailsProvider())
|
||||
val user = try {
|
||||
identityClient.getUser(profile.userId)
|
||||
} catch (e: Exception) {
|
||||
logger.warn(e) { "Oracle 账号信息获取失败. (UserId: ${profile.userId})" }
|
||||
null
|
||||
}
|
||||
val newKeyboardMarkup = InlineKeyboardGroupBuilder()
|
||||
.newRow()
|
||||
.addButton {
|
||||
text("服务器列表")
|
||||
callbackData(action = "oc_server_list", keyboardCallback.extraData)
|
||||
}
|
||||
.newRow()
|
||||
.addButton {
|
||||
text("账号管理")
|
||||
callbackData(action = "oc_account_edit", keyboardCallback.extraData)
|
||||
}
|
||||
.newRow().addButton {
|
||||
text("<<< 返回上一级")
|
||||
callbackData(action = "oc_account_list")
|
||||
}
|
||||
.then().build()
|
||||
|
||||
val editMessageText = EditMessageText.builder()
|
||||
.chatId(upd.callbackQuery.message.chatId.toString())
|
||||
.messageId(upd.callbackQuery.message.messageId)
|
||||
.text(
|
||||
"""
|
||||
${profile.name}
|
||||
账号名(甲骨文上面的账号名): ${user?.name}
|
||||
区域 Id:${profile.regionId}
|
||||
邮箱:${user?.email}
|
||||
当前状态:${user?.lifecycleState?.value}
|
||||
(账号名、邮箱和当前状态为 null 不一定是因为封号,也可能是服务器网络问题)
|
||||
""".trimIndent()
|
||||
)
|
||||
.replyMarkup(newKeyboardMarkup)
|
||||
.build()
|
||||
bot.silent().execute(editMessageText)
|
||||
}, callbackQueryAt("oc_account_manager"))
|
||||
|
||||
fun editOracleAccount(): Reply = Reply.of({ bot, upd ->
|
||||
val keyboardCallback = upd.callbackQuery.callbackData
|
||||
val newKeyboardMarkup = InlineKeyboardGroupBuilder()
|
||||
.newRow()
|
||||
.addButton {
|
||||
text("更改名称")
|
||||
callbackData(action = "oc_account_change_name", keyboardCallback.extraData)
|
||||
}
|
||||
.newRow()
|
||||
.addButton {
|
||||
text("解绑 Oracle 账号")
|
||||
callbackData(action = "oc_account_remove", keyboardCallback.extraData)
|
||||
}
|
||||
.newRow().addButton {
|
||||
text("<<< 返回上一级")
|
||||
callbackData(action = "oc_account_manager", keyboardCallback.extraData)
|
||||
}
|
||||
.then().build()
|
||||
|
||||
val editMessageReplyMarkup = EditMessageReplyMarkup.builder()
|
||||
.chatId(upd.callbackQuery.message.chatId.toString())
|
||||
.messageId(upd.callbackQuery.message.messageId)
|
||||
.replyMarkup(newKeyboardMarkup)
|
||||
.build()
|
||||
bot.silent().execute(editMessageReplyMarkup)
|
||||
}, callbackQueryAt("oc_account_edit"))
|
||||
|
||||
fun removeOracleAccount(): Reply = ReplyFlow.builder(bot.db())
|
||||
.action { bot, upd ->
|
||||
val profile = OracleAccountProfile.fromJson(upd.callbackQuery.callbackData.extraData!!)
|
||||
val keyboardCallback = upd.callbackQuery.callbackData
|
||||
EditMessageText.builder()
|
||||
.chatId(upd.callbackQuery.message.chatId.toString())
|
||||
.messageId(upd.callbackQuery.message.messageId)
|
||||
.text(
|
||||
"""
|
||||
${profile.name} (${profile.regionId})
|
||||
你确定解绑这个 Oracle 账号吗?
|
||||
""".trimIndent()
|
||||
)
|
||||
.replyMarkup(
|
||||
createPromptKeyboard(
|
||||
yesCallback = keyboardCallback.next("oc_account_remove_yes"),
|
||||
noCallback = keyboardCallback.next("oc_account_edit")
|
||||
)
|
||||
)
|
||||
.build()
|
||||
.execute(bot.silent())
|
||||
}
|
||||
.onlyIf(callbackQueryAt("oc_account_remove"))
|
||||
.next(Reply.of({ bot, upd ->
|
||||
val keyboardCallback = upd.callbackQuery.callbackData
|
||||
val profile = OracleAccountProfile.fromJson(keyboardCallback.extraData!!)
|
||||
val result =
|
||||
OracleAccountManage.removeOracleAccountByOracleUserId(profile.userId, upd.callbackQuery.from.id)
|
||||
val msg = if (result) {
|
||||
"Oracle 账号 ${profile.userId} 已成功解除绑定。"
|
||||
} else {
|
||||
"Oracle 账号 ${profile.userId} 已成功解除绑定。"
|
||||
}
|
||||
EditMessageText.builder()
|
||||
.text(msg)
|
||||
.chatId(upd.callbackQuery.message.chatId.toString())
|
||||
.messageId(upd.callbackQuery.message.messageId)
|
||||
.replyMarkup(InlineKeyboardMarkup.builder().clearKeyboard().build())
|
||||
.build()
|
||||
.execute(bot.silent())
|
||||
}, callbackQueryAt("oc_account_remove_yes")))
|
||||
.build()
|
||||
|
||||
fun changeOracleAccountName(): Reply = ReplyFlow.builder(bot.db())
|
||||
.enableStats(getStatsName("oc_account_change_name", "query_name"))
|
||||
.action { bot, upd ->
|
||||
if (upd.callbackQuery.data == null || upd.callbackQuery.data.trim().isEmpty()) {
|
||||
logger.error { "存在未传递 Profile 的 CallbackQuery 路径,请检查!" }
|
||||
bot.silent().send("出现未知错误,请联系机器人管理员。", upd.callbackQuery.message.chatId)
|
||||
return@action
|
||||
}
|
||||
val profile = OracleAccountProfile.fromJson(upd.callbackQuery.callbackData.extraData!!)
|
||||
val entryName = "oc_account_change_name::cache::" +
|
||||
"chat_${upd.callbackQuery.message.chatId}::user_${upd.callbackQuery.from.id}::profile"
|
||||
logger.debug { "询问名称 - Profile 键名称:$entryName" }
|
||||
|
||||
bot.db().getVar<String>(entryName).set(upd.callbackQuery.callbackData.extraData)
|
||||
bot.silent().send(
|
||||
"当前机器人的名称为:\n${profile.name}\n请发送机器人的新名称。",
|
||||
upd.callbackQuery.message.chatId
|
||||
)
|
||||
}
|
||||
.onlyIf(callbackQueryAt("oc_account_change_name"))
|
||||
.next(Reply.of({ bot, upd ->
|
||||
val entryName = "oc_account_change_name::cache::" +
|
||||
"chat_${upd.message.chatId}::user_${upd.message.from.id}::profile"
|
||||
|
||||
val profileJson = bot.db().getVar<String>(entryName).get()
|
||||
if (profileJson == null || profileJson.trim().isEmpty()) {
|
||||
bot.silent().send("会话已过期,请重试一次。", upd.message.chatId)
|
||||
return@of
|
||||
}
|
||||
|
||||
val profile = OracleAccountProfile.fromJson(profileJson)
|
||||
profile.name = upd.message.text.trim()
|
||||
try {
|
||||
OracleAccountManage.updateOracleAccount(profile)
|
||||
bot.silent().send("Oracle 账号名称已更新成功。", upd.message.chatId)
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "更新 Oracle 账号时发生错误." }
|
||||
bot.silent().send("更新 Oracle 账号名称时发生错误,请联系机器人管理员。", upd.message.chatId)
|
||||
}
|
||||
}, { upd -> upd.hasMessage() && upd.message.hasText() }))
|
||||
.build()
|
||||
|
||||
fun clearUnusedAccessKey(): Ability = Ability.builder()
|
||||
.name("oc_clear_key")
|
||||
.info("清除未使用的 API 访问密钥")
|
||||
.locality(Locality.USER)
|
||||
.privacy(Privacy.ADMIN)
|
||||
.action {
|
||||
val count = OracleAccessKeyManager.cleanUnusedAccessKey()
|
||||
it.bot().silent().send("已清理 $count 个未使用的访问密钥。", it.chatId())
|
||||
}
|
||||
.build()
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
private val logger = KotlinLogging.logger { }
|
||||
}
|
||||
}
|
158
src/main/kotlin/OracleAccountManage.kt
Normal file
158
src/main/kotlin/OracleAccountManage.kt
Normal file
@ -0,0 +1,158 @@
|
||||
package net.lamgc.scext.oraclemanager
|
||||
|
||||
import com.google.common.base.Supplier
|
||||
import com.oracle.bmc.OCID
|
||||
import com.oracle.bmc.Region
|
||||
import com.oracle.bmc.auth.AuthenticationDetailsProvider
|
||||
import com.oracle.bmc.auth.SimpleAuthenticationDetailsProvider
|
||||
import com.oracle.bmc.auth.StringPrivateKeySupplier
|
||||
import mu.KotlinLogging
|
||||
import net.lamgc.scalabot.extension.BotExtensionFactory
|
||||
import org.ktorm.dsl.and
|
||||
import org.ktorm.dsl.eq
|
||||
import org.ktorm.entity.*
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot
|
||||
import org.telegram.abilitybots.api.util.AbilityExtension
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.security.PrivateKey
|
||||
import java.security.interfaces.RSAPrivateCrtKey
|
||||
|
||||
class ExtensionFactory : BotExtensionFactory {
|
||||
override fun createExtensionInstance(bot: BaseAbilityBot, shareDataFolder: File): AbilityExtension {
|
||||
dataDirectory = shareDataFolder
|
||||
// 初始化一下数据库.
|
||||
database
|
||||
DatabaseManager.initialDatabase(bot, shareDataFolder)
|
||||
return OracleAccountManagerExtension(bot)
|
||||
}
|
||||
}
|
||||
|
||||
data class OracleAccountProfile(
|
||||
val userId: String,
|
||||
val tenantId: String,
|
||||
val regionId: String,
|
||||
val keyFingerprint: String,
|
||||
val telegramUserId: Long,
|
||||
var name: String,
|
||||
) : java.io.Serializable {
|
||||
|
||||
fun toJson(): String = gson.toJson(this)
|
||||
|
||||
fun getAuthenticationDetailsProvider(accessKeyProvider: Supplier<InputStream>? = null): AuthenticationDetailsProvider {
|
||||
val accessKey = accessKeyProvider
|
||||
?: (OracleAccessKeyManager.getAccessKeyByFingerprint(keyFingerprint)?.toPrivateKeySupplier()
|
||||
?: throw IllegalStateException("Failed to get accessKey."))
|
||||
val builder = SimpleAuthenticationDetailsProvider.builder()
|
||||
.userId(userId)
|
||||
.tenantId(tenantId)
|
||||
.fingerprint(keyFingerprint.chunked(2).joinToString(separator = ":"))
|
||||
.region(Region.fromRegionId(regionId))
|
||||
.privateKeySupplier(accessKey)
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun fromJson(json: String): OracleAccountProfile =
|
||||
gson.fromJson(json, OracleAccountProfile::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Oracle API 访问密钥.
|
||||
* @property fingerprint 密钥指纹, 算法为 MD5, Base64 编码不带分隔符(所以总长度固定 32 个字符)
|
||||
* @property privateKeyContent 密钥的 PEM 格式, 编码协议为 PKCS#8
|
||||
*/
|
||||
data class OracleAccessKey(
|
||||
val fingerprint: String,
|
||||
val privateKeyContent: String
|
||||
) : java.io.Serializable {
|
||||
fun toPrivateKeySupplier(): StringPrivateKeySupplier = StringPrivateKeySupplier(privateKeyContent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Oracle API 密钥管理.
|
||||
*/
|
||||
object OracleAccessKeyManager {
|
||||
|
||||
private val logger = KotlinLogging.logger { }
|
||||
|
||||
fun addAccessKey(privateKey: PrivateKey): Boolean {
|
||||
val fingerprint = getKeyPairFingerprint(privateKey as RSAPrivateCrtKey, separator = "")
|
||||
val formatFingerprint = fingerprint.chunked(2).joinToString(separator = ":")
|
||||
if (accessKeyContains(fingerprint)) {
|
||||
logger.debug { "密钥 $formatFingerprint 已存在, 跳过加载." }
|
||||
return true
|
||||
}
|
||||
return try {
|
||||
database.OracleAccessKeys.add(
|
||||
OracleAccessKeyPO.fromDataClass(
|
||||
OracleAccessKey(
|
||||
fingerprint,
|
||||
privateKey.toPemString()
|
||||
)
|
||||
)
|
||||
)
|
||||
logger.debug { "密钥 $formatFingerprint 已添加." }
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "添加访问密钥 $formatFingerprint 失败!" }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun getAccessKeyByFingerprint(fingerprint: String): OracleAccessKey? {
|
||||
return database.OracleAccessKeys.filter { it.keyFingerprint eq fingerprint }.firstOrNull()?.toDataClass()
|
||||
}
|
||||
|
||||
fun accessKeyContains(fingerprint: String): Boolean {
|
||||
return getAccessKeyByFingerprint(fingerprint) != null
|
||||
}
|
||||
|
||||
fun cleanUnusedAccessKey(): Int {
|
||||
var count = 0
|
||||
database.OracleAccessKeys.forEach { accessKey ->
|
||||
val filter = database.OracleAccounts.filter { it.keyFingerprint eq accessKey.fingerprint }.toList()
|
||||
if (filter.isEmpty()) {
|
||||
database.OracleAccessKeys.removeIf { it.keyFingerprint eq accessKey.fingerprint }
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Oracle 账号管理.
|
||||
*/
|
||||
object OracleAccountManage {
|
||||
|
||||
fun addOracleAccount(accountProfile: OracleAccountProfile) {
|
||||
database.OracleAccounts.add(OracleAccountProfilePO.fromDataClass(accountProfile))
|
||||
}
|
||||
|
||||
fun updateOracleAccount(profile: OracleAccountProfile) {
|
||||
database.OracleAccounts.update(OracleAccountProfilePO.fromDataClass(profile))
|
||||
}
|
||||
|
||||
fun getOracleAccountByOracleUserId(userId: String): OracleAccountProfilePO? {
|
||||
if (!OCID.isValid(userId)) {
|
||||
throw IllegalArgumentException("Invalid UserId: $userId")
|
||||
}
|
||||
return database.OracleAccounts.filter { it.userId eq userId }.firstOrNull()
|
||||
}
|
||||
|
||||
fun removeOracleAccountByOracleUserId(ocUserId: String, tgUserId: Long): Boolean {
|
||||
return database.OracleAccounts.removeIf { it.userId eq ocUserId and (it.tgUserId eq tgUserId) } != 0
|
||||
}
|
||||
|
||||
fun getOracleAccountsByTelegramUserId(tgUserId: Long): Set<OracleAccountProfile> {
|
||||
return database.OracleAccounts
|
||||
.filter { it.tgUserId eq tgUserId }
|
||||
.map { it.toDataClass() }
|
||||
.toSet()
|
||||
}
|
||||
|
||||
}
|
13
src/main/kotlin/OracleBmcUtils.kt
Normal file
13
src/main/kotlin/OracleBmcUtils.kt
Normal file
@ -0,0 +1,13 @@
|
||||
package net.lamgc.scext.oraclemanager
|
||||
|
||||
import com.oracle.bmc.identity.IdentityClient
|
||||
import com.oracle.bmc.identity.model.User
|
||||
import com.oracle.bmc.identity.requests.GetUserRequest
|
||||
|
||||
fun IdentityClient.getUser(userId: String): User {
|
||||
return getUser(
|
||||
GetUserRequest.builder()
|
||||
.userId(userId)
|
||||
.build()
|
||||
).user
|
||||
}
|
838
src/main/kotlin/RandomNames.kt
Normal file
838
src/main/kotlin/RandomNames.kt
Normal file
@ -0,0 +1,838 @@
|
||||
package net.lamgc.scext.oraclemanager
|
||||
|
||||
/*
|
||||
* 这些代码来自这里:
|
||||
* https://github.com/moby/moby/blob/master/pkg/namesgenerator/names-generator.go
|
||||
*/
|
||||
|
||||
private val left = listOf(
|
||||
"admiring",
|
||||
"adoring",
|
||||
"affectionate",
|
||||
"agitated",
|
||||
"amazing",
|
||||
"angry",
|
||||
"awesome",
|
||||
"beautiful",
|
||||
"blissful",
|
||||
"bold",
|
||||
"boring",
|
||||
"brave",
|
||||
"busy",
|
||||
"charming",
|
||||
"clever",
|
||||
"cool",
|
||||
"compassionate",
|
||||
"competent",
|
||||
"condescending",
|
||||
"confident",
|
||||
"cranky",
|
||||
"crazy",
|
||||
"dazzling",
|
||||
"determined",
|
||||
"distracted",
|
||||
"dreamy",
|
||||
"eager",
|
||||
"ecstatic",
|
||||
"elastic",
|
||||
"elated",
|
||||
"elegant",
|
||||
"eloquent",
|
||||
"epic",
|
||||
"exciting",
|
||||
"fervent",
|
||||
"festive",
|
||||
"flamboyant",
|
||||
"focused",
|
||||
"friendly",
|
||||
"frosty",
|
||||
"funny",
|
||||
"gallant",
|
||||
"gifted",
|
||||
"goofy",
|
||||
"gracious",
|
||||
"great",
|
||||
"happy",
|
||||
"hardcore",
|
||||
"heuristic",
|
||||
"hopeful",
|
||||
"hungry",
|
||||
"infallible",
|
||||
"inspiring",
|
||||
"interesting",
|
||||
"intelligent",
|
||||
"jolly",
|
||||
"jovial",
|
||||
"keen",
|
||||
"kind",
|
||||
"laughing",
|
||||
"loving",
|
||||
"lucid",
|
||||
"magical",
|
||||
"mystifying",
|
||||
"modest",
|
||||
"musing",
|
||||
"naughty",
|
||||
"nervous",
|
||||
"nice",
|
||||
"nifty",
|
||||
"nostalgic",
|
||||
"objective",
|
||||
"optimistic",
|
||||
"peaceful",
|
||||
"pedantic",
|
||||
"pensive",
|
||||
"practical",
|
||||
"priceless",
|
||||
"quirky",
|
||||
"quizzical",
|
||||
"recursing",
|
||||
"relaxed",
|
||||
"reverent",
|
||||
"romantic",
|
||||
"sad",
|
||||
"serene",
|
||||
"sharp",
|
||||
"silly",
|
||||
"sleepy",
|
||||
"stoic",
|
||||
"strange",
|
||||
"stupefied",
|
||||
"suspicious",
|
||||
"sweet",
|
||||
"tender",
|
||||
"thirsty",
|
||||
"trusting",
|
||||
"unruffled",
|
||||
"upbeat",
|
||||
"vibrant",
|
||||
"vigilant",
|
||||
"vigorous",
|
||||
"wizardly",
|
||||
"wonderful",
|
||||
"xenodochial",
|
||||
"youthful",
|
||||
"zealous",
|
||||
"zen",
|
||||
)
|
||||
|
||||
// Docker, starting from 0.7.x, generates names from notable scientists and hackers.
|
||||
// Please, for any amazing man that you add to the list, consider adding an equally amazing woman to it, and vice versa.
|
||||
private val right = listOf(
|
||||
// Maria Gaetana Agnesi - Italian mathematician, philosopher, theologian and humanitarian. She was the first woman to write a mathematics handbook and the first woman appointed as a Mathematics Professor at a University. https://en.wikipedia.org/wiki/Maria_Gaetana_Agnesi
|
||||
"agnesi",
|
||||
|
||||
// Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. https://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB
|
||||
"albattani",
|
||||
|
||||
// Frances E. Allen, became the first female IBM Fellow in 1989. In 2006, she became the first female recipient of the ACM's Turing Award. https://en.wikipedia.org/wiki/Frances_E._Allen
|
||||
"allen",
|
||||
|
||||
// June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida
|
||||
"almeida",
|
||||
|
||||
// Kathleen Antonelli, American computer programmer and one of the six original programmers of the ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli
|
||||
"antonelli",
|
||||
|
||||
// Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. https://en.wikipedia.org/wiki/Archimedes
|
||||
"archimedes",
|
||||
|
||||
// Maria Ardinghelli - Italian translator, mathematician and physicist - https://en.wikipedia.org/wiki/Maria_Ardinghelli
|
||||
"ardinghelli",
|
||||
|
||||
// Aryabhata - Ancient Indian mathematician-astronomer during 476-550 CE https://en.wikipedia.org/wiki/Aryabhata
|
||||
"aryabhata",
|
||||
|
||||
// Wanda Austin - Wanda Austin is the President and CEO of The Aerospace Corporation, a leading architect for the US security space programs. https://en.wikipedia.org/wiki/Wanda_Austin
|
||||
"austin",
|
||||
|
||||
// Charles Babbage invented the concept of a programmable computer. https://en.wikipedia.org/wiki/Charles_Babbage.
|
||||
"babbage",
|
||||
|
||||
// Stefan Banach - Polish mathematician, was one of the founders of modern functional analysis. https://en.wikipedia.org/wiki/Stefan_Banach
|
||||
"banach",
|
||||
|
||||
// Buckaroo Banzai and his mentor Dr. Hikita perfected the "oscillation overthruster", a device that allows one to pass through solid matter. - https://en.wikipedia.org/wiki/The_Adventures_of_Buckaroo_Banzai_Across_the_8th_Dimension
|
||||
"banzai",
|
||||
|
||||
// John Bardeen co-invented the transistor - https://en.wikipedia.org/wiki/John_Bardeen
|
||||
"bardeen",
|
||||
|
||||
// Jean Bartik, born Betty Jean Jennings, was one of the original programmers for the ENIAC computer. https://en.wikipedia.org/wiki/Jean_Bartik
|
||||
"bartik",
|
||||
|
||||
// Laura Bassi, the world's first female professor https://en.wikipedia.org/wiki/Laura_Bassi
|
||||
"bassi",
|
||||
|
||||
// Hugh Beaver, British engineer, founder of the Guinness Book of World Records https://en.wikipedia.org/wiki/Hugh_Beaver
|
||||
"beaver",
|
||||
|
||||
// Alexander Graham Bell - an eminent Scottish-born scientist, inventor, engineer and innovator who is credited with inventing the first practical telephone - https://en.wikipedia.org/wiki/Alexander_Graham_Bell
|
||||
"bell",
|
||||
|
||||
// Karl Friedrich Benz - a German automobile engineer. Inventor of the first practical motorcar. https://en.wikipedia.org/wiki/Karl_Benz
|
||||
"benz",
|
||||
|
||||
// Homi J Bhabha - was an Indian nuclear physicist, founding director, and professor of physics at the Tata Institute of Fundamental Research. Colloquially known as "father of Indian nuclear programme"- https://en.wikipedia.org/wiki/Homi_J._Bhabha
|
||||
"bhabha",
|
||||
|
||||
// Bhaskara II - Ancient Indian mathematician-astronomer whose work on calculus predates Newton and Leibniz by over half a millennium - https://en.wikipedia.org/wiki/Bh%C4%81skara_II#Calculus
|
||||
"bhaskara",
|
||||
|
||||
// Sue Black - British computer scientist and campaigner. She has been instrumental in saving Bletchley Park, the site of World War II codebreaking - https://en.wikipedia.org/wiki/Sue_Black_(computer_scientist)
|
||||
"black",
|
||||
|
||||
// Elizabeth Helen Blackburn - Australian-American Nobel laureate; best known for co-discovering telomerase. https://en.wikipedia.org/wiki/Elizabeth_Blackburn
|
||||
"blackburn",
|
||||
|
||||
// Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - https://en.wikipedia.org/wiki/Elizabeth_Blackwell
|
||||
"blackwell",
|
||||
|
||||
// Niels Bohr is the father of quantum theory. https://en.wikipedia.org/wiki/Niels_Bohr.
|
||||
"bohr",
|
||||
|
||||
// Kathleen Booth, she's credited with writing the first assembly language. https://en.wikipedia.org/wiki/Kathleen_Booth
|
||||
"booth",
|
||||
|
||||
// Anita Borg - Anita Borg was the founding director of the Institute for Women and Technology (IWT). https://en.wikipedia.org/wiki/Anita_Borg
|
||||
"borg",
|
||||
|
||||
// Satyendra Nath Bose - He provided the foundation for Bose–Einstein statistics and the theory of the Bose–Einstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose
|
||||
"bose",
|
||||
|
||||
// Katherine Louise Bouman is an imaging scientist and Assistant Professor of Computer Science at the California Institute of Technology. She researches computational methods for imaging, and developed an algorithm that made possible the picture first visualization of a black hole using the Event Horizon Telescope. - https://en.wikipedia.org/wiki/Katie_Bouman
|
||||
"bouman",
|
||||
|
||||
// Evelyn Boyd Granville - She was one of the first African-American woman to receive a Ph.D. in mathematics; she earned it in 1949 from Yale University. https://en.wikipedia.org/wiki/Evelyn_Boyd_Granville
|
||||
"boyd",
|
||||
|
||||
// Brahmagupta - Ancient Indian mathematician during 598-670 CE who gave rules to compute with zero - https://en.wikipedia.org/wiki/Brahmagupta#Zero
|
||||
"brahmagupta",
|
||||
|
||||
// Walter Houser Brattain co-invented the transistor - https://en.wikipedia.org/wiki/Walter_Houser_Brattain
|
||||
"brattain",
|
||||
|
||||
// Emmett Brown invented time travel. https://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff)
|
||||
"brown",
|
||||
|
||||
// Linda Brown Buck - American biologist and Nobel laureate best known for her genetic and molecular analyses of the mechanisms of smell. https://en.wikipedia.org/wiki/Linda_B._Buck
|
||||
"buck",
|
||||
|
||||
// Dame Susan Jocelyn Bell Burnell - Northern Irish astrophysicist who discovered radio pulsars and was the first to analyse them. https://en.wikipedia.org/wiki/Jocelyn_Bell_Burnell
|
||||
"burnell",
|
||||
|
||||
// Annie Jump Cannon - pioneering female astronomer who classified hundreds of thousands of stars and created the system we use to understand stars today. https://en.wikipedia.org/wiki/Annie_Jump_Cannon
|
||||
"cannon",
|
||||
|
||||
// Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. https://en.wikipedia.org/wiki/Rachel_Carson
|
||||
"carson",
|
||||
|
||||
// Dame Mary Lucy Cartwright - British mathematician who was one of the first to study what is now known as chaos theory. Also known for Cartwright's theorem which finds applications in signal processing. https://en.wikipedia.org/wiki/Mary_Cartwright
|
||||
"cartwright",
|
||||
|
||||
// George Washington Carver - American agricultural scientist and inventor. He was the most prominent black scientist of the early 20th century. https://en.wikipedia.org/wiki/George_Washington_Carver
|
||||
"carver",
|
||||
|
||||
// Vinton Gray Cerf - American Internet pioneer, recognised as one of "the fathers of the Internet". With Robert Elliot Kahn, he designed TCP and IP, the primary data communication protocols of the Internet and other computer networks. https://en.wikipedia.org/wiki/Vint_Cerf
|
||||
"cerf",
|
||||
|
||||
// Subrahmanyan Chandrasekhar - Astrophysicist known for his mathematical theory on different stages and evolution in structures of the stars. He has won nobel prize for physics - https://en.wikipedia.org/wiki/Subrahmanyan_Chandrasekhar
|
||||
"chandrasekhar",
|
||||
|
||||
// Sergey Alexeyevich Chaplygin (Russian: Серге́й Алексе́евич Чаплы́гин; April 5, 1869 – October 8, 1942) was a Russian and Soviet physicist, mathematician, and mechanical engineer. He is known for mathematical formulas such as Chaplygin's equation and for a hypothetical substance in cosmology called Chaplygin gas, named after him. https://en.wikipedia.org/wiki/Sergey_Chaplygin
|
||||
"chaplygin",
|
||||
|
||||
// Émilie du Châtelet - French natural philosopher, mathematician, physicist, and author during the early 1730s, known for her translation of and commentary on Isaac Newton's book Principia containing basic laws of physics. https://en.wikipedia.org/wiki/%C3%89milie_du_Ch%C3%A2telet
|
||||
"chatelet",
|
||||
|
||||
// Asima Chatterjee was an Indian organic chemist noted for her research on vinca alkaloids, development of drugs for treatment of epilepsy and malaria - https://en.wikipedia.org/wiki/Asima_Chatterjee
|
||||
"chatterjee",
|
||||
|
||||
// David Lee Chaum - American computer scientist and cryptographer. Known for his seminal contributions in the field of anonymous communication. https://en.wikipedia.org/wiki/David_Chaum
|
||||
"chaum",
|
||||
|
||||
// Pafnuty Chebyshev - Russian mathematician. He is known fo his works on probability, statistics, mechanics, analytical geometry and number theory https://en.wikipedia.org/wiki/Pafnuty_Chebyshev
|
||||
"chebyshev",
|
||||
|
||||
// Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke
|
||||
"clarke",
|
||||
|
||||
// Bram Cohen - American computer programmer and author of the BitTorrent peer-to-peer protocol. https://en.wikipedia.org/wiki/Bram_Cohen
|
||||
"cohen",
|
||||
|
||||
// Jane Colden - American botanist widely considered the first female American botanist - https://en.wikipedia.org/wiki/Jane_Colden
|
||||
"colden",
|
||||
|
||||
// Gerty Theresa Cori - American biochemist who became the third woman—and first American woman—to win a Nobel Prize in science, and the first woman to be awarded the Nobel Prize in Physiology or Medicine. Cori was born in Prague. https://en.wikipedia.org/wiki/Gerty_Cori
|
||||
"cori",
|
||||
|
||||
// Seymour Roger Cray was an American electrical engineer and supercomputer architect who designed a series of computers that were the fastest in the world for decades. https://en.wikipedia.org/wiki/Seymour_Cray
|
||||
"cray",
|
||||
|
||||
// This entry reflects a husband and wife team who worked together:
|
||||
// Joan Curran was a Welsh scientist who developed radar and invented chaff, a radar countermeasure. https://en.wikipedia.org/wiki/Joan_Curran
|
||||
// Samuel Curran was an Irish physicist who worked alongside his wife during WWII and invented the proximity fuse. https://en.wikipedia.org/wiki/Samuel_Curran
|
||||
"curran",
|
||||
|
||||
// Marie Curie discovered radioactivity. https://en.wikipedia.org/wiki/Marie_Curie.
|
||||
"curie",
|
||||
|
||||
// Charles Darwin established the principles of natural evolution. https://en.wikipedia.org/wiki/Charles_Darwin.
|
||||
"darwin",
|
||||
|
||||
// Leonardo Da Vinci invented too many things to list here. https://en.wikipedia.org/wiki/Leonardo_da_Vinci.
|
||||
"davinci",
|
||||
|
||||
// A. K. (Alexander Keewatin) Dewdney, Canadian mathematician, computer scientist, author and filmmaker. Contributor to Scientific American's "Computer Recreations" from 1984 to 1991. Author of Core War (program), The Planiverse, The Armchair Universe, The Magic Machine, The New Turing Omnibus, and more. https://en.wikipedia.org/wiki/Alexander_Dewdney
|
||||
"dewdney",
|
||||
|
||||
// Satish Dhawan - Indian mathematician and aerospace engineer, known for leading the successful and indigenous development of the Indian space programme. https://en.wikipedia.org/wiki/Satish_Dhawan
|
||||
"dhawan",
|
||||
|
||||
// Bailey Whitfield Diffie - American cryptographer and one of the pioneers of public-key cryptography. https://en.wikipedia.org/wiki/Whitfield_Diffie
|
||||
"diffie",
|
||||
|
||||
// Edsger Wybe Dijkstra was a Dutch computer scientist and mathematical scientist. https://en.wikipedia.org/wiki/Edsger_W._Dijkstra.
|
||||
"dijkstra",
|
||||
|
||||
// Paul Adrien Maurice Dirac - English theoretical physicist who made fundamental contributions to the early development of both quantum mechanics and quantum electrodynamics. https://en.wikipedia.org/wiki/Paul_Dirac
|
||||
"dirac",
|
||||
|
||||
// Agnes Meyer Driscoll - American cryptanalyst during World Wars I and II who successfully cryptanalysed a number of Japanese ciphers. She was also the co-developer of one of the cipher machines of the US Navy, the CM. https://en.wikipedia.org/wiki/Agnes_Meyer_Driscoll
|
||||
"driscoll",
|
||||
|
||||
// Donna Dubinsky - played an integral role in the development of personal digital assistants (PDAs) serving as CEO of Palm, Inc. and co-founding Handspring. https://en.wikipedia.org/wiki/Donna_Dubinsky
|
||||
"dubinsky",
|
||||
|
||||
// Annie Easley - She was a leading member of the team which developed software for the Centaur rocket stage and one of the first African-Americans in her field. https://en.wikipedia.org/wiki/Annie_Easley
|
||||
"easley",
|
||||
|
||||
// Thomas Alva Edison, prolific inventor https://en.wikipedia.org/wiki/Thomas_Edison
|
||||
"edison",
|
||||
|
||||
// Albert Einstein invented the general theory of relativity. https://en.wikipedia.org/wiki/Albert_Einstein
|
||||
"einstein",
|
||||
|
||||
// Alexandra Asanovna Elbakyan (Russian: Алекса́ндра Аса́новна Элбакя́н) is a Kazakhstani graduate student, computer programmer, internet pirate in hiding, and the creator of the site Sci-Hub. Nature has listed her in 2016 in the top ten people that mattered in science, and Ars Technica has compared her to Aaron Swartz. - https://en.wikipedia.org/wiki/Alexandra_Elbakyan
|
||||
"elbakyan",
|
||||
|
||||
// Taher A. ElGamal - Egyptian cryptographer best known for the ElGamal discrete log cryptosystem and the ElGamal digital signature scheme. https://en.wikipedia.org/wiki/Taher_Elgamal
|
||||
"elgamal",
|
||||
|
||||
// Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - https://en.wikipedia.org/wiki/Gertrude_Elion
|
||||
"elion",
|
||||
|
||||
// James Henry Ellis - British engineer and cryptographer employed by the GCHQ. Best known for conceiving for the first time, the idea of public-key cryptography. https://en.wikipedia.org/wiki/James_H._Ellis
|
||||
"ellis",
|
||||
|
||||
// Douglas Engelbart gave the mother of all demos: https://en.wikipedia.org/wiki/Douglas_Engelbart
|
||||
"engelbart",
|
||||
|
||||
// Euclid invented geometry. https://en.wikipedia.org/wiki/Euclid
|
||||
"euclid",
|
||||
|
||||
// Leonhard Euler invented large parts of modern mathematics. https://de.wikipedia.org/wiki/Leonhard_Euler
|
||||
"euler",
|
||||
|
||||
// Michael Faraday - British scientist who contributed to the study of electromagnetism and electrochemistry. https://en.wikipedia.org/wiki/Michael_Faraday
|
||||
"faraday",
|
||||
|
||||
// Horst Feistel - German-born American cryptographer who was one of the earliest non-government researchers to study the design and theory of block ciphers. Co-developer of DES and Lucifer. Feistel networks, a symmetric structure used in the construction of block ciphers are named after him. https://en.wikipedia.org/wiki/Horst_Feistel
|
||||
"feistel",
|
||||
|
||||
// Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat
|
||||
"fermat",
|
||||
|
||||
// Enrico Fermi invented the first nuclear reactor. https://en.wikipedia.org/wiki/Enrico_Fermi.
|
||||
"fermi",
|
||||
|
||||
// Richard Feynman was a key contributor to quantum mechanics and particle physics. https://en.wikipedia.org/wiki/Richard_Feynman
|
||||
"feynman",
|
||||
|
||||
// Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod.
|
||||
"franklin",
|
||||
|
||||
// Yuri Alekseyevich Gagarin - Soviet pilot and cosmonaut, best known as the first human to journey into outer space. https://en.wikipedia.org/wiki/Yuri_Gagarin
|
||||
"gagarin",
|
||||
|
||||
// Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. https://en.wikipedia.org/wiki/Galileo_Galilei
|
||||
"galileo",
|
||||
|
||||
// Évariste Galois - French mathematician whose work laid the foundations of Galois theory and group theory, two major branches of abstract algebra, and the subfield of Galois connections, all while still in his late teens. https://en.wikipedia.org/wiki/%C3%89variste_Galois
|
||||
"galois",
|
||||
|
||||
// Kadambini Ganguly - Indian physician, known for being the first South Asian female physician, trained in western medicine, to graduate in South Asia. https://en.wikipedia.org/wiki/Kadambini_Ganguly
|
||||
"ganguly",
|
||||
|
||||
// William Henry "Bill" Gates III is an American business magnate, philanthropist, investor, computer programmer, and inventor. https://en.wikipedia.org/wiki/Bill_Gates
|
||||
"gates",
|
||||
|
||||
// Johann Carl Friedrich Gauss - German mathematician who made significant contributions to many fields, including number theory, algebra, statistics, analysis, differential geometry, geodesy, geophysics, mechanics, electrostatics, magnetic fields, astronomy, matrix theory, and optics. https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss
|
||||
"gauss",
|
||||
|
||||
// Marie-Sophie Germain - French mathematician, physicist and philosopher. Known for her work on elasticity theory, number theory and philosophy. https://en.wikipedia.org/wiki/Sophie_Germain
|
||||
"germain",
|
||||
|
||||
// Adele Goldberg, was one of the designers and developers of the Smalltalk language. https://en.wikipedia.org/wiki/Adele_Goldberg_(computer_scientist)
|
||||
"goldberg",
|
||||
|
||||
// Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. https://en.wikipedia.org/wiki/Adele_Goldstine
|
||||
"goldstine",
|
||||
|
||||
// Shafi Goldwasser is a computer scientist known for creating theoretical foundations of modern cryptography. Winner of 2012 ACM Turing Award. https://en.wikipedia.org/wiki/Shafi_Goldwasser
|
||||
"goldwasser",
|
||||
|
||||
// James Golick, all around gangster.
|
||||
"golick",
|
||||
|
||||
// Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall
|
||||
"goodall",
|
||||
|
||||
// Stephen Jay Gould was was an American paleontologist, evolutionary biologist, and historian of science. He is most famous for the theory of punctuated equilibrium - https://en.wikipedia.org/wiki/Stephen_Jay_Gould
|
||||
"gould",
|
||||
|
||||
// Carolyn Widney Greider - American molecular biologist and joint winner of the 2009 Nobel Prize for Physiology or Medicine for the discovery of telomerase. https://en.wikipedia.org/wiki/Carol_W._Greider
|
||||
"greider",
|
||||
|
||||
// Alexander Grothendieck - German-born French mathematician who became a leading figure in the creation of modern algebraic geometry. https://en.wikipedia.org/wiki/Alexander_Grothendieck
|
||||
"grothendieck",
|
||||
|
||||
// Lois Haibt - American computer scientist, part of the team at IBM that developed FORTRAN - https://en.wikipedia.org/wiki/Lois_Haibt
|
||||
"haibt",
|
||||
|
||||
// Margaret Hamilton - Director of the Software Engineering Division of the MIT Instrumentation Laboratory, which developed on-board flight software for the Apollo space program. https://en.wikipedia.org/wiki/Margaret_Hamilton_(scientist)
|
||||
"hamilton",
|
||||
|
||||
// Caroline Harriet Haslett - English electrical engineer, electricity industry administrator and champion of women's rights. Co-author of British Standard 1363 that specifies AC power plugs and sockets used across the United Kingdom (which is widely considered as one of the safest designs). https://en.wikipedia.org/wiki/Caroline_Haslett
|
||||
"haslett",
|
||||
|
||||
// Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. https://en.wikipedia.org/wiki/Stephen_Hawking
|
||||
"hawking",
|
||||
|
||||
// Martin Edward Hellman - American cryptologist, best known for his invention of public-key cryptography in co-operation with Whitfield Diffie and Ralph Merkle. https://en.wikipedia.org/wiki/Martin_Hellman
|
||||
"hellman",
|
||||
|
||||
// Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg
|
||||
"heisenberg",
|
||||
|
||||
// Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann
|
||||
"hermann",
|
||||
|
||||
// Caroline Lucretia Herschel - German astronomer and discoverer of several comets. https://en.wikipedia.org/wiki/Caroline_Herschel
|
||||
"herschel",
|
||||
|
||||
// Heinrich Rudolf Hertz - German physicist who first conclusively proved the existence of the electromagnetic waves. https://en.wikipedia.org/wiki/Heinrich_Hertz
|
||||
"hertz",
|
||||
|
||||
// Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD
|
||||
"heyrovsky",
|
||||
|
||||
// Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin
|
||||
"hodgkin",
|
||||
|
||||
// Douglas R. Hofstadter is an American professor of cognitive science and author of the Pulitzer Prize and American Book Award-winning work Goedel, Escher, Bach: An Eternal Golden Braid in 1979. A mind-bending work which coined Hofstadter's Law: "It always takes longer than you expect, even when you take into account Hofstadter's Law." https://en.wikipedia.org/wiki/Douglas_Hofstadter
|
||||
"hofstadter",
|
||||
|
||||
// Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephone switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover
|
||||
"hoover",
|
||||
|
||||
// Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. https://en.wikipedia.org/wiki/Grace_Hopper
|
||||
"hopper",
|
||||
|
||||
// Frances Hugle, she was an American scientist, engineer, and inventor who contributed to the understanding of semiconductors, integrated circuitry, and the unique electrical principles of microscopic materials. https://en.wikipedia.org/wiki/Frances_Hugle
|
||||
"hugle",
|
||||
|
||||
// Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - https://en.wikipedia.org/wiki/Hypatia
|
||||
"hypatia",
|
||||
|
||||
// Teruko Ishizaka - Japanese scientist and immunologist who co-discovered the antibody class Immunoglobulin E. https://en.wikipedia.org/wiki/Teruko_Ishizaka
|
||||
"ishizaka",
|
||||
|
||||
// Mary Jackson, American mathematician and aerospace engineer who earned the highest title within NASA's engineering department - https://en.wikipedia.org/wiki/Mary_Jackson_(engineer)
|
||||
"jackson",
|
||||
|
||||
// Yeong-Sil Jang was a Korean scientist and astronomer during the Joseon Dynasty; he invented the first metal printing press and water gauge. https://en.wikipedia.org/wiki/Jang_Yeong-sil
|
||||
"jang",
|
||||
|
||||
// Mae Carol Jemison - is an American engineer, physician, and former NASA astronaut. She became the first black woman to travel in space when she served as a mission specialist aboard the Space Shuttle Endeavour - https://en.wikipedia.org/wiki/Mae_Jemison
|
||||
"jemison",
|
||||
|
||||
// Betty Jennings - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Jean_Bartik
|
||||
"jennings",
|
||||
|
||||
// Mary Lou Jepsen, was the founder and chief technology officer of One Laptop Per Child (OLPC), and the founder of Pixel Qi. https://en.wikipedia.org/wiki/Mary_Lou_Jepsen
|
||||
"jepsen",
|
||||
|
||||
// Katherine Coleman Goble Johnson - American physicist and mathematician contributed to the NASA. https://en.wikipedia.org/wiki/Katherine_Johnson
|
||||
"johnson",
|
||||
|
||||
// Irène Joliot-Curie - French scientist who was awarded the Nobel Prize for Chemistry in 1935. Daughter of Marie and Pierre Curie. https://en.wikipedia.org/wiki/Ir%C3%A8ne_Joliot-Curie
|
||||
"joliot",
|
||||
|
||||
// Karen Spärck Jones came up with the concept of inverse document frequency, which is used in most search engines today. https://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones
|
||||
"jones",
|
||||
|
||||
// A. P. J. Abdul Kalam - is an Indian scientist aka Missile Man of India for his work on the development of ballistic missile and launch vehicle technology - https://en.wikipedia.org/wiki/A._P._J._Abdul_Kalam
|
||||
"kalam",
|
||||
|
||||
// Sergey Petrovich Kapitsa (Russian: Серге́й Петро́вич Капи́ца; 14 February 1928 – 14 August 2012) was a Russian physicist and demographer. He was best known as host of the popular and long-running Russian scientific TV show, Evident, but Incredible. His father was the Nobel laureate Soviet-era physicist Pyotr Kapitsa, and his brother was the geographer and Antarctic explorer Andrey Kapitsa. - https://en.wikipedia.org/wiki/Sergey_Kapitsa
|
||||
"kapitsa",
|
||||
|
||||
// Susan Kare, created the icons and many of the interface elements for the original Apple Macintosh in the 1980s, and was an original employee of NeXT, working as the Creative Director. https://en.wikipedia.org/wiki/Susan_Kare
|
||||
"kare",
|
||||
|
||||
// Mstislav Keldysh - a Soviet scientist in the field of mathematics and mechanics, academician of the USSR Academy of Sciences (1946), President of the USSR Academy of Sciences (1961–1975), three times Hero of Socialist Labor (1956, 1961, 1971), fellow of the Royal Society of Edinburgh (1968). https://en.wikipedia.org/wiki/Mstislav_Keldysh
|
||||
"keldysh",
|
||||
|
||||
// Mary Kenneth Keller, Sister Mary Kenneth Keller became the first American woman to earn a PhD in Computer Science in 1965. https://en.wikipedia.org/wiki/Mary_Kenneth_Keller
|
||||
"keller",
|
||||
|
||||
// Johannes Kepler, German astronomer known for his three laws of planetary motion - https://en.wikipedia.org/wiki/Johannes_Kepler
|
||||
"kepler",
|
||||
|
||||
// Omar Khayyam - Persian mathematician, astronomer and poet. Known for his work on the classification and solution of cubic equations, for his contribution to the understanding of Euclid's fifth postulate and for computing the length of a year very accurately. https://en.wikipedia.org/wiki/Omar_Khayyam
|
||||
"khayyam",
|
||||
|
||||
// Har Gobind Khorana - Indian-American biochemist who shared the 1968 Nobel Prize for Physiology - https://en.wikipedia.org/wiki/Har_Gobind_Khorana
|
||||
"khorana",
|
||||
|
||||
// Jack Kilby invented silicon integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Jack_Kilby
|
||||
"kilby",
|
||||
|
||||
// Maria Kirch - German astronomer and first woman to discover a comet - https://en.wikipedia.org/wiki/Maria_Margarethe_Kirch
|
||||
"kirch",
|
||||
|
||||
// Donald Knuth - American computer scientist, author of "The Art of Computer Programming" and creator of the TeX typesetting system. https://en.wikipedia.org/wiki/Donald_Knuth
|
||||
"knuth",
|
||||
|
||||
// Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - https://en.wikipedia.org/wiki/Sofia_Kovalevskaya
|
||||
"kowalevski",
|
||||
|
||||
// Marie-Jeanne de Lalande - French astronomer, mathematician and cataloguer of stars - https://en.wikipedia.org/wiki/Marie-Jeanne_de_Lalande
|
||||
"lalande",
|
||||
|
||||
// Hedy Lamarr - Actress and inventor. The principles of her work are now incorporated into modern Wi-Fi, CDMA and Bluetooth technology. https://en.wikipedia.org/wiki/Hedy_Lamarr
|
||||
"lamarr",
|
||||
|
||||
// Leslie B. Lamport - American computer scientist. Lamport is best known for his seminal work in distributed systems and was the winner of the 2013 Turing Award. https://en.wikipedia.org/wiki/Leslie_Lamport
|
||||
"lamport",
|
||||
|
||||
// Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - https://en.wikipedia.org/wiki/Mary_Leakey
|
||||
"leakey",
|
||||
|
||||
// Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt
|
||||
"leavitt",
|
||||
|
||||
// Esther Miriam Zimmer Lederberg - American microbiologist and a pioneer of bacterial genetics. https://en.wikipedia.org/wiki/Esther_Lederberg
|
||||
"lederberg",
|
||||
|
||||
// Inge Lehmann - Danish seismologist and geophysicist. Known for discovering in 1936 that the Earth has a solid inner core inside a molten outer core. https://en.wikipedia.org/wiki/Inge_Lehmann
|
||||
"lehmann",
|
||||
|
||||
// Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin
|
||||
"lewin",
|
||||
|
||||
// Ruth Lichterman - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Ruth_Teitelbaum
|
||||
"lichterman",
|
||||
|
||||
// Barbara Liskov - co-developed the Liskov substitution principle. Liskov was also the winner of the Turing Prize in 2008. - https://en.wikipedia.org/wiki/Barbara_Liskov
|
||||
"liskov",
|
||||
|
||||
// Ada Lovelace invented the first algorithm. https://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull)
|
||||
"lovelace",
|
||||
|
||||
// Auguste and Louis Lumière - the first filmmakers in history - https://en.wikipedia.org/wiki/Auguste_and_Louis_Lumi%C3%A8re
|
||||
"lumiere",
|
||||
|
||||
// Mahavira - Ancient Indian mathematician during 9th century AD who discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician)
|
||||
"mahavira",
|
||||
|
||||
// Lynn Margulis (b. Lynn Petra Alexander) - an American evolutionary theorist and biologist, science author, educator, and popularizer, and was the primary modern proponent for the significance of symbiosis in evolution. - https://en.wikipedia.org/wiki/Lynn_Margulis
|
||||
"margulis",
|
||||
|
||||
// Yukihiro Matsumoto - Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language. https://en.wikipedia.org/wiki/Yukihiro_Matsumoto
|
||||
"matsumoto",
|
||||
|
||||
// James Clerk Maxwell - Scottish physicist, best known for his formulation of electromagnetic theory. https://en.wikipedia.org/wiki/James_Clerk_Maxwell
|
||||
"maxwell",
|
||||
|
||||
// Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - https://en.wikipedia.org/wiki/Maria_Mayer
|
||||
"mayer",
|
||||
|
||||
// John McCarthy invented LISP: https://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)
|
||||
"mccarthy",
|
||||
|
||||
// Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. https://en.wikipedia.org/wiki/Barbara_McClintock
|
||||
"mcclintock",
|
||||
|
||||
// Anne Laura Dorinthea McLaren - British developmental biologist whose work helped lead to human in-vitro fertilisation. https://en.wikipedia.org/wiki/Anne_McLaren
|
||||
"mclaren",
|
||||
|
||||
// Malcolm McLean invented the modern shipping container: https://en.wikipedia.org/wiki/Malcom_McLean
|
||||
"mclean",
|
||||
|
||||
// Kay McNulty - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli
|
||||
"mcnulty",
|
||||
|
||||
// Gregor Johann Mendel - Czech scientist and founder of genetics. https://en.wikipedia.org/wiki/Gregor_Mendel
|
||||
"mendel",
|
||||
|
||||
// Dmitri Mendeleev - a chemist and inventor. He formulated the Periodic Law, created a farsighted version of the periodic table of elements, and used it to correct the properties of some already discovered elements and also to predict the properties of eight elements yet to be discovered. https://en.wikipedia.org/wiki/Dmitri_Mendeleev
|
||||
"mendeleev",
|
||||
|
||||
// Lise Meitner - Austrian/Swedish physicist who was involved in the discovery of nuclear fission. The element meitnerium is named after her - https://en.wikipedia.org/wiki/Lise_Meitner
|
||||
"meitner",
|
||||
|
||||
// Carla Meninsky, was the game designer and programmer for Atari 2600 games Dodge 'Em and Warlords. https://en.wikipedia.org/wiki/Carla_Meninsky
|
||||
"meninsky",
|
||||
|
||||
// Ralph C. Merkle - American computer scientist, known for devising Merkle's puzzles - one of the very first schemes for public-key cryptography. Also, inventor of Merkle trees and co-inventor of the Merkle-Damgård construction for building collision-resistant cryptographic hash functions and the Merkle-Hellman knapsack cryptosystem. https://en.wikipedia.org/wiki/Ralph_Merkle
|
||||
"merkle",
|
||||
|
||||
// Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf
|
||||
"mestorf",
|
||||
|
||||
// Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani
|
||||
"mirzakhani",
|
||||
|
||||
// Rita Levi-Montalcini - Won Nobel Prize in Physiology or Medicine jointly with colleague Stanley Cohen for the discovery of nerve growth factor (https://en.wikipedia.org/wiki/Rita_Levi-Montalcini)
|
||||
"montalcini",
|
||||
|
||||
// Gordon Earle Moore - American engineer, Silicon Valley founding father, author of Moore's law. https://en.wikipedia.org/wiki/Gordon_Moore
|
||||
"moore",
|
||||
|
||||
// Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse
|
||||
"morse",
|
||||
|
||||
// Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock
|
||||
"murdock",
|
||||
|
||||
// May-Britt Moser - Nobel prize winner neuroscientist who contributed to the discovery of grid cells in the brain. https://en.wikipedia.org/wiki/May-Britt_Moser
|
||||
"moser",
|
||||
|
||||
// John Napier of Merchiston - Scottish landowner known as an astronomer, mathematician and physicist. Best known for his discovery of logarithms. https://en.wikipedia.org/wiki/John_Napier
|
||||
"napier",
|
||||
|
||||
// John Forbes Nash, Jr. - American mathematician who made fundamental contributions to game theory, differential geometry, and the study of partial differential equations. https://en.wikipedia.org/wiki/John_Forbes_Nash_Jr.
|
||||
"nash",
|
||||
|
||||
// John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture
|
||||
"neumann",
|
||||
|
||||
// Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton
|
||||
"newton",
|
||||
|
||||
// Florence Nightingale, more prominently known as a nurse, was also the first female member of the Royal Statistical Society and a pioneer in statistical graphics https://en.wikipedia.org/wiki/Florence_Nightingale#Statistics_and_sanitary_reform
|
||||
"nightingale",
|
||||
|
||||
// Alfred Nobel - a Swedish chemist, engineer, innovator, and armaments manufacturer (inventor of dynamite) - https://en.wikipedia.org/wiki/Alfred_Nobel
|
||||
"nobel",
|
||||
|
||||
// Emmy Noether, German mathematician. Noether's Theorem is named after her. https://en.wikipedia.org/wiki/Emmy_Noether
|
||||
"noether",
|
||||
|
||||
// Poppy Northcutt. Poppy Northcutt was the first woman to work as part of NASA’s Mission Control. http://www.businessinsider.com/poppy-northcutt-helped-apollo-astronauts-2014-12?op=1
|
||||
"northcutt",
|
||||
|
||||
// Robert Noyce invented silicon integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Robert_Noyce
|
||||
"noyce",
|
||||
|
||||
// Panini - Ancient Indian linguist and grammarian from 4th century CE who worked on the world's first formal system - https://en.wikipedia.org/wiki/P%C4%81%E1%B9%87ini#Comparison_with_modern_formal_systems
|
||||
"panini",
|
||||
|
||||
// Ambroise Pare invented modern surgery. https://en.wikipedia.org/wiki/Ambroise_Par%C3%A9
|
||||
"pare",
|
||||
|
||||
// Blaise Pascal, French mathematician, physicist, and inventor - https://en.wikipedia.org/wiki/Blaise_Pascal
|
||||
"pascal",
|
||||
|
||||
// Louis Pasteur discovered vaccination, fermentation and pasteurization. https://en.wikipedia.org/wiki/Louis_Pasteur.
|
||||
"pasteur",
|
||||
|
||||
// Cecilia Payne-Gaposchkin was an astronomer and astrophysicist who, in 1925, proposed in her Ph.D. thesis an explanation for the composition of stars in terms of the relative abundances of hydrogen and helium. https://en.wikipedia.org/wiki/Cecilia_Payne-Gaposchkin
|
||||
"payne",
|
||||
|
||||
// Radia Perlman is a software designer and network engineer and most famous for her invention of the spanning-tree protocol (STP). https://en.wikipedia.org/wiki/Radia_Perlman
|
||||
"perlman",
|
||||
|
||||
// Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. https://en.wikipedia.org/wiki/Rob_Pike
|
||||
"pike",
|
||||
|
||||
// Henri Poincaré made fundamental contributions in several fields of mathematics. https://en.wikipedia.org/wiki/Henri_Poincar%C3%A9
|
||||
"poincare",
|
||||
|
||||
// Laura Poitras is a director and producer whose work, made possible by open source crypto tools, advances the causes of truth and freedom of information by reporting disclosures by whistleblowers such as Edward Snowden. https://en.wikipedia.org/wiki/Laura_Poitras
|
||||
"poitras",
|
||||
|
||||
// Tat’yana Avenirovna Proskuriakova (Russian: Татья́на Авени́ровна Проскуряко́ва) (January 23 [O.S. January 10] 1909 – August 30, 1985) was a Russian-American Mayanist scholar and archaeologist who contributed significantly to the deciphering of Maya hieroglyphs, the writing system of the pre-Columbian Maya civilization of Mesoamerica. https://en.wikipedia.org/wiki/Tatiana_Proskouriakoff
|
||||
"proskuriakova",
|
||||
|
||||
// Claudius Ptolemy - a Greco-Egyptian writer of Alexandria, known as a mathematician, astronomer, geographer, astrologer, and poet of a single epigram in the Greek Anthology - https://en.wikipedia.org/wiki/Ptolemy
|
||||
"ptolemy",
|
||||
|
||||
// C. V. Raman - Indian physicist who won the Nobel Prize in 1930 for proposing the Raman effect. - https://en.wikipedia.org/wiki/C._V._Raman
|
||||
"raman",
|
||||
|
||||
// Srinivasa Ramanujan - Indian mathematician and autodidact who made extraordinary contributions to mathematical analysis, number theory, infinite series, and continued fractions. - https://en.wikipedia.org/wiki/Srinivasa_Ramanujan
|
||||
"ramanujan",
|
||||
|
||||
// Sally Kristen Ride was an American physicist and astronaut. She was the first American woman in space, and the youngest American astronaut. https://en.wikipedia.org/wiki/Sally_Ride
|
||||
"ride",
|
||||
|
||||
// Dennis Ritchie - co-creator of UNIX and the C programming language. - https://en.wikipedia.org/wiki/Dennis_Ritchie
|
||||
"ritchie",
|
||||
|
||||
// Ida Rhodes - American pioneer in computer programming, designed the first computer used for Social Security. https://en.wikipedia.org/wiki/Ida_Rhodes
|
||||
"rhodes",
|
||||
|
||||
// Julia Hall Bowman Robinson - American mathematician renowned for her contributions to the fields of computability theory and computational complexity theory. https://en.wikipedia.org/wiki/Julia_Robinson
|
||||
"robinson",
|
||||
|
||||
// Wilhelm Conrad Röntgen - German physicist who was awarded the first Nobel Prize in Physics in 1901 for the discovery of X-rays (Röntgen rays). https://en.wikipedia.org/wiki/Wilhelm_R%C3%B6ntgen
|
||||
"roentgen",
|
||||
|
||||
// Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin
|
||||
"rosalind",
|
||||
|
||||
// Vera Rubin - American astronomer who pioneered work on galaxy rotation rates. https://en.wikipedia.org/wiki/Vera_Rubin
|
||||
"rubin",
|
||||
|
||||
// Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha
|
||||
"saha",
|
||||
|
||||
// Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet
|
||||
"sammet",
|
||||
|
||||
// Mildred Sanderson - American mathematician best known for Sanderson's theorem concerning modular invariants. https://en.wikipedia.org/wiki/Mildred_Sanderson
|
||||
"sanderson",
|
||||
|
||||
// Satoshi Nakamoto is the name used by the unknown person or group of people who developed bitcoin, authored the bitcoin white paper, and created and deployed bitcoin's original reference implementation. https://en.wikipedia.org/wiki/Satoshi_Nakamoto
|
||||
"satoshi",
|
||||
|
||||
// Adi Shamir - Israeli cryptographer whose numerous inventions and contributions to cryptography include the Ferge Fiat Shamir identification scheme, the Rivest Shamir Adleman (RSA) public-key cryptosystem, the Shamir's secret sharing scheme, the breaking of the Merkle-Hellman cryptosystem, the TWINKLE and TWIRL factoring devices and the discovery of differential cryptanalysis (with Eli Biham). https://en.wikipedia.org/wiki/Adi_Shamir
|
||||
"shamir",
|
||||
|
||||
// Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon)
|
||||
"shannon",
|
||||
|
||||
// Carol Shaw - Originally an Atari employee, Carol Shaw is said to be the first female video game designer. https://en.wikipedia.org/wiki/Carol_Shaw_(video_game_designer)
|
||||
"shaw",
|
||||
|
||||
// Dame Stephanie "Steve" Shirley - Founded a software company in 1962 employing women working from home. https://en.wikipedia.org/wiki/Steve_Shirley
|
||||
"shirley",
|
||||
|
||||
// William Shockley co-invented the transistor - https://en.wikipedia.org/wiki/William_Shockley
|
||||
"shockley",
|
||||
|
||||
// Lina Solomonovna Stern (or Shtern; Russian: Лина Соломоновна Штерн; 26 August 1878 – 7 March 1968) was a Soviet biochemist, physiologist and humanist whose medical discoveries saved thousands of lives at the fronts of World War II. She is best known for her pioneering work on blood–brain barrier, which she described as hemato-encephalic barrier in 1921. https://en.wikipedia.org/wiki/Lina_Stern
|
||||
"shtern",
|
||||
|
||||
// Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. https://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi
|
||||
"sinoussi",
|
||||
|
||||
// Betty Snyder - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Betty_Holberton
|
||||
"snyder",
|
||||
|
||||
// Cynthia Solomon - Pioneer in the fields of artificial intelligence, computer science and educational computing. Known for creation of Logo, an educational programming language. https://en.wikipedia.org/wiki/Cynthia_Solomon
|
||||
"solomon",
|
||||
|
||||
// Frances Spence - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Frances_Spence
|
||||
"spence",
|
||||
|
||||
// Michael Stonebraker is a database research pioneer and architect of Ingres, Postgres, VoltDB and SciDB. Winner of 2014 ACM Turing Award. https://en.wikipedia.org/wiki/Michael_Stonebraker
|
||||
"stonebraker",
|
||||
|
||||
// Ivan Edward Sutherland - American computer scientist and Internet pioneer, widely regarded as the father of computer graphics. https://en.wikipedia.org/wiki/Ivan_Sutherland
|
||||
"sutherland",
|
||||
|
||||
// Janese Swanson (with others) developed the first of the Carmen Sandiego games. She went on to found Girl Tech. https://en.wikipedia.org/wiki/Janese_Swanson
|
||||
"swanson",
|
||||
|
||||
// Aaron Swartz was influential in creating RSS, Markdown, Creative Commons, Reddit, and much of the internet as we know it today. He was devoted to freedom of information on the web. https://en.wikiquote.org/wiki/Aaron_Swartz
|
||||
"swartz",
|
||||
|
||||
// Bertha Swirles was a theoretical physicist who made a number of contributions to early quantum theory. https://en.wikipedia.org/wiki/Bertha_Swirles
|
||||
"swirles",
|
||||
|
||||
// Helen Brooke Taussig - American cardiologist and founder of the field of paediatric cardiology. https://en.wikipedia.org/wiki/Helen_B._Taussig
|
||||
"taussig",
|
||||
|
||||
// Valentina Tereshkova is a Russian engineer, cosmonaut and politician. She was the first woman to fly to space in 1963. In 2013, at the age of 76, she offered to go on a one-way mission to Mars. https://en.wikipedia.org/wiki/Valentina_Tereshkova
|
||||
"tereshkova",
|
||||
|
||||
// Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla
|
||||
"tesla",
|
||||
|
||||
// Marie Tharp - American geologist and oceanic cartographer who co-created the first scientific map of the Atlantic Ocean floor. Her work led to the acceptance of the theories of plate tectonics and continental drift. https://en.wikipedia.org/wiki/Marie_Tharp
|
||||
"tharp",
|
||||
|
||||
// Ken Thompson - co-creator of UNIX and the C programming language - https://en.wikipedia.org/wiki/Ken_Thompson
|
||||
"thompson",
|
||||
|
||||
// Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds
|
||||
"torvalds",
|
||||
|
||||
// Youyou Tu - Chinese pharmaceutical chemist and educator known for discovering artemisinin and dihydroartemisinin, used to treat malaria, which has saved millions of lives. Joint winner of the 2015 Nobel Prize in Physiology or Medicine. https://en.wikipedia.org/wiki/Tu_Youyou
|
||||
"tu",
|
||||
|
||||
// Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing.
|
||||
"turing",
|
||||
|
||||
// Varahamihira - Ancient Indian mathematician who discovered trigonometric formulae during 505-587 CE - https://en.wikipedia.org/wiki/Var%C4%81hamihira#Contributions
|
||||
"varahamihira",
|
||||
|
||||
// Dorothy Vaughan was a NASA mathematician and computer programmer on the SCOUT launch vehicle program that put America's first satellites into space - https://en.wikipedia.org/wiki/Dorothy_Vaughan
|
||||
"vaughan",
|
||||
|
||||
// Cédric Villani - French mathematician, won Fields Medal, Fermat Prize and Poincaré Price for his work in differential geometry and statistical mechanics. https://en.wikipedia.org/wiki/C%C3%A9dric_Villani
|
||||
"villani",
|
||||
|
||||
// Sir Mokshagundam Visvesvaraya - is a notable Indian engineer. He is a recipient of the Indian Republic's highest honour, the Bharat Ratna, in 1955. On his birthday, 15 September is celebrated as Engineer's Day in India in his memory - https://en.wikipedia.org/wiki/Visvesvaraya
|
||||
"visvesvaraya",
|
||||
|
||||
// Christiane Nüsslein-Volhard - German biologist, won Nobel Prize in Physiology or Medicine in 1995 for research on the genetic control of embryonic development. https://en.wikipedia.org/wiki/Christiane_N%C3%BCsslein-Volhard
|
||||
"volhard",
|
||||
|
||||
// Marlyn Wescoff - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Marlyn_Meltzer
|
||||
"wescoff",
|
||||
|
||||
// Sylvia B. Wilbur - British computer scientist who helped develop the ARPANET, was one of the first to exchange email in the UK and a leading researcher in computer-supported collaborative work. https://en.wikipedia.org/wiki/Sylvia_Wilbur
|
||||
"wilbur",
|
||||
|
||||
// Andrew Wiles - Notable British mathematician who proved the enigmatic Fermat's Last Theorem - https://en.wikipedia.org/wiki/Andrew_Wiles
|
||||
"wiles",
|
||||
|
||||
// Roberta Williams, did pioneering work in graphical adventure games for personal computers, particularly the King's Quest series. https://en.wikipedia.org/wiki/Roberta_Williams
|
||||
"williams",
|
||||
|
||||
// Malcolm John Williamson - British mathematician and cryptographer employed by the GCHQ. Developed in 1974 what is now known as Diffie-Hellman key exchange (Diffie and Hellman first published the scheme in 1976). https://en.wikipedia.org/wiki/Malcolm_J._Williamson
|
||||
"williamson",
|
||||
|
||||
// Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. https://en.wikipedia.org/wiki/Sophie_Wilson
|
||||
"wilson",
|
||||
|
||||
// Jeannette Wing - co-developed the Liskov substitution principle. - https://en.wikipedia.org/wiki/Jeannette_Wing
|
||||
"wing",
|
||||
|
||||
// Steve Wozniak invented the Apple I and Apple II. https://en.wikipedia.org/wiki/Steve_Wozniak
|
||||
"wozniak",
|
||||
|
||||
// The Wright brothers, Orville and Wilbur - credited with inventing and building the world's first successful airplane and making the first controlled, powered and sustained heavier-than-air human flight - https://en.wikipedia.org/wiki/Wright_brothers
|
||||
"wright",
|
||||
|
||||
// Chien-Shiung Wu - Chinese-American experimental physicist who made significant contributions to nuclear physics. https://en.wikipedia.org/wiki/Chien-Shiung_Wu
|
||||
"wu",
|
||||
|
||||
// Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. https://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow
|
||||
"yalow",
|
||||
|
||||
// Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. https://en.wikipedia.org/wiki/Ada_Yonath
|
||||
"yonath",
|
||||
|
||||
// Nikolay Yegorovich Zhukovsky (Russian: Никола́й Его́рович Жуко́вский, January 17 1847 – March 17, 1921) was a Russian scientist, mathematician and engineer, and a founding father of modern aero- and hydrodynamics. Whereas contemporary scientists scoffed at the idea of human flight, Zhukovsky was the first to undertake the study of airflow. He is often called the Father of Russian Aviation. https://en.wikipedia.org/wiki/Nikolay_Yegorovich_Zhukovsky
|
||||
"zhukovsky",
|
||||
)
|
||||
|
||||
fun generateRandomName(): String {
|
||||
return "${left.random()}_${right.random()}"
|
||||
}
|
330
src/main/kotlin/Utils.kt
Normal file
330
src/main/kotlin/Utils.kt
Normal file
@ -0,0 +1,330 @@
|
||||
package net.lamgc.scext.oraclemanager
|
||||
|
||||
import com.google.common.base.Strings
|
||||
import com.google.common.cache.Cache
|
||||
import com.google.common.cache.CacheBuilder
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.annotations.SerializedName
|
||||
import com.oracle.bmc.ConfigFileReader.ConfigFile
|
||||
import com.oracle.bmc.OCID
|
||||
import com.oracle.bmc.Region
|
||||
import com.oracle.bmc.auth.AuthenticationDetailsProvider
|
||||
import org.apache.hc.core5.http.HttpEntityContainer
|
||||
import org.apache.hc.core5.http.HttpResponse
|
||||
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo
|
||||
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
|
||||
import org.bouncycastle.openssl.jcajce.JcaPKCS8Generator
|
||||
import org.bouncycastle.util.io.pem.PemWriter
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot
|
||||
import org.telegram.abilitybots.api.sender.MessageSender
|
||||
import org.telegram.abilitybots.api.sender.SilentSender
|
||||
import org.telegram.telegrambots.meta.api.methods.BotApiMethod
|
||||
import org.telegram.telegrambots.meta.api.methods.GetFile
|
||||
import org.telegram.telegrambots.meta.api.objects.CallbackQuery
|
||||
import org.telegram.telegrambots.meta.api.objects.Update
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup.InlineKeyboardMarkupBuilder
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton
|
||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton.InlineKeyboardButtonBuilder
|
||||
import org.telegram.telegrambots.meta.bots.AbsSender
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.io.StringWriter
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.security.KeyFactory
|
||||
import java.security.MessageDigest
|
||||
import java.security.PrivateKey
|
||||
import java.security.interfaces.RSAPrivateCrtKey
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import java.security.spec.RSAPublicKeySpec
|
||||
import java.util.*
|
||||
import java.util.concurrent.ThreadLocalRandom
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import java.util.regex.Pattern
|
||||
|
||||
fun BaseAbilityBot.getFileUrl(fileId: String, apiServer: String = "https://api.telegram.org"): String {
|
||||
val file = execute(GetFile(fileId))
|
||||
return "$apiServer/file/bot${botToken}/${file.filePath}"
|
||||
}
|
||||
|
||||
fun <T : HttpResponse> T.isSuccess(): Boolean = code == 200
|
||||
|
||||
fun <T : HttpResponse> T.hasContent(): Boolean = this is HttpEntityContainer
|
||||
|
||||
fun <T : AuthenticationDetailsProvider> T.validate(): Boolean {
|
||||
return !Strings.isNullOrEmpty(userId) &&
|
||||
!Strings.isNullOrEmpty(tenantId) &&
|
||||
!Strings.isNullOrEmpty(fingerprint)
|
||||
}
|
||||
|
||||
private val fingerprintCheckPattern = Pattern.compile("^[\\da-zA-Z]{2}(:[\\da-zA-Z]{2}){15}\$")
|
||||
|
||||
fun ConfigFile.validate(requireKeyPath: Boolean = false): Boolean {
|
||||
val result = OCID.isValid(this["user"]) &&
|
||||
OCID.isValid(this["tenancy"]) &&
|
||||
this["fingerprint"] != null &&
|
||||
fingerprintCheckPattern.matcher(this["fingerprint"]).matches()
|
||||
this["region"] != null &&
|
||||
(!requireKeyPath || this["key_file"] != null)
|
||||
if (result) {
|
||||
try {
|
||||
Region.fromRegionId(this["region"])
|
||||
return true
|
||||
} catch (_: IllegalArgumentException) {
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun ConfigFile.toOracleAccountProfile(telegramUserId: Long, name: String = generateRandomName()): OracleAccountProfile {
|
||||
if (!validate()) {
|
||||
throw IllegalStateException("Invalid BMC ConfigFile")
|
||||
}
|
||||
return OracleAccountProfile(
|
||||
this["user"],
|
||||
this["tenancy"],
|
||||
this["region"],
|
||||
clearFingerprintSeparator(this["fingerprint"]),
|
||||
telegramUserId,
|
||||
name
|
||||
)
|
||||
}
|
||||
|
||||
private fun clearFingerprintSeparator(source: String): String {
|
||||
return source.replace(":", "")
|
||||
}
|
||||
|
||||
fun Boolean.not(action: () -> Unit) {
|
||||
if (!this) {
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
private const val BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----"
|
||||
private const val END_PRIVATE_KEY = "-----END PRIVATE KEY-----"
|
||||
|
||||
fun loadPkcs8PrivateKeyFromStream(input: InputStream): PrivateKey {
|
||||
val pemContent = input.readAllBytes()
|
||||
.toString(StandardCharsets.UTF_8)
|
||||
.trim { it == '\n' || it == '\r' || it == ' ' }
|
||||
if (!pemContent.startsWith(BEGIN_PRIVATE_KEY) ||
|
||||
!pemContent.endsWith(END_PRIVATE_KEY)
|
||||
) {
|
||||
throw IllegalArgumentException("Incorrect private key format.")
|
||||
}
|
||||
|
||||
val keyString = pemContent
|
||||
.replace(BEGIN_PRIVATE_KEY, "")
|
||||
.replace(END_PRIVATE_KEY, "")
|
||||
.replace("\n", "")
|
||||
.replace("\r", "")
|
||||
val keyBytes = Base64.getDecoder().decode(keyString)
|
||||
return KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(keyBytes))
|
||||
}
|
||||
|
||||
fun getKeyPairFingerprint(privateKey: RSAPrivateCrtKey, separator: String = ""): String {
|
||||
val keySpec = RSAPublicKeySpec(privateKey.modulus, privateKey.publicExponent)
|
||||
val keyFactory = KeyFactory.getInstance("RSA")
|
||||
val publicKey = keyFactory.generatePublic(keySpec)
|
||||
val digest = MessageDigest.getInstance("MD5")
|
||||
val digestBytes = digest.digest(publicKey.encoded)
|
||||
return digestBytes.joinToString(separator = separator) { eachByte -> "%02x".format(eachByte) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 PrivateKeyInfo 转换成 PrivateKey.
|
||||
* @param info 要转换的 PrivateKeyInfo.
|
||||
* @return 从 PrivateKeyInfo 转换出来的 PrivateKey 对象.
|
||||
*/
|
||||
private fun privateKeyInfoToPrivateKey(info: PrivateKeyInfo): PrivateKey = JcaPEMKeyConverter().getPrivateKey(info)
|
||||
|
||||
fun <T : PrivateKey> T.toPemString(): String {
|
||||
val writer = StringWriter()
|
||||
val pemWriter = PemWriter(writer)
|
||||
pemWriter.writeObject(JcaPKCS8Generator(this, null))
|
||||
pemWriter.flush()
|
||||
return writer.toString()
|
||||
}
|
||||
|
||||
private val internalDataDirectory = AtomicReference<File>()
|
||||
|
||||
var dataDirectory: File
|
||||
set(value) {
|
||||
internalDataDirectory.compareAndSet(null, value)
|
||||
}
|
||||
get() = internalDataDirectory.get()
|
||||
|
||||
class InlineKeyboardGroupBuilder {
|
||||
private val builder = InlineKeyboardMarkup.builder()
|
||||
|
||||
fun configure(block: InlineKeyboardMarkupBuilder.() -> Unit): InlineKeyboardGroupBuilder {
|
||||
builder.block()
|
||||
return this
|
||||
}
|
||||
|
||||
fun newRow(): InlineKeyboardRowBuilder {
|
||||
return InlineKeyboardRowBuilder(this)
|
||||
}
|
||||
|
||||
fun addRow(row: List<InlineKeyboardButton>) {
|
||||
builder.keyboardRow(row)
|
||||
}
|
||||
|
||||
fun build(): InlineKeyboardMarkup = builder.build()
|
||||
}
|
||||
|
||||
class InlineKeyboardRowBuilder(private val groupBuilder: InlineKeyboardGroupBuilder) {
|
||||
|
||||
private val row = mutableListOf<InlineKeyboardButton>()
|
||||
|
||||
fun addButton(button: InlineKeyboardButton): InlineKeyboardRowBuilder {
|
||||
row.add(button)
|
||||
return this
|
||||
}
|
||||
|
||||
fun addButton(buttonBuilder: InlineKeyboardButtonBuilder): InlineKeyboardRowBuilder {
|
||||
addButton(buttonBuilder.build())
|
||||
return this
|
||||
}
|
||||
|
||||
fun addButton(apply: InlineKeyboardButtonBuilder.() -> Unit): InlineKeyboardRowBuilder {
|
||||
val builder = InlineKeyboardButton.builder()
|
||||
builder.apply()
|
||||
addButton(builder)
|
||||
return this
|
||||
}
|
||||
|
||||
fun then(): InlineKeyboardGroupBuilder {
|
||||
groupBuilder.addRow(row)
|
||||
return groupBuilder
|
||||
}
|
||||
|
||||
fun newRow(): InlineKeyboardRowBuilder {
|
||||
return then().newRow()
|
||||
}
|
||||
|
||||
fun build(): InlineKeyboardMarkup {
|
||||
return then().build()
|
||||
}
|
||||
}
|
||||
|
||||
val CallbackQuery.callbackData: InlineKeyboardCallback
|
||||
get() {
|
||||
val refJson = gson.fromJson(data, JsonObject::class.java)
|
||||
return if (refJson.has("rcode") && refJson.get("rcode").isJsonPrimitive) {
|
||||
val refCode = refJson.get("rcode").asString
|
||||
callbackCache.getIfPresent(refCode) ?: throw IllegalStateException("CallbackData has expired.")
|
||||
} else {
|
||||
throw IllegalStateException("RefCode is invalid.")
|
||||
}
|
||||
}
|
||||
|
||||
val CallbackQuery.callbackDataOrNull: InlineKeyboardCallback?
|
||||
get() {
|
||||
return try {
|
||||
callbackData
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun callbackQueryAt(actionName: String): (Update) -> Boolean {
|
||||
return {
|
||||
it.hasCallbackQuery() && it.callbackQuery.callbackDataOrNull != null &&
|
||||
actionName == it.callbackQuery.callbackData.action
|
||||
}
|
||||
}
|
||||
|
||||
private val callbackCache: Cache<String, InlineKeyboardCallback> = CacheBuilder.newBuilder()
|
||||
.expireAfterAccess(30, TimeUnit.MINUTES)
|
||||
.build()
|
||||
|
||||
fun InlineKeyboardButtonBuilder.callbackData(callback: InlineKeyboardCallback): InlineKeyboardButtonBuilder {
|
||||
val cacheReferenceCode = ThreadLocalRandom.current().randomString(32)
|
||||
callbackCache.put(cacheReferenceCode, callback)
|
||||
callbackData("{\"rcode\":\"$cacheReferenceCode\"}")
|
||||
return this
|
||||
}
|
||||
|
||||
fun InlineKeyboardButtonBuilder.callbackData(action: String, extraData: String? = null): InlineKeyboardButtonBuilder {
|
||||
callbackData(InlineKeyboardCallback(action, extraData))
|
||||
return this
|
||||
}
|
||||
|
||||
fun createPromptKeyboard(
|
||||
yesCallback: InlineKeyboardCallback,
|
||||
noCallback: InlineKeyboardCallback,
|
||||
yesMsg: String = "确认",
|
||||
noMsg: String = "取消"
|
||||
): InlineKeyboardMarkup {
|
||||
return InlineKeyboardGroupBuilder()
|
||||
.newRow()
|
||||
.addButton {
|
||||
text(yesMsg)
|
||||
callbackData(yesCallback)
|
||||
}
|
||||
.newRow()
|
||||
.addButton {
|
||||
text(noMsg)
|
||||
callbackData(noCallback)
|
||||
}
|
||||
.build()
|
||||
}
|
||||
|
||||
fun <T : java.io.Serializable, Method : BotApiMethod<T>, Sender : AbsSender> Method.execute(sender: Sender): T {
|
||||
return sender.execute(this)
|
||||
}
|
||||
|
||||
fun <T : java.io.Serializable, Method : BotApiMethod<T>, Sender : MessageSender> Method.execute(sender: Sender): T {
|
||||
return sender.execute(this)
|
||||
}
|
||||
|
||||
fun <T : java.io.Serializable, Method : BotApiMethod<T>, Sender : SilentSender> Method.execute(sender: Sender): Optional<T>? {
|
||||
return sender.execute(this)
|
||||
}
|
||||
|
||||
val gson = Gson()
|
||||
|
||||
@Suppress("MemberVisibilityCanBePrivate")
|
||||
data class InlineKeyboardCallback(
|
||||
@SerializedName("a") val action: String,
|
||||
@SerializedName("d") val extraData: String? = null
|
||||
) {
|
||||
|
||||
fun toJson(): String {
|
||||
return gson.toJson(this)
|
||||
}
|
||||
|
||||
fun next(newAction: String, newExtraData: String? = null): InlineKeyboardCallback {
|
||||
return InlineKeyboardCallback(newAction, newExtraData ?: this.extraData)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun fromJson(json: String): InlineKeyboardCallback {
|
||||
return gson.fromJson(json, InlineKeyboardCallback::class.java)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getStatsName(action: String, subActonName: String): String {
|
||||
return "$action::action::$subActonName"
|
||||
}
|
||||
|
||||
fun Random.randomString(length: Int): String {
|
||||
val builder = StringBuilder()
|
||||
for (i in 1..length) {
|
||||
val charNumber = nextInt(62)
|
||||
val char = when (charNumber) {
|
||||
in 0..25 -> (charNumber + 65)
|
||||
in 26..51 -> (charNumber % 26 + 97)
|
||||
else -> (charNumber - 52 + 48)
|
||||
}.toChar()
|
||||
builder.append(char)
|
||||
}
|
||||
return builder.toString()
|
||||
}
|
||||
|
@ -0,0 +1 @@
|
||||
net.lamgc.scext.oraclemanager.ExtensionFactory
|
Loading…
Reference in New Issue
Block a user