download.sh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/bin/bash
  2. # Config
  3. 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"
  4. TRANS_URL="http://vera.uberzach.com:9091/transmission/rpc"
  5. TIMEOUT=10
  6. # Exclude URLs that match a given regex
  7. GREP_EXCLUDE=""
  8. if [ -n "${DOWNLOAD_EXCLUDE}" ]; then
  9. GREP_EXCLUDE="(`head -c -1 ${DOWNLOAD_EXCLUDE} | tr $'\n' '|'`)"
  10. fi
  11. # Grab the input URLs
  12. URLS="`cat -`"
  13. # Bail if there's nothing to process
  14. if [ -z "${URLS}" ]; then
  15. exit 0
  16. fi
  17. # Choose an inter-file delay
  18. DELAY="${2}"
  19. if [ -z "${DELAY}" ]; then
  20. DELAY=10
  21. fi
  22. # Find the destination directory
  23. DEST="${1}"
  24. if [ -z "${DEST}" ]; then
  25. DEST="${HOME}/Desktop"
  26. if [ -e "${DEST}" ]; then DEST="${HOME}"; fi
  27. fi
  28. # Use Transmission if the URL is a magenet link
  29. if echo "${URLS}" | head -n 1 | grep -Eqi '^magnet:'; then
  30. SESSION_ID=$(curl --silent --max-time "${TIMEOUT}" "${TRANS_URL}" | sed 's/.*<code>//g;s/<\/code>.*//g')
  31. if [ -n "${SESSION_ID}" ]; then
  32. SLEEP=0
  33. IFS=$'\n'
  34. for i in ${URLS}; do
  35. if [ -n "${GREP_EXCLUDE}" ] && echo "${i}" | grep -Eq "${GREP_EXCLUDE}"; then continue; fi
  36. if [ $SLEEP -gt 0 ]; then sleep $SLEEP; fi
  37. SLEEP="${DELAY}"
  38. RESULT="`curl --silent --max-time "${TIMEOUT}" \
  39. --header "${SESSION_ID}" "${TRANS_URL}" \
  40. -d '{"method":"torrent-add", "arguments":{"paused": "false", "filename": "'${i}'"}}'`"
  41. if ! echo "${RESULT}" | grep -q '"result":"success"'; then
  42. exit 1
  43. fi
  44. done
  45. exit 0
  46. else
  47. echo "Transmission not available for magnet link, falling back..." 1>&2
  48. fi
  49. fi
  50. # Use "open", if available, for non-HTTP URLs
  51. if ! echo "${URLS}" | head -n 1 | grep -Eqi '^http'; then
  52. if open >/dev/null 2>&1; then
  53. echo "${URLS}" | xargs -n 1 open
  54. exit "${?}"
  55. else
  56. echo "Non-HTTP URL, open() not available. Aborting..." 1>&2
  57. exit 1
  58. fi
  59. fi
  60. # Download
  61. cd "${DEST}"
  62. wget --quiet \
  63. --connect-timeout "${TIMEOUT}" \
  64. --wait "${DELAY}" --random-wait \
  65. "--user-agent=${AGENT}" \
  66. --continue \
  67. --no-check-certificate \
  68. --input-file -