audiobookshelf/server/Watcher.js

77 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-08-18 00:01:11 +02:00
var EventEmitter = require('events')
var Logger = require('./Logger')
var Watcher = require('watcher')
2021-08-18 00:01:11 +02:00
class FolderWatcher extends EventEmitter {
constructor(audiobookPath) {
super()
this.AudiobookPath = audiobookPath
this.folderMap = {}
this.watcher = null
}
initWatcher() {
try {
Logger.info('[FolderWatcher] Initializing..')
this.watcher = new Watcher(this.AudiobookPath, {
2021-08-18 00:01:11 +02:00
ignored: /(^|[\/\\])\../, // ignore dotfiles
renameDetection: true,
renameTimeout: 2000,
recursive: true,
ignoreInitial: true,
persistent: true
2021-08-18 00:01:11 +02:00
})
this.watcher
.on('add', (path) => {
this.onNewFile(path)
}).on('change', (path) => {
// This is triggered from metadata changes, not what we want
// this.onFileUpdated(path)
2021-08-18 00:01:11 +02:00
}).on('unlink', path => {
this.onFileRemoved(path)
}).on('rename', (path, pathNext) => {
this.onRename(path, pathNext)
2021-08-18 00:01:11 +02:00
}).on('error', (error) => {
Logger.error(`[FolderWatcher] ${error}`)
2021-08-18 00:01:11 +02:00
}).on('ready', () => {
Logger.info('[FolderWatcher] Ready')
2021-08-18 00:01:11 +02:00
})
} catch (error) {
Logger.error('Chokidar watcher failed', error)
}
}
close() {
return this.watcher.close()
}
onNewFile(path) {
Logger.debug('FolderWatcher: New File', path)
2021-08-18 00:01:11 +02:00
this.emit('file_added', {
path: path.replace(this.AudiobookPath, ''),
fullPath: path
})
}
onFileRemoved(path) {
Logger.debug('[FolderWatcher] File Removed', path)
2021-08-18 00:01:11 +02:00
this.emit('file_removed', {
path: path.replace(this.AudiobookPath, ''),
fullPath: path
})
}
onFileUpdated(path) {
Logger.debug('[FolderWatcher] Updated File', path)
2021-08-18 00:01:11 +02:00
this.emit('file_updated', {
path: path.replace(this.AudiobookPath, ''),
fullPath: path
})
}
onRename(pathFrom, pathTo) {
Logger.debug(`[FolderWatcher] Rename ${pathFrom} => ${pathTo}`)
}
2021-08-18 00:01:11 +02:00
}
module.exports = FolderWatcher