53 Commits

Author SHA1 Message Date
Bel LaPointe
64d9ce332b rm temp 2022-02-17 14:42:34 -07:00
Bel LaPointe
497840ab66 update about 2022-02-17 14:33:56 -07:00
Bel LaPointe
32f9ad9073 todo 2022-02-17 14:30:23 -07:00
Bel LaPointe
1bc0f17014 shorted pid for scraped and do not change title 2022-02-17 14:29:45 -07:00
Bel LaPointe
4dbe8072dd gitlab logs less, both 1 and 0 expand results mod original 2022-02-17 14:19:12 -07:00
Bel LaPointe
b365810e6a todo 2022-02-17 13:36:53 -07:00
Bel LaPointe
f8ee3173ae todo, gomod 2022-02-17 13:24:31 -07:00
Bel LaPointe
45ba71c199 todo 2022-02-17 13:04:46 -07:00
Bel LaPointe
f80b5a262d restore easymde min height a bit 2022-02-17 13:01:07 -07:00
Bel LaPointe
f1bbc4657d fix up gitlab wiki anchor annoyance 2022-02-17 13:01:01 -07:00
Bel LaPointe
6bae1ce832 todo 2022-02-17 12:43:04 -07:00
Bel LaPointe
ff8a77beea redir to /ui/files for about page, fix root+ button 2022-02-17 12:42:35 -07:00
Bel LaPointe
21f671517b about page 2022-02-17 12:37:46 -07:00
Bel LaPointe
7109d419f9 todo 2022-02-17 12:20:17 -07:00
Bel LaPointe
d02c120e50 if readonly, do not draw add-child button in tree 2022-02-17 12:19:19 -07:00
Bel LaPointe
a5fff37ba0 put with readonly uses put value 2022-02-17 12:15:21 -07:00
Bel LaPointe
aa8ca4d967 query param to edit readonly page and link on readonly pages to it 2022-02-17 12:04:33 -07:00
Bel LaPointe
553df97240 template readonly, make it plain html for fast 2022-02-17 11:58:37 -07:00
Bel LaPointe
20c1b738a6 if read only then dump content for ui files 2022-02-17 11:43:34 -07:00
Bel LaPointe
0fe427242b remove generated files 2022-02-17 11:43:05 -07:00
Bel LaPointe
3a0c49157a server supports ReadOnly header 2022-02-17 11:07:00 -07:00
Bel LaPointe
2bec0dd1b6 move leaf to own file 2022-02-17 11:00:30 -07:00
Bel LaPointe
ced507ca68 render reflects new Leaf 2022-02-17 10:56:21 -07:00
Bel LaPointe
3addc717a3 add leaf parser, http writer to limit title instances 2022-02-17 10:49:45 -07:00
Bel LaPointe
3a9f2c831e server code unittests to Meta. from .Title and .Deleted 2022-02-17 10:37:52 -07:00
Bel LaPointe
983772d40d todo up 2022-02-17 10:31:03 -07:00
Bel LaPointe
ffa8632c20 todo 2022-02-16 17:07:16 -07:00
Bel LaPointe
33a8558f26 todo 2022-02-16 17:05:43 -07:00
Bel LaPointe
c3d8210969 todo 2022-02-16 17:04:45 -07:00
Bel LaPointe
b03d997a16 todo 2022-02-16 17:04:19 -07:00
Bel LaPointe
2589da8dda todo 2022-02-16 17:03:08 -07:00
Bel LaPointe
bf5679878c todos 2022-02-16 16:56:57 -07:00
Bel LaPointe
9cf58a6a47 todo 2022-02-16 16:49:34 -07:00
Bel LaPointe
9fb58862e8 todo 2022-02-16 16:48:56 -07:00
Bel LaPointe
b1d3d8a83e readme for crawler 2022-02-16 16:25:13 -07:00
Bel LaPointe
c7c728d567 docker image name in readme 2022-02-16 16:24:04 -07:00
Bel LaPointe
0db5818b47 readme for running with docker with dockerized 2022-02-16 16:23:16 -07:00
Bel LaPointe
5a569cb6d4 move ui under server for docker build 2022-02-16 16:20:08 -07:00
Bel LaPointe
eadc4080b1 google slides works enough for search 2022-02-16 16:14:31 -07:00
Bel LaPointe
9219e3656b cache tree traversal for both full and meta on disk as json 2022-02-16 16:09:02 -07:00
Bel LaPointe
76d67cff7a remove tree.cached...root as it wasnt used in server notable 2022-02-16 15:56:17 -07:00
Bel LaPointe
b076b6a9cf grr cached root doesnt matter because server.tree called each time 2022-02-16 15:47:35 -07:00
Bel LaPointe
2781114863 only look at first 1kb of data.yaml when building tree 2022-02-16 15:21:51 -07:00
Bel LaPointe
51a8c8b425 editor loads content as initial 2022-02-16 15:13:49 -07:00
Bel LaPointe
8c87cdf0b2 simplify google docs markdown 2022-02-16 15:09:08 -07:00
Bel LaPointe
c0d49d23bb google converts csv to md table 2022-02-16 14:35:19 -07:00
Bel LaPointe
98df3f2372 google sheets and docs cache in rclone, put title as first line h1, load to file tree 2022-02-16 14:26:34 -07:00
Bel LaPointe
c85813ad76 impl crawler rclone wrapper to get google files by id 2022-02-16 13:53:01 -07:00
Bel LaPointe
3774d3eba1 add google and update crawlable detection 2022-02-16 12:19:32 -07:00
Bel LaPointe
e3b97814ea fix buttons on chrome vs firefox height 2022-02-16 12:09:21 -07:00
Bel LaPointe
62c927d5ec update go mod for restructure 2022-02-16 12:03:27 -07:00
Bel LaPointe
c000168dc6 rm big 2022-02-16 12:01:33 -07:00
Bel LaPointe
9739a73265 reorg repo 2022-02-16 12:01:11 -07:00
55 changed files with 1084 additions and 202 deletions

20
.gitignore vendored
View File

@@ -1,9 +1,13 @@
**/*.sw*
spike/review/reinvent/ezmded/server/ezmded
spike/review/reinvent/ezmded/server/server
spike/review/reinvent/ezmded/server/testdata/files/**/*
spike/review/reinvent/ezmded/server/testdata/workd/**/*
spike/review/reinvent/ezmded/server/testdata/media/**/*
spike/review/reinvent/ezmded/server/testdata/index.html
spike/review/reinvent/ezmded/ui/render
spike/review/reinvent/ezmded/ui/**/.*.html
server/exec-server
server/ezmded
server/exec-ezmded
server/server
server/testdata/files/**/*
server/testdata/workd/**/*
server/testdata/media/**/*
server/testdata/index.html
ui/render
server/public/ui/**/.*.html
**/*.ctmpl.html
server/public/ui/render

View File

@@ -1 +0,0 @@
../../spike/review/run.sh

10
crawler/README.md Normal file
View File

@@ -0,0 +1,10 @@
## running
export RCLONE_CONFIG=/tmp/rclone.temp.conf
export RCLONE_CONFIG_PASS=abc
export CACHE=/tmp/notea-team3
export NOTES_ADDR=${NOTES_ADDR:-http://localhost:3004}
export GITLAB_PAT=$(get_secret GITLAB_PAT)
mkdir -p $CACHE
bash main.sh
echo $?

View File

@@ -32,7 +32,6 @@ gitlab() (
blob="$(urlencode "$blob")"
local path="api/v4/projects/$project/repository/files/$blob/raw"
log "url: https://gitlab-app.eng.qops.net/$path (blob=$blob, project=$project)"
echo "https://gitlab-app.eng.qops.net/$path"
}
@@ -73,7 +72,6 @@ gitlab() (
root="${root#tree/}"
root="$(echo "$root" | sed 's/^[^\/]*//')"
root="${root#/}"
log project=$project, root=$root, url=$url
echo "$project"
echo "$root"
}

View File

@@ -6,8 +6,9 @@ gitlab_wiki() (
}
human_url() {
log "not impl: human url: $@"
exit 1
local url="${1%/}"
url="${url%%#*}"
echo "$url/$(echo "$2" | base64 --decode)"
}
_host() {
@@ -25,7 +26,7 @@ gitlab_wiki() (
project="${project%/-/}"
project="${project#/}"
project="${project%/}"
echo "$project"
echo "${project%%#*}"
}
_blob() {
@@ -36,7 +37,7 @@ gitlab_wiki() (
local blob="${path#*/wikis}"
blob="${blob#/}"
blob="${blob%/}"
echo "$blob"
echo "${blob%%#*}"
}
get() {

76
crawler/google.sh Normal file
View File

@@ -0,0 +1,76 @@
#! /bin/bash
google() (
_is_slides() {
echo "$@" | grep -q 'docs.google.com.presentation'
}
_is_sheets() {
echo "$@" | grep -q 'docs.google.com.spreadsheets'
}
_is_doc() {
echo "$@" | grep -q 'docs.google.com.document'
}
is() {
_is_sheets "$@" || _is_doc "$@" || _is_slides "$@"
}
human_url() {
echo "$1"
}
get() {
local url="$1"
local id="${url%/*}"
id="${id##*/}"
local downloaded="$(rclone get_google "$id")"
echo "# ${downloaded##*/}"
echo ""
if [ "${downloaded##*.}" == "csv" ]; then
_csv_to_md "$downloaded"
elif [ "${downloaded##*.}" == "html" ]; then
_html_to_md "$downloaded"
else
cat "$downloaded"
fi
}
_html_to_md() {
which pandoc &> /dev/null
local f="$1"
#log f=$f
cat "$f" \
| sed 's/.*<body/<body/' \
| sed 's/<\/body>.*/<\/body>/' \
| sed 's/<[\/]*span[^>]*>//g' \
| perl -pe 's|<div class="c[0-9][0-9]*">.*?<\/div>||g' \
| sed 's/<\([a-z][a-z]*\)[^>]*/<\1/g' \
| pandoc - -f html -t commonmark -s -o - \
| sed 's/^<[\/]*div>$//g'
}
_csv_to_md() {
local f="$1"
(
head -n 1 "$f"
head -n 1 "$f" \
| sed 's/^[^,][^,]*/--- /' \
| sed 's/[^,][^,]*$/ ---/' \
| sed 's/,[^,][^,]*/, --- /g' \
| sed 's/[^|]$/|/'
tail -n +2 "$f"
) \
| grep . \
| sed 's/,/ | /g' \
| sed 's/^/| /'
}
expand() {
get "$@" | head -n 1 | sed 's/^[#]* //' | base64
}
"$@"
)

View File

@@ -4,6 +4,7 @@ main() {
config
log crawling ids...
for id in $(crawlable_ids); do
log crawling id $id
crawl "$id"
done
log rewriting ids...
@@ -20,8 +21,12 @@ config() {
export CACHE_DURATION=$((60*50))
export NOTES_ADDR="${NOTES_ADDR:-"http://localhost:3004"}"
export GITLAB_PAT="$GITLAB_PAT"
export RCLONE_CONFIG="$RCLONE_CONFIG"
export RCLONE_CONFIG_PASS="$RCLONE_CONFIG_PASS"
source ./gitlab.sh
source ./gitlab_wiki.sh
source ./google.sh
source ./rclone.sh
source ./cache.sh
source ./notes.sh
}
@@ -56,12 +61,7 @@ crawlable_ids() {
}
crawl() {
local cache_key="crawled $*"
# TODO
if false && cache get "$cache_key"; then
return
fi
_crawl "$@" | cache put "$cache_key"
_crawl "$@"
}
_crawl() {
@@ -73,7 +73,7 @@ _crawl() {
"$id"
)"
local crawlable_source="$(extract_crawlable_source "$content")"
for backend in gitlab gitlab_wiki; do
for backend in gitlab gitlab_wiki google; do
if $backend is "$crawlable_source"; then
crawl_with $backend "$json"
return $?
@@ -95,6 +95,8 @@ crawl_with() {
local content="$(echo "$json" | jq -r .content)"
local crawlable_source="$(extract_crawlable_source "$content")"
notes put "$pid" "$(notes meta "$pid" | jq -r .Meta.Title)" "$crawlable_source"
local expanded=($($backend expand "$crawlable_source"))
log purge $crawlable_source:
@@ -102,7 +104,7 @@ crawl_with() {
notes del "$subid"
done
log expand $crawlable_source:"$expanded"
log expand $crawlable_source:"${#expanded[@]}: ${expanded[@]}"
notes_mkdir_p() {
local id="$1"
local subtitle="${2%/}"
@@ -123,6 +125,7 @@ crawl_with() {
export CONTENT="$(
echo "**!! WARNING !! This page is autogenerated and prone to destruction and replacement**"
echo "**[See the original]($human_url)**"
echo ""
$backend get "$crawlable_source" "$i" \
| sed 's/](\([^#h]\)/]\(%%%\1/g'
)"
@@ -147,8 +150,14 @@ crawl_with() {
echo "$sum"
)"
ID="${ID%/}"
if [ "${#expanded[@]}" -lt 2 ]; then
ID="$pid"
TITLE="$(notes meta "$ID" | jq -r .Meta.Title)"
CONTENT="$(printf "%s\n\n%s", "$crawlable_source" "$CONTENT")"
fi
log " $ID ($TITLE): ${#CONTENT}"
push_crawled "$ID" "$TITLE" "$CONTENT"
log " /$ID ($TITLE): ${#CONTENT}"
}
if [ "${#expanded[@]}" -gt 0 ]; then
for i in $(seq 0 $(("${#expanded[@]}"-1))); do
@@ -166,7 +175,7 @@ push_crawled() {
is_crawlable() {
local crawlable_source="$(extract_crawlable_source "$*")"
# https://unix.stackexchange.com/questions/181254/how-to-use-grep-and-cut-in-script-to-obtain-website-urls-from-an-html-file
local url_pattern="(http|https)://[a-zA-Z0-9./?=_%:-]*"
local url_pattern="(http|https)://[a-zA-Z0-9./?=_%:\-\#--]*"
echo "$crawlable_source" | cut -c 1-300 | grep -q -E "^[ ]*$url_pattern[ ]*$"
}

View File

@@ -2,11 +2,15 @@
notes() (
ids() {
_recurse_ids "" "$(_tree)"
_recurse_ids "$(_tree)"
}
_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() {
@@ -18,8 +22,7 @@ notes() (
}
_recurse_ids() {
local prefix="$1"
local json="$2"
local json="$1"
if echo "$json" | jq .Branches | grep -q ^null$; then
return 0
fi
@@ -29,22 +32,32 @@ notes() (
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"
if ! _is_deleted "$line"; then
echo "$line"
_recurse_ids "$(echo "$json" | jq -c ".Branches[\"$line\"]")"
fi
_recurse_ids "$subfix" "$(echo "$json" | jq -c ".Branches[\"$line\"]")"
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)"
for subid in ${id//\// }; do
tree="$(echo "$tree" | jq -c .Branches | jq -c ".[\"$subid\"]")"
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 .Leaf
echo "$tree" | jq ".Branches[\"$id\"].Leaf"
}
_is_deleted() {
@@ -90,11 +103,12 @@ notes() (
local id="$1"
local title="$2"
local body="$3"
echo "$body" | _nncurl \
_nncurl \
-X PUT \
-H "Title: $title" \
-H "Read-Only: true" \
-d "$body" \
$NOTES_ADDR/api/v0/files/$id
$NOTES_ADDR/api/v0/files/$id >&2
}
"$@"

62
crawler/rclone.sh Normal file
View File

@@ -0,0 +1,62 @@
#! /bin/bash
rclone() (
get_google() {
local cache_key="rclone get google 2 $*"
if cache get "$cache_key"; then
return 0
fi
_get_google "$@" | cache put "$cache_key"
}
_get_google() {
_rate_limit
local id="$1"
local out="$(mktemp -d)"
_cmd backend copyid work-notes-google: --drive-export-formats=csv,html,txt "$id" "$out/"
find "$out" -type f
}
_rate_limit() {
local f="/tmp/rclone.rate.limit"
local last=0
if [ -f "$f" ]; then
last="$(date -r "$f" +%s)"
fi
local now="$(date +%s)"
local since_last=$((now-last))
if ((since_last>2)); then
dur=-2
fi
dur=$((dur+2))
sleep $dur
touch "$f"
}
_ensure() {
which rclone &> /dev/null && rclone version &> /dev/null
}
_cmd() {
_ensure_google_config
__cmd "$@"
}
__cmd() {
_ensure
RCLONE_CONFIG_PASS="$RCLONE_CONFIG_PASS" \
$(which rclone) \
--config "$RCLONE_CONFIG" \
--size-only \
--fast-list \
--retries 10 \
--retries-sleep 10s \
"$@"
}
_ensure_google_config() {
__cmd config show | grep -q work-notes-google
}
"$@"
)

9
server/README.md Normal file
View File

@@ -0,0 +1,9 @@
## running with docker
d1=${d1:-$(mktemp -d)}
d2=${d2:-$(mktemp -d)}
docker run \
-v $d1:/main/public/files \
-v $d2:/main/public/media \
-p 3004:3004 \
--rm -it registry-app.eng.qops.net:5001/bel/work-notes:latest

29
server/go.mod Normal file
View File

@@ -0,0 +1,29 @@
module ezmded
go 1.17
require (
github.com/gomarkdown/markdown v0.0.0-20220114203417-14399d5448c4
github.com/google/uuid v1.3.0
gopkg.in/yaml.v2 v2.4.0
local/args v0.0.0-00010101000000-000000000000
local/gziphttp v0.0.0-00010101000000-000000000000
local/router v0.0.0-00010101000000-000000000000
local/simpleserve v0.0.0-00010101000000-000000000000
)
replace local/args => ../../../../args
replace local/logb => ../../../../logb
replace local/storage => ../../../../storage
replace local/router => ../../../../router
replace local/simpleserve => ../../../../simpleserve
replace local/gziphttp => ../../../../gziphttp
replace local/notes-server => ../../../../notes-server
replace local/oauth2 => ../../../../oauth2

View File

@@ -18,14 +18,12 @@ github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghf
github.com/coreos/bbolt v0.0.0-20180318001526-af9db2027c98/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/cpuguy83/go-md2man v1.0.8/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/djherbis/times v1.1.0/go.mod h1:CGMZlo255K5r4Yw0b9RRfFQpM2y7uOmxg4jm9HsaVf8=
github.com/dropbox/dropbox-sdk-go-unofficial v5.4.0+incompatible/go.mod h1:lr+LhMM3F6Y3lW1T9j2U5l7QeuWm87N9+PPXo3yH4qY=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/fairlyblank/md2min v0.0.0-20171213131418-39cd6e9904ac/go.mod h1:QAobgT+CwT/SRphqV6Jrz5jt3wkW9Q72QNquEvh6dLk=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
@@ -57,8 +55,9 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomarkdown/markdown v0.0.0-20210208175418-bda154fe17d8/go.mod h1:aii0r/K0ZnHv7G0KF7xy1v0A7s2Ljrb5byB7MO5p6TU=
github.com/gomarkdown/markdown v0.0.0-20220114203417-14399d5448c4 h1:6GlsnS3GQYfrJZTJEUsheoyLE6kLXQJDvQKIKxgL/9Q=
github.com/gomarkdown/markdown v0.0.0-20220114203417-14399d5448c4/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA=
github.com/gomodule/redigo v1.8.5/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
@@ -113,7 +112,6 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.8.3/go.mod h1:NxmoDg/QLVWluQDUYG7XBZTLUpKeFa8e3aMf1BfjyHk=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rfjakob/eme v0.0.0-20171028163933-2222dbd4ba46/go.mod h1:U2bmx0hDj8EyDdcxmD5t3XHDnBFnyNNc22n1R4008eM=
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
@@ -141,11 +139,9 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
github.com/t3rm1n4l/go-mega v0.0.0-20190205172012-55a226cf41da/go.mod h1:XWL4vDyd3JKmJx+hZWUVgCNmmhZ2dTBcaNDcxH465s0=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/xanzy/ssh-agent v0.2.0/go.mod h1:0NyE30eGUDliuLEHJgYte/zncp2zdTStcOnWhgSqHD8=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
@@ -154,7 +150,6 @@ github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
github.com/yuin/goldmark v1.3.4-0.20210326114109-75d8cce5b78c/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yunify/qingstor-sdk-go v2.2.15+incompatible/go.mod h1:w6wqLDQ5bBTzxGJ55581UrSwLrsTAsdo9N6yX/8d9RY=
go.mongodb.org/mongo-driver v1.7.2 h1:pFttQyIiJUHEn50YfZgC9ECjITMT44oiN36uArf/OFg=
go.mongodb.org/mongo-driver v1.7.2/go.mod h1:Q4oFMbo1+MSNqICAdYMlC/zSTrwCogR4R8NzkI+yfU8=
golang.org/dl v0.0.0-20190829154251-82a15e2f2ead/go.mod h1:IUMfjQLJQd4UTqG1Z90tenwKoCX93Gn3MAQJMOSBsDQ=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
@@ -211,5 +206,4 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -47,5 +47,9 @@ func (id ID) withClean() ID {
splits[i] = t
}
}
return ID(path.Join(splits...))
clean := path.Join(splits...)
if clean == "" || clean == "." {
clean = ""
}
return ID(clean)
}

68
server/leaf.go Normal file
View File

@@ -0,0 +1,68 @@
package main
import (
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
type Leaf struct {
Meta Meta
Content string
}
type Meta struct {
Title string
ReadOnly bool
Deleted bool
}
func NewHTTPRequestLeaf(r *http.Request) (Leaf, error) {
var leaf Leaf
if b, err := ioutil.ReadAll(r.Body); err != nil {
return leaf, err
} else {
leaf.Content = string(b)
}
if leaf.Meta.Title = r.Header.Get("Title"); leaf.Meta.Title == "" {
leaf.Meta.Title = "Untitled"
}
if readOnly := r.Header.Get("Read-Only"); readOnly == "true" {
leaf.Meta.ReadOnly = true
} else if readOnly == "false" {
leaf.Meta.ReadOnly = false
}
leaf.Meta.Deleted = r.Method == http.MethodDelete
return leaf, nil
}
func NewLeaf(title string, content string) (Leaf, error) {
return NewHTTPRequestLeaf(&http.Request{
Header: http.Header{
"Title": []string{title},
},
Body: io.NopCloser(strings.NewReader(content)),
})
}
func (leaf Leaf) WriteHTTP(w http.ResponseWriter) error {
w.Header().Set("Title", leaf.Meta.Title)
w.Header().Set("Read-Only", strconv.FormatBool(leaf.Meta.ReadOnly))
_, err := w.Write([]byte(leaf.Content))
return err
}
func (base Leaf) Merge(updated Leaf) Leaf {
if updated.Meta.Title != "" {
base.Meta.Title = updated.Meta.Title
}
if base.Meta.Title == "" {
base.Meta.Title = "Untitled"
}
base.Meta.Deleted = updated.Meta.Deleted
base.Meta.ReadOnly = updated.Meta.ReadOnly
base.Content = updated.Content
return base
}

View File

@@ -0,0 +1,456 @@
<!DOCTYPE html>
<html>
<header>
<title>Notes</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
<script src="https://cdn.jsdelivr.net/highlight.js/latest/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/highlight.js/latest/styles/github.min.css">
<link rel="stylesheet" href="https://unpkg.com/turretcss/dist/turretcss.min.css" crossorigin="anonymous">
<!-- todo css
<link rel="stylesheet" href="https://cdn.concisecss.com/concise.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/light.css">
<link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css">
-->
<style>
html, body {
background-color: #f8f8f8;
}
.EasyMDEContainer button {
color: black;
}
img {
max-width: 100%;
max-height: 100%;
}
.filetree {
max-width: 15em;
width: 15em;
min-width: 15em;
overflow-x: scroll;
white-space: nowrap;
}
.filesummary {
min-width: 10em;
}
.filedetails {
padding-inline-start: 2em;
}
.filetree > .filedetails,
.filetree > .filedetails > .filedetails {
padding-inline-start: 0em;
}
.fileleaf {
display: inline-flex;
flex-direction: row;
width: calc(100% - 1em);
}
.fileleaf > input {
border: none;
border-radius: 0;
background: none;
outline: none;
}
.fileleaf > input:hover,
input.live_leaf {
background: #ddd;
}
.lr_fullscreen {
width: 90%;
max-width: 1024px;
margin-right: auto;
margin-left: auto;
}
.tb_fullscreen {
margin-top: 1em;
}
.columns {
display: flex;
flex-direction: row;
}
.rows {
width: 100%;
display: flex;
flex-direction: column;
}
.thic_flex {
text-align: left;
flex-grow: 1;
}
.mia {
display: none;
}
.align_left {
text-align: left;
}
.tb_buffer {
margin-top: 1em;
margin-bottom: 1em;
}
.r_buffer {
margin-right: 1em;
}
.l_buffer {
margin-left: 1em;
}
.monospace {
font-family: Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;
}
.lil_btn {
width: initial;
display: inline-block;
}
input, label, textarea {
margin: initial;
}
.editor-toolbar > button.preview {
color: #08c;
}
</style>
<script>
function init() {
drawTree()
setInterval(drawTree, 100000)
navigateToQueryParams()
}
function navigateToQueryParams() {
var queryF = getParameterByName("f")
var queryQ = getParameterByName("q")
console.log("init query f:", queryF, "q:", queryQ)
if (queryF && queryF.length > 0) {
drawFile(queryF)
} else if (queryQ && queryQ.length > 0) {
searchFilesFor(queryQ)
}
}
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function deleteFile() {
if (!confirm("would you like to delete this file?"))
return
const id = easyMDE.meta.id
if (!id || id.length == 0)
return
http("DELETE", "/api/v0/files/" + id, (body, status) => {
if (status != 200) {
alert(`failed to delete file ${id}: ${status}: ${body}`)
throw `failed to delete file ${id}: ${status}: ${body}`
}
drawTree()
var pid = id.slice(0, id.lastIndexOf("/"))
if (pid) {
drawFile(pid)
} else {
disableMDE()
}
})
}
function searchFiles() {
const q = document.getElementById("searchbox").value
searchFilesFor(q)
}
function searchFilesFor(q) {
http("GET", "/api/v0/search?q=" + q, (body, status) => {
var results = JSON.parse(body)
console.log(q, results)
results.sort()
var innerHTML = "<ul>"
for (var result in results)
innerHTML += `<li><input class="align_left" type="button" onclick="drawFile('${results[result]}');" value="${idsToFullTitle(results[result].split("/"))}"</li>`
innerHTML += "</ul>"
if (!results || results.length == 0)
innerHTML = "no results"
disableMDE()
navigateToQuery("q", q)
document.getElementById("searchResults").innerHTML = innerHTML
})
}
var saveFeedbackInterval = null
function pushFile() {
const title = document.getElementById("title").innerHTML ? document.getElementById("title").innerHTML : ""
const body = easyMDE.value() ? easyMDE.value() : ""
const id = easyMDE.meta.id ? easyMDE.meta.id : ""
headers = {}
if (title)
headers["Title"] = title
http("PUT", "/api/v0/files/" + id, (body, status) => {
if (status != 200) {
alert(`failed to push file ${id}: ${status}: ${body}`)
throw `failed to push file ${id}: ${status}: ${body}`
}
drawTree()
//drawFile(id)
document.getElementById("saveFeedback").innerHTML = "success!"
if (saveFeedbackInterval) {
clearTimeout(saveFeedbackInterval)
}
saveFeedbackInterval = setTimeout(() => {document.getElementById("saveFeedback").innerHTML = ""}, 5000)
}, body, headers)
}
function drawFile(id) {
if (!id || id.length < 1) {
return
}
http("GET", "/api/v0/files/"+id, (body, status, headers) => {
if (status != 200) {
throw `ERR loading file: ${status}: ${body}`
}
const title = headers("title") ? headers("title") : ""
setMDE(id, title, body)
})
}
function drawNewFile(pid) {
setMDE(pid + "/" + crypto.randomUUID().substr(0, 5), "", "")
if (easyMDE.isPreviewActive()) {
easyMDE.togglePreview()
}
}
function enableMDE() {
document.getElementById("searchResults").className = "mia";
document.getElementById("article").className = "";
}
function disableMDE() {
document.getElementById("article").className = "mia";
document.getElementById("searchResults").className = "";
}
var liveLeafTimeout = null
function setMDE(id, title, body) {
if (id[0] == "/")
id = id.slice(1, id.length)
if (id[id.length-1] == "/")
id = id.slice(0, id.length-1)
var pids = id.split("/")
pids = pids.slice(0, pids.length-1)
var titlePath = "/"
for (var i = 0; i < pids.length; i++) {
const fullPid = pids.slice(0, i+1)
titlePath = `/ <input type="button" class="lil_btn" value="${idsToTitle(fullPid)}" onclick="drawFile('${fullPid.join("/")}');"/> /`
}
if (pids.length > 1) {
titlePath = "/ ... "+titlePath
}
enableMDE()
document.getElementById("titlePath").innerHTML = titlePath
document.getElementById("title").innerHTML = title
easyMDE.value(body)
easyMDE.meta = {
id: id,
}
if (!easyMDE.isPreviewActive()) {
easyMDE.togglePreview()
var previews = document.getElementsByClassName("preview")
}
const previouslyHighlighted = document.getElementsByClassName("live_leaf")
for (var i in previouslyHighlighted)
if (previouslyHighlighted && previouslyHighlighted[i] && previouslyHighlighted[i].classList)
previouslyHighlighted[i].classList.remove("live_leaf")
if (liveLeafTimeout)
clearTimeout(liveLeafTimeout)
liveLeafTimeout = setTimeout(() => {
const toHighlight = document.getElementsByClassName(btoa("/"+id))
for (var i = 0; i < toHighlight.length; i++) {
if (toHighlight && toHighlight[i] && toHighlight[i].classList)
toHighlight[i].classList.add("live_leaf")
}
}, 100)
navigateToQuery("f", id)
}
var lastNavigateToQuery = new Date()
function navigateToQuery(k, v) {
if (new Date() - lastNavigateToQuery < .1)
return
lastNavigateToQuery = new Date()
const url = new URL(window.location)
url.searchParams.set(k, v)
var hash = "#?"
const it = url.searchParams.entries()
let result = it.next()
while (!result.done) {
hash = hash + result.value[0] + "=" + result.value[1] + "&"
result = it.next()
}
window.location.hash = hash
}
var lastTree = {}
function idsToTitle(original_ids) {
const fullTitle = idsToFullTitle(original_ids)
return fullTitle.slice(fullTitle.lastIndexOf("/")+1, fullTitle.length)
}
function idsToFullTitle(original_ids) {
var ids = original_ids.slice(0, original_ids.length)
var subtree = lastTree
var fullTitle = ""
while (ids && ids.length > 0) {
if (!subtree || !subtree["Branches"] || !subtree["Branches"][ids[0]])
break
subtree = subtree["Branches"][ids[0]]
if (subtree && subtree.Leaf && subtree.Leaf.Title)
fullTitle += "/" + subtree.Leaf.Title
ids = ids.slice(1, ids.length)
if (ids.length == 0) {
return fullTitle.slice(1, fullTitle.length)
}
}
return ids[ids.length-1]
}
function drawTree() {
function htmlifyBranch(id, branch) {
const maxTreeTitleLength = 35
var parent = `
<input class="thic_flex ${btoa(id)}" type="button" value="${branch.Leaf.Title.substr(0, maxTreeTitleLength)}" onclick="drawFile('${id}');"/>
<input type="button" class="lil_btn" value="+" onclick="drawNewFile('${id}');"/>
`
if (id == "") {
parent = `
<span class="thic_flex"></span>
<input type="button" value="+" onclick="drawNewFile('${id}');"/>
`
}
var children = []
for (var child in branch.Branches)
children.push({title: branch.Branches[child].Leaf.Title, content: htmlifyBranch(id + "/" + child, branch.Branches[child])})
children = children.map((e) => `<!--${e.title}-->${e.content}`)
children.sort();
children = children.join("\n")
return `
<details class="filedetails" open>
<summary class="filesummary">
<div class="fileleaf">${parent}</div>
</summary>
${children}
</details>
`
}
http("GET", "/api/v0/tree", (body, status) => {
if (status != 200)
throw `bad status getting tree: ${status}: ${body}`
lastTree = JSON.parse(body)
document.getElementById("tree").innerHTML = htmlifyBranch("", lastTree)
})
}
function http(method, remote, callback, body, headers) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
callback(xmlhttp.responseText, xmlhttp.status, (key) => xmlhttp.getResponseHeader(key))
}
};
xmlhttp.open(method, remote, true);
if (typeof body == "undefined") {
body = null
}
if (headers) {
for (var key in headers)
xmlhttp.setRequestHeader(key, headers[key])
}
xmlhttp.send(body);
}
</script>
</header>
<body class="lr_fullscreen tb_fullscreen" onload="init(); return false;">
<br>
<div class="rows">
<form class="columns" action="return false;">
<input class="thic_flex" type="text" id="searchbox" placeholder="search regexp"/>
<input class="info lil_btn" type="submit" value="search" onclick="searchFiles(); return false;"/>
</form>
<div class="columns thic_flex tb_buffer">
<div id="tree" class="filetree"></div>
<div class="thic_flex lr_fullscreen" style="margin-left: 1em; width: 5px;">
<article id="searchResults" class="mia">
</article>
<article id="article" class="mia">
<div>
<h1 class="columns">
<span class="r_buffer">
<input class="button-info lil_btn" type="submit" value="SAVE" onclick="pushFile(); return false;"/>
</span>
<span id="titlePath">
</span>
<span id="title" class="thic_flex" contenteditable></span>
<span class="l_buffer">
<input class="button-error lil_btn" type="submit" value="DELETE" onclick="deleteFile(); return false;"/>
</span>
</h1>
</div>
<div id="saveFeedback" style="min-height: 1.2em; text-align: right;">
</div>
<!-- todo: each line no is an anchor -->
<div class="monospace">
<textarea id="my-text-area"></textarea>
</font>
</article>
</div>
</div>
</div>
</body>
<footer>
<script>
const easyMDE = new EasyMDE({
autoDownloadFontAwesome: true,
autofocus: true,
autosave: {
enabled: false,
},
element: document.getElementById('my-text-area'),
forceSync: true,
indentWithTabs: false,
initialValue: "# initial\nvalue",
showIcons: ["code", "table"],
spellChecker: false,
sideBySideFullscreen: false,
tabSize: 3,
previewImagesInEditor: true,
insertTexts: {
image: ["![](", ")"],
link: ["[](", ")"],
},
lineNumbers: true,
lineWrapping: false,
uploadImage: true,
imageUploadEndpoint: "/api/v0/media", // POST wants {data: {filePath: "/..."}}
imagePathAbsolute: false,
renderingConfig: {
codeSyntaxHighlighting: true,
},
})
function logValue() {
console.log(easyMDE.value())
}
logValue()
</script>
</footer>
</html>

View File

@@ -11,7 +11,15 @@
<div class="columns thic_flex tb_buffer" style="height: calc(100% - 4rem);">
{{ template "_filetree" . }}
<div class="thic_flex lr_fullscreen" style="margin-left: 1em; width: 5px;">
{{ if eq .This.ID "" }}
{{ template "_about" . }}
{{ else }}
{{ if .This.ReadOnly }}
{{ template "_readonly" . }}
{{ else }}
{{ template "_editor" . }}
{{ end }}
{{ end }}
</div>
</div>
</div>

View File

@@ -39,6 +39,7 @@ func main() {
"This": map[string]interface{}{
"ID": "id00/id11",
"Title": "title id11",
"ReadOnly": false,
"PID": "id00",
"PTitle": "title id00",
"Content": `# hello
@@ -47,8 +48,8 @@ func main() {
| this | is | my | table |
| ---- | --- | --- | ----- |
| hey |
| ya | hey | ya |
| hey | ya | hey | ya |
| a | b | c | d |
* and
* a bulleted
@@ -93,25 +94,25 @@ newlines
{Title: "title id00 / title id10 / title id20", ID: "id00/id10/id20"},
},
"Tree": `{
"Leaf": {"Title": ""},
"Leaf": {"Meta":{"Title": "","ReadOnly":false}},
"Branches": {
"id00": {
"Leaf": {"Title": "title id00"},
"Leaf": {"Meta":{"Title": "title id00","ReadOnly":false}},
"Branches": {
"id10": {"Leaf":{"Title":"title id10"},"Branches":{
"id20": {"Leaf":{"Title":"title id20"},"Branches":{}}
"id10": {"Leaf":{"Meta":{"Title":"title id10","ReadOnly":false}},"Branches":{
"id20": {"Leaf":{"Meta":{"Title":"title id20","ReadOnly":false}},"Branches":{}}
}},
"id11": {"Leaf":{"Title":"title id11"},"Branches":{}}
"id11": {"Leaf":{"Meta":{"Title":"title id11","ReadOnly":false}},"Branches":{}}
}
},
"id01": {"Leaf":{"Title":"title id01"},"Branches":{}},
"id02": {"Leaf":{"Title":"title id02"},"Branches":{}},
"id03": {"Leaf":{"Title":"title id03"},"Branches":{}},
"id04": {"Leaf":{"Title":"title id04"},"Branches":{}},
"id04": {"Leaf":{"Title":"title id04"},"Branches":{}},
"id05": {"Leaf":{"Title":"title id05"},"Branches":{}},
"id06": {"Leaf":{"Title":"title id06"},"Branches":{}},
"id07": {"Leaf":{"Title":"title id07 but it's really really really long"},"Branches":{}}
"id01": {"Leaf":{"Meta":{"Title":"title id01","ReadOnly":false}},"Branches":{}},
"id02": {"Leaf":{"Meta":{"Title":"title id02","ReadOnly":false}},"Branches":{}},
"id03": {"Leaf":{"Meta":{"Title":"title id03","ReadOnly":false}},"Branches":{}},
"id04": {"Leaf":{"Meta":{"Title":"title id04","ReadOnly":false}},"Branches":{}},
"id04": {"Leaf":{"Meta":{"Title":"title id04","ReadOnly":false}},"Branches":{}},
"id05": {"Leaf":{"Meta":{"Title":"title id05","ReadOnly":false}},"Branches":{}},
"id06": {"Leaf":{"Meta":{"Title":"title id06","ReadOnly":false}},"Branches":{}},
"id07": {"Leaf":{"Meta":{"Title":"title id07 but it's really really really long","ReadOnly":false}},"Branches":{}}
}
}`,
}

View File

@@ -2,7 +2,7 @@
<!DOCTYPE html>
<html>
<header>
<title>{{ .This.Title }}</title>
<title>Search</title>
{{ template "_import" }}
</header>
<body class="fullscreen tb_fullscreen lr_fullscreen" style="position: absolute">

View File

@@ -0,0 +1,57 @@
{{ define "_about" }}
<div class="fullscreen tb_fullscreen">
<h1>Welcome!</h1>
<h2>TLDR; how do I write something?</h2>
<div>
<ol>
<li>Click a `+` button somewhere in the tree on the left</li>
<li>Hit "save"</li>
<li>You'll see "Success!" in green at the bottom on save</li>
</ol>
</div>
<h2>What is this?</h2>
<div>
This is a one-stop shop for reading, searching, and optionally writing docs.
</div>
<h2>Why would I use it? (It looks a little... "janky", no offense)</h2>
<div>
<ul>
<li>Load your Gitlab, Gitlab Wikis, Google Docs, Google Spreadsheets, and Google Slides and enjoy that search bar above.</li>
<li>No version control BUT very fast to edit and hit "save"</li>
<li>Automagically updates, so throw a link to your docs here and continue using Gitlab/Google/etc. as you were</li>
<li>Link to a Gitlab repo/path/wiki and automagically get the entire tree</li>
</ul>
</div>
<h2>What's this about magic?</h2>
<div>
<ul>
<li>Create a file that just contains "https://gitlab.com/my/repo/-/tree/master/README.md" or "https://docs.google.com/docs/my-doc/edit", wait some time, and now it's an updating version of that doc</li>
<li>Create a file that just contains "https://gitlab.com/my/repo/-/tree/master/runbooks", wait some time, and now it's an updating version of all those docs</li>
</ul>
<h3>Butt how do I use it?</h3>
<div>
<ol>
<li>Make or edit a file</li>
<li>The first line is a link to Gitlab or Google</li>
<li>Save</li>
<li>Wait</li>
</ol>
</div>
</div>
<h2>I got a bone to pick with you!!! Who are you exactly?</h2>
<div>
<table>
<tr><td> Slack User </td><td> @breel </td></tr>
<tr><td> Email </td><td> breel@qualtrics.com </td></tr>
<tr><td> Slack Channel </td><td> #storage-platform </td></tr>
<tr><td> Gitlab </td><td> TODO </td></tr>
</table>
</div>
</div>
{{ end }}

View File

@@ -5,10 +5,15 @@
#easyMDEwrap {
flex-grow: 1;
}
.CodeMirror {
min-height: 7em;
}
.CodeMirror-scroll, .CodeMirror-sizer {
min-height: 10px !important;
height: auto !important;
}
.CodeMirror-sizer {
min-height: 10rem !important;
}
#article {
display: flex;
flex-direction: column;
@@ -113,7 +118,7 @@
element: document.getElementById('my-text-area'),
forceSync: true,
indentWithTabs: false,
initialValue: "loading...",
initialValue: "{{ .This.Content }}",
showIcons: ["code", "table"],
spellChecker: false,
sideBySideFullscreen: false,
@@ -133,6 +138,5 @@
},
status: ["lines", "words", "cursor"],
})
easyMDE.value({{ .This.Content }})
</script>
{{ end }}

View File

@@ -43,21 +43,25 @@
`
}
function leafHTML(id, branch) {
const href="/ui/files/" + (id ? id : "#")
const href="/ui/files/" + (id ? id : "")
var nameSafeId = id.replace(/\//g, "-")
var parentNameSafeId = nameSafeId
if (id.includes("/"))
parentNameSafeId = id.slice(0, id.lastIndexOf("/")).replace(/\//g, "-")
const name=`filetree-leaf-${nameSafeId}`
const parentname=`filetree-leaf-${parentNameSafeId}`
const title=id ? branch.Leaf.Title : "ROOT"
const title=id ? branch.Leaf.Meta.Title : "ROOT"
const isLiveParent = '{{ .This.ID }}'.slice(0, id.length) == id
const isLive = '{{ .This.ID }}' == id
return `
const linkToFile = `
<div style="margin: 0; padding: 0; height: 0; width: 0;" id="${name}"></div>
<a style="flex-grow: 1;" href="${href}#${parentname}"><button style="width: 100%; text-align: left; outline: none;" class="${isLiveParent ? `button button-info ${!isLive ? "button-border" : ""}` : ""}">${title}</button></a>
<a href="${href}/${generateUUID().split("-")[0]}#${parentname}"><button>+</button></a>
<a style="flex-grow: 1;" href="${href}#${parentname}">
<button style="width: 100%; text-align: left; outline: none;" class="${isLiveParent ? `button button-info ${!isLive ? "button-border" : ""}` : ""}">
${title}
</button>
</a>
`
return linkToFile + (branch.Leaf.Meta.ReadOnly ? "" : `<a href="${href}/${generateUUID().split("-")[0]}#${parentname}"><button>+</button></a>`)
}
function branchesHTML(id, branches) {
if (!branchesHaveContent(branches))
@@ -65,7 +69,7 @@
var html = []
var out = ``
for(var i in branches) {
html.push([branches[i].Leaf.Title, `<details open>` + branchHTML(i, branches[i]) + `</details>`])
html.push([branches[i].Leaf.Meta.Title, `<details open>` + branchHTML(i, branches[i]) + `</details>`])
}
html.sort()
for(var i in html)

View File

@@ -75,6 +75,9 @@
.tb_fullscreen {
height: 100%;
}
.button, button, input[type="button"] {
height: auto;
}
</style>
<script>
function http(method, remote, callback, body, headers) {

View File

@@ -0,0 +1,9 @@
{{ define "_readonly" }}
<div class="fullscreen tb_fullscreen">
<a href="/ui/files/{{ .This.ID }}?edit"><button>Edit this page</button></a>
<article id="article"></article>
<script>
document.getElementById("article").innerHTML = {{ .This.Content }}
</script>
</div>
{{ end }}

View File

@@ -1,6 +1,7 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
@@ -17,6 +18,10 @@ import (
"regexp"
"strings"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
"github.com/google/uuid"
)
@@ -237,9 +242,6 @@ func (server *Server) uiSearchHandler(w http.ResponseWriter, r *http.Request) er
func (server *Server) uiFilesHandler(w http.ResponseWriter, r *http.Request) error {
id := NewID(strings.TrimPrefix(r.URL.Path, "/ui/files"))
if id == "" {
return server.rootHandler(w, r)
}
t, err := server.uiSubTemplates()
if err != nil {
return err
@@ -258,23 +260,34 @@ func (server *Server) uiFilesHandler(w http.ResponseWriter, r *http.Request) err
return err
}
var parent Leaf
var leaf Leaf
if id != "" {
if id.Pop() != "" {
parent, err = tree.Get(id.Pop())
if err != nil {
return fmt.Errorf("failed to get pid %q: %v", id.Pop(), err)
}
}
leaf, err := tree.Get(id)
leaf, err = tree.Get(id)
if err != nil {
leaf.Title = "My New File"
leaf.Meta.Title = "My New File"
}
}
if leaf.Meta.ReadOnly {
if _, ok := r.URL.Query()["edit"]; !ok {
leaf.Content = Gomarkdown([]byte(leaf.Content))
} else {
leaf.Meta.ReadOnly = false
}
}
data := map[string]interface{}{
"This": map[string]interface{}{
"Title": leaf.Title,
"Title": leaf.Meta.Title,
"ReadOnly": leaf.Meta.ReadOnly,
"Content": leaf.Content,
"ID": id.String(),
"PID": id.Pop().String(),
"PTitle": parent.Title,
"PTitle": parent.Meta.Title,
},
"Tree": string(branchesJSON),
}
@@ -309,7 +322,7 @@ func (server *Server) uiSubTemplates() (*template.Template, error) {
}
func (server *Server) rootHandler(w http.ResponseWriter, r *http.Request) error {
http.Redirect(w, r, "/ui/files/"+uuid.New().String()[:5], 302)
http.Redirect(w, r, "/ui/files", 302)
return nil
}
@@ -354,10 +367,15 @@ func (server *Server) apiV0FilesPostHandler(w http.ResponseWriter, r *http.Reque
if err != nil {
return err
}
r.Body = io.NopCloser(bytes.NewReader(b))
pid := server.fileId(r)
id := NewID(pid).Push(strings.Split(uuid.New().String(), "-")[0])
if err := server.tree().Put(id, Leaf{Title: r.Header.Get("Title"), Content: string(b)}); err != nil {
leaf, err := NewHTTPRequestLeaf(r)
if err != nil {
return err
}
if err := server.tree().Put(id, leaf); err != nil {
return err
}
return json.NewEncoder(w).Encode(map[string]map[string]string{
@@ -381,9 +399,7 @@ func (server *Server) apiV0FilesIDGetHandler(w http.ResponseWriter, r *http.Requ
return err
}
w.Header().Set("Title", leaf.Title)
_, err = w.Write([]byte(leaf.Content))
return err
return leaf.WriteHTTP(w)
}
func (server *Server) apiV0FilesIDDelHandler(w http.ResponseWriter, r *http.Request) error {
@@ -398,7 +414,7 @@ func (server *Server) apiV0FilesIDDelHandler(w http.ResponseWriter, r *http.Requ
} else if err != nil {
return err
}
leaf.Deleted = true
leaf.Meta.Deleted = true
return server.tree().Put(id, leaf)
}
@@ -424,14 +440,12 @@ func (server *Server) apiV0FilesIDPutHandler(w http.ResponseWriter, r *http.Requ
} else if err != nil {
return err
}
b, err := ioutil.ReadAll(r.Body)
updatedLeaf, err := NewHTTPRequestLeaf(r)
if err != nil {
return err
}
leaf.Content = string(b)
leaf.Title = r.Header.Get("Title")
leaf.Deleted = false
leaf = leaf.Merge(updatedLeaf)
if err := server.tree().Put(id, leaf); err != nil {
return err
@@ -479,18 +493,18 @@ func (server *Server) _apiV0SearchHandler(query string) ([][2]string, error) {
result := [][2]string{}
if err := tree.ForEach(func(id ID, leaf Leaf) error {
for _, pattern := range patterns {
if !pattern.MatchString(leaf.Content) && !pattern.MatchString(leaf.Title) {
if !pattern.MatchString(leaf.Content) && !pattern.MatchString(leaf.Meta.Title) {
return nil
}
}
title := leaf.Title
title := leaf.Meta.Title
pid := id.Pop()
for pid != "" {
parent, err := server.tree().Get(pid)
if err != nil {
return err
}
title = path.Join(parent.Title, title)
title = path.Join(parent.Meta.Title, title)
pid = pid.Pop()
}
result = append(result, [2]string{id.URLSafeString(), title})
@@ -500,3 +514,30 @@ func (server *Server) _apiV0SearchHandler(query string) ([][2]string, error) {
}
return result, nil
}
func Gomarkdown(b []byte) string {
renderer := html.NewRenderer(html.RendererOptions{
Flags: html.CommonFlags | html.TOC,
})
ext := parser.NoExtensions
for _, extension := range []parser.Extensions{
parser.NoIntraEmphasis,
parser.Tables,
parser.FencedCode,
parser.Autolink,
parser.Strikethrough,
parser.SpaceHeadings,
parser.HeadingIDs,
parser.BackslashLineBreak,
parser.DefinitionLists,
parser.MathJax,
parser.Titleblock,
parser.AutoHeadingIDs,
parser.Includes,
} {
ext |= extension
}
parser := parser.NewWithExtensions(ext)
content := markdown.ToHTML(b, parser, renderer)
return string(content) + "\n"
}

View File

@@ -31,11 +31,17 @@ func TestServerRoutes(t *testing.T) {
ensureAndWrite(server.diskMediaPath("delid"), []byte("hi"))
tree := server.tree()
if err := tree.Put(NewID("getfid"), Leaf{Title: "", Content: "getfid body"}); err != nil {
leaf, _ := NewLeaf("", "getfid body")
if err := tree.Put(NewID("getfid"), leaf); err != nil {
t.Fatal(err)
}
tree.Put(NewID("putfid"), Leaf{Title: "putfid title", Content: "initial putfid body"})
tree.Put(NewID("delfid"), Leaf{Title: "delfid title", Content: "delfid body"})
leaf, _ = NewLeaf("putfid title", "initial putfid body")
tree.Put(NewID("putfid"), leaf)
leaf, _ = NewLeaf("delfid title", "delfid body")
tree.Put(NewID("delfid"), leaf)
t.Log(tree.GetRoot())
ensureAndWrite(path.Join(server.root, "index.html"), []byte("mom"))
@@ -49,7 +55,7 @@ func TestServerRoutes(t *testing.T) {
"v0: /: get": {
path: "/",
method: http.MethodGet,
want: "/ui/files/",
want: "/ui/files",
},
"v0: search: get": {
path: "/api/v0/search?q=getf%20bod",
@@ -96,17 +102,17 @@ func TestServerRoutes(t *testing.T) {
"v0: /: redir": {
path: "/",
method: http.MethodGet,
want: "/ui/files/",
want: "/ui/files",
},
"v0: /ui/: redir": {
path: "/ui/",
method: http.MethodGet,
want: "/ui/files/",
want: "/ui/files",
},
"v0: /ui: redir": {
path: "/ui",
method: http.MethodGet,
want: "/ui/files/",
want: "/ui/files",
},
"v0: /ui/search": {
path: "/ui/search",
@@ -207,7 +213,7 @@ func TestServerPutTreeGetFile(t *testing.T) {
if w.Code != http.StatusOK {
t.Fatal(w)
}
if !bytes.Contains(w.Body.Bytes(), []byte(`{"Title":"my title","Deleted":false,"Content":"`)) {
if !bytes.Contains(w.Body.Bytes(), []byte(`{"Meta":{"Title":"my title","ReadOnly":false,"Deleted":false},"Content":"`)) {
t.Fatal(w)
}
var branch Branch
@@ -220,11 +226,11 @@ func TestServerPutTreeGetFile(t *testing.T) {
}
if parent, ok := branch.Branches["my pid"]; !ok {
t.Error(ok, branch)
} else if parent.Leaf.Title != "Untitled" {
} else if parent.Leaf.Meta.Title != "Untitled" {
t.Error(parent.Leaf)
} else if child, ok := parent.Branches[NewID(id)]; !ok {
t.Error(ok, NewID("my pid").Push(id), parent)
} else if child.Leaf.Title != "my title" {
} else if child.Leaf.Meta.Title != "my title" {
t.Error(child.Leaf)
}
})

1
server/testdata/ui vendored Symbolic link
View File

@@ -0,0 +1 @@
../public/ui

View File

@@ -1,6 +1,7 @@
package main
import (
"encoding/json"
"io/ioutil"
"os"
"path"
@@ -33,27 +34,8 @@ func (branch Branch) forEach(preid ID, foo func(ID, Leaf) error) error {
return nil
}
type Leaf struct {
Title string
Deleted bool
Content string
}
func (base Leaf) Merge(updated Leaf) Leaf {
if updated.Title != "" {
base.Title = updated.Title
}
if base.Title == "" {
base.Title = "Untitled"
}
base.Deleted = updated.Deleted
base.Content = updated.Content
return base
}
type Tree struct {
root string
cachedRoot Branch
}
func NewTree(root string) Tree {
@@ -62,25 +44,72 @@ func NewTree(root string) Tree {
func (tree Tree) WithRoot(root string) Tree {
tree.root = root
tree.cachedRoot = Branch{}
return tree
}
func (tree Tree) GetRootMeta() (Branch, error) {
return tree.getRoot(NewID(""), false, false)
if meta, ok := tree.getCachedRootMeta(); ok {
return meta, nil
}
got, err := tree.getRoot(NewID(""), false, false)
if err != nil {
return Branch{}, err
}
tree.cacheRootMeta(got)
return got, err
}
func (tree Tree) GetRoot() (Branch, error) {
if !tree.cachedRoot.IsZero() {
return tree.cachedRoot, nil
if root, ok := tree.getCachedRoot(); ok {
return root, nil
}
got, err := tree.getRoot(NewID(""), true, false)
if err == nil {
tree.cachedRoot = got
if err != nil {
return Branch{}, err
}
tree.cacheRoot(got)
return got, err
}
func (tree Tree) getCachedRoot() (Branch, bool) {
return tree.getCachedFrom("root.json")
}
func (tree Tree) getCachedRootMeta() (Branch, bool) {
return tree.getCachedFrom("root_meta.json")
}
func (tree Tree) getCachedFrom(name string) (Branch, bool) {
b, err := ioutil.ReadFile(path.Join(tree.root, name))
if err != nil {
return Branch{}, false
}
var branch Branch
err = json.Unmarshal(b, &branch)
return branch, err == nil
}
func (tree Tree) cacheRoot(branch Branch) {
tree.cacheRootFrom("root.json", branch)
}
func (tree Tree) cacheRootMeta(branch Branch) {
tree.cacheRootFrom("root_meta.json", branch)
}
func (tree Tree) cacheRootFrom(name string, branch Branch) {
b, err := json.Marshal(branch)
if err != nil {
return
}
ensureAndWrite(path.Join(tree.root, name), b)
}
func (tree Tree) cacheClear() {
os.Remove(path.Join(path.Join(tree.root, "root.json")))
os.Remove(path.Join(path.Join(tree.root, "root_meta.json")))
}
func (tree Tree) getRoot(pid ID, withContent, withDeleted bool) (Branch, error) {
m := Branch{Branches: map[ID]Branch{}}
entries, err := os.ReadDir(tree.root)
@@ -92,7 +121,7 @@ func (tree Tree) getRoot(pid ID, withContent, withDeleted bool) (Branch, error)
}
for _, entry := range entries {
if entry.Name() == "data.yaml" {
if b, err := ioutil.ReadFile(path.Join(tree.root, entry.Name())); err != nil {
if b, err := peekLeaf(withContent, path.Join(tree.root, entry.Name())); err != nil {
return Branch{}, err
} else if err := yaml.Unmarshal(b, &m.Leaf); err != nil {
return Branch{}, err
@@ -100,14 +129,14 @@ func (tree Tree) getRoot(pid ID, withContent, withDeleted bool) (Branch, error)
if !withContent {
m.Leaf.Content = ""
}
if m.Leaf.Deleted && !withDeleted {
return m, nil
if m.Leaf.Meta.Deleted && !withDeleted {
return Branch{Branches: map[ID]Branch{}}, nil
}
} else if entry.IsDir() {
subtree := tree.WithRoot(path.Join(tree.root, entry.Name()))
if branch, err := subtree.getRoot(pid.Push(entry.Name()), withContent, withDeleted); err != nil {
return Branch{}, err
} else if !branch.IsZero() && (!branch.Leaf.Deleted || withDeleted) {
} else if !branch.IsZero() && (!branch.Leaf.Meta.Deleted || withDeleted) {
m.Branches[pid.Push(entry.Name())] = branch
}
}
@@ -115,6 +144,10 @@ func (tree Tree) getRoot(pid ID, withContent, withDeleted bool) (Branch, error)
return m, nil
}
func peekLeaf(all bool, path string) ([]byte, error) {
return ioutil.ReadFile(path)
}
func (tree Tree) toDir(id ID) string {
return path.Dir(tree.toData(id))
}
@@ -124,6 +157,7 @@ func (tree Tree) toData(id ID) string {
}
func (tree Tree) Put(id ID, input Leaf) error {
tree.cacheClear()
if _, err := os.Stat(tree.toData(id)); os.IsNotExist(err) {
b, err := yaml.Marshal(Leaf{})
if err != nil {
@@ -144,11 +178,11 @@ func (tree Tree) Put(id ID, input Leaf) error {
if err := ensureAndWrite(tree.toData(id), b); err != nil {
return err
}
tree.cachedRoot = Branch{}
return nil
}
func (tree Tree) Del(id ID) error {
tree.cacheClear()
got, err := tree.Get(id)
if os.IsNotExist(err) {
return nil
@@ -156,16 +190,16 @@ func (tree Tree) Del(id ID) error {
if err != nil {
return err
}
if got.Deleted {
if got.Meta.Deleted {
return nil
}
got.Deleted = true
got.Meta.Deleted = true
return tree.Put(id, got)
}
func (tree Tree) HardDel(id ID) error {
tree.cacheClear()
os.RemoveAll(tree.toDir(id))
tree.cachedRoot = Branch{}
return nil
}

View File

@@ -13,7 +13,9 @@ func TestTreeForEach(t *testing.T) {
id := ""
for i := 0; i < 5; i++ {
id = path.Join(id, strconv.Itoa(i))
if err := tree.Put(NewID(id), Leaf{Title: id, Content: id}); err != nil {
leaf := Leaf{Content: id}
leaf.Meta.Title = id
if err := tree.Put(NewID(id), leaf); err != nil {
t.Fatal(err)
}
}
@@ -42,7 +44,7 @@ func TestTreeDel(t *testing.T) {
t.Fatal(err)
} else if got, err := tree.Get(NewID("id")); err != nil {
t.Fatal(err)
} else if !got.Deleted {
} else if !got.Meta.Deleted {
t.Fatal(got)
}
@@ -72,11 +74,10 @@ func TestTreeCrud(t *testing.T) {
t.Fatal(err)
}
want := Leaf{
Title: "leaf title",
Deleted: false,
Content: "leaf content",
}
want := Leaf{}
want.Meta.Title = "leaf title"
want.Meta.Deleted = false
want.Content = "leaf content"
if err := tree.Put(NewID("id"), want); err != nil {
t.Fatal(err)
} else if l, err := tree.Get(NewID("id")); err != nil {

Binary file not shown.

View File

@@ -1,31 +0,0 @@
module ezmded
go 1.17
require (
github.com/google/uuid v1.3.0
go.mongodb.org/mongo-driver v1.7.2
gopkg.in/yaml.v2 v2.4.0
local/args v0.0.0-00010101000000-000000000000
local/gziphttp v0.0.0-00010101000000-000000000000
local/router v0.0.0-00010101000000-000000000000
local/simpleserve v0.0.0-00010101000000-000000000000
)
require github.com/go-stack/stack v1.8.0 // indirect
replace local/args => ../../../../../../../../args
replace local/logb => ../../../../../../../../logb
replace local/storage => ../../../../../../../../storage
replace local/router => ../../../../../../../../router
replace local/simpleserve => ../../../../../../../../simpleserve
replace local/gziphttp => ../../../../../../../../gziphttp
replace local/notes-server => ../../../../../../../../notes-server
replace local/oauth2 => ../../../../../../../../oauth2

View File

@@ -1 +0,0 @@
../../ui/

View File

@@ -1,15 +1,27 @@
todo:
- table of contents
- anchor per line
- scrape odo
- scrape gdoc
- scrape gsheet
- scrape gslide
- anchor links work
- rewrite links if available to local
- ui; last updated; 2022.02.01T12:34:56
- mark generated via meta so other files in the dir can be created, deleted, replaced safely
- links like `/Smoktests` in user-files home wiki don't rewrite
- map fullURLScraped->internalURL for relative links sometimes
- scrape odo
- rewrite links if available to local
- anchor per line
- anchor links work
- ui; last updated; 2022.02.01T12:34:56
done:
- gitlab/-/blob/about.md does NOT map to exactly 1 file
- crawler does NOT modify title cause readme.md everywhere
- use `meta` so no need for extra level for explicit single files
- table of contents
- min-height for easymde
- /ui/files does not redir in b1
- anchors on gitlab wikis at least are bad
- gitlab wiki original links are empty
- /ui/files is an about page over a redir
- use `read-only` for autogenerated things;; could skip easymde and make google docs much faster
- new line after original link
- scrape gslide
- scrape gsheet
- scrape gdoc
- alert box; https://concisecss.com/documentation/ui
- hide checkbox for tree
- do not rewrite .md title vs. link cause hrefs to ./gobs.md wont work