tm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env bash
  2. #
  3. # TextMagic REST API Client
  4. #
  5. # Copyright (C) 2015 TextMagic Ltd.
  6. readonly E_OK=0
  7. readonly E_INVALID_PARAMETERS=1
  8. readonly E_MISSING_CREDENTIALS=2
  9. ################
  10. # CONFIGURATION
  11. ################
  12. readonly BASE_URL="https://rest.textmagic.com/api/v2" # API base URL
  13. readonly USERNAME=${TM_USERNAME:-} # Account username
  14. readonly TOKEN=${TM_APIKEY:-} # API access token
  15. readonly CURLOPTS="" # Custom cURL options
  16. function usage() {
  17. echo "Usage:"
  18. echo -e "\t$0 send [parameters]"
  19. echo -e "\t$0 <http-method> <resource> [parameters]\n"
  20. echo "Examples:"
  21. echo -e "\t$0 send --phones=99912345,9997890 --text=\"Hello guys\""
  22. echo -e "\t$0 GET /replies"
  23. echo -e "\t$0 POST /messages --phones=99912345 --text=\"Hello guys\""
  24. echo -e "\t$0 PUT /user --firstName=Charles --lastName=Conway --company=\"TextMagic Ltd.\""
  25. echo -e "\t$0 DELETE /contacts/183905"
  26. }
  27. function request() {
  28. local method path param data curl_string
  29. if [ -z $BASE_URL ] || [ -z $USERNAME ] || [ -z $TOKEN ]; then
  30. echo "Please configure your access credentials first"
  31. exit $E_MISSING_CREDENTIALS
  32. fi
  33. method="$1"; [[ $# > 0 ]] && shift
  34. case "$method" in
  35. GET|DELETE|POST|PUT)
  36. if [[ $# = 0 ]] || [ -z "$1" ] || [ "${1#/}" = "$1" ]; then
  37. usage
  38. exit $E_INVALID_PARAMETERS
  39. fi
  40. path=${BASE_URL}${1} && shift
  41. [[ "$method" = "GET" ]] && curlopts="-G"
  42. curlopts="$curlopts $CURLOPTS"
  43. i=1
  44. for param in "$@"; do
  45. [[ $param == --*=* ]] && param=${param#*--} && data[i]="--data-urlencode '${param%%=*}=${param#*=}'" && i=$((i+1))
  46. done
  47. curl_string="curl -s -X $method $curlopts -H 'X-TM-Username: $USERNAME' -H 'X-TM-Key: $TOKEN' ${data[@]} $path"
  48. eval "$curl_string"
  49. exit $E_OK
  50. ;;
  51. *)
  52. usage
  53. exit $E_INVALID_PARAMETERS
  54. ;;
  55. esac
  56. }
  57. if [[ "$1" = "send" ]]; then
  58. shift
  59. request POST /messages "$@"
  60. fi
  61. request "$@"