summaryrefslogtreecommitdiffstats
path: root/clerk_fzf/clerk_fzf
blob: 66ba3e256ed7e78924a5e3aad97fac2b2abd72d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env bash

TMUX_TMPDIR="/tmp/clerk/tmux"

# default tmux config
tmux_config="/etc/clerk/tmux.conf"

# set default settings
script="$0 $1"
random_artist="albumartist"
shuf=$([[ "$OSTYPE" == "darwin"* ]] && echo 'gshuf' || echo 'shuf')  
value=20
# table customization
track_width="2"
title_width="40"
artist_width="50"
date_width="6"
# album is much longer in order to keep filename off screen
album_width="200"
pl_title_width="110"

# read global config
if [[ -f "/etc/clerk_fzf.conf" ]]; then
  source /etc/clerk_fzf.conf
fi

# create config dir, if needed
if [[ ! -d $HOME/.config/clerk ]]; then
  mkdir $HOME/.config/clerk
fi

# read user config
if [[ -f "$HOME/.config/clerk/clerk_fzf.conf" ]]; then
  source $HOME/.config/clerk/clerk_fzf.conf
fi

if [[ -n $mpd_host ]]; then
  if [[ -n $mpd_password ]]; then
    export MPD_HOST="${mpd_password}@${mpd_host}"
  else
    export MPD_HOST="${mpd_host}"
  fi
fi
 
if [[ -n $mpd_port ]]; then
  ┆ export MPD_PORT="${mpd_port}"
fi

albums () {
  script="$0 --albums"
  tracklist="$(cat ~/.config/clerk/albums.cache | fzf --no-sort -m -e --reverse -i --with-nth=1,2,3 -d '\t' --tabstop=4 +s --ansi --bind "ctrl-a:select-all,ctrl-n:deselect-all")"
  val=$?
  if [[ $val -eq 130 ]]; then
    albums
  fi
  track="$(echo "${tracklist}" | gawk -F "\t" '{print $NF}')"
  actions
}

latest () {
  script="$0 --latest"
  tracklist=$(cat ~/.config/clerk/latest.cache | fzf --no-sort -m -e --reverse -i --with-nth=1,2,3 -d '\t' --tabstop=4 +s --ansi --bind "ctrl-a:select-all,ctrl-n:deselect-all")
  val=$?
  if [[ $val -eq 130 ]]; then
    latest
  fi
  track="$(echo "${tracklist}" | gawk -F "\t" '{print $NF}')"
  actions
}

tracks () {
  script="$0 --tracks"
  tracklist=$(cat ~/.config/clerk/tracks.cache | fzf -m --reverse -i -e --with-nth=1,2,3,4,5 -d '\t' --tabstop=4 +s --ansi --bind "ctrl-a:select-all,ctrl-n:deselect-all")
  val=$?
  if [[ $val -eq 130 ]]; then
    tracks
  fi
  if [[ $tracklist == "< Go to Albumlist"* ]]; then
    latest
  fi
  track="$(echo "${tracklist}" | gawk -F "\t" '{print $NF}')"
  actions
}

actions () {
  action=$(echo -e "1. Replace\n2. Add\n3. Insert" | fzf --reverse -i --header="Choose Action or quit with ESC" --inline-info)

  if [[ $action == "1. Replace" ]]; then
    mpc clear > /dev/null
    echo "${track}" | while read line; do
      mpc add "${line}" > /dev/null
    done
    mpc play > /dev/null
  elif [[ $action == "2. Add" ]]; then
    echo "${track}" | while read line; do
      mpc add "${line}" > /dev/null
    done
  elif [[ $action == "3. Insert" ]]; then
    echo "${track}" | while read line; do
      mpc insert "${line}" > /dev/null
    done
  elif [[ $action -eq 130 ]]; then
    exit
  fi
  tmux findw -t music queue
  $(${script})
}

playRandomAlbum () {
    mpc clear > /dev/null
    artist="$(mpc list "albumartist" | $shuf -n 1)"
    album="$(mpc list album "albumartist" "$artist" | $shuf -n 1)"
    mpc findadd album "$album" "albumartist" "$artist" > /dev/null;
    mpc play > /dev/null
    tmux findw -t music queue
}

# same for tracks, no artist should be preferred because it has more tracks.
playRandomTracks () {
    mpc clear > /dev/null
    artist="$(mpc list "$random_artist" | $shuf -n 1)"
    album="$(mpc list album "$random_artist" "$artist" | $shuf -n 1)"
    title="$(mpc list title album "$album" "$random_artist" "$artist" | $shuf -n 1)"
    mpc findadd album "$album" "$random_artist" "$artist" title "$title" > /dev/null
    mpc play > /dev/null

    n=0; while (( n++ < $value -1 )); do
        artist="$(mpc list "$random_artist" | $shuf -n 1)"
        album="$(mpc list album "$random_artist" "$artist" | $shuf -n 1)"
        title="$(mpc list title album "$album" "$random_artist" "$artist" | $shuf -n 1)"
        mpc findadd album "$album" "$random_artist" "$artist" title "$title" > /dev/null
    done
    mpc play > /dev/null
    tmux findw -t music queue
}

fix_date_format() {
    # provided by Thorsten Wißmann:
    # https://github.com/t-wissmann/dotfiles/blob/master/menu/rofi-mpd.sh
    # reformats the date given in column $1 from format %c of locale LC_TIME=C
    # (see man strftime) to the format specified in argument $2 column indices
    # start with 1
    column_index="$1"
    gawk -F $'\t' '
    # parse a date which was formated using %c to unix time
    BEGIN {
        # generated by the following bash one-liner:
        # for i in {1..12} ; do LC_TIME=C date -d "1972-$i-01" +month2num[\"%b\"]\ =\ %_m ; done
        month2num["Jan"] =  1
        month2num["Feb"] =  2
        month2num["Mar"] =  3
        month2num["Apr"] =  4
        month2num["May"] =  5
        month2num["Jun"] =  6
        month2num["Jul"] =  7
        month2num["Aug"] =  8
        month2num["Sep"] =  9
        month2num["Oct"] = 10
        month2num["Nov"] = 11
        month2num["Dec"] = 12
    }
    function reformat_c_date(str) {
        monthname = gensub(/^([^ ]*)[ ]+([^ ]*)[ ]+([^ ]*)[ ]+([^ ]*)[ ]+([^ ]*)$/, "\\2", "g", str)
        monthnum = month2num[monthname]
        nicedate = gensub(/^([^ ]*)[ ]+([^ ]*)[ ]+([^ ]*)[ ]+([^ ]*)[ ]+([^ ]*)$/, "\\5 " monthnum " \\3 \\4", "g", str)
        nicedate = gensub(/:/, " ", "g", nicedate)
        return nicedate
    }
    {
        # modify the $column_index-th field
        $'"$1"' = strftime("'"$2"'", mktime(reformat_c_date($'"$1"')))
        print $0
    }
    '
}

updateCache () {
    notify-send "clerk" "updating cache files"
    cd $HOME/.config/clerk
    rm -f *.cache

    mpc --format '%mtime%\t[%albumartist%|%artist%] ○ (%date%) ○ %album% [(CD %disc%)] ○ %file%' \
        search filename '' \
        | fix_date_format 1 '%Y-%m-%d-%H:%M:%S' \
        | sort -nr \
        | gawk '{for (i=2; i<NF; i++) printf $i " "; print $NF }' \
        | perl -ne 'print unless $seen{$_}++' \
        | sed 's:/[^/]*$::' | awk -F ' ○ ' '!seen[$1 $2 $3 $4]++' \
        | uniq \
        | gawk -F ' ○ ' '{ printf "%-"'${artist_width}'"."'${artist_width}'"s\t%-"'${date_width}'"."'${date_width}'"s\t%-"'${album_width}'"."'${album_width}'"s\t%.300s\n", $1, $2, $3, $4 }' \
        > $HOME/.config/clerk/latest.cache
    mpc --format '[%albumartist%|%artist%]\t(%date%)\t%album% [(CD %disc%)]\t%file%' \
        search filename '' \
        | sed 's:/[^/]*$::' \
        | awk -F '\t' '!seen[$1 $2 $3 $4]++' \
        | sort \
        | gawk -F '\t' '{ printf "%-"'${artist_width}'"."'${artist_width}'"s\t%-"'${date_width}'"."'${date_width}'"s\t%-"'${album_width}'"."'${album_width}'"s\t%.300s\n", $1, $2, $3, $4 }' \
        > $HOME/.config/clerk/albums.cache
    mpc --format '%track%\t%title%\t%artist%\t(%date%)\t%album%\t%file%' \
        search filename '' \
        | gawk -F '\t' '{ printf "%-"'${track_width}'"."'${track_width}'"s\t%-"'${title_width}'"."'${title_width}'"s\t%-"'${artist_width}'"."'${artist_width}'"s\t%-"'${date_width}'"."'${date_width}'"s\t%-"'${album_width}'"."'${album_width}'"s\t%.500s\n", $1, $2, $3, $4, $5, $6 }' \
        > $HOME/.config/clerk/tracks.cache
    notify-send "clerk" "finished updating cache files"
    date=$(mpc stats | grep 'DB Updated: ')
    file="$HOME/.config/clerk/.lastupdate"
    echo "${date}" > "${file}"
#        | gawk -F '\t' '{ printf "%.2s\t%.40s\t%.40s\t%.200s\t%.500s\n", $1, $2, $3, $4, $5, $6 }' \
    if [[ $forceupdate == "true" ]]; then
      exit
    fi
}

clerk_update () {
screen=$(tmux list-panes -F "#W")

if [[ $1 == "--create-caches" ]]; then
  if [[ $animation == "1" ]]; then
    tmux new-session -s notify -n 'Updating Cache Files. Please wait a moment' -d 'sl'
  else
    tmux new-session -s notify -n 'Updating Cache Files. Please wait a moment' -d 'sh'
  fi
  tmux switchc -t notify
  clerk_fzf --caches &
  pid=$!
  wait $pid
fi

tmux new-session -s music2 -n albums -d 'clerk_fzf --albums'
tmux new-window -t music2 -n tracks 'clerk_fzf --tracks'
tmux new-window -t music2 -n latest 'clerk_fzf --latest'
tmux new-window -t music2 -n playlists 'clerk_fzf --playlists'
tmux new-window -t music2 -n queue 'ncmpcpp'

tmux rename-session -t music music_old
tmux rename-session -t music2 music
tmux switchc -t music
tmux findw -t music ${screen}
tmux kill-session -t music_old

if [[ $1 == "--create-caches" ]]; then
  tmux kill-session -t notify
fi
}

playlists () {
  pls=(
  "$(mpc lsplaylists)"
  "---"
  "Save current Queue as Playlist")


  plsmenu="$(printf '%s\n' "${pls[@]}" | fzf --no-sort -m -e --reverse -i --ansi --bind "ctrl-a:select-all,ctrl-n:deselect-all")"
  val=$?
  if [[ $val -eq 130 ]]; then
    playlists
  fi
  if [[ $plsmenu == "Save current Queue as Playlist" ]]; then
    mpc save "$(date +'%Y-%m-%d_%H:%M:%S')" 
    tmux findw -t music queue
    $(${script})
  else
    playlistactions
  fi
}

playlistactions () {
  menu_content=(
  "Load Playlist"
  "Append Playlist"
  "Delete Playlist"
  "Cancel")

  plmenu="$(printf '%s\n' "${menu_content[@]}" | fzf -m -e --reverse -i --ansi)"
  if [[ $val -eq 130 ]]; then
    tmux findw -t playlists
  fi
  if [[ $plmenu == "Load Playlist" ]]; then
    mpc clear > /dev/null; mpc load "${plsmenu}" > /dev/null; mpc play > /dev/null
    tmux findw -t music queue
    $(${script})
  elif [[ $plmenu == "Add Playlist" ]]; then
    mpc load "${plsmenu}" > /dev/null
    tmux findw -t music queue
    $(${script})
  elif [[ $plmenu == "Delete Playlist" ]]; then
    del_content=(
    "Yes"
    "No")

    delmenu="$(printf '%s\n' "${del_content[@]}" | fzf --reverse -i --ansi --header="Delete Playlist ${plsmenu}?")"
    if [[ $delmenu == "Yes" ]]; then
      mpc rm "${plsmenu}"
      playlists
    elif [[ $delmenu == "No" ]]; then
      playlists
    fi
  elif [[ $plmenu == "Cancel" ]]; then
    playlists
  fi
}

clerk_help () {
  grep -A14 '^## Key Bindings' "${tmux_config}" | awk -F '-n ' '{ print $2 }' | \
  sed 's/clerk_fzf --//g; s/run-shell//g; s/findw//g; s/\x27//g; s/--quiet//g; s/mpc //g; s/clerk_update --create-caches/create caches/; s/_/ /g; s/kill-session -t music/ kill session/g; s/  /\t/g' | \
  sed 's/clerk update/update views/' | column -t -s $'\t'
}


if [[ $1 == "--update" ]]; then
    :
else
    date=$(mpc stats | grep 'DB Updated: ')
    file="$HOME/.config/clerk/.lastupdate"
    if [ "$(< $file)" = "$date" ] && [ -f "$file" ] ; then
        :
    else
        updateCache
        date=$(mpc stats | grep 'DB Updated: ')
        echo "${date}" > "${file}"
    fi
fi

tmux_config="/etc/clerk/tmux.conf"

# read global config
if [[ -f "/etc/clerk_fzf.conf" ]]; then
  source /etc/clerk_fzf.conf
fi

clerk_start () {
# create config dir, if needed
if [[ ! -d $HOME/.config/clerk ]]; then
  mkdir $HOME/.config/clerk
fi

# read user config
if [[ -f "$HOME/.config/clerk/clerk_fzf.conf" ]]; then
  source $HOME/.config/clerk/clerk_fzf.conf
fi

# export MPD_HOST
if [[ -n $mpd_host ]]; then
  if [[ -n $mpd_password ]]; then
    export MPD_HOST="${mpd_password}@${mpd_host}"
  else
    export MPD_HOST="${mpd_host}"
  fi
fi

if [[ -n $mpd_port ]]; then
  ┆ export MPD_PORT="${mpd_port}"
fi


export TMUX_TMPDIR="/tmp/clerk/tmux"

if [[ ! -d "${TMUX_TMPDIR}" ]]; then
  mkdir -p "${TMUX_TMPDIR}"
fi
main
}

main() {
  tmux has-session -t music
  if [ $? != 0 ]; then
    tmux -f "${tmux_config}" new-session -s music -n albums -d 'clerk_fzf --albums'
    tmux new-window -t music -n tracks 'clerk_fzf --tracks'
    tmux new-window -t music -n latest 'clerk_fzf --latest'
    tmux new-window -t music -n playlists 'clerk_fzf --playlists'
    tmux new-window -t music -n queue 'ncmpcpp'
  fi
  tmux attach -t music
}


if [[ $1 == "--help" || $1 == "-h" ]]; then
  echo "clerk: MPD Interface using fzf and tmux"
  echo "Copyright © 2016 Rasmus Steinke"
  echo ""
  echo "--help, -h    this help message"
  echo "--kill        kill running clerk sessions"
elif [[ $1 == "--kill" ]]; then
  tmux kill-session -t music
elif [[ $1 == "--albums" ]]; then
  albums
elif [[ $1 == "--tracks" ]]; then
  tracks
elif [[ $1 == "--latest" ]]; then
  latest
elif [[ $1 == "--random_album" ]]; then
  playRandomAlbum
elif [[ $1 == "--random_tracks" ]]; then
  playRandomTracks
elif [[ $1 == "--update" ]]; then
  clerk_update --create-caches
elif [[ $1 == "--help" ]]; then
  clerk_help
elif [[ $1 == "--caches" ]]; then
  updateCache
elif [[ $1 == "--playlists" ]]; then
  playlists
else
  clerk_start
fi