#! /bin/bash notes() ( ids() { _recurse_ids "$(_tree)" } _tree() { local cache_key="notes _tree" if CACHE_DURATION=5 cache get "$cache_key"; then return 0 fi __tree "$@" | cache put "$cache_key" } __tree() { _nncurl $NOTES_ADDR/api/v0/tree } _nncurl() { curl -sS "$@" } _recurse_ids() { local json="$1" if echo "$json" | jq .Branches | grep -q ^null$; then return 0 fi local b64lines="$(echo "$json" | jq -r '.Branches | keys[]' | while read -r line; do echo "$line" | base64; done)" if [ -z "$b64lines" ]; then return 0 fi for line in $b64lines; do line="$(echo "$line" | base64 --decode)" if ! _is_deleted "$line"; then echo "$line" _recurse_ids "$(echo "$json" | jq -c ".Branches[\"$line\"]")" fi done } meta() { local cache_key="notes meta $*" if CACHE_DURATION=5 cache get "$cache_key"; then return 0 fi _meta "$@" | cache put "$cache_key" } _meta() { local id="$1" local tree="$(_tree)" local pid="${id%%/*}" while [ "$id" != "$pid" ]; do tree="$(echo "$tree" | jq ".Branches[\"$pid\"]")" local to_add="${id#$pid/}" to_add="${to_add%%/*}" pid="$pid/$to_add" done echo "$tree" | jq ".Branches[\"$id\"].Leaf" } _is_deleted() { local id="$1" while [ -n "$id" ]; do if meta "$id" | jq .Deleted | grep -q true; then return 0 fi if [ "$id" == "${id%/*}" ]; then return 1 fi id="${id%/*}" done return 1 } get() { _get "$@" } _get() { _nncurl $NOTES_ADDR/api/v0/files/$1 } del() { local id="$1" _nncurl \ -X DELETE \ $NOTES_ADDR/api/v0/files/$id } put() { set -u local ret=0 if ! _put "$@"; then ret=1 fi set +u return $ret } _put() { local id="$1" local title="$2" local body="$3" _nncurl \ -X PUT \ -H "Title: $title" \ -H "Read-Only: true" \ -d "$body" \ $NOTES_ADDR/api/v0/files/$id >&2 } "$@" )