No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

goog 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env bash
  2. declare -r esc=$'\033'
  3. declare -r c_reset="${esc}[0m"
  4. declare -r c_red="${esc}[31m"
  5. err() {
  6. printf "${c_red}%s${c_reset}\n" "$*" >&2
  7. }
  8. die() {
  9. [[ -n "$1" ]] && err "$1"
  10. exit 1
  11. }
  12. has() {
  13. local verbose=0
  14. if [[ $1 == '-v' ]]; then
  15. verbose=1
  16. shift
  17. fi
  18. for c; do c="${c%% *}"
  19. if ! command -v "$c" &> /dev/null; then
  20. (( verbose > 0 )) && err "$c not found"
  21. return 1
  22. fi
  23. done
  24. }
  25. openurl() {
  26. local url="$1"
  27. local browser
  28. case "$url" in
  29. *youtube.com*|*youtu.be*|*vimeo.com*)
  30. browser=$(select_from \
  31. mpv mplayer2 mplayer) ;;
  32. *)
  33. browser=$(select_from \
  34. -c "pgrep -u $USER -i" \
  35. firefox chromium-browser chrome)
  36. [[ ! $browser ]] && browser='w3m'
  37. ;;
  38. esac
  39. $browser "$url"
  40. }
  41. # http://stackoverflow.com/a/10660730
  42. rawurlencode() {
  43. local string="$*"
  44. local strlen=${#string}
  45. local encoded=""
  46. for (( pos=0; pos < strlen; pos++ )); do
  47. c="${string:$pos:1}"
  48. case "$c" in
  49. [-_.~a-zA-Z0-9])
  50. o="$c" ;;
  51. *)
  52. printf -v o '%%%02x' "'$c"
  53. esac
  54. encoded+="${o}"
  55. done
  56. echo "${encoded}"
  57. }
  58. has -v curl jq fzf || die
  59. if [[ -z "$*" ]]; then
  60. die 'nothing to search for'
  61. fi
  62. response=$( curl -sfL "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=$(rawurlencode "$*")" ) || die 'error connecting to google, check connection'
  63. json=$( jq -c '.["responseData"]["results"] | map("\(.unescapedUrl) \(.title) | \(.content)") | .[]' <<< "$response" ) || die 'error parsing results :('
  64. url=$( fzf -e --ansi --cycle --inline-info <\
  65. <( sed -r 's/<[^>]*>//g; s/\\n//g; s/^\s*"//; s/",?$//' <<< "$json" ) |
  66. cut -d' ' -f1 )
  67. if [[ -n "$url" ]]; then
  68. openurl "$url"
  69. fi