Last active
December 20, 2016 23:43
-
-
Save RWJMurphy/e54a07341e8bf641b615c8da2c5e3f6b to your computer and use it in GitHub Desktop.
terrible bulk emoji uploader for mattermost. needs [`jq`](https://stedolan.github.io/jq/), [`jo`](https://github.com/jpmens/jo), GNU `parallel`, and `curl`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eu | |
MM_URL="https://mm.example.org" | |
API_URL="${MM_URL}/api/v3" | |
LOGIN_URL="${API_URL}/users/login" | |
USERS_ME_URL="${API_URL}/users/me" | |
ADD_EMOJI_URL="${API_URL}/emoji/create" | |
banner() { | |
echo "Mattermost Bulk Emoji thing v0" | |
echo "Mattermost Instance: $MM_URL" | |
echo | |
} | |
USERNAME="" | |
PASSWORD="" | |
get_username_and_password() { | |
read -p "Username: " USERNAME | |
read -sp "Password: " PASSWORD | |
echo | |
} | |
TOKEN="" | |
get_token() { | |
TOKEN="$(curl -sSi "${LOGIN_URL}" \ | |
-d "$(jo login_id="${USERNAME}" password="${PASSWORD}")" \ | |
| grep -E "^Token: " \ | |
| sed -e 's/Token: //;s/[^a-z0-9]//g')" | |
if [ "${TOKEN}" = "" ]; then | |
echo "Error logging in" | |
exit 1 | |
fi | |
} | |
USER_ID="" | |
get_user_id() { | |
local user_data="$(curl -sS \ | |
-H "Authorization: Bearer ${TOKEN}" \ | |
"${USERS_ME_URL}")" | |
USER_ID="$(echo "${user_data}" | jq -r '.id')" | |
} | |
emoji_name_and_path() { | |
for f in "${EMOJI_PATHS[@]}"; do | |
echo "$(basename $f | sed -e 's/\..*$//')" | |
echo $f | |
done | |
} | |
upload_emoji() { | |
export -f upload_one_emoji | |
export TOKEN USER_ID ADD_EMOJI_URL | |
emoji_name_and_path \ | |
| parallel -j20 -n2 "upload_one_emoji {1} {2}" | |
} | |
upload_one_emoji() { | |
local name="$1" | |
local path="$2" | |
upload_response="$(curl -sS \ | |
--header "Authorization: Bearer ${TOKEN}" \ | |
--form "image=@${path}" \ | |
--form "emoji=$(jo creator_id="${USER_ID}" name=\"${name}\")" \ | |
"${ADD_EMOJI_URL}")" | |
status_code="$(echo "${upload_response}" | jq -r '.status_code')" | |
if [ "$status_code" != "null" ]; then | |
error_id="$(echo "${upload_response}" | jq -r '.id')" | |
case "$error_id" in | |
api.emoji.create.duplicate.app_error) | |
echo "Emoji :$name: exists, not added" | |
return 1 | |
;; | |
null) | |
;; | |
*) | |
echo "Error $error_id: $(echo "${upload_response}" | jq -r '.message')" | |
echo "${upload_response}" | |
return 1 | |
;; | |
esac | |
fi | |
echo "uploaded $path as :$name:" | |
return 0 | |
} | |
EMOJI_PATHS=("$@") | |
if [ "${#EMOJI_PATHS[@]}" -eq 0 ]; then | |
echo "Must pass one or more files." | |
echo "Usage: $0 <file> [file ...]" | |
exit 1 | |
fi | |
banner | |
get_username_and_password | |
get_token | |
get_user_id | |
upload_emoji |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment