notea-de-me/app/crawler/notnotea.sh

119 lines
2.5 KiB
Bash

#! /bin/bash
notnotea() (
ids() {
_recurse_ids "" "$(_tree)"
}
_tree() {
local cache_key="notnotea cache _tree"
if cache get "$cache_key"; then
return 0
fi
__tree "$@" | cache put "$cache_key"
}
__tree() {
_nncurl $NNOTEA_ADDR/api/v0/tree
}
_nncurl() {
curl -sS "$@"
}
_recurse_ids() {
local prefix="$1"
local json="$2"
local b64lines="$(echo "$json" | jq -r '.Branches | keys[]' | base64)"
if [ -z "$b64lines" ]; then
return 0
fi
for line in $b64lines; do
line="$(echo "$line" | base64 --decode)"
local subfix="$(printf "%s/%s" "$prefix" "$line")"
subfix="${subfix#/}"
if ! _is_deleted "$subfix"; then
echo "$subfix"
fi
_recurse_ids "$subfix" "$(echo "$json" | jq ".Branches.$line")"
done
}
meta() {
local id="$1"
id="${id//\//.Branches.}"
_tree | jq -c ".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
}
_tree_ids() {
_ncurl $NOTEA_ADDR/api/tree \
| jq '.items | to_entries[].value.id' \
| grep -v '^null$' \
| jq -r . \
| grep -v '^root$'
}
get() {
local cache_key="notea cache $1"
if cache get "$cache_key"; then
return 0
fi
_get "$@" | cache put "$cache_key"
}
_get() {
_ncurl $NOTEA_ADDR/api/notes/$1
}
put() {
set -u
local ret=0
if ! _put "$@"; then
ret=1
fi
set +u
return $ret
}
_put() {
local xsrf_key="xsrf-token"
local contains_tokens="$(_ncurl -i $NOTEA_ADDR/api)"
local xsrf_token="$(echo "$contains_tokens" | grep -o '"csrfToken":[^,]*' | tr ':' '\n' | jq -r . | tail -n 1)"
local xsrf_cookie="$(echo "$contains_tokens" | grep ^set.cookie: | sed 's/^set.cookie: //' | tr ';' '\n' | head -n 1)"
local request="$(echo '{
"content": '"$(printf "%s\n" "$CONTENT" | jq -Rs)"',
"deleted": 0,
"id": '"$(echo "$ID" | jq -R)"',
"pid": '"$(echo "$PID" | jq -R)"',
"pinned": 0,
"shared": 0,
"title": '"$(echo "$TITLE [generated]" | jq -R)"'
}' | jq -c .)"
echo "$request" | _ncurl \
-X POST \
-H "$xsrf_key: $xsrf_token" \
-b "$xsrf_cookie" \
-H "Content-Type: application/json" \
-d @- \
$NOTEA_ADDR/api/notes \
| grep -q "$ID"
}
"$@"
)