From 3914e4f3049951351943f01599e9cb1ea9973110 Mon Sep 17 00:00:00 2001 From: Abiram070207 Date: Wed, 19 Aug 2026 11:03:29 +0530 Subject: [PATCH] initial commit --- .gitattributes | 2 + .gitignore | 33 + .mvn/wrapper/maven-wrapper.properties | 3 + APIforIMS.md | 1381 +++++++++++++++++ mvnw | 295 ++++ mvnw.cmd | 189 +++ pom.xml | 108 ++ .../rit/whatsapp/WhatsappBotApplication.java | 13 + .../controller/WebhookController.java | 178 +++ .../whatsapp/handler/GrievanceHandler.java | 71 + .../rit/whatsapp/handler/LoginHandler.java | 64 + .../whatsapp/handler/StudentMenuHandler.java | 117 ++ .../com/rit/whatsapp/model/UserEntity.java | 50 + .../com/rit/whatsapp/model/UserState.java | 9 + .../whatsapp/repository/UserRepository.java | 9 + .../rit/whatsapp/service/ImsApiService.java | 105 ++ .../rit/whatsapp/service/SessionService.java | 107 ++ .../service/WhatsAppMessageBuilder.java | 66 + .../service/WhatsAppMessageService.java | 68 + .../rit/whatsapp/util/EncryptionUtils.java | 43 + .../rit/whatsapp/util/MessageFormatter.java | 104 ++ src/main/resources/application.properties | 22 + .../whatsapp/WhatsappBotApplicationTests.java | 13 + 23 files changed, 3050 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 APIforIMS.md create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/rit/whatsapp/WhatsappBotApplication.java create mode 100644 src/main/java/com/rit/whatsapp/controller/WebhookController.java create mode 100644 src/main/java/com/rit/whatsapp/handler/GrievanceHandler.java create mode 100644 src/main/java/com/rit/whatsapp/handler/LoginHandler.java create mode 100644 src/main/java/com/rit/whatsapp/handler/StudentMenuHandler.java create mode 100644 src/main/java/com/rit/whatsapp/model/UserEntity.java create mode 100644 src/main/java/com/rit/whatsapp/model/UserState.java create mode 100644 src/main/java/com/rit/whatsapp/repository/UserRepository.java create mode 100644 src/main/java/com/rit/whatsapp/service/ImsApiService.java create mode 100644 src/main/java/com/rit/whatsapp/service/SessionService.java create mode 100644 src/main/java/com/rit/whatsapp/service/WhatsAppMessageBuilder.java create mode 100644 src/main/java/com/rit/whatsapp/service/WhatsAppMessageService.java create mode 100644 src/main/java/com/rit/whatsapp/util/EncryptionUtils.java create mode 100644 src/main/java/com/rit/whatsapp/util/MessageFormatter.java create mode 100644 src/main/resources/application.properties create mode 100644 src/test/java/com/rit/whatsapp/WhatsappBotApplicationTests.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..216df05 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/APIforIMS.md b/APIforIMS.md new file mode 100644 index 0000000..b732d4b --- /dev/null +++ b/APIforIMS.md @@ -0,0 +1,1381 @@ +# RIT IMS API Documentation + +**Base URL:** `https://ims-api.sidharthprabhu.co.in` + +This API provides programmatic access to authenticated student information from the RIT IMS portal. + +The API communicates server-side with: + +`https://ims.ritchennai.edu.in` + +Clients do **not** need to manage the upstream RIT IMS cookies or CSRF token. The API handles the upstream IMS session internally and returns an API session token to the client. + +--- + +# Quick Start + +The API can be used directly from: + +- macOS / Linux / Bash / Zsh +- Windows PowerShell +- Windows Command Prompt (CMD) + +Each step below contains the commands for all supported operating systems. You do not need to jump to a separate Windows section. + +--- + +# Step 1 — Set the API URL + +## macOS / Linux / Bash / Zsh + +```bash +BASE_URL="https://ims-api.sidharthprabhu.co.in" +``` + +## Windows PowerShell + +```powershell +$BaseUrl = "https://ims-api.sidharthprabhu.co.in" +``` + +## Windows CMD + +```cmd +set BASE_URL=https://ims-api.sidharthprabhu.co.in +``` + +--- + +# Step 2 — Authenticate + +The login endpoint is: + +```text +POST /api/auth/login +``` + +Request body: + +```json +{ + "username": "YOUR_REGISTER_NUMBER", + "password": "YOUR_PASSWORD" +} +``` + +## macOS / Linux / Bash / Zsh + +```bash +LOGIN_RESPONSE=$(curl -s \ + -X POST \ + "$BASE_URL/api/auth/login" \ + -H "Content-Type: application/json" \ + -d '{ + "username": "YOUR_REGISTER_NUMBER", + "password": "YOUR_PASSWORD" + }') + +echo "$LOGIN_RESPONSE" +``` + +## Windows PowerShell + +PowerShell should use `Invoke-RestMethod` for the recommended workflow. It automatically converts the JSON response into a PowerShell object. + +```powershell +$LoginBody = @{ + username = "YOUR_REGISTER_NUMBER" + password = "YOUR_PASSWORD" +} | ConvertTo-Json -Compress + +$Login = Invoke-RestMethod ` + -Uri "$BaseUrl/api/auth/login" ` + -Method POST ` + -ContentType "application/json" ` + -Body $LoginBody + +$Login +``` + +A successful PowerShell response will contain properties similar to: + +```text +success message +------- ------- +True Authentication successful +``` + +It will also contain a `session` property. + +## Windows CMD + +```cmd +curl -s -X POST "%BASE_URL%/api/auth/login" ^ + -H "Content-Type: application/json" ^ + -d "{\"username\":\"YOUR_REGISTER_NUMBER\",\"password\":\"YOUR_PASSWORD\"}" +``` + +A successful response looks like: + +```json +{ + "success": true, + "message": "Authentication successful", + "session": "YOUR_API_SESSION_TOKEN" +} +``` + +--- + +# Step 3 — Extract the API Session Token + +The API returns an opaque session token after successful authentication. + +## macOS / Linux / Bash / Zsh + +If `jq` is installed: + +```bash +API_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.session') +``` + +Check it: + +```bash +echo "$API_TOKEN" +``` + +Without `jq`, inspect the login response and copy the value of `session` manually: + +```bash +echo "$LOGIN_RESPONSE" +``` + +Then: + +```bash +API_TOKEN="YOUR_API_SESSION_TOKEN" +``` + +## Windows PowerShell + +Because `Invoke-RestMethod` already parses JSON, use: + +```powershell +$ApiToken = $Login.session +``` + +Check it: + +```powershell +$ApiToken +``` + +**Do not use:** + +```powershell +$ApiToken = ($Login | ConvertFrom-Json).session +``` + +That is incorrect when `$Login` was created using `Invoke-RestMethod`. + +## Windows CMD + +CMD does not have a built-in JSON parser. Copy the `session` value from the login response and set: + +```cmd +set API_TOKEN=YOUR_API_SESSION_TOKEN +``` + +--- + +# Step 4 — Fetch Semester Marks + +Endpoint: + +```text +GET /api/student/results?semester=N +``` + +`N` can be a semester number from `1` through `8`. + +## macOS / Linux / Bash / Zsh + +Semester 1: + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=1" +``` + +Formatted JSON with `jq`: + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=1" | jq . +``` + +Semester 2: + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=2" | jq . +``` + +Semester 3: + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=3" | jq . +``` + +For any other semester, change the value: + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=4" | jq . +``` + +## Windows PowerShell + +Semester 1: + +```powershell +$Results = Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/results?semester=1" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } + +$Results | ConvertTo-Json -Depth 10 +``` + +Semester 2: + +```powershell +$Results = Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/results?semester=2" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } + +$Results | ConvertTo-Json -Depth 10 +``` + +For another semester, change the value: + +```powershell +$Results = Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/results?semester=3" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } + +$Results | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +Semester 1: + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/results?semester=1" +``` + +Semester 2: + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/results?semester=2" +``` + +For another semester, change the value: + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/results?semester=3" +``` + +--- + +# Step 5 — Fetch Student Profile + +Endpoint: + +```text +GET /api/student/profile +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/profile" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/profile" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/profile" +``` + +--- + +# Step 6 — Fetch Attendance + +Endpoint: + +```text +GET /api/student/attendance +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/attendance" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/attendance" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/attendance" +``` + +--- + +# Step 7 — Fetch Timetable + +Endpoint: + +```text +GET /api/student/timetable +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/timetable" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/timetable" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/timetable" +``` + +--- + +# Step 8 — Fetch CAT Marks + +Endpoint: + +```text +GET /api/student/cat-marks +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/cat-marks" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/cat-marks" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/cat-marks" +``` + +--- + +# Step 9 — Fetch Assignment Marks + +Endpoint: + +```text +GET /api/student/assignment-marks +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/assignment-marks" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/assignment-marks" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/assignment-marks" +``` + +--- + +# Step 10 — Fetch Leave History + +Endpoint: + +```text +GET /api/student/leaves +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/leaves" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/leaves" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/leaves" +``` + +--- + +# Step 11 — Fetch Academic Fees + +Endpoint: + +```text +GET /api/student/fees +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/fees" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/fees" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/fees" +``` + +--- + +# Step 12 — Logout + +Endpoint: + +```text +POST /api/auth/logout +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -X POST \ + "$BASE_URL/api/auth/logout" \ + -H "Authorization: Bearer $API_TOKEN" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/auth/logout" ` + -Method POST ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -X POST ^ + "%BASE_URL%/api/auth/logout" ^ + -H "Authorization: Bearer %API_TOKEN%" +``` + +--- + +# Step 13 — API Health Check + +Endpoint: + +```text +GET /api/health +``` + +No authentication is required. + +## macOS / Linux / Bash / Zsh + +```bash +curl -s "$BASE_URL/api/health" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/health" ` + -Method GET | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s "%BASE_URL%/api/health" +``` + +Expected: + +```json +{ + "success": true, + "status": "ok" +} +``` + +If this returns the site's frontend HTML instead of JSON, `/api/*` is not being routed to the `ims-api` Edge Function correctly. + +--- + +# Step 14 — Upstream IMS Health Check + +Endpoint: + +```text +GET /api/health/upstream +``` + +No authentication is required. + +## macOS / Linux / Bash / Zsh + +```bash +curl -s "$BASE_URL/api/health/upstream" | jq . +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/health/upstream" ` + -Method GET | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s "%BASE_URL%/api/health/upstream" +``` + +Example: + +```json +{ + "success": true, + "api": "ok", + "upstream_ims": "reachable" +} +``` + +--- + +# API Reference + +## Authentication + +### POST `/api/auth/login` + +Authenticates the user against RIT IMS and creates an API session. + +Request: + +```json +{ + "username": "YOUR_REGISTER_NUMBER", + "password": "YOUR_PASSWORD" +} +``` + +Successful response: + +```json +{ + "success": true, + "message": "Authentication successful", + "session": "API_SESSION_TOKEN" +} +``` + +The `session` value is an opaque API session token. + +--- + +## Authorization + +Authenticated requests use: + +```http +Authorization: Bearer API_SESSION_TOKEN +``` + +The client does not need to send: + +- `laravel_session` +- `XSRF-TOKEN` +- IMS CSRF token +- IMS cookies + +The API handles the upstream IMS session internally. + +--- + +# Semester Results + +## GET `/api/student/results?semester=N` + +Fetch marks for the authenticated student. + +`N` must be a semester number from `1` to `8`. + +Example: + +```text +GET /api/student/results?semester=1 +``` + +Example response: + +```json +{ + "success": true, + "semester": 1, + "data": [ + { + "course_code": "CS1234", + "course_name": "Data Structures", + "internal_mark": 40, + "external_mark": 55, + "total_mark": 95, + "grade": "A", + "result": "PASS" + } + ] +} +``` + +The exact fields and values depend on the data returned by the upstream IMS. + +Internally, the API retrieves semester marks from: + +```text +POST https://ims.ritchennai.edu.in/admin/grade/student/mark/get_marks +``` + +with: + +```text +semester=N +``` + +--- + +# Alternative Results POST + +## POST `/api/student/results` + +Request: + +```json +{ + "semester": 1 +} +``` + +## macOS / Linux / Bash / Zsh + +```bash +curl -s \ + -X POST \ + "$BASE_URL/api/student/results" \ + -H "Authorization: Bearer $API_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"semester":1}' | jq . +``` + +## Windows PowerShell + +```powershell +$Body = @{ + semester = 1 +} | ConvertTo-Json -Compress + +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/results" ` + -Method POST ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } ` + -ContentType "application/json" ` + -Body $Body | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -s ^ + -X POST ^ + "%BASE_URL%/api/student/results" ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + -H "Content-Type: application/json" ^ + -d "{\"semester\":1}" +``` + +GET is recommended for simple read-only retrieval. + +--- + +# Response and Error Handling + +## Success + +Successful requests return JSON with: + +```json +{ + "success": true +} +``` + +Additional fields depend on the endpoint. + +## Invalid credentials + +```json +{ + "success": false, + "error": "INVALID_CREDENTIALS", + "message": "The IMS username or password is incorrect." +} +``` + +HTTP status: + +```text +401 +``` + +## Unauthorized + +```json +{ + "success": false, + "error": "UNAUTHORIZED", + "message": "Missing or invalid Authorization header." +} +``` + +HTTP status: + +```text +401 +``` + +## Expired IMS session + +```json +{ + "success": false, + "error": "IMS_SESSION_EXPIRED", + "message": "The upstream IMS session has expired. Please authenticate again." +} +``` + +HTTP status: + +```text +401 +``` + +## Invalid semester + +```json +{ + "success": false, + "error": "INVALID_SEMESTER", + "message": "Semester must be a valid integer between 1 and 8." +} +``` + +HTTP status: + +```text +400 +``` + +## General error format + +```json +{ + "success": false, + "error": "ERROR_CODE", + "message": "Human-readable description" +} +``` + +--- + +# HTTP Status Codes + +| Status | Meaning | +|---:|---| +| 200 | Successful request | +| 400 | Invalid request | +| 401 | Missing, invalid, or expired authentication | +| 404 | API endpoint not found | +| 429 | Rate limit exceeded | +| 500 | Internal API error | +| 502 | Upstream IMS failure | + +--- + +# Architecture + +```text +Client + | + | HTTPS + v +https://ims-api.sidharthprabhu.co.in/api/* + | + | Netlify Edge Function: ims-api + v +https://ims.ritchennai.edu.in +``` + +The `/api/*` routes are handled by the `ims-api` Edge Function. + +The legacy `/ims/*` route is a separate proxy and should not be used for normal API authentication. + +--- + +# Authentication Flow + +```text +POST /api/auth/login + | + v +GET RIT IMS /login + | + +-- obtain session cookies + | + +-- extract CSRF token + | + v +POST RIT IMS /login + | + +-- username + +-- password + +-- CSRF token + | + v +Verify authenticated IMS session + | + +-- authenticated cookies + +-- authenticated CSRF token + | + v +Create API session token + | + v +Return token to client +``` + +Subsequent requests: + +```text +Authorization: Bearer + | + v +Restore API session + | + +-- IMS cookies + +-- IMS CSRF token + | + v +Request RIT IMS + | + v +Parse response + | + v +Return JSON +``` + +--- + +# Complete Workflow by Operating System + +## macOS / Linux / Bash / Zsh + +```bash +BASE_URL="https://ims-api.sidharthprabhu.co.in" + +LOGIN_RESPONSE=$(curl -s \ + -X POST \ + "$BASE_URL/api/auth/login" \ + -H "Content-Type: application/json" \ + -d '{ + "username": "YOUR_REGISTER_NUMBER", + "password": "YOUR_PASSWORD" + }') + +echo "$LOGIN_RESPONSE" | jq . + +API_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.session') + +curl -s \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=1" | jq . + +curl -s \ + -X POST \ + "$BASE_URL/api/auth/logout" \ + -H "Authorization: Bearer $API_TOKEN" | jq . +``` + +## Windows PowerShell + +```powershell +$BaseUrl = "https://ims-api.sidharthprabhu.co.in" + +$LoginBody = @{ + username = "YOUR_REGISTER_NUMBER" + password = "YOUR_PASSWORD" +} | ConvertTo-Json -Compress + +$Login = Invoke-RestMethod ` + -Uri "$BaseUrl/api/auth/login" ` + -Method POST ` + -ContentType "application/json" ` + -Body $LoginBody + +$Login + +$ApiToken = $Login.session + +$Results = Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/results?semester=1" ` + -Method GET ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } + +$Results | ConvertTo-Json -Depth 10 + +Invoke-RestMethod ` + -Uri "$BaseUrl/api/auth/logout" ` + -Method POST ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +**Important:** Since this workflow uses `Invoke-RestMethod`, `$Login` is already a PowerShell object. + +Use: + +```powershell +$ApiToken = $Login.session +``` + +Do not use: + +```powershell +$ApiToken = ($Login | ConvertFrom-Json).session +``` + +## Windows CMD + +```cmd +set BASE_URL=https://ims-api.sidharthprabhu.co.in + +curl -s -X POST "%BASE_URL%/api/auth/login" ^ + -H "Content-Type: application/json" ^ + -d "{\"username\":\"YOUR_REGISTER_NUMBER\",\"password\":\"YOUR_PASSWORD\"}" +``` + +Copy the `session` value: + +```cmd +set API_TOKEN=YOUR_API_SESSION_TOKEN +``` + +Fetch Semester 1: + +```cmd +curl -s ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/results?semester=1" +``` + +Logout: + +```cmd +curl -s ^ + -X POST ^ + "%BASE_URL%/api/auth/logout" ^ + -H "Authorization: Bearer %API_TOKEN%" +``` + +--- + +# Important Client-Side Rules + +Clients should **not**: + +- request `/ims/*` for normal API usage +- send upstream `laravel_session` cookies manually +- send the upstream `XSRF-TOKEN` manually +- send the upstream CSRF token +- submit credentials directly to `ims.ritchennai.edu.in` +- follow upstream IMS redirects themselves + +Clients should communicate with: + +```text +https://ims-api.sidharthprabhu.co.in/api/* +``` + +and authenticate using: + +```http +Authorization: Bearer +``` + +--- + +# Security + +The API handles sensitive student authentication and academic information. + +Never log: + +- IMS passwords +- API bearer tokens +- upstream cookies +- upstream CSRF tokens +- unnecessary student academic information + +Use HTTPS only. + +Apply rate limiting to login and authenticated endpoints. + +Do not create arbitrary upstream URL forwarding. + +Do not turn the service into an open proxy. + +Authenticated student data should not be publicly cached. + +Responses containing student information should use: + +```http +Cache-Control: no-store +``` + +--- + +# API Endpoint Summary + +| Method | Endpoint | Authentication | +|---|---|---| +| GET | `/api/health` | No | +| GET | `/api/health/upstream` | No | +| POST | `/api/auth/login` | No | +| POST | `/api/auth/logout` | Yes | +| GET | `/api/student/profile` | Yes | +| GET | `/api/student/attendance` | Yes | +| GET | `/api/student/timetable` | Yes | +| GET | `/api/student/cat-marks` | Yes | +| GET | `/api/student/assignment-marks` | Yes | +| GET | `/api/student/leaves` | Yes | +| GET | `/api/student/results?semester=N` | Yes | +| POST | `/api/student/results` | Yes | +| GET | `/api/student/fees` | Yes | + +--- + +# Troubleshooting + +## `/api/health` returns HTML + +Expected: + +```json +{ + "success": true, + "status": "ok" +} +``` + +If the response is the frontend `index.html`, the request is reaching the SPA instead of the `ims-api` Edge Function. + +Fix the Netlify `/api/*` routing. + +## Login returns 404 + +Verify that: + +```text +/api/auth/login +``` + +is routed to the `ims-api` Edge Function. + +## PowerShell says `ConvertFrom-Json` is invalid + +If login was performed using: + +```powershell +$Login = Invoke-RestMethod ... +``` + +use: + +```powershell +$ApiToken = $Login.session +``` + +Do not pipe `$Login` into `ConvertFrom-Json`. + +## Results return `UNAUTHORIZED` + +Verify that the token exists: + +```powershell +$ApiToken +``` + +or: + +```bash +echo "$API_TOKEN" +``` + +The request must contain: + +```http +Authorization: Bearer +``` + +## Results return `IMS_SESSION_EXPIRED` + +Authenticate again to create a new API session. + +## Results return the IMS login HTML + +The upstream IMS session was not preserved or has expired. The API should detect this and return `401 IMS_SESSION_EXPIRED` rather than exposing the IMS login HTML. + +--- + +# Production Verification + +Verify the API in this order. + +## macOS / Linux + +```bash +curl -i "$BASE_URL/api/health" +``` + +```bash +curl -i "$BASE_URL/api/health/upstream" +``` + +```bash +curl -i -X POST "$BASE_URL/api/auth/login" \ + -H "Content-Type: application/json" \ + -d '{"username":"YOUR_REGISTER_NUMBER","password":"YOUR_PASSWORD"}' +``` + +Then: + +```bash +curl -i \ + -H "Authorization: Bearer $API_TOKEN" \ + "$BASE_URL/api/student/results?semester=1" +``` + +## Windows PowerShell + +```powershell +Invoke-RestMethod "$BaseUrl/api/health" | ConvertTo-Json -Depth 10 +``` + +```powershell +Invoke-RestMethod "$BaseUrl/api/health/upstream" | ConvertTo-Json -Depth 10 +``` + +```powershell +$LoginBody = @{ + username = "YOUR_REGISTER_NUMBER" + password = "YOUR_PASSWORD" +} | ConvertTo-Json -Compress + +$Login = Invoke-RestMethod ` + -Uri "$BaseUrl/api/auth/login" ` + -Method POST ` + -ContentType "application/json" ` + -Body $LoginBody + +$ApiToken = $Login.session +``` + +Then: + +```powershell +Invoke-RestMethod ` + -Uri "$BaseUrl/api/student/results?semester=1" ` + -Headers @{ + Authorization = "Bearer $ApiToken" + } | ConvertTo-Json -Depth 10 +``` + +## Windows CMD + +```cmd +curl -i "%BASE_URL%/api/health" +``` + +```cmd +curl -i "%BASE_URL%/api/health/upstream" +``` + +```cmd +curl -i -X POST "%BASE_URL%/api/auth/login" ^ + -H "Content-Type: application/json" ^ + -d "{\"username\":\"YOUR_REGISTER_NUMBER\",\"password\":\"YOUR_PASSWORD\"}" +``` + +After copying the returned session token: + +```cmd +curl -i ^ + -H "Authorization: Bearer %API_TOKEN%" ^ + "%BASE_URL%/api/student/results?semester=1" +``` + +The client should receive JSON containing the requested data, not the upstream IMS login HTML. diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -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-,maven-mvnd--}/ +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" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..11e2628 --- /dev/null +++ b/pom.xml @@ -0,0 +1,108 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.1.0 + + + com.rit + whatsapp-bot + 0.0.1-SNAPSHOT + whatsapp-bot + + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + com.fasterxml.jackson.core + jackson-databind + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.projectlombok + lombok + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + + + + + + + + diff --git a/src/main/java/com/rit/whatsapp/WhatsappBotApplication.java b/src/main/java/com/rit/whatsapp/WhatsappBotApplication.java new file mode 100644 index 0000000..6494766 --- /dev/null +++ b/src/main/java/com/rit/whatsapp/WhatsappBotApplication.java @@ -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); + } + +} diff --git a/src/main/java/com/rit/whatsapp/controller/WebhookController.java b/src/main/java/com/rit/whatsapp/controller/WebhookController.java new file mode 100644 index 0000000..11addae --- /dev/null +++ b/src/main/java/com/rit/whatsapp/controller/WebhookController.java @@ -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 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 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); + } + } +} diff --git a/src/main/java/com/rit/whatsapp/handler/GrievanceHandler.java b/src/main/java/com/rit/whatsapp/handler/GrievanceHandler.java new file mode 100644 index 0000000..5137562 --- /dev/null +++ b/src/main/java/com/rit/whatsapp/handler/GrievanceHandler.java @@ -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> buttons = new ArrayList<>(); + buttons.add(createButton("grievance_academic", "Academic")); + buttons.add(createButton("grievance_hostel", "Hostel")); + buttons.add(createButton("grievance_other", "Other")); + + Map 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 createButton(String id, String title) { + Map btn = new HashMap<>(); + btn.put("id", id); + btn.put("title", title); + return btn; + } +} diff --git a/src/main/java/com/rit/whatsapp/handler/LoginHandler.java b/src/main/java/com/rit/whatsapp/handler/LoginHandler.java new file mode 100644 index 0000000..45b5ff3 --- /dev/null +++ b/src/main/java/com/rit/whatsapp/handler/LoginHandler.java @@ -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:"); + } + } +} diff --git a/src/main/java/com/rit/whatsapp/handler/StudentMenuHandler.java b/src/main/java/com/rit/whatsapp/handler/StudentMenuHandler.java new file mode 100644 index 0000000..d1e7a28 --- /dev/null +++ b/src/main/java/com/rit/whatsapp/handler/StudentMenuHandler.java @@ -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> 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 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> logoutBtn = new ArrayList<>(); + Map btn = new HashMap<>(); + btn.put("id", "student_logout"); + btn.put("title", "Logout"); + logoutBtn.add(btn); + + Map 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 createRow(String id, String title, String description) { + Map row = new HashMap<>(); + row.put("id", id); + row.put("title", title); + row.put("description", description); + return row; + } +} diff --git a/src/main/java/com/rit/whatsapp/model/UserEntity.java b/src/main/java/com/rit/whatsapp/model/UserEntity.java new file mode 100644 index 0000000..fd1659a --- /dev/null +++ b/src/main/java/com/rit/whatsapp/model/UserEntity.java @@ -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; + } +} diff --git a/src/main/java/com/rit/whatsapp/model/UserState.java b/src/main/java/com/rit/whatsapp/model/UserState.java new file mode 100644 index 0000000..e126e8c --- /dev/null +++ b/src/main/java/com/rit/whatsapp/model/UserState.java @@ -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 +} diff --git a/src/main/java/com/rit/whatsapp/repository/UserRepository.java b/src/main/java/com/rit/whatsapp/repository/UserRepository.java new file mode 100644 index 0000000..eb5eeaa --- /dev/null +++ b/src/main/java/com/rit/whatsapp/repository/UserRepository.java @@ -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 { +} diff --git a/src/main/java/com/rit/whatsapp/service/ImsApiService.java b/src/main/java/com/rit/whatsapp/service/ImsApiService.java new file mode 100644 index 0000000..1f093b0 --- /dev/null +++ b/src/main/java/com/rit/whatsapp/service/ImsApiService.java @@ -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 requestBody = new HashMap<>(); + requestBody.put("username", imsId); + requestBody.put("password", passcode); + + HttpEntity> request = new HttpEntity<>(requestBody, headers); + + try { + ResponseEntity 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 request = new HttpEntity<>(headers); + + try { + ResponseEntity 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 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()); + } + } +} diff --git a/src/main/java/com/rit/whatsapp/service/SessionService.java b/src/main/java/com/rit/whatsapp/service/SessionService.java new file mode 100644 index 0000000..b0c17ee --- /dev/null +++ b/src/main/java/com/rit/whatsapp/service/SessionService.java @@ -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 userStates = new ConcurrentHashMap<>(); + + // In-memory cache for API session tokens + private final Map sessionTokens = new ConcurrentHashMap<>(); + private final Map 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 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); + } +} diff --git a/src/main/java/com/rit/whatsapp/service/WhatsAppMessageBuilder.java b/src/main/java/com/rit/whatsapp/service/WhatsAppMessageBuilder.java new file mode 100644 index 0000000..0c3153a --- /dev/null +++ b/src/main/java/com/rit/whatsapp/service/WhatsAppMessageBuilder.java @@ -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 buildListMessage(String header, String body, String buttonText, List> rows) { + Map interactive = new HashMap<>(); + interactive.put("type", "list"); + + if (header != null && !header.isEmpty()) { + Map headerMap = new HashMap<>(); + headerMap.put("type", "text"); + headerMap.put("text", header); + interactive.put("header", headerMap); + } + + Map bodyMap = new HashMap<>(); + bodyMap.put("text", body); + interactive.put("body", bodyMap); + + Map action = new HashMap<>(); + action.put("button", buttonText); + + List> sections = new ArrayList<>(); + Map 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 buildButtonMessage(String body, List> buttons) { + Map interactive = new HashMap<>(); + interactive.put("type", "button"); + + Map bodyMap = new HashMap<>(); + bodyMap.put("text", body); + interactive.put("body", bodyMap); + + Map action = new HashMap<>(); + List> actionButtons = new ArrayList<>(); + + for (Map btn : buttons) { + Map buttonWrapper = new HashMap<>(); + buttonWrapper.put("type", "reply"); + Map 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; + } +} diff --git a/src/main/java/com/rit/whatsapp/service/WhatsAppMessageService.java b/src/main/java/com/rit/whatsapp/service/WhatsAppMessageService.java new file mode 100644 index 0000000..ae5ae5c --- /dev/null +++ b/src/main/java/com/rit/whatsapp/service/WhatsAppMessageService.java @@ -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 payload = new HashMap<>(); + payload.put("messaging_product", "whatsapp"); + payload.put("to", toPhoneNumber); + payload.put("type", "text"); + + Map textPayload = new HashMap<>(); + textPayload.put("body", messageText); + payload.put("text", textPayload); + + executePost(payload); + } + + public void sendInteractiveMessage(String toPhoneNumber, Map interactiveObject) { + Map 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 payload) { + String url = "https://graph.facebook.com/v19.0/" + phoneNumberId + "/messages"; + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setBearerAuth(apiToken); + + HttpEntity> request = new HttpEntity<>(payload, headers); + + try { + ResponseEntity 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()); + } + } +} diff --git a/src/main/java/com/rit/whatsapp/util/EncryptionUtils.java b/src/main/java/com/rit/whatsapp/util/EncryptionUtils.java new file mode 100644 index 0000000..b23f5c8 --- /dev/null +++ b/src/main/java/com/rit/whatsapp/util/EncryptionUtils.java @@ -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); + } + } +} diff --git a/src/main/java/com/rit/whatsapp/util/MessageFormatter.java b/src/main/java/com/rit/whatsapp/util/MessageFormatter.java new file mode 100644 index 0000000..81fd67c --- /dev/null +++ b/src/main/java/com/rit/whatsapp/util/MessageFormatter.java @@ -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."; + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..f0cc8fd --- /dev/null +++ b/src/main/resources/application.properties @@ -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 diff --git a/src/test/java/com/rit/whatsapp/WhatsappBotApplicationTests.java b/src/test/java/com/rit/whatsapp/WhatsappBotApplicationTests.java new file mode 100644 index 0000000..5bdaf10 --- /dev/null +++ b/src/test/java/com/rit/whatsapp/WhatsappBotApplicationTests.java @@ -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() { + } + +}