PMSCheck.sh 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/bin/bash
  2. # Config
  3. CURL_TIMEOUT=5
  4. RESTART_DELAY=120
  5. PMS_URL="http://localhost:32400/"
  6. UNWATCHED_URL="${PMS_URL}library/sections/2/unwatched"
  7. UNWATCHED_TIMEOUT=$(( $CURL_TIMEOUT * 3 ))
  8. MIN_UNWATCHED_COUNT=10
  9. ADMIN_EMAIL="zach@kotlarek.com"
  10. # Command-line config
  11. LOOP=-1
  12. if [ "${1}" ]; then
  13. LOOP="${1}"
  14. fi
  15. # Run at least once, loop if requested
  16. while [ $LOOP -ne 0 ]; do
  17. # State tracking
  18. FAILED=""
  19. # Ensure the media share is mounted
  20. if [ -z "${FAILED}" ]; then
  21. if ! ~/bin/video/isMediaMounted; then
  22. FAILED="Media share not mounted"
  23. fi
  24. fi
  25. # Ask Plex for the top-level status page
  26. if [ -z "${FAILED}" ]; then
  27. PAGE="`curl --silent --max-time "${CURL_TIMEOUT}" "${PMS_URL}"`"
  28. if [ -z "${PAGE}" ]; then
  29. FAILED="HTTP timeout"
  30. else
  31. UPDATE="`echo "${PAGE}" | grep 'updatedAt=' | sed 's%^.*updatedAt="\([0-9]*\)".*$%\1%'`"
  32. if [ -z "${UPDATE}" ]; then
  33. FAILED="Invalid update timestamp on status page"
  34. fi
  35. fi
  36. fi
  37. # Ask Plex for a list of unwatched TV series
  38. if [ -z "${FAILED}" ]; then
  39. PAGE="`curl --silent --max-time "${UNWATCHED_TIMEOUT}" "${UNWATCHED_URL}"`"
  40. if [ -z "${PAGE}" ]; then
  41. FAILED="HTTP timeout"
  42. else
  43. COUNT="`echo "${PAGE}" | grep '</Directory>' | wc -l`"
  44. if [ $COUNT -lt $MIN_UNWATCHED_COUNT ]; then
  45. FAILED="Too few unwatched series"
  46. fi
  47. fi
  48. fi
  49. # If Plex has failed kill it
  50. if [ -n "${FAILED}" ]; then
  51. ERR_MSG="PMS is non-responsive (${FAILED}). Killing..."
  52. echo "${ERR_MSG}" 1>&2
  53. ~/bin/video/pms/killPMS.sh
  54. if [ $LOOP -lt 1 ]; then
  55. exit 1
  56. elif [ -n "${ADMIN_EMAIL}" ]; then
  57. echo -e "Subject: PMS Restart\n\n${ERR_MSG}" | sendmail "${ADMIN_EMAIL}"
  58. fi
  59. # Give plex a breather to get restarted before we check again
  60. sleep "${RESTART_DELAY}"
  61. # Re-index (in the background)
  62. ~/bin/video/isScanning && \
  63. curl --silent --upload-file /dev/null "${PMS_URL}library/optimize" &
  64. fi
  65. # Sleep for the next loop or exit
  66. if [ $LOOP -gt 0 ]; then
  67. sleep $LOOP
  68. else
  69. exit 0
  70. fi
  71. done