32 lines
1.5 KiB
Swift
32 lines
1.5 KiB
Swift
|
|
import Foundation
|
||
|
|
|
||
|
|
/// Decides whether a finished turn is worth a notification. A quick turn means you are probably
|
||
|
|
/// still at the keyboard, so notifying would just be noise.
|
||
|
|
public enum TurnTimer {
|
||
|
|
public static let defaultMinimumSeconds: TimeInterval = 30
|
||
|
|
|
||
|
|
public static func shouldNotify(startedAt: Date?, endedAt: Date, minimumSeconds: TimeInterval) -> Bool {
|
||
|
|
// No recorded start (hook not installed, or app restarted mid-turn): err toward telling the user.
|
||
|
|
guard let startedAt else { return true }
|
||
|
|
return endedAt.timeIntervalSince(startedAt) >= minimumSeconds
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func startFilePath(directory: String) -> String {
|
||
|
|
(directory as NSString).appendingPathComponent("turn-start")
|
||
|
|
}
|
||
|
|
|
||
|
|
public static func recordStart(at date: Date, directory: String) throws {
|
||
|
|
try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)
|
||
|
|
let text = String(date.timeIntervalSince1970)
|
||
|
|
try text.write(toFile: startFilePath(directory: directory), atomically: true, encoding: .utf8)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Returns nil when no start was recorded or the file is unreadable, never throws, so a damaged
|
||
|
|
/// file cannot stop a notification.
|
||
|
|
public static func readStart(directory: String) -> Date? {
|
||
|
|
guard let text = try? String(contentsOfFile: startFilePath(directory: directory), encoding: .utf8),
|
||
|
|
let seconds = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines)) else { return nil }
|
||
|
|
return Date(timeIntervalSince1970: seconds)
|
||
|
|
}
|
||
|
|
}
|