initial commit
This commit is contained in:
2
.gitattributes
vendored
Normal file
2
.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/mvnw text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
33
.gitignore
vendored
Normal file
33
.gitignore
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
HELP.md
|
||||
target/
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
3
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
3
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
|
||||
1381
APIforIMS.md
Normal file
1381
APIforIMS.md
Normal file
File diff suppressed because it is too large
Load Diff
295
mvnw
vendored
Normal file
295
mvnw
vendored
Normal file
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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
|
||||
#
|
||||
# http://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.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
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"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
189
mvnw.cmd
vendored
Normal file
189
mvnw.cmd
vendored
Normal file
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
108
pom.xml
Normal file
108
pom.xml
Normal file
@@ -0,0 +1,108 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.1.0</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.rit</groupId>
|
||||
<artifactId>whatsapp-bot</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>whatsapp-bot</name>
|
||||
<description/>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-compile</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>default-testCompile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
13
src/main/java/com/rit/whatsapp/WhatsappBotApplication.java
Normal file
13
src/main/java/com/rit/whatsapp/WhatsappBotApplication.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.rit.whatsapp;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class WhatsappBotApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WhatsappBotApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
178
src/main/java/com/rit/whatsapp/controller/WebhookController.java
Normal file
178
src/main/java/com/rit/whatsapp/controller/WebhookController.java
Normal file
@@ -0,0 +1,178 @@
|
||||
package com.rit.whatsapp.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rit.whatsapp.handler.GrievanceHandler;
|
||||
import com.rit.whatsapp.handler.LoginHandler;
|
||||
import com.rit.whatsapp.handler.StudentMenuHandler;
|
||||
import com.rit.whatsapp.model.UserState;
|
||||
import com.rit.whatsapp.service.SessionService;
|
||||
import com.rit.whatsapp.service.WhatsAppMessageService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/webhook")
|
||||
public class WebhookController {
|
||||
|
||||
@Value("${whatsapp.verify-token:my_secure_verify_token}")
|
||||
private String verifyToken;
|
||||
|
||||
private final WhatsAppMessageService messageService;
|
||||
private final SessionService sessionService;
|
||||
private final StudentMenuHandler studentMenuHandler;
|
||||
private final GrievanceHandler grievanceHandler;
|
||||
private final LoginHandler loginHandler;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
public WebhookController(WhatsAppMessageService messageService,
|
||||
SessionService sessionService,
|
||||
StudentMenuHandler studentMenuHandler,
|
||||
GrievanceHandler grievanceHandler,
|
||||
LoginHandler loginHandler) {
|
||||
this.messageService = messageService;
|
||||
this.sessionService = sessionService;
|
||||
this.studentMenuHandler = studentMenuHandler;
|
||||
this.grievanceHandler = grievanceHandler;
|
||||
this.loginHandler = loginHandler;
|
||||
this.objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<String> verifyWebhook(
|
||||
@RequestParam(name = "hub.mode", required = false) String mode,
|
||||
@RequestParam(name = "hub.verify_token", required = false) String token,
|
||||
@RequestParam(name = "hub.challenge", required = false) String challenge) {
|
||||
|
||||
if ("subscribe".equals(mode) && verifyToken.equals(token)) {
|
||||
return ResponseEntity.ok(challenge);
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<String> receiveMessage(@RequestBody String payload) {
|
||||
System.out.println("Received Webhook Payload: " + payload);
|
||||
try {
|
||||
JsonNode rootNode = objectMapper.readTree(payload);
|
||||
|
||||
if (rootNode.has("entry") && rootNode.get("entry").isArray()) {
|
||||
JsonNode entryNode = rootNode.get("entry").get(0);
|
||||
|
||||
if (entryNode.has("changes") && entryNode.get("changes").isArray()) {
|
||||
JsonNode changesNode = entryNode.get("changes").get(0);
|
||||
JsonNode valueNode = changesNode.get("value");
|
||||
|
||||
if (valueNode != null && valueNode.has("messages") && valueNode.get("messages").isArray()) {
|
||||
JsonNode messageNode = valueNode.get("messages").get(0);
|
||||
|
||||
String fromPhoneNumber = messageNode.get("from").asText();
|
||||
String messageType = messageNode.get("type").asText();
|
||||
|
||||
UserState currentState = sessionService.getUserState(fromPhoneNumber);
|
||||
boolean isAuthenticated = sessionService.isAuthenticated(fromPhoneNumber);
|
||||
|
||||
// Global reset command
|
||||
if ("text".equals(messageType) && messageNode.get("text").get("body").asText().trim().equalsIgnoreCase("reset")) {
|
||||
sessionService.resetState(fromPhoneNumber);
|
||||
if (isAuthenticated) {
|
||||
studentMenuHandler.sendMainMenu(fromPhoneNumber);
|
||||
} else {
|
||||
loginHandler.startLoginFlow(fromPhoneNumber);
|
||||
}
|
||||
return ResponseEntity.ok("EVENT_RECEIVED");
|
||||
}
|
||||
|
||||
// Route unauthenticated users strictly to Login Flow
|
||||
if (!isAuthenticated) {
|
||||
if ("text".equals(messageType)) {
|
||||
String body = messageNode.get("text").get("body").asText();
|
||||
handleUnauthenticatedUser(fromPhoneNumber, body, currentState);
|
||||
} else {
|
||||
// If they send a sticker/image/etc before logging in, force login
|
||||
handleUnauthenticatedUser(fromPhoneNumber, "", currentState);
|
||||
}
|
||||
return ResponseEntity.ok("EVENT_RECEIVED");
|
||||
}
|
||||
|
||||
// Authenticated users flow
|
||||
if ("text".equals(messageType)) {
|
||||
String messageBody = messageNode.get("text").get("body").asText();
|
||||
handleAuthenticatedTextMessage(fromPhoneNumber, messageBody, currentState);
|
||||
} else if ("interactive".equals(messageType)) {
|
||||
JsonNode interactiveNode = messageNode.get("interactive");
|
||||
String interactiveType = interactiveNode.get("type").asText();
|
||||
|
||||
if ("list_reply".equals(interactiveType)) {
|
||||
String selectedListId = interactiveNode.get("list_reply").get("id").asText();
|
||||
handleInteractiveListSelection(fromPhoneNumber, selectedListId, currentState);
|
||||
} else if ("button_reply".equals(interactiveType)) {
|
||||
String selectedButtonId = interactiveNode.get("button_reply").get("id").asText();
|
||||
handleInteractiveButtonSelection(fromPhoneNumber, selectedButtonId, currentState);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error processing webhook payload: " + e.getMessage());
|
||||
}
|
||||
|
||||
return ResponseEntity.ok("EVENT_RECEIVED");
|
||||
}
|
||||
|
||||
private void handleUnauthenticatedUser(String phoneNumber, String messageBody, UserState currentState) {
|
||||
switch (currentState) {
|
||||
case AWAITING_LOGIN_ID:
|
||||
loginHandler.handleLoginIdInput(phoneNumber, messageBody);
|
||||
break;
|
||||
case AWAITING_LOGIN_PASSCODE:
|
||||
loginHandler.handlePasscodeInput(phoneNumber, messageBody);
|
||||
break;
|
||||
default:
|
||||
// Trigger the start of the login flow
|
||||
loginHandler.startLoginFlow(phoneNumber);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleAuthenticatedTextMessage(String phoneNumber, String messageBody, UserState currentState) {
|
||||
switch (currentState) {
|
||||
case AWAITING_GRIEVANCE_DESC:
|
||||
grievanceHandler.handleGrievanceDescription(phoneNumber, messageBody);
|
||||
break;
|
||||
case MAIN_MENU:
|
||||
default:
|
||||
// Fallback to main menu
|
||||
studentMenuHandler.sendMainMenu(phoneNumber);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleInteractiveListSelection(String phoneNumber, String selectedListId, UserState currentState) {
|
||||
if (currentState == UserState.MAIN_MENU) {
|
||||
studentMenuHandler.handleMenuSelection(phoneNumber, selectedListId);
|
||||
} else {
|
||||
studentMenuHandler.sendMainMenu(phoneNumber);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleInteractiveButtonSelection(String phoneNumber, String selectedButtonId, UserState currentState) {
|
||||
if ("student_logout".equals(selectedButtonId)) {
|
||||
sessionService.logoutUser(phoneNumber);
|
||||
messageService.sendMessage(phoneNumber, "You have been logged out successfully. Type 'Hi' to log in again.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentState == UserState.AWAITING_GRIEVANCE_CATEGORY) {
|
||||
grievanceHandler.handleCategorySelection(phoneNumber, selectedButtonId);
|
||||
} else {
|
||||
studentMenuHandler.sendMainMenu(phoneNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
71
src/main/java/com/rit/whatsapp/handler/GrievanceHandler.java
Normal file
71
src/main/java/com/rit/whatsapp/handler/GrievanceHandler.java
Normal file
@@ -0,0 +1,71 @@
|
||||
package com.rit.whatsapp.handler;
|
||||
|
||||
import com.rit.whatsapp.model.UserState;
|
||||
import com.rit.whatsapp.service.SessionService;
|
||||
import com.rit.whatsapp.service.WhatsAppMessageBuilder;
|
||||
import com.rit.whatsapp.service.WhatsAppMessageService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class GrievanceHandler {
|
||||
|
||||
private final WhatsAppMessageService messageService;
|
||||
private final SessionService sessionService;
|
||||
|
||||
@Autowired
|
||||
public GrievanceHandler(WhatsAppMessageService messageService, SessionService sessionService) {
|
||||
this.messageService = messageService;
|
||||
this.sessionService = sessionService;
|
||||
}
|
||||
|
||||
public void startGrievanceFlow(String phoneNumber) {
|
||||
sessionService.setUserState(phoneNumber, UserState.AWAITING_GRIEVANCE_CATEGORY);
|
||||
|
||||
List<Map<String, String>> buttons = new ArrayList<>();
|
||||
buttons.add(createButton("grievance_academic", "Academic"));
|
||||
buttons.add(createButton("grievance_hostel", "Hostel"));
|
||||
buttons.add(createButton("grievance_other", "Other"));
|
||||
|
||||
Map<String, Object> buttonMessage = WhatsAppMessageBuilder.buildButtonMessage(
|
||||
"Please select the category for your grievance:",
|
||||
buttons
|
||||
);
|
||||
|
||||
messageService.sendInteractiveMessage(phoneNumber, buttonMessage);
|
||||
}
|
||||
|
||||
public void handleCategorySelection(String phoneNumber, String selectedCategory) {
|
||||
sessionService.setUserState(phoneNumber, UserState.AWAITING_GRIEVANCE_DESC);
|
||||
messageService.sendMessage(phoneNumber, "You selected " + selectedCategory + ". Please type a brief description of your issue:");
|
||||
}
|
||||
|
||||
public void handleGrievanceDescription(String phoneNumber, String description) {
|
||||
// Generate a mock ticket ID
|
||||
String ticketId = "TKT-" + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
|
||||
|
||||
String confirmationMessage = "Thank you. Your grievance has been recorded.\n\n" +
|
||||
"Ticket ID: *" + ticketId + "*\n" +
|
||||
"Department Notified: Yes\n" +
|
||||
"Status: Open\n\n" +
|
||||
"You can check the status of this ticket anytime using the main menu.";
|
||||
|
||||
messageService.sendMessage(phoneNumber, confirmationMessage);
|
||||
|
||||
// Reset state back to main menu
|
||||
sessionService.resetState(phoneNumber);
|
||||
}
|
||||
|
||||
private Map<String, String> createButton(String id, String title) {
|
||||
Map<String, String> btn = new HashMap<>();
|
||||
btn.put("id", id);
|
||||
btn.put("title", title);
|
||||
return btn;
|
||||
}
|
||||
}
|
||||
64
src/main/java/com/rit/whatsapp/handler/LoginHandler.java
Normal file
64
src/main/java/com/rit/whatsapp/handler/LoginHandler.java
Normal file
@@ -0,0 +1,64 @@
|
||||
package com.rit.whatsapp.handler;
|
||||
|
||||
import com.rit.whatsapp.model.UserState;
|
||||
import com.rit.whatsapp.service.ImsApiService;
|
||||
import com.rit.whatsapp.service.SessionService;
|
||||
import com.rit.whatsapp.service.WhatsAppMessageService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class LoginHandler {
|
||||
|
||||
private final WhatsAppMessageService messageService;
|
||||
private final SessionService sessionService;
|
||||
private final ImsApiService imsApiService;
|
||||
private final StudentMenuHandler studentMenuHandler;
|
||||
|
||||
@Autowired
|
||||
public LoginHandler(WhatsAppMessageService messageService,
|
||||
SessionService sessionService,
|
||||
ImsApiService imsApiService,
|
||||
StudentMenuHandler studentMenuHandler) {
|
||||
this.messageService = messageService;
|
||||
this.sessionService = sessionService;
|
||||
this.imsApiService = imsApiService;
|
||||
this.studentMenuHandler = studentMenuHandler;
|
||||
}
|
||||
|
||||
public void startLoginFlow(String phoneNumber) {
|
||||
sessionService.setUserState(phoneNumber, UserState.AWAITING_LOGIN_ID);
|
||||
messageService.sendMessage(phoneNumber, "Welcome to RIT Digital Assistant! 🎓\n\nPlease enter your IMS User ID to login:");
|
||||
}
|
||||
|
||||
public void handleLoginIdInput(String phoneNumber, String imsId) {
|
||||
sessionService.setTempLoginId(phoneNumber, imsId);
|
||||
sessionService.setUserState(phoneNumber, UserState.AWAITING_LOGIN_PASSCODE);
|
||||
messageService.sendMessage(phoneNumber, "Thanks. Now, please enter your IMS Passcode:");
|
||||
}
|
||||
|
||||
public void handlePasscodeInput(String phoneNumber, String passcode) {
|
||||
String imsId = sessionService.getTempLoginId(phoneNumber);
|
||||
|
||||
messageService.sendMessage(phoneNumber, "Authenticating with IMS... ⏳");
|
||||
|
||||
String imsSessionToken = imsApiService.authenticate(imsId, passcode);
|
||||
|
||||
if (imsSessionToken != null) {
|
||||
// Authentication successful
|
||||
sessionService.authenticateUser(phoneNumber, imsId, passcode, imsSessionToken);
|
||||
sessionService.clearTempLoginId(phoneNumber);
|
||||
sessionService.resetState(phoneNumber); // Reset the flow state
|
||||
|
||||
messageService.sendMessage(phoneNumber, "✅ Login Successful!");
|
||||
|
||||
// Show the main menu
|
||||
studentMenuHandler.sendMainMenu(phoneNumber);
|
||||
} else {
|
||||
// Authentication failed
|
||||
sessionService.clearTempLoginId(phoneNumber);
|
||||
sessionService.setUserState(phoneNumber, UserState.AWAITING_LOGIN_ID);
|
||||
messageService.sendMessage(phoneNumber, "❌ Login Failed. Invalid ID or Passcode. Please try again.\n\nEnter your IMS User ID:");
|
||||
}
|
||||
}
|
||||
}
|
||||
117
src/main/java/com/rit/whatsapp/handler/StudentMenuHandler.java
Normal file
117
src/main/java/com/rit/whatsapp/handler/StudentMenuHandler.java
Normal file
@@ -0,0 +1,117 @@
|
||||
package com.rit.whatsapp.handler;
|
||||
|
||||
import com.rit.whatsapp.model.UserState;
|
||||
import com.rit.whatsapp.service.ImsApiService;
|
||||
import com.rit.whatsapp.service.SessionService;
|
||||
import com.rit.whatsapp.service.WhatsAppMessageBuilder;
|
||||
import com.rit.whatsapp.service.WhatsAppMessageService;
|
||||
import com.rit.whatsapp.util.MessageFormatter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class StudentMenuHandler {
|
||||
|
||||
private final WhatsAppMessageService messageService;
|
||||
private final SessionService sessionService;
|
||||
private final GrievanceHandler grievanceHandler;
|
||||
private final ImsApiService imsApiService;
|
||||
|
||||
@Autowired
|
||||
public StudentMenuHandler(WhatsAppMessageService messageService,
|
||||
SessionService sessionService,
|
||||
GrievanceHandler grievanceHandler,
|
||||
ImsApiService imsApiService) {
|
||||
this.messageService = messageService;
|
||||
this.sessionService = sessionService;
|
||||
this.grievanceHandler = grievanceHandler;
|
||||
this.imsApiService = imsApiService;
|
||||
}
|
||||
|
||||
public void sendMainMenu(String phoneNumber) {
|
||||
sessionService.setUserState(phoneNumber, UserState.MAIN_MENU);
|
||||
|
||||
List<Map<String, String>> rows = new ArrayList<>();
|
||||
rows.add(createRow("student_attendance", "Attendance", "Overall % and Subject-wise"));
|
||||
rows.add(createRow("student_timetable", "Timetable", "Today's classes and Weekly"));
|
||||
rows.add(createRow("student_internal_marks", "Internal marks", "CAT 1, CAT 2, Overall"));
|
||||
rows.add(createRow("student_semester_results", "Semester results", "Latest result and CGPA"));
|
||||
rows.add(createRow("student_fee_details", "Fee details & receipt", "Fee paid, Pending, Due date"));
|
||||
rows.add(createRow("student_academic_calendar", "Academic calendar", "Holidays and Important dates"));
|
||||
rows.add(createRow("student_exam_schedule", "Exam schedule", "Upcoming exams and Hall details"));
|
||||
rows.add(createRow("student_circulars", "Circulars & Notices", "Department circulars"));
|
||||
rows.add(createRow("student_raise_grievance", "Raise a grievance \u2B50", "Submit an issue ticket"));
|
||||
rows.add(createRow("student_contact_department", "Contact department", "Faculty mentor, HOD, etc."));
|
||||
|
||||
Map<String, Object> interactiveList = WhatsAppMessageBuilder.buildListMessage(
|
||||
"RIT Digital Assistant",
|
||||
"Welcome to the RITz Student Portal! Please select an option from the menu below.",
|
||||
"Student Menu",
|
||||
rows
|
||||
);
|
||||
|
||||
messageService.sendInteractiveMessage(phoneNumber, interactiveList);
|
||||
|
||||
// Send a separate Logout button since the list is maxed out at 10 items
|
||||
List<Map<String, String>> logoutBtn = new ArrayList<>();
|
||||
Map<String, String> btn = new HashMap<>();
|
||||
btn.put("id", "student_logout");
|
||||
btn.put("title", "Logout");
|
||||
logoutBtn.add(btn);
|
||||
|
||||
Map<String, Object> logoutMessage = WhatsAppMessageBuilder.buildButtonMessage(
|
||||
"Need to switch accounts?",
|
||||
logoutBtn
|
||||
);
|
||||
messageService.sendInteractiveMessage(phoneNumber, logoutMessage);
|
||||
}
|
||||
|
||||
public void handleMenuSelection(String phoneNumber, String selectedOptionId) {
|
||||
String token = sessionService.getImsToken(phoneNumber);
|
||||
if (token == null) {
|
||||
messageService.sendMessage(phoneNumber, "Your session has expired. Please type 'Reset' to login again.");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (selectedOptionId) {
|
||||
case "student_attendance":
|
||||
String rawAttendance = imsApiService.getAttendance(token);
|
||||
messageService.sendMessage(phoneNumber, MessageFormatter.formatAttendance(rawAttendance));
|
||||
break;
|
||||
|
||||
case "student_timetable":
|
||||
String rawTimetable = imsApiService.getTimetable(token);
|
||||
messageService.sendMessage(phoneNumber, MessageFormatter.formatTimetable(rawTimetable));
|
||||
break;
|
||||
|
||||
case "student_semester_results":
|
||||
// Defaulting to semester 1 for now
|
||||
String rawResults = imsApiService.getResults(token, 1);
|
||||
messageService.sendMessage(phoneNumber, MessageFormatter.formatResults(rawResults, 1));
|
||||
break;
|
||||
|
||||
case "student_raise_grievance":
|
||||
grievanceHandler.startGrievanceFlow(phoneNumber);
|
||||
break;
|
||||
|
||||
default:
|
||||
messageService.sendMessage(phoneNumber, "You selected an option that is currently under development. Please check back later!");
|
||||
// Resend main menu
|
||||
sendMainMenu(phoneNumber);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> createRow(String id, String title, String description) {
|
||||
Map<String, String> row = new HashMap<>();
|
||||
row.put("id", id);
|
||||
row.put("title", title);
|
||||
row.put("description", description);
|
||||
return row;
|
||||
}
|
||||
}
|
||||
50
src/main/java/com/rit/whatsapp/model/UserEntity.java
Normal file
50
src/main/java/com/rit/whatsapp/model/UserEntity.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.rit.whatsapp.model;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity {
|
||||
|
||||
@Id
|
||||
private String phoneNumber;
|
||||
|
||||
private String imsId;
|
||||
|
||||
private String encryptedPasscode;
|
||||
|
||||
public UserEntity() {
|
||||
}
|
||||
|
||||
public UserEntity(String phoneNumber, String imsId, String encryptedPasscode) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.imsId = imsId;
|
||||
this.encryptedPasscode = encryptedPasscode;
|
||||
}
|
||||
|
||||
public String getPhoneNumber() {
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public String getImsId() {
|
||||
return imsId;
|
||||
}
|
||||
|
||||
public void setImsId(String imsId) {
|
||||
this.imsId = imsId;
|
||||
}
|
||||
|
||||
public String getEncryptedPasscode() {
|
||||
return encryptedPasscode;
|
||||
}
|
||||
|
||||
public void setEncryptedPasscode(String encryptedPasscode) {
|
||||
this.encryptedPasscode = encryptedPasscode;
|
||||
}
|
||||
}
|
||||
9
src/main/java/com/rit/whatsapp/model/UserState.java
Normal file
9
src/main/java/com/rit/whatsapp/model/UserState.java
Normal file
@@ -0,0 +1,9 @@
|
||||
package com.rit.whatsapp.model;
|
||||
|
||||
public enum UserState {
|
||||
MAIN_MENU,
|
||||
AWAITING_LOGIN_ID,
|
||||
AWAITING_LOGIN_PASSCODE,
|
||||
AWAITING_GRIEVANCE_CATEGORY,
|
||||
AWAITING_GRIEVANCE_DESC
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.rit.whatsapp.repository;
|
||||
|
||||
import com.rit.whatsapp.model.UserEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<UserEntity, String> {
|
||||
}
|
||||
105
src/main/java/com/rit/whatsapp/service/ImsApiService.java
Normal file
105
src/main/java/com/rit/whatsapp/service/ImsApiService.java
Normal file
@@ -0,0 +1,105 @@
|
||||
package com.rit.whatsapp.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class ImsApiService {
|
||||
|
||||
private final String BASE_URL = "https://ims-api.sidharthprabhu.co.in";
|
||||
private final RestTemplate restTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ImsApiService() {
|
||||
this.restTemplate = new RestTemplate();
|
||||
this.objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates the user against the real IMS backend.
|
||||
* @param imsId The user ID
|
||||
* @param passcode The passcode
|
||||
* @return The API session token if successful, null otherwise.
|
||||
*/
|
||||
public String authenticate(String imsId, String passcode) {
|
||||
String url = BASE_URL + "/api/auth/login";
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
Map<String, String> requestBody = new HashMap<>();
|
||||
requestBody.put("username", imsId);
|
||||
requestBody.put("password", passcode);
|
||||
|
||||
HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
|
||||
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
|
||||
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
|
||||
JsonNode rootNode = objectMapper.readTree(response.getBody());
|
||||
if (rootNode.has("success") && rootNode.get("success").asBoolean()) {
|
||||
if (rootNode.has("session")) {
|
||||
return rootNode.get("session").asText();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to authenticate with IMS API: " + e.getMessage());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private String fetchFromIms(String endpoint, String token) {
|
||||
String url = BASE_URL + endpoint;
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(token);
|
||||
|
||||
HttpEntity<String> request = new HttpEntity<>(headers);
|
||||
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.exchange(url, org.springframework.http.HttpMethod.GET, request, String.class);
|
||||
if (response.getStatusCode().is2xxSuccessful()) {
|
||||
return response.getBody();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to fetch from IMS API (" + endpoint + "): " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getAttendance(String token) {
|
||||
return fetchFromIms("/api/student/attendance", token);
|
||||
}
|
||||
|
||||
public String getTimetable(String token) {
|
||||
return fetchFromIms("/api/student/timetable", token);
|
||||
}
|
||||
|
||||
public String getResults(String token, int semester) {
|
||||
return fetchFromIms("/api/student/results?semester=" + semester, token);
|
||||
}
|
||||
|
||||
public void logout(String token) {
|
||||
String url = BASE_URL + "/api/auth/logout";
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(token);
|
||||
|
||||
HttpEntity<String> request = new HttpEntity<>(headers);
|
||||
|
||||
try {
|
||||
restTemplate.postForEntity(url, request, String.class);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to logout from IMS API: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
107
src/main/java/com/rit/whatsapp/service/SessionService.java
Normal file
107
src/main/java/com/rit/whatsapp/service/SessionService.java
Normal file
@@ -0,0 +1,107 @@
|
||||
package com.rit.whatsapp.service;
|
||||
|
||||
import com.rit.whatsapp.model.UserEntity;
|
||||
import com.rit.whatsapp.model.UserState;
|
||||
import com.rit.whatsapp.repository.UserRepository;
|
||||
import com.rit.whatsapp.util.EncryptionUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class SessionService {
|
||||
|
||||
private final Map<String, UserState> userStates = new ConcurrentHashMap<>();
|
||||
|
||||
// In-memory cache for API session tokens
|
||||
private final Map<String, String> sessionTokens = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> temporaryLoginIds = new ConcurrentHashMap<>();
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final EncryptionUtils encryptionUtils;
|
||||
private final ImsApiService imsApiService;
|
||||
|
||||
@Autowired
|
||||
public SessionService(UserRepository userRepository,
|
||||
EncryptionUtils encryptionUtils,
|
||||
ImsApiService imsApiService) {
|
||||
this.userRepository = userRepository;
|
||||
this.encryptionUtils = encryptionUtils;
|
||||
this.imsApiService = imsApiService;
|
||||
}
|
||||
|
||||
public UserState getUserState(String phoneNumber) {
|
||||
return userStates.getOrDefault(phoneNumber, UserState.MAIN_MENU);
|
||||
}
|
||||
|
||||
public void setUserState(String phoneNumber, UserState state) {
|
||||
userStates.put(phoneNumber, state);
|
||||
}
|
||||
|
||||
public void resetState(String phoneNumber) {
|
||||
userStates.remove(phoneNumber);
|
||||
}
|
||||
|
||||
public boolean isAuthenticated(String phoneNumber) {
|
||||
if (sessionTokens.containsKey(phoneNumber)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check database for persistent session
|
||||
Optional<UserEntity> userOpt = userRepository.findById(phoneNumber);
|
||||
if (userOpt.isPresent()) {
|
||||
UserEntity user = userOpt.get();
|
||||
String decryptedPasscode = encryptionUtils.decrypt(user.getEncryptedPasscode());
|
||||
|
||||
// Silent background login
|
||||
String token = imsApiService.authenticate(user.getImsId(), decryptedPasscode);
|
||||
if (token != null) {
|
||||
sessionTokens.put(phoneNumber, token);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void authenticateUser(String phoneNumber, String imsId, String passcode, String token) {
|
||||
sessionTokens.put(phoneNumber, token);
|
||||
|
||||
// Persist to database
|
||||
String encryptedPasscode = encryptionUtils.encrypt(passcode);
|
||||
UserEntity user = new UserEntity(phoneNumber, imsId, encryptedPasscode);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
public String getImsToken(String phoneNumber) {
|
||||
// Ensure they are authenticated (which populates the token cache if needed)
|
||||
if (isAuthenticated(phoneNumber)) {
|
||||
return sessionTokens.get(phoneNumber);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void logoutUser(String phoneNumber) {
|
||||
String token = sessionTokens.remove(phoneNumber);
|
||||
if (token != null) {
|
||||
imsApiService.logout(token);
|
||||
}
|
||||
userRepository.deleteById(phoneNumber);
|
||||
resetState(phoneNumber);
|
||||
}
|
||||
|
||||
public void setTempLoginId(String phoneNumber, String tempId) {
|
||||
temporaryLoginIds.put(phoneNumber, tempId);
|
||||
}
|
||||
|
||||
public String getTempLoginId(String phoneNumber) {
|
||||
return temporaryLoginIds.get(phoneNumber);
|
||||
}
|
||||
|
||||
public void clearTempLoginId(String phoneNumber) {
|
||||
temporaryLoginIds.remove(phoneNumber);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.rit.whatsapp.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class WhatsAppMessageBuilder {
|
||||
|
||||
public static Map<String, Object> buildListMessage(String header, String body, String buttonText, List<Map<String, String>> rows) {
|
||||
Map<String, Object> interactive = new HashMap<>();
|
||||
interactive.put("type", "list");
|
||||
|
||||
if (header != null && !header.isEmpty()) {
|
||||
Map<String, Object> headerMap = new HashMap<>();
|
||||
headerMap.put("type", "text");
|
||||
headerMap.put("text", header);
|
||||
interactive.put("header", headerMap);
|
||||
}
|
||||
|
||||
Map<String, Object> bodyMap = new HashMap<>();
|
||||
bodyMap.put("text", body);
|
||||
interactive.put("body", bodyMap);
|
||||
|
||||
Map<String, Object> action = new HashMap<>();
|
||||
action.put("button", buttonText);
|
||||
|
||||
List<Map<String, Object>> sections = new ArrayList<>();
|
||||
Map<String, Object> section = new HashMap<>();
|
||||
section.put("title", "Options"); // Default section title
|
||||
section.put("rows", rows);
|
||||
sections.add(section);
|
||||
|
||||
action.put("sections", sections);
|
||||
interactive.put("action", action);
|
||||
|
||||
return interactive;
|
||||
}
|
||||
|
||||
public static Map<String, Object> buildButtonMessage(String body, List<Map<String, String>> buttons) {
|
||||
Map<String, Object> interactive = new HashMap<>();
|
||||
interactive.put("type", "button");
|
||||
|
||||
Map<String, Object> bodyMap = new HashMap<>();
|
||||
bodyMap.put("text", body);
|
||||
interactive.put("body", bodyMap);
|
||||
|
||||
Map<String, Object> action = new HashMap<>();
|
||||
List<Map<String, Object>> actionButtons = new ArrayList<>();
|
||||
|
||||
for (Map<String, String> btn : buttons) {
|
||||
Map<String, Object> buttonWrapper = new HashMap<>();
|
||||
buttonWrapper.put("type", "reply");
|
||||
Map<String, String> reply = new HashMap<>();
|
||||
reply.put("id", btn.get("id"));
|
||||
reply.put("title", btn.get("title"));
|
||||
buttonWrapper.put("reply", reply);
|
||||
actionButtons.add(buttonWrapper);
|
||||
}
|
||||
|
||||
action.put("buttons", actionButtons);
|
||||
interactive.put("action", action);
|
||||
|
||||
return interactive;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.rit.whatsapp.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class WhatsAppMessageService {
|
||||
|
||||
@Value("${whatsapp.api-token}")
|
||||
private String apiToken;
|
||||
|
||||
@Value("${whatsapp.phone-number-id}")
|
||||
private String phoneNumberId;
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
public WhatsAppMessageService() {
|
||||
this.restTemplate = new RestTemplate();
|
||||
}
|
||||
|
||||
public void sendMessage(String toPhoneNumber, String messageText) {
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("messaging_product", "whatsapp");
|
||||
payload.put("to", toPhoneNumber);
|
||||
payload.put("type", "text");
|
||||
|
||||
Map<String, String> textPayload = new HashMap<>();
|
||||
textPayload.put("body", messageText);
|
||||
payload.put("text", textPayload);
|
||||
|
||||
executePost(payload);
|
||||
}
|
||||
|
||||
public void sendInteractiveMessage(String toPhoneNumber, Map<String, Object> interactiveObject) {
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("messaging_product", "whatsapp");
|
||||
payload.put("to", toPhoneNumber);
|
||||
payload.put("type", "interactive");
|
||||
payload.put("interactive", interactiveObject);
|
||||
|
||||
executePost(payload);
|
||||
}
|
||||
|
||||
private void executePost(Map<String, Object> payload) {
|
||||
String url = "https://graph.facebook.com/v19.0/" + phoneNumberId + "/messages";
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.setBearerAuth(apiToken);
|
||||
|
||||
HttpEntity<Map<String, Object>> request = new HttpEntity<>(payload, headers);
|
||||
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
|
||||
System.out.println("Message sent successfully. Response: " + response.getBody());
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to send message: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
43
src/main/java/com/rit/whatsapp/util/EncryptionUtils.java
Normal file
43
src/main/java/com/rit/whatsapp/util/EncryptionUtils.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package com.rit.whatsapp.util;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
@Component
|
||||
public class EncryptionUtils {
|
||||
|
||||
@Value("${bot.encryption.secret}")
|
||||
private String secretKey;
|
||||
|
||||
private static final String ALGORITHM = "AES";
|
||||
|
||||
public String encrypt(String value) {
|
||||
try {
|
||||
SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key);
|
||||
byte[] encryptedValue = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(encryptedValue);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error encrypting value", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String value) {
|
||||
try {
|
||||
SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.DECRYPT_MODE, key);
|
||||
byte[] decodedValue = Base64.getDecoder().decode(value);
|
||||
byte[] decryptedValue = cipher.doFinal(decodedValue);
|
||||
return new String(decryptedValue, StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error decrypting value", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
104
src/main/java/com/rit/whatsapp/util/MessageFormatter.java
Normal file
104
src/main/java/com/rit/whatsapp/util/MessageFormatter.java
Normal file
@@ -0,0 +1,104 @@
|
||||
package com.rit.whatsapp.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class MessageFormatter {
|
||||
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public static String formatAttendance(String rawJson) {
|
||||
if (rawJson == null) return "❌ Failed to retrieve attendance data.";
|
||||
|
||||
try {
|
||||
JsonNode root = mapper.readTree(rawJson);
|
||||
// Assuming the JSON has an array of subjects or an overall percentage
|
||||
// Since we don't have the exact schema, this is a best-effort template.
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("\ud83d\udcca *Your Attendance Report*\n\n");
|
||||
|
||||
if (root.has("overall_percentage")) {
|
||||
sb.append("*Overall Attendance:* ").append(root.get("overall_percentage").asText()).append("% \ud83d\udfe2\n\n");
|
||||
} else {
|
||||
sb.append("*Overall Attendance:* Data unavailable\n\n");
|
||||
}
|
||||
|
||||
sb.append("*Subject-wise Breakdown:*\n");
|
||||
if (root.has("data") && root.get("data").isArray()) {
|
||||
for (JsonNode subject : root.get("data")) {
|
||||
String name = subject.has("course_name") ? subject.get("course_name").asText() : "Unknown";
|
||||
String percentage = subject.has("percentage") ? subject.get("percentage").asText() : "0";
|
||||
sb.append("- ").append(name).append(": ").append(percentage).append("%\n");
|
||||
}
|
||||
} else {
|
||||
sb.append("- Details not available in this format.\n");
|
||||
}
|
||||
|
||||
sb.append("\n_Keep up the good work!_");
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
return "⚠️ Error formatting attendance data.";
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatTimetable(String rawJson) {
|
||||
if (rawJson == null) return "❌ Failed to retrieve timetable data.";
|
||||
|
||||
try {
|
||||
JsonNode root = mapper.readTree(rawJson);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("\ud83d\uddd3\ufe0f *Today's Classes*\n\n");
|
||||
|
||||
if (root.has("data") && root.get("data").isArray()) {
|
||||
for (JsonNode classNode : root.get("data")) {
|
||||
String time = classNode.has("time") ? classNode.get("time").asText() : "TBA";
|
||||
String course = classNode.has("course_name") ? classNode.get("course_name").asText() : "Unknown";
|
||||
String room = classNode.has("room") ? classNode.get("room").asText() : "Unknown";
|
||||
|
||||
sb.append("*").append(time).append(":* ").append(course).append(" (Room ").append(room).append(")\n");
|
||||
}
|
||||
} else {
|
||||
sb.append("No classes scheduled for today.\n");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
return "⚠️ Error formatting timetable data.";
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatResults(String rawJson, int semester) {
|
||||
if (rawJson == null) return "❌ Failed to retrieve semester results.";
|
||||
|
||||
try {
|
||||
JsonNode root = mapper.readTree(rawJson);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("\ud83c\udf93 *Semester ").append(semester).append(" Results*\n\n");
|
||||
|
||||
boolean passedAll = true;
|
||||
|
||||
if (root.has("data") && root.get("data").isArray()) {
|
||||
for (JsonNode courseNode : root.get("data")) {
|
||||
String name = courseNode.has("course_name") ? courseNode.get("course_name").asText() : "Unknown";
|
||||
String total = courseNode.has("total_mark") ? courseNode.get("total_mark").asText() : "0";
|
||||
String grade = courseNode.has("grade") ? courseNode.get("grade").asText() : "N/A";
|
||||
String result = courseNode.has("result") ? courseNode.get("result").asText() : "N/A";
|
||||
|
||||
if (!"PASS".equalsIgnoreCase(result)) {
|
||||
passedAll = false;
|
||||
}
|
||||
|
||||
sb.append("*").append(name).append(":* ").append(total).append("/100 (Grade: ").append(grade).append(")\n");
|
||||
}
|
||||
} else {
|
||||
sb.append("No results found for this semester.\n");
|
||||
}
|
||||
|
||||
sb.append("\n*Result:* ").append(passedAll ? "PASS \ud83c\udf89" : "Arrears \u26a0\ufe0f");
|
||||
return sb.toString();
|
||||
} catch (Exception e) {
|
||||
return "⚠️ Error formatting results data.";
|
||||
}
|
||||
}
|
||||
}
|
||||
22
src/main/resources/application.properties
Normal file
22
src/main/resources/application.properties
Normal file
@@ -0,0 +1,22 @@
|
||||
spring.application.name=whatsapp-bot
|
||||
server.port=8080
|
||||
|
||||
# WhatsApp Verification Token (You provide this to Meta during webhook setup)
|
||||
whatsapp.verify-token=rit_bot_secret_token_123
|
||||
|
||||
# WhatsApp Graph API Token (You get this from the Meta developer console)
|
||||
whatsapp.api-token=EAAc3Wjql00oBSZAZAWjbSjOOoX3dZBPZAb4VHcQqg1oZAYqPQXvd9fpoNb3bOoPeHtR6irmZB5zQtBApBctcS72eMRgIMa0TOqbP9huKHFoeKq3RJVgcLEtMRJGus4yDrSM23YJpkEbolrT2HDIxahm75fI3oetVZC27jmtoqkdTnVEAOO5wbhZAF7ZAg05nMqFWwMBvpd6cf4Regtfljj0ZBCZBfDaUkOSAf4ZC6D7VFU7djl6RY0qfbRRMRuf0F2D9gV7JzF8WZBZBcvepFixU7PAd6SUsCrxQZDZD
|
||||
# WhatsApp Phone Number ID (You get this from the Meta developer console)
|
||||
whatsapp.phone-number-id=1236658909534007
|
||||
|
||||
# H2 Database Configuration
|
||||
spring.datasource.url=jdbc:h2:file:./db/whatsappbot
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.h2.console.enabled=true
|
||||
|
||||
# Encryption Secret for Passcodes (Must be 16, 24, or 32 bytes)
|
||||
bot.encryption.secret=12345678901234567890123456789012
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.rit.whatsapp;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class WhatsappBotApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user