summaryrefslogtreecommitdiffstats
path: root/update_mensa.sh
diff options
context:
space:
mode:
authorNiklas Halle <niklas@niklashalle.net>2024-02-10 11:42:03 +0100
committerNiklas Halle <niklas@niklashalle.net>2024-02-10 11:42:03 +0100
commitcc7c4bb3383e4358050dccb56a49dd0dbcec43dc (patch)
tree71c84de6feaf3d50acc9e71972ee55368cfc5d48 /update_mensa.sh
downloadserver_scripts-cc7c4bb3383e4358050dccb56a49dd0dbcec43dc.tar.gz
server_scripts-cc7c4bb3383e4358050dccb56a49dd0dbcec43dc.zip
inital
Diffstat (limited to 'update_mensa.sh')
-rwxr-xr-xupdate_mensa.sh252
1 files changed, 252 insertions, 0 deletions
diff --git a/update_mensa.sh b/update_mensa.sh
new file mode 100755
index 0000000..6719f2a
--- /dev/null
+++ b/update_mensa.sh
@@ -0,0 +1,252 @@
+#!/usr/bin/env bash
+
+# Source the common utils and the environment variable loader
+source load_common_and_env.sh
+
+# (Attempt to) take variable we need
+BENUTZERID=${MENSA_USER}
+PASSWORT=${MENSA_PASS}
+FF3PAT=${FF3_PAT}
+FF3URL=${FF3_URL}
+
+# Fixed variables
+AUTHORIZATION="S0FTVkM6ekt2NXlFMUxaVW12VzI5SQ=="
+USER_AGENT="Mozilla/5.0 (Windows NT 10.0; rv:120.0) Gecko/20100101 Firefox/120.0"
+
+# Function to format date to DD.MM.YYYY
+format_date() {
+ date -d "$1" '+%d.%m.%Y'
+}
+
+# Function to get Unix timestamp
+get_unix_timestamp() {
+ echo $(date +%s)
+}
+
+# Function to url-encode strings
+url_encode() {
+ local encoded=""
+ local length="${#1}"
+ for (( i=0; i<length; i++ )); do
+ local c="${1:i:1}"
+ case $c in
+ [a-zA-Z0-9.~_-]) encoded+="$c" ;;
+ *) encoded+=$(printf '%%%02X' "'$c") ;;
+ esac
+ done
+
+ echo "$encoded"
+}
+
+# Function to log in and get auth token
+login_and_get_token() {
+ local login_url="https://ks.stw.berlin:4433/TL1/TLM/KASVC/LOGIN?karteNr=$BENUTZERID&format=JSON&datenformat=JSON"
+
+ # Perform the login request and extract the authToken
+ local login_response=$(curl -s -X POST "$login_url" \
+ -H "User-Agent: $USER_AGENT" \
+ -H 'Accept: application/json, text/javascript, */*; q=0.01' \
+ -H 'Accept-Language: en-US,en;q=0.5' \
+ -H 'Accept-Encoding: gzip, deflate, br' \
+ -H 'Referer: https://ks.stw.berlin:4433/Kartenservice/' \
+ -H "Authorization: Basic $AUTHORIZATION" \
+ -H 'X-Requested-With: XMLHttpRequest' \
+ -H 'DNT: 1' \
+ -H 'Sec-GPC: 1' \
+ -H 'Connection: keep-alive' \
+ -H 'Sec-Fetch-Dest: empty' \
+ -H 'Sec-Fetch-Mode: cors' \
+ -H 'Sec-Fetch-Site: same-origin' \
+ -H 'TE: trailers' \
+ -H 'Content-Type: application/json' \
+ --data-raw '{"BenutzerID":"'"$BENUTZERID"'","Passwort":"'"$PASSWORT"'"}')
+
+ echo $(echo "$login_response" | jq -r '.[0].authToken')
+}
+
+# Default date range: From 10 days ago to today
+START_DATE=$(format_date '10 days ago')
+END_DATE=$(format_date 'tomorrow')
+
+# Check for user-provided parameters
+if [ "$#" -eq 2 ]; then
+ START_DATE=$(format_date "$1")
+ END_DATE=$(format_date "$2")
+elif [ "$#" -ne 0 ]; then
+ echo "Invalid number of arguments. Usage: $0 [start_date end_date]"
+ exit 1
+fi
+
+# Login and get auth token
+auth_token=$(login_and_get_token)
+#echo "Auth token: $auth_token"
+encoded_auth_token=$(url_encode "$auth_token")
+#echo "Encoded Auth token: $encoded_auth_token"
+
+# Modify these URLs and parameters as per your API documentation
+data_retrieval_url1="https://ks.stw.berlin:4433/TL1/TLM/KASVC/TRANSPOS"
+data_retrieval_url2="https://ks.stw.berlin:4433/TL1/TLM/KASVC/TRANS"
+
+# Data Retrieval
+DATA1=$(curl -s "$data_retrieval_url1?format=JSON&authToken=$encoded_auth_token&karteNr=$BENUTZERID&datumVon=$START_DATE&datumBis=$END_DATE&_=$(get_unix_timestamp)" \
+-H "User-Agent: $USER_AGENT" \
+-H 'Accept: application/json, text/javascript, */*; q=0.01' \
+-H 'Accept-Language: en-US,en;q=0.5' \
+-H 'Accept-Encoding: gzip, deflate, br' \
+-H 'Referer: https://ks.stw.berlin:4433/Kartenservice/' \
+-H "Authorization: Basic $AUTHORIZATION" \
+-H 'X-Requested-With: XMLHttpRequest' \
+-H 'DNT: 1' \
+-H 'Sec-GPC: 1' \
+-H 'Connection: keep-alive' \
+-H 'Sec-Fetch-Dest: empty' \
+-H 'Sec-Fetch-Mode: cors' \
+-H 'Sec-Fetch-Site: same-origin' \
+-H 'TE: trailers')
+
+DATA2=$(curl -s "$data_retrieval_url2?format=JSON&authToken=$encoded_auth_token&karteNr=$BENUTZERID&datumVon=$START_DATE&datumBis=$END_DATE&_=$(get_unix_timestamp)" \
+-H "User-Agent: $USER_AGENT" \
+-H 'Accept: application/json, text/javascript, */*; q=0.01' \
+-H 'Accept-Language: en-US,en;q=0.5' \
+-H 'Accept-Encoding: gzip, deflate, br' \
+-H 'Referer: https://ks.stw.berlin:4433/Kartenservice/' \
+-H "Authorization: Basic $AUTHORIZATION" \
+-H 'X-Requested-With: XMLHttpRequest' \
+-H 'DNT: 1' \
+-H 'Sec-GPC: 1' \
+-H 'Connection: keep-alive' \
+-H 'Sec-Fetch-Dest: empty' \
+-H 'Sec-Fetch-Mode: cors' \
+-H 'Sec-Fetch-Site: same-origin' \
+-H 'TE: trailers')
+
+## Print the retrieved data
+#echo "Data from the first request:"
+#echo "$DATA1"
+
+#echo "Data from the second request:"
+#echo "$DATA2"
+
+# Assuming DATA1 and DATA2 are set with the respective JSON data
+combine_data() {
+ local positions="$1"
+ local transactions="$2"
+
+ echo "$transactions" | jq --argjson positions "$positions" '[
+ .[] as $transaction |
+ {
+ date: $transaction.datum,
+ mensa: $transaction.ortName,
+ totalAmount: (-1 * $transaction.zahlBetrag),
+ items: ($positions | map(select(.transFullId == $transaction.transFullId)) | map({name: .name, menge: .menge, epreis: .epreis}))
+ }
+ ]'
+}
+
+combined_data=$(combine_data "$DATA1" "$DATA2")
+
+#echo "Combined data:"
+#echo "$combined_data"
+
+# Function to create a Firefly III transaction
+create_firefly_transaction() {
+ local transaction_data="$1"
+
+ curl -X POST "$FF3URL" \
+ -H 'accept: application/vnd.api+json' \
+ -H "Authorization: Bearer $FF3PAT" \
+ -H 'Content-Type: application/json' \
+ --data "$transaction_data"
+
+ echo
+}
+
+format_date_for_firefly() {
+ local input_date="$1"
+ # Extract components from the input date format "DD.MM.YYYY HH:MM"
+ local day=$(echo "$input_date" | cut -d. -f1)
+ local month=$(echo "$input_date" | cut -d. -f2)
+ local year=$(echo "$input_date" | cut -d. -f3 | cut -d' ' -f1)
+ local ti_me=$(echo "$input_date" | cut -d' ' -f2)
+
+ # Construct the date in the format "YYYY-MM-DDTHH:MM:00"
+ local converted_date="${year}-${month}-${day}T${ti_me}:00"
+
+ # Get the timezone offset for Berlin
+ local timezone_offset=$(date '+%:z')
+
+ # Combine the date and timezone offset
+ local formatted_date="${converted_date}${timezone_offset}"
+
+ echo "$formatted_date"
+}
+
+# Process and send each transaction
+echo "$combined_data" | jq -c '.[]' | while read -r transaction; do
+ # Check if the transaction is "Karte aufwerten"
+ if echo "$transaction" | jq -e '.items[] | select(.name == "Karte aufwerten")' > /dev/null; then
+ # Special handling for "Karte aufwerten"
+ date=$(echo "$transaction" | jq -r '.date')
+ formatted_date=$(format_date_for_firefly "$date")
+ totalAmount=$(echo "$transaction" | jq -r '(-1 * .totalAmount)')
+
+# echo "Recharge:"
+
+ firefly_data=$(jq -n \
+ --arg date "$formatted_date" \
+ --arg amount "$totalAmount" \
+ '{
+ error_if_duplicate_hash: true,
+ apply_rules: false,
+ transactions: [
+ {
+ type: "transfer",
+ date: $date,
+ amount: $amount,
+ description: " Guthaben Mensa",
+ category_id: 5,
+ source_id: 31,
+ destination_id: 45,
+ }
+ ]
+ }')
+ else
+ # Extract and format transaction data
+ date=$(echo "$transaction" | jq -r '.date')
+ formatted_date=$(format_date_for_firefly "$date")
+ totalAmount=$(echo "$transaction" | jq -r '.totalAmount')
+ notes=$(echo "$transaction" | jq -c '[.items[] | "\(.menge): \(.name) (\(.epreis) €)"]')
+ mensa=$(echo "$transaction" | jq -r '.mensa')
+
+# echo "$notes, $totalAmount"
+
+ # Prepare the data for the Firefly III API
+ firefly_data=$(jq -n \
+ --arg date "$formatted_date" \
+ --arg amount "$totalAmount" \
+ --argjson notes "$notes" \
+ --arg tag "$mensa" \
+ '{
+ error_if_duplicate_hash: true,
+ apply_rules: false,
+ transactions: [
+ {
+ type: "withdrawal",
+ date: $date,
+ amount: $amount,
+ description: ("Essen " + $tag),
+ budget_id: "2",
+ category_id: "1",
+ source_id: "45",
+ destination_id: "191",
+ tags: [$tag],
+ notes: (if $notes | length == 0 then null else $notes | join(" \n") end)
+ }
+ ]
+ }')
+ fi
+
+ # Create the transaction in Firefly III
+# echo "$firefly_data"
+ create_firefly_transaction "$firefly_data"
+done