0%

使用Nextcloud+Syncthing同步Obsidian资料库

前言

在不使用官方的Obsidian Sync的情况下,在移动设备如Android、IOS上进行笔记同步是比较麻烦的事情,看过不少文章使用各种方式进行同步,比如以下:

综上,本人使用Nextcloud和Syncthing在PC端和移动设备进行笔记的同步,使用inotifywait监控两边目录改动,运行nextcloudcmd命令进行同步。

准备

  • 自建NextCloud服务端
  • 自建Syncthing服务
  • 安装nextcloudcmd、inotifywait

步骤

运行以下脚本即可,说明:

  • 填入参数即可
  • 启动命令: bash nextcloud-sync.sh start
  • 停止命令: bash nextcloud-sync.sh stop
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
#!/bin/bash  
# author: kkzzhizhou
# desc: nextcloud inotify sync script.
# This script is a wrapper around nextcloudcmd, designed to keep a local directory synchronised with a Nextcloud repository.
#
# Usage: nextcloud-sync.sh configfile
#
# The config file must contain "username", "password", "local" directory and "remote" URL to a Nextcloud service.

PROG=$(basename "$0")
PROGDIR=$(cd "$(dirname "$0")" && pwd)

set -e
set -u
set -o pipefail

USERNAME='xxx'
PASSWORD='xxx'
LOCAL_DIR="xxx" # 本地Syncthing文件夹路径
REMOTE_URI="https://xxx" # 填写Nextcloud服务地址
DAVPATH="Notes"
NEXTCLOUD_DATA_DIR='xxx' # 填写Nextcloud用户数据路径
NEXTCLOUD_DIR="$NEXTCLOUD_DATA_DIR/$USERNAME/files/$DAVPATH"

case $1 in
start)
echo 0 > "$PROGDIR/sync.lock"
echo "start monitoring: ${LOCAL_DIR}"
echo "start monitoring: ${NEXTCLOUD_DIR}"
/usr/bin/inotifywait -mrq --exclude '/\..*' --timefmt '%d/%m/%y %H:%M:%S' --format '%T %w %f %e' -e modify,delete,create "$LOCAL_DIR" -o $PROGDIR/inotify.log -d
/usr/bin/inotifywait -mrq --exclude '/\..*' --timefmt '%d/%m/%y %H:%M:%S' --format '%T %w %f %e' -e modify,delete,create ${NEXTCLOUD_DIR} -o $PROGDIR/inotify.log -d
nohup /usr/bin/inotifywait -mq --timefmt '%d/%m/%y %H:%M:%S' --format '%T %w %f %e' -e modify $PROGDIR/inotify.log | while read file
do
last_sync_timestamp=$(cat $PROGDIR/sync.lock)
current_timestamp=$(date +%s)
timestamp_check=$[$last_sync_timestamp + 10]
if [ $timestamp_check -lt $current_timestamp ];then
echo $current_timestamp > "$PROGDIR/sync.lock"
echo "$current_timestamp: sync was started"
nextcloudcmd -s --non-interactive --user "$USERNAME" --password "$PASSWORD" --path "$DAVPATH" "$LOCAL_DIR" "$REMOTE_URI"
#else
#echo "$current_timestamp: sync ignored"
fi
done > "$PROGDIR/sync.log" & 2>&1
;;
stop)
echo "stop all monitoring"
pkill inotifywait
;;
esac

欢迎关注我的其它发布渠道