Compare commits

...

3 commits

Author SHA1 Message Date
Bruno BELANYI efd6d5ddbb matrix-notifier: use 'notice' default message type
All checks were successful
continuous-integration/drone/push Build is passing
2021-06-12 18:57:29 +02:00
Bruno BELANYI 08dac65a55 matrix-notifier: allow specifying message type 2021-06-12 18:56:58 +02:00
Bruno BELANYI 811e04813a matrix-notifier: add usage
And split into functions to make it more manageable.
2021-06-12 18:56:36 +02:00

View file

@ -4,6 +4,16 @@ print_err() {
printf "%s\n" "$1" >&2
}
usage() {
print_err "Usage: $0 [option]..."
print_err ""
print_err " -h, --help"
print_err " print this usage screen and exit"
print_err " -t, --type"
print_err " which message type should be sent"
print_err " must be one of 'text' or 'notice'"
}
# Blessed Stack Overflow
rawurlencode() {
(set +x
@ -30,6 +40,7 @@ default_drone_message() {
printf '%s' "$msg"
}
ensure_variables() {
if [ "$DRONE" == "true" ] && [ -z "$MESSAGE" ]; then
MESSAGE="$(default_drone_message)"
fi
@ -44,6 +55,12 @@ elif [ -z "$MESSAGE" ]; then
print_err "You must provide MESSAGE"
exit 1
fi
}
send_message() {
local login_json
local token
local message_json
if [ "$(curl -XGET "$ADDRESS/_matrix/client/r0/login" 2>/dev/null |
jq 'any(.flows[].type; .== "m.login.password")')" != "true" ]; then
@ -52,19 +69,54 @@ if [ "$(curl -XGET "$ADDRESS/_matrix/client/r0/login" 2>/dev/null |
fi
LOGIN_JSON="$(printf '%s\n%s' "$USER" "$PASS" |
login_json="$(printf '%s\n%s' "$USER" "$PASS" |
jq -Rn '[inputs] | {type: "m.login.password", user: .[0], password: .[1]}')" &>/dev/null
TOKEN="$(curl -XPOST \
-d "$LOGIN_JSON" \
token="$(curl -XPOST \
-d "$login_json" \
"$ADDRESS/_matrix/client/r0/login" 2>/dev/null| jq .access_token --raw-output)"
if [ -z "$TOKEN" ] || [ "$TOKEN" == "null" ]; then
if [ -z "$token" ] || [ "$token" == "null" ]; then
print_err "Error during login"
exit 1
fi
MESSAGE_JSON="$(printf '%s' "$MESSAGE" |
jq --raw-input --slurp '{msgtype: "m.text", body: .}')"
message_json="$(printf '%s' "$MESSAGE" |
jq --raw-input --slurp "{msgtype: \"$MSG_TYPE\", body: .}")"
curl -XPOST \
-d "$MESSAGE_JSON" \
"$ADDRESS/_matrix/client/r0/rooms/$(rawurlencode "$ROOM")/send/m.room.message?access_token=$(rawurlencode "$TOKEN")" 2>/dev/null
-d "$message_json" \
"$ADDRESS/_matrix/client/r0/rooms/$(rawurlencode "$ROOM")/send/m.room.message?access_token=$(rawurlencode "$token")" 2>/dev/null
}
MSG_TYPE='m.notice'
while [ $# -gt 0 ]; do
opt="$1"
shift
case "$opt" in
-t|--type)
arg="$1"
shift
if [ -z "$arg" ]; then
print_err "Must give a message type when using '-t|--type'"
exit 1
elif [ "$arg" != "text" ] && [ "$arg" != "notice" ]; then
print_err "Invalid message type '$arg'"
exit 1
fi
MSG_TYPE="m.$arg"
;;
-h|--help)
usage
exit
;;
*)
print_err "Unknown argument '$opt'"
usage
exit 1
;;
esac
done
ensure_variables
send_message