blob: c7ca85a46dfca9fd1f256ea9ec1edc337c41a047 (
plain)
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
|
import Logging
import ServiceLifecycle
import SystemPackage
import _NIOFileSystem
struct Watcher: Service {
let directory: FilePath
let logger: Logger
let suffix: String
func run() async {
let sleepInhibitor = SleepInhibitor()
while !Task.isCancelled {
let isDownloading: Bool
do {
isDownloading = try await FileSystem.shared.withDirectoryHandle(atPath: self.directory) {
try await $0.listContents().contains {
$0.name.extension?.hasSuffix(self.suffix) ?? false
}
}
} catch is CancellationError {
return
} catch {
self.logger.error("Failed to check directory: \(error)")
return
}
switch (isDownloading, await sleepInhibitor.isInhibitingSleep) {
case (true, false):
self.logger.debug("Ongoing downloads found, inhibiting sleep")
do {
try await sleepInhibitor.create(
name: "caffeinate-downloads",
details: "There are files being downloaded"
)
} catch {
self.logger.error("Failed to create assertion: \(error)")
}
case (false, true):
self.logger.debug("No ongoing downloads found, allowing sleep")
do {
try await sleepInhibitor.release()
} catch {
self.logger.error("Failed to release assertion: \(error)")
}
default:
break
}
guard (try? await Task.sleep(for: .seconds(30))) != nil else {
return
}
}
}
}
|