
if [ -z "$DB" ]
  then DB="urls.db"
fi
db="$(realpath "$DB")"

db-init(){
  sqlite3 "$db" "CREATE TABLE urls (shortened VARCHAR(30) PRIMARY KEY, original TEXT)"
}

get-shortened(){
  grep -ro "https://t.co/[0-9a-zA-Z…]\+" | grep -o 'https.*' | grep -v … | sort -u
}

get-location(){
  curl -X HEAD -vvv "$1" -o /dev/null 2>&1 | sed -n 's/< location: *\([^ ]*\)/\1/p'
}

unshorten-all(){
  get-shortened |
  while read line
  do
    printf '%s: ' "$line"
    get-real-url "$line"
  done
}

get-real-url(){
  shortened="$1"
  original="$(sqlite3 "$db" "SELECT original FROM urls WHERE shortened='$shortened'")"
  if [ -z "$original" ]
  then
    if original="$(get-location "$shortened")"
      then sqlite3 "$db" "INSERT INTO urls (shortened,original) VALUES ('$shortened','$original')"
    fi
  fi
  echo "$original"
}

get-video-urls(){
  sqlite3 "$db" 'SELECT original FROM urls WHERE original LIKE "https://twitter.com/%/status/%/video/%"'
}

get-photo-urls(){
  sqlite3 "$db" 'SELECT original FROM urls WHERE original LIKE "https://twitter.com/%/status/%/photo/%"'
}

download-videos()(
  cd video || exit 1
  get-video-urls |
  while read video
  do
    yt-dlp --download-archive downloaded --xattrs -o "%(title).127s.%(ext)s" "$video"
  done
)

download-photos(){
  set -x
  get-photo-urls |
  while read image
  do (
    set -e
    for file in $(gallery-dl --write-metadata --write-info-json --download-archive "gallery-dl/downloaded" "$image" | grep -v "^#.*")
    do
      setfattr --raw -n user.xdg.referrer.url -v "$image" "$file"
    done
  ); done
}

file-get-url(){
  getfattr --only-values -n user.xdg.referrer.url "$1"
}
