download.sh 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/bin/bash
  2. # Config
  3. source ~/.download.config
  4. TIMEOUT=10
  5. AGENT="Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"
  6. # Grab the input URLs
  7. URLS="`cat -`"
  8. # Bail if there's nothing to process
  9. if [ -z "${URLS}" ]; then
  10. exit 0
  11. fi
  12. # Choose an inter-file delay
  13. DELAY="${2}"
  14. if [ -z "${DELAY}" ]; then
  15. DELAY=10
  16. fi
  17. # Find the destination directory
  18. DEST="${1}"
  19. if [ -z "${DEST}" ]; then
  20. DEST="${HOME}/Desktop"
  21. if [ -e "${DEST}" ]; then DEST="${HOME}"; fi
  22. fi
  23. # Use Transmission if the URL is a magenet link
  24. if [ -n "${TRANS_URL}" ] && echo "${URLS}" | head -n 1 | grep -Eqi '^magnet:'; then
  25. SESSION_ID=$(curl --silent --max-time "${TIMEOUT}" "${TRANS_URL}" | sed 's/.*<code>//g;s/<\/code>.*//g')
  26. if [ -n "${SESSION_ID}" ]; then
  27. IFS=$'\n'
  28. SLEEP=0
  29. for i in ${URLS}; do
  30. if [ $SLEEP -gt 0 ]; then sleep $SLEEP; fi
  31. SLEEP="${DELAY}"
  32. RESULT="`curl --silent --max-time "${TIMEOUT}" \
  33. --header "${SESSION_ID}" "${TRANS_URL}" \
  34. -d '{"method":"torrent-add", "arguments":{"paused": "false", "filename": "'${i}'"}}'`"
  35. if ! echo "${RESULT}" | grep -q '"result":"success"'; then
  36. exit 1
  37. fi
  38. done
  39. exit 0
  40. else
  41. echo "Transmission not available for magnet link, falling back..." 1>&2
  42. fi
  43. # Use NZBGet if the URL is an NZB file
  44. elif [ -n "${NZB_URL}" ] && echo "${URLS}" | head -n 1 | grep -Eqi 'nzb.cat/getnzb/'; then
  45. if curl --silent --max-time "${TIMEOUT}" "${NZB_URL}" | grep -q 'version'; then
  46. IFS=$'\n'
  47. SLEEP=0
  48. for i in ${URLS}; do
  49. if [ $SLEEP -gt 0 ]; then sleep $SLEEP; fi
  50. SLEEP="${DELAY}"
  51. NAME="`echo "${i}" | cut -d '#' -f 2-`"
  52. RESULT="`curl --silent --max-time "${TIMEOUT}" "${NZB_URL}" \
  53. -d '{"method":"append","params":["'"${NAME}"'.nzb","'"${i}"'","",0,false,false,"",0,"force"]}'`"
  54. if ! echo "${RESULT}" | grep 'result' | grep -q '[1-9]'; then
  55. exit 1
  56. fi
  57. done
  58. exit 0
  59. else
  60. echo "NZBGet not available for NZB link, falling back..." 1>&2
  61. fi
  62. fi
  63. # Use "open", if available, for non-HTTP URLs
  64. if ! echo "${URLS}" | head -n 1 | grep -Eqi '^http'; then
  65. if open >/dev/null 2>&1; then
  66. echo "${URLS}" | xargs -n 1 open
  67. exit "${?}"
  68. else
  69. echo "Non-HTTP URL, open() not available. Aborting..." 1>&2
  70. exit 1
  71. fi
  72. fi
  73. # Download
  74. cd "${DEST}"
  75. wget --quiet \
  76. --connect-timeout "${TIMEOUT}" \
  77. --wait "${DELAY}" --random-wait \
  78. "--user-agent=${AGENT}" \
  79. --continue \
  80. --no-check-certificate \
  81. --input-file -