Advertisement
JLindvig

Library_Shell

Jun 19th, 2020
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.96 KB | None | 0 0
  1. PARSEHUB_API_TOKEN="DIT_PARSEHUB_TOKEN"
  2. PARSEHUB_LIBRARY_TOKEN="DIT_PARSEHUB_PROJECT"
  3. PARSEHUB_LIBRARY_URL="https://bibliotek.dk/"
  4. PARSEHUB_LIBRARY_CREDENTIALS="{\"mail\":\"din@mail.dk\", \"password\":\"KODE\"}"
  5.  
  6. APITOKEN="TOKEN FRA HOME ASSISTANT"
  7. API_STATES_PATH="api/states"
  8.  
  9. BASE_URL="http://DIN_HA_URL:8123/"
  10. TEMP_PATH="temp"
  11.  
  12. # PUBLIC
  13. # START SCRAPER
  14. library_start_scrape() {
  15.   _parsehub_start_scrape \
  16.     $PARSEHUB_API_TOKEN \
  17.     $PARSEHUB_LIBRARY_URL \
  18.     $PARSEHUB_LIBRARY_TOKEN \
  19.     $PARSEHUB_LIBRARY_CREDENTIALS  
  20. }
  21.  
  22. # GET DATA
  23. # Get the library loans and send it to HA
  24. # 1: Friendly_name for sensor in HA
  25. # 2: Entity_id for sensor
  26. library_get() {
  27.   rm -f $TEMP_PATH/parsehub.json $TEMP_PATH/parsehub_edit.json
  28.  
  29.   curl -X GET "https://www.parsehub.com/api/v2/projects/$PARSEHUB_LIBRARY_TOKEN/last_ready_run/data?api_key=$PARSEHUB_API_TOKEN" | gunzip > $TEMP_PATH/parsehub.json
  30.  
  31.   sed 's/.*\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\).*/|\1/' $TEMP_PATH/parsehub.json | while read d; do if [[ ${d:0:1} == "|" ]]; then echo '"Due_In" :"'$(( ($(date -d ${d#?} +%s) - $(date +%s) ) / 86400 ))'",'; else echo $d; fi; done > $TEMP_PATH/parsehub_edit.json
  32.  
  33.   _send_data "{\"state\": "$(grep -m 1 "Due_In" $TEMP_PATH/parsehub_edit.json | cut -d':' -f2)"\"attributes\": $(cat $TEMP_PATH/parsehub_edit.json), \"friendly_name\": \"$1\"}}" $BASE_URL$API_STATES_PATH/sensor.library_$2
  34. }
  35.  
  36. # PRIVATE
  37.  
  38. # Start a Parsehub Scraper
  39. # 1: API_Key for Parsehub
  40. # 2: Start URL for scraper
  41. # 3: Project ID
  42. # 4: Start values aka login credentials
  43. _parsehub_start_scrape() {
  44.   curl -X POST \
  45.     -d "api_key=$1" \
  46.     -d "start_url=$2" \
  47.     -d "start_value_override=$4" \
  48.     -d "send_email=0" \
  49.     "https://www.parsehub.com/api/v2/projects/$3/run"
  50. }
  51.  
  52. # SEND TO HOME ASSISTANT
  53. # $1 = query
  54. # $2 = URL
  55. _send_data() {
  56.   curl -X POST \
  57.   -H "Accept: application/json" \
  58.   -H "Authorization: Bearer $APITOKEN" \
  59.   -H "Content-Type: application/json" \
  60.   -d "$1" \
  61.   $2
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement