+ /a/opt/android-studio/bin/studio.sh "$@" & r
+}
+
+# convert brains path to url
+# /f/brains/sysadmin/interns/2022/nick_shrader/intro_blog_post.mdwn
+# becomes
+# https://brains.fsf.org/wiki/sysadmin/interns/2022/nick_shrader/intro_blog_post
+iki() {
+ local url path
+ if [[ $1 ]]; then
+ path="$*"
+ else
+ read -r -p "enter path" path
+ fi
+ url=$(readlink -f "$path")
+ url="https://brains.fsf.org/wiki/${url#*brains/}"
+ url="${url%.mdwn}"
+ echo "$url"
+
+}
+
+# Generate beet smartplaylists for navidrome.
+# for going in the reverse direction, run
+# /b/ds/navidrome-playlist-export
+beetsmartplaylists() {
+ install -m 0700 -d /tmp/ianbeetstmp
+ beet splupdate
+ # kill off any playlists we deleted. they will still need manual
+ # killing from a navidrome client.
+ rm -rf /i/converted/beetsmartplaylists
+ mkdir -p /i/converted/beetsmartplaylists
+ for f in /tmp/ianbeetstmp/*; do
+ sed 's,^/i/m,/i/converted,;s,\.flac$,.mp3,' "$f" >"/i/converted/beetsmartplaylists/${f##*/}"
+ rm "$f"
+ done
+ rmdir /tmp/ianbeetstmp
+}
+
+# internal function for beetrating, in case we need to ssh
+beetrating-stdin() {
+ local tmp rating path cpath sqlpath userid
+ # plucked this from the db. im the only user.
+ userid=23cc2eb9-e35e-4811-a0f0-d5f0dd6eb634
+ while read -r rating path; do
+ cpath="/i/converted${path#/i/m}" # converted path
+ case $cpath in
+ *.flac)
+ cpath="${cpath%.*}.mp3"
+ ;;
+ esac
+ if [[ ! -e $cpath ]]; then
+ echo "beetraing: error: this should not happen, path does not exist: $cpath"
+ return 1
+ fi
+ sqlpath="${cpath//\'/\'\'}"
+ old_rating=$(sqlite3 /i/navidrome/navidrome.db "select rating from annotation inner join media_file on item_id = id where path = '$sqlpath' and item_type = 'media_file';")
+ if [[ $old_rating ]]; then
+ if [[ $old_rating != "$rating" ]]; then
+ echo "setting rating $old_rating -> $rating $cpath"
+ # https://stackoverflow.com/a/50317320
+ # we got a timeout error once. arbitrarily chose 15 seconds.
+ sqlite3 /i/navidrome/navidrome.db ".timeout 15000" "
+update annotation set rating = $rating
+ where item_id in (
+ select media_file.id from annotation inner join media_file on annotation.item_id = media_file.id
+ where media_file.path = '$sqlpath' and annotation.item_type = 'media_file' );"
+ fi
+ else
+ echo "setting rating $rating $cpath"
+ # /a/opt/navidrome/persistence/sql_annotations.go v0.48.0
+ # https://www.sqlite.org/lang_insert.html
+ sqlite3 /i/navidrome/navidrome.db ".timeout 15000" "insert into annotation select '$(uuidgen)', '$userid', id, 'media_file', 0, NULL, $rating, 0, NULL from media_file where path = '$sqlpath';"
+ fi
+ done
+}
+
+# Export beets ratings into navidrome
+beetrating() {
+ local ssh_prefix
+ if [[ $HOSTNAME != kd ]]; then
+ ssh_prefix="ssh b8.nz"
+ fi
+ # shellcheck disable=SC2016 # obvious reason
+ beet ls -f '$rating $path' $nav_convert_query | $ssh_prefix beetrating-stdin
+}
+
+# Do transcoding and hardlinking of audio files for navidrome.
+beetconvert() {
+ local tmpf
+ tmpf="$(mktemp)"
+ # a bunch of effort to ignore output we dont care about...
+ sed 's/^format_item:.*/format_item: ignore_this/' ~/.config/beets/config.yaml >$tmpf
+ beet -c $tmpf convert -y $nav_convert_query > >(grep -vFx 'ignore_this' ||:) 2> >(grep -v '^convert: Skipping' ||:)
+ rm "$tmpf"
+}
+# This deletes files in the converted directory which should no longer
+# be there due to a rename of the unconverted file.
+beetconvert-rm-extras() {
+ local l tmpf
+ local -A paths
+ tmpf="$(mktemp)"
+ # shellcheck disable=SC2016 # obvious reason
+ beet ls -f '$path' $nav_convert_query >"$tmpf"
+ ## begin removal of files that are leftover from previous conversion,
+ # eg, previously rated > 1, now rated 1.
+ while read -r l; do
+ convertedpath="/i/converted${l#/i/m}"
+ case $convertedpath in
+ *.flac) convertedpath="${convertedpath%.flac}.mp3" ;;
+ esac
+ paths[$convertedpath]=t
+ done <"$tmpf"
+
+ find /i/converted -path /i/converted/beetsmartplaylists -prune -o \( -type f -print \) -name '*.mp3' -o -name '*.m4a' >"$tmpf"
+ while read -r l; do
+ if [[ ! ${paths[$l]} ]]; then
+ rm -v "$l"
+ fi
+ # note: the pruning is duplicative of filtering on name, but whatever.
+ done <"$tmpf"
+ rm "$tmpf"
+}
+
+beets-gen-playlists() {
+ local i str
+ local -a query_array query_str
+ for i in "${!bpla[@]}"; do
+ query_str=()
+ eval "query_array=(${bpla[$i]})"
+ for str in "${query_array[@]}"; do
+ query_str+=("\"$str\"")
+ done
+ cat <<EOF
+ - name: $i.m3u
+ query: '${query_str[@]}'
+EOF
+ done
+}
+
+# beet playlist. use beetag with a playlist name
+bpl() {
+ eval beetag -r "$@" "${bpla[${@: -1}]}"
+}
+complete -W "${!bpla[*]}" bpl
+
+
+# beet modify quietly
+beetmq() {
+ local tmpf
+ tmpf="$(mktemp)"
+ # a bunch of effort to ignore output we dont care about...
+ sed 's/^format_item:.*/format_item: ignore_this/' ~/.config/beets/config.yaml >$tmpf
+ beet -c $tmpf modify -y "$@" > >(grep -vFx -e 'ignore_this' -e 'Modifying 1 items.' ||:)
+ rm "$tmpf"
+ scrolled+=1
+}
+
+# Must be called from beetag for variables to be setup
+beetag-help() {
+ # - 3 is just a constant that helps things work in practice.
+ if [[ $LINES ]] && (( LINES - 3 < scrolled )); then
+ hr
+ for (( i=0; i<${#button_map[@]}; i++)); do
+ if (( i % 3 == 2 )); then
+ printf "%s %s\n" ${buttons[i]} ${button_map[i]}
+ else
+ printf "%s %-15s" ${buttons[i]} ${button_map[i]}
+ fi
+ done
+ echo
+ cat <<'EOF'
+y other genres z fg player ' = toggle play
+; previous _ = delete -/+ volume ->/<- skip
+EOF
+ hr
+ scrolled=10
+ fi
+}
+
+# tag with beets.
+# usage: beetag [-r] [-s] QUERY
+# it lists the query, reads an input char for tagging one by one.
+#
+# note, you may want to change the play command for doing rapid taging
+# by immediately jumping forward into the song. this is set in the beets
+# config yaml.
+#
+# (available buttons: ` \ ) ] [ and non-printing chars, see
+# https://stackoverflow.com/questions/10679188/casing-arrow-keys-in-bash
+#
+#
+# note: after foregrounding the player, must quit it to get back. can't ctrl-c.
+#
+# keys I dont need help to remember:
+# 1-5 rate
+# q quit
+# ret next
+beetag() {
+ local last_genre_i fstring tag id char new_item char_i genre tag remove doplay i j random
+ local do_rare_genres read_wait help line lsout tmp ls_line
+ local escape_char escaped_input expected_input skip_input_regex
+ local -a pl_tags buttons button_map ids tags rare_genres tmp_tags initial_ls ls_lines
+ local -A button_i
+ local -i i j volume scrolled id_count line_int skip_start pre_j_count head_count
+
+
+ escape_char=$(printf "\u1b")
+ scrolled=999 # more than any $LINES
+ ### begin arg processing ###
+ random=false
+ case $1 in
+ -r)
+ random=true
+ shift
+ ;;
+ -s)
+ random=false
+ shift
+ ;;
+ esac
+ if (( ! $# )); then
+ echo beetag: error expected a query arg >&2
+ return 1
+ fi
+ ### end arg processing ###
+
+ beetpull
+
+ do_rare_genres=false
+ volume=70
+ read_wait=2
+ doplay=true
+ # because we were destined to run out of single key buttons.
+ rare_genres=(
+ jazz
+ musical
+ noise
+ skit
+ spoken-w
+ )
+
+ last_genre_i=$(( ${#common_genres[@]} - 1 ))
+ buttons=( {a..p} {r..w} 0 {6..9} , . / )
+ button_map=(${common_genres[@]} ${pl_tags[@]})
+ fstring=
+ for tag in "${pl_tags[@]}"; do
+ fstring+="%ifdef{$tag,$tag }"
+ done
+
+ for (( i=0; i<${#buttons[@]}; i++ )); do
+ button_i[${buttons[i]}]=$i
+ done
+
+ # TODO: use shuf --random-source=FILE to save the random sort order
+ # for reusing later, so we can pickup where we left off in a playlist.
+
+ # shellcheck disable=SC2016 # obvious reason
+ mapfile -t initial_ls < <(beet ls -f '$id %ifdef{rating,$rating }'"$fstring"'$genre | $artist - $album - $title $length' "$@" | { if $random; then sort -R; else cat; fi; } )
+ j=0
+ # i only care to see the head of the list.
+ head_count=$(( LINES - 14 ))
+ for line in "${initial_ls[@]}"; do
+ id="${line%% *}"
+ ids+=("$id")
+ ls_line="${line#* }"
+ ls_line="$ls_line $id"
+ ls_lines+=("$ls_line")
+ if (( j < head_count )); then
+ echo "$ls_line"
+ fi
+ j=$(( j+1 ))
+ done
+ id_count=${#ids[@]}
+ for (( j=0; j < id_count; j++ )); do
+ id=${ids[j]}
+ lsout="${ls_lines[j]}"
+ tags=( ${lsout%%,*} )
+ beetag-help
+ printf "██ %s\n" "$lsout"
+ scrolled+=1
+ if $doplay; then
+ # https://stackoverflow.com/a/7687716
+ # note: duplicated down below
+ { beet play "--args=--volume=$volume" "id:$id" 2>&1 & } 2>/dev/null
+ fi
+ while true; do
+ char=
+ if $doplay; then
+ ret=0
+ read -rsN1 -t $read_wait char || ret=$?
+ read_wait=2
+ # Automatically skip to the next song if this one ends, unless
+ # we turn off the autoplay.
+ if (( ret == 142 )) || [[ ! $char ]]; then
+ if bg %% &>/dev/null; then
+ continue
+ else
+ break
+ fi
+ fi
+ else
+ read -rsN1 char
+ fi
+ beetag-help
+ if [[ $char == $'\n' ]]; then
+ # https://stackoverflow.com/a/5722874
+ kill %%; wait %% 2>/dev/null ||:
+ break
+ fi
+ case $char in
+ ";")
+ kill %%; wait %% 2>/dev/null ||:
+ j=$(( j - 2 ))
+ break
+ ;;
+ "'")
+ if $doplay; then
+ echo "play toggled off"
+ doplay=false
+ else
+ doplay=true
+ kill %%; wait %% 2>/dev/null ||:
+ { beet play "--args=--volume=$volume" "id:$id" 2>&1 & } 2>/dev/null
+ fi
+ scrolled+=1
+ continue
+ ;;
+ _)
+ kill %%; wait %% 2>/dev/null ||:
+ m beet rm --delete --force "id:$id"
+ scrolled+=4 # guessing. dont want to test atm
+ break
+ ;;
+ [1-5])
+ beetmq "id:$id" rating=$char
+ continue
+ ;;
+ -)
+ volume=$(( volume - 5 ))
+ if (( volume < 0 )); then
+ volume=0
+ fi
+ echo volume=$volume
+ scrolled+=1
+ continue
+ ;;
+ q)
+ kill %%; wait %% 2>/dev/null ||:
+ return
+ ;;
+ +)
+ volume+=5
+ if (( volume > 130 )); then
+ volume=130
+ fi
+ echo volume=$volume
+ scrolled+=1
+ continue
+ ;;
+ y)
+ if $do_rare_genres; then
+ do_rare_genres=false
+ button_map=(${common_genres[@]} ${pl_tags[@]})
+ last_genre_i=$(( ${#rare_genres[@]} - 1 ))
+ else
+ do_rare_genres=true
+ button_map=(${rare_genres[@]} ${pl_tags[@]})
+ last_genre_i=$(( ${#rare_genres[@]} - 1 ))
+ fi
+ local -A button_i
+ for (( i=0; i<${#buttons[@]}; i++ )); do
+ button_i[${buttons[i]}]=$i
+ done
+ for (( i=0; i<${#button_map[@]}; i++ )); do
+ echo ${buttons[i]} ${button_map[i]}
+ done
+ continue
+ ;;
+ z)
+ scrolled+=3
+ # if we ctrl-z, it will put the whole function into sleep. so
+ # basically, we can't return from a foregrounded mpv like we
+ # would like to without some strange mechanism I can't think
+ # of. So, instead, detect ctrl-c and wait a while for prompt
+ # input. One idea would be to use a music player like mpd where
+ # we can send it messages.
+ if ! fg; then
+ read_wait=10
+ fi
+ continue
+ ;;
+ "$escape_char")
+ expected_input=true
+ read -rsn2 escaped_input
+ skip_input_regex="^[0-9]+$"
+ skip_back=false
+ case $escaped_input in
+ '[D')
+ # skip backward
+ if (( j == 0 )); then
+ echo "no earlier songs"
+ continue
+ fi
+ skip_back=true
+ {
+ line_int=0
+ for (( i=j-1; i >= 0; i-- )); do
+ echo "$line_int | ${ls_lines[i]}"
+ line_int+=1
+ done
+ } | less -F
+ scrolled+=$j
+ ;;
+ '[C')
+ # skip forward, but show the last few songs anyways.
+ skip_start=0
+ if (( j - 3 > skip_start )); then
+ skip_start=$(( j - 3 ))
+ fi
+ {
+ line_int=0
+ for (( i=skip_start; i < id_count; i++ )); do
+ if (( i == j )); then
+ echo " * ${ls_lines[i]}"
+ continue
+ fi
+ echo "$line_int | ${ls_lines[i]}"
+ line_int+=1
+ done
+ } | less -F
+ scrolled+=$(( id_count - skip_start - 1 ))
+ ;;
+ *)
+ expected_input=false
+ ;;
+ esac
+ if $expected_input; then
+ read -r skip_input
+ if [[ $skip_input =~ $skip_input_regex ]]; then
+ if $skip_back; then
+ j=$(( j - skip_input - 2 ))
+ else
+ pre_j_count=$(( j - skip_start ))
+ j=$(( j + skip_input - pre_j_count ))
+ if (( skip_input < pre_j_count )); then
+ j=$(( j - 1 ))
+ fi
+ fi
+ kill %%; wait %% 2>/dev/null ||:
+ break
+ fi
+ fi
+ ;;
+ esac
+ char_i=${button_i[$char]}
+ new_item=${button_map[$char_i]}
+ if [[ ! $char_i || ! $new_item ]]; then
+ echo "error: no mapping of input: $char found, try again"
+ continue
+ fi
+ if (( char_i <= last_genre_i )); then
+ m beetmq "id:$id" genre=$new_item
+ else
+ remove=false
+ tmp_tags=()
+ for tag in ${tags[@]}; do
+ if [[ $new_item == "$tag" ]]; then
+ remove=true
+ else
+ tmp_tags+=("$tag")
+ fi
+ done
+ if $remove; then
+ tags=("${tags[@]}")
+ m beetmq "id:$id" "$new_item!"
+ else
+ tags+=("$new_item")
+ m beetmq "id:$id" $new_item=t
+ fi
+ fi
+ done
+ done
+}
+
+# usage: FILE|ALBUM_DIR [GENRE]
+beetadd() {
+ local import_path genre_arg single_track_arg
+ import_path="$1"
+ if [[ ! -e $import_path ]]; then
+ echo "beetadd error: path does not exist"
+ fi
+ if [[ $2 ]]; then
+ genre_arg="--set genre=$2"
+ fi
+ if [[ -f $import_path ]]; then
+ single_track_arg=-s
+ fi
+ beet import --set totag=t $single_track_arg $genre_arg "$import_path"
+ beetag totag:t
+ beet modify -y totag:t "totag!"
+}
+
+# update navidrome music data after doing beets tagging
+beet2nav() {
+ m beetpull
+ m beetconvert
+ m beetrating
+ # this function would naturally just be part of beetconvert,
+ # but we want beetrating to happen sooner so that our ssh auth dialog
+ # happens earlier. Currently 17 seconds for that.
+ m beetconvert-rm-extras
+ m beetsmartplaylists
+}
+
+# pull in beets library locally
+beetpull() {
+ if [[ $HOSTNAME == kd ]]; then
+ return 0
+ fi
+ if [[ ! -e /i ]]; then
+ s mkdir /i
+ s chown iank:iank /i
+ fi
+ if ! mountpoint /i &>/dev/null; then
+ m sshfs b8.nz:/i /i
+ fi
+}
+
+# remove all playlists in navidrome, for when I make big
+# playlist name changes and just want to scrap everything.
+nav-rm-plists() {
+ local tmpf id
+ tmpf=$(mktemp)
+ if [[ $HOSTNAME != kd ]]; then
+ echo "error: run on kd"
+ return 1
+ fi
+ sqlite3 /i/navidrome/navidrome.db "select id from playlist" >$tmpf
+ while read -r id; do
+
+ curl --http1.1 --user "iank:$navidrome_pw" "https://b8.nz/rest/deletePlaylist.view?u=iank&s=sb219dvv7egnoe4i47k75cli0m&t=1c8f5575cd0fdf03deb971187c9c88b1&v=1.2.0&c=DSub&id=$id"
+ done <$tmpf
+ rm $tmpf
+}
+
+# escape regex.
+#
+# This is not perfect but generally good enough. It escapes all
+# metachars listed man 3 pcrepattern.
+er() {
+ sed 's/[]\\^$.[|()?*+{}]/[&]/g; s/\^/\\^/g' <<<"$*"
+}
+
+# usage beegenre QUERY
+#
+# beet set genre for QUERY based on existing artist most used genre on
+#
+# inverse of query for each artist found in QUERY. If query starts with
+# "artist:" it is used as the artist instead of each artist in QUERY.
+#
+beegenre() {
+ local count artist artregex genre singleartist tmpf tmpf2
+ local -a artists genres
+ singleartist=false
+ case $1 in
+ artist:*)
+ singleartist=true
+ artist="$1"
+ shift
+ ;;
+ esac
+ tmpf=$(mktemp)
+ tmpf2=$(mktemp)
+ if $singleartist; then
+ # shellcheck disable=SC2016 # obvious reason
+ beet ls -f '$genre' "$artist" "${@/#/^}" | sort | uniq -c | sort -n | tail -n1 >$tmpf
+ read -r count genre <$tmpf ||:
+ beet modify "$artist" "$@" genre=$genre
+ else
+ # shellcheck disable=SC2016 # obvious reason
+ beet ls -f '$artist' "$@" | sort -u >$tmpf
+ while read -r artist; do
+ artregex=$(er "$artist")
+ # shellcheck disable=SC2016 # obvious reason
+ beet ls -f '$genre' "artist::^$artregex$" "${@/#/^}" | sort | uniq -c | sort -n | tail -n1 >$tmpf2
+ read -r count genre <$tmpf2 || continue
+ if [[ $count ]]; then
+ artists+=("$artregex")
+ genres+=("$genre")
+ echo "beet modify -y $* \"artist::^$artist$\" genre=$genre # $count"
+ fi
+ done <$tmpf
+ read -r -N 1 -s -p "Y/n " char
+ case $char in
+ [Yy$'\n'])
+ for (( i=0; i<${#artists[@]}; i++ )); do
+ beet modify -y "$@" "artist::^${artists[i]}$" genre=${genre[i]}
+ done
+ ;;
+ esac
+ fi
+ rm $tmpf