Repository navigation
Expand file tree
/
Copy pathMediaScanner.ts
More file actions
201 lines (161 loc) · 5.65 KB
/
Copy pathMediaScanner.ts
File metadata and controls
201 lines (161 loc) · 5.65 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import moment from 'moment'
import { BError } from 'berror'
import { fs } from '@nofrills/fs'
import { EventEmitter } from 'events'
import { Lincoln } from '@nnode/lincoln'
import { Throttle } from '@nnode/common'
import { FfprobeData, FfprobeStream } from 'fluent-ffmpeg'
import { MediaStore } from './MediaStore'
import { StreamFile } from './StreamFile'
import { getMediaInfo } from './MediaFunctions'
import { MediaInfo } from './MediaInfo'
export type MediaFileNameFilter = (filename: string) => boolean
const DefaultFilter = () => true
export class MediaScanner extends EventEmitter {
static readonly codecs = ['aac', 'hevc']
static readonly extensions = ['avi', 'mkv', 'mp4', 'mpeg', 'mpg', 'wmv']
static readonly events = {
progress: 'progress',
start: 'start',
stop: 'stop',
}
private readonly globs: string[]
private readonly log: Lincoln
private readonly media: MediaStore
constructor(
logger: Lincoln,
readonly allowedExtensions = MediaScanner.extensions,
readonly allowedCodecs = MediaScanner.codecs,
) {
super()
this.globs = allowedExtensions.map((glob) => `**/*.${glob}`)
this.log = logger.extend('scanner')
this.media = new MediaStore(logger)
}
async scan(path: string, minutes: number = 0, reverse: boolean = false, filter: MediaFileNameFilter = DefaultFilter) {
const documents: MediaInfo[] = await this.media.all({
selector: {
filepath: {
$regex: path,
},
source: {
streams: {
$elemMatch: {
codec_name: {
$ne: 'hevc',
},
codec_type: {
$eq: 'video',
},
},
},
},
},
limit: Number.MAX_SAFE_INTEGER,
skip: 0,
})
this.log.info('[scan] retrieving cached', { cached: documents.length })
this.log.info('[scan] gathering globs')
const unsorted = await fs.globs(this.globs, path)
this.log.info('[scan] unsorted', { length: unsorted.length })
const sorted = this.applySort(unsorted, reverse)
this.log.info('[scan] sorted', { length: sorted.length, reverse })
const final = sorted
const total = final.length
this.log.info('[scan] total', { total })
this.emit(MediaScanner.events.start, total)
const files = await Throttle(
final.map((fullname, index) => async () => {
try {
const filename = fs.basename(fullname)
const filepath = fs.dirname(fullname)
if (this.media.has(filename, documents)) {
const document = await this.media.get(filename)
if (document) {
return this.convertible(document, index, total)
}
}
const source = await getMediaInfo(fullname)
const document: MediaInfo = this.media.document({
filename,
filepath,
host: null,
locked: false,
source,
})
await this.media.upsert(filename, document)
return this.convertible(document, index, total)
} catch (error) {
this.log.error(new BError('scan', error), error)
}
return null
}),
)
this.emit(MediaScanner.events.stop)
return files.reduce<StreamFile[]>((results, file) => (file !== null ? [...results, file] : results), [])
}
private async convertible(info: MediaInfo, index: number, total: number): Promise<StreamFile | null> {
try {
const audio = this.findAudioStream(info.source)
const video = this.findVideoStream(info.source)
const audioCodeDisallowed = this.codec_allowed(audio.codec_name) === false
const videoCodecDisallowed = this.codec_allowed(video.codec_name) === false
const locked = await this.media.locked(info.filename)
this.log.trace(info.filename, 'lock-status', locked, 'progress', index, total)
this.emit(MediaScanner.events.progress, info.filename, locked)
if ((audioCodeDisallowed || videoCodecDisallowed) && locked === false) {
const streamFile: StreamFile = {
audio,
video,
fullpath: fs.join(info.filepath, info.filename),
data: info.source,
format: info.source.format,
}
return streamFile
}
return null
} catch (error) {
throw new BError('convertible', error)
}
}
private applyAgeFilter(files: string[], minutes: number): Promise<string[]> {
return files.reduce<Promise<string[]>>(async (previous, current) => {
const results = await previous
const stat = await fs.stat(current)
const created = stat.stats.ctime
const $created = moment(created)
const diff = $created.diff(new Date(), 'minutes')
if (Math.abs(diff) > minutes) {
results.push(current)
}
return results
}, Promise.resolve([]))
}
private applySort(files: string[], reverse: boolean): string[] {
return files.sort((source, target) => {
if (source > target) {
return reverse ? -1 : 1
}
if (source < target) {
return reverse ? 1 : -1
}
return 0
})
}
private codec_allowed(codec?: string): boolean {
if (codec) {
return this.allowedCodecs.some((name) => codec === name)
}
return false
}
private findAudioStream(data: FfprobeData): FfprobeStream {
return data.streams
.filter((stream) => stream.codec_type === 'audio')
.reduce<FfprobeStream | any>((_, current) => current, {})
}
private findVideoStream(data: FfprobeData): FfprobeStream {
return data.streams
.filter((stream) => stream.codec_type === 'video')
.reduce<FfprobeStream | any>((_, current) => current, {})
}
}