用inotify实现nextcloud文件自动扫描

来源:https://github.com/Blaok/nextcloud-inotifyscan
有点小问题,简单修改了一下

① nextcloud-inotifyscan.service:

[Unit]
Description=Nextcloud inotify scan

[Service]
Type=simple
User=www-data
ExecStart=/usr/bin/nextcloud-inotifyscan

[Install]
WantedBy=multi-user.target

② nextcloud-inotifyscan

#!/usr/bin/python
import fcntl
import os
import subprocess
import sys
import time

interval = os.environ.get('INTERVAL', 1.)
nextcloud_home = '/nextcloud_home'
user_name = 'nextcloud_user'
occ_path = '/var/www/nextcloud/occ'
data_prefix = nextcloud_home+''
data_prefix_len = len(data_prefix)
scan_paths = set()
inotifywait_proc = subprocess.Popen(['inotifywait', '--event', 'create,modify,move,delete', '--exclude', '/\.', '--recursive', data_prefix+'/'+user_name+'/files', '--quiet', '--format', '%e/%f%w/', '--monitor'], stdout=subprocess.PIPE, bufsize=0)
inotifywait_fd = inotifywait_proc.stdout.fileno()
inotifywait_fl = fcntl.fcntl(inotifywait_fd, fcntl.F_GETFL)
while True:
    event = ''
    file_name = ''
    file_path = ''
    while True:
        fcntl.fcntl(inotifywait_fd, fcntl.F_SETFL, inotifywait_fl|os.O_NONBLOCK)
        try:
            c = inotifywait_proc.stdout.read(1)
        except:
            for p in scan_paths:
                sys.stderr.write('Scan for %s\n' % p)
                subprocess.call(['php', occ_path, 'files:scan', '--no-interaction', '--path='+p, '--shallow'])
            scan_paths = set()
            time.sleep(interval)
            continue
        fcntl.fcntl(inotifywait_fd, fcntl.F_SETFL, inotifywait_fl)
        if c != '/':
            event += c
        else:
            while True:
                c = inotifywait_proc.stdout.read(1)
                if c != '/':
                    file_name += c
                else:
                    lastc = ''
                    while True:
                        lastlastc = lastc
                        lastc = c
                        c = inotifywait_proc.stdout.read(1)
                        if c == '\n' and lastc == '/' and lastlastc == '/':
                            break
                        else:
                            file_path += lastc
                    break
            break
    if set(event.split(',')) & {'CREATE', 'MODIFY'}:
        scan_path = file_path+file_name
    else:
        scan_path = file_path
    if data_prefix == scan_path[:data_prefix_len]:
        scan_path = scan_path[data_prefix_len:]
    sys.stderr.write('Found %s %s %s\n' % (file_path, event, file_name))
    scan_paths |= {scan_path}

发表评论

电子邮件地址不会被公开。