Skip to content

Commit

Permalink
move isScreenSharing logic to DNDServer private framework
Browse files Browse the repository at this point in the history
  • Loading branch information
erikng committed May 25, 2022
1 parent ed027b1 commit a0bdd7b
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 62 deletions.
1 change: 0 additions & 1 deletion Nudge/UI/ContentView.swift
Expand Up @@ -25,7 +25,6 @@ class ViewState: ObservableObject {
@Published var hasLoggedRequireDualQuitButtons = false
@Published var hasLoggedRequireMajorUgprade = false
@Published var hoursRemaining = Utils().getNumberOfHoursRemaining()
@Published var isScreenSharing = false
@Published var lastRefreshTime = Utils().getFormattedDate()
@Published var requireDualQuitButtons = false
@Published var shouldExit = false
Expand Down
1 change: 0 additions & 1 deletion Nudge/UI/Main.swift
Expand Up @@ -286,7 +286,6 @@ class AppDelegate: NSObject, NSApplicationDelegate {
// Check to see if camera was turned off or on in the last x amount of minutes
if logReferralTime > 0 && !nudgeLogState.afterFirstRun {
LogReader().cameraShow()
LogReader().screenSharingShow()
}
// Stream camera status from here on out
LogReader().Stream()
Expand Down
52 changes: 1 addition & 51 deletions Nudge/Utilities/Logger.swift
Expand Up @@ -30,7 +30,7 @@ class LogReader {
func Stream() {
let task = Process()
task.launchPath = "/usr/bin/log"
task.arguments = ["stream", "--predicate", "(subsystem contains \"com.apple.donotdisturb\" and composedMessage contains \"isScreenShared\") or (subsystem contains \"com.apple.UVCExtension\" and composedMessage contains \"Post PowerLog\" OR eventMessage contains \"Post event kCameraStream\")", "--style", "ndjson"]
task.arguments = ["stream", "--predicate", "(subsystem contains \"com.apple.UVCExtension\" and composedMessage contains \"Post PowerLog\" OR eventMessage contains \"Post event kCameraStream\")", "--style", "ndjson"]

let pipe = Pipe()
task.standardOutput = pipe
Expand All @@ -55,14 +55,6 @@ class LogReader {
uiLog.notice("\("Camera was detected powering off", privacy: .public)")
nudgePrimaryState.cameraOn = false
}
if eventMessage.contains("isScreenShared=1") {
uiLog.notice("\("Screen sharing was detected being enabled", privacy: .public)")
nudgePrimaryState.isScreenSharing = true
}
if eventMessage.contains("isScreenShared=0") {
uiLog.notice("\("Screen sharing was detected being disabled", privacy: .public)")
nudgePrimaryState.isScreenSharing = false
}
}
} catch {}
outHandle.waitForDataInBackgroundAndNotify()
Expand Down Expand Up @@ -115,46 +107,4 @@ class LogReader {
} catch {}
}
}
func screenSharingShow() {
let task = Process()
task.launchPath = "/usr/bin/log"
task.arguments = ["show", "--last", "\(logReferralTime)m", "--predicate", "subsystem contains \"com.apple.donotdisturb\" and composedMessage contains \"isScreenShared\"", "--style", "json"]

let outputPipe = Pipe(), errorPipe = Pipe()

task.standardOutput = outputPipe
task.standardError = errorPipe

do {
try task.run()
} catch {
utilsLog.error("\("Error returning log show", privacy: .public)")
}

task.waitUntilExit()

let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile(), errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()

let error = String(decoding: errorData, as: UTF8.self)

if task.terminationStatus != 0 {
utilsLog.error("Error returning log show: \(error, privacy: .public)")
} else {
do {
let jsonResult: NSArray = try JSONSerialization.jsonObject(with: outputData, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
if let lastResult = jsonResult.lastObject as? NSDictionary {
if let eventMessage : NSString = lastResult["eventMessage"] as? NSString {
if eventMessage.contains("isScreenShared=1") {
uiLog.notice("\("Screen sharing was detected as enabled prior to Nudge launching", privacy: .public)")
nudgePrimaryState.isScreenSharing = true
}
if eventMessage.contains("isScreenShared=0") {
uiLog.notice("\("Screen sharing was detected as disabled prior to Nudge launching", privacy: .public)")
nudgePrimaryState.isScreenSharing = false
}
}
}
} catch {}
}
}
}
31 changes: 22 additions & 9 deletions Nudge/Utilities/UILogic.swift
Expand Up @@ -7,14 +7,17 @@

import AppKit
import Foundation
import IOKit.pwr_mgt
import IOKit.pwr_mgt // Asertions

// Idea from https://github.com/saagarjha/vers/blob/d9460f6e14311e0a90c4c171975c93419481586b/vers/Headers.swift
let DNDServer = Bundle(path: "/System/Library/PrivateFrameworks/DoNotDisturbServer.framework")?.load() ?? false

class DNDConfig {
static let rawType = NSClassFromString("DNDSAuxiliaryStateMonitor") as! NSObject.Type
let rawValue: NSObject

init() {
self.rawValue = Self.rawType.init() as! NSObject
self.rawValue = Self.rawType.init()
}

required init(rawValue: NSObject) {
Expand Down Expand Up @@ -92,10 +95,6 @@ func needToActivateNudge() -> Bool {
let frontmostApplication = NSWorkspace.shared.frontmostApplication
let runningApplications = NSWorkspace.shared.runningApplications
let pastRequiredInstallationDate = Utils().pastRequiredInstallationDate()

// // Idea from https://github.com/saagarjha/vers/blob/d9460f6e14311e0a90c4c171975c93419481586b/vers/Headers.swift
// Bundle(path: "/System/Library/PrivateFrameworks/DoNotDisturbServer.framework")!.load()
// print(DNDConfig().rawValue.value(forKey: "isScreenShared"))

// Center Nudge
Utils().centerNudge()
Expand All @@ -122,6 +121,9 @@ func needToActivateNudge() -> Bool {
// Print both controllers back to back
if !nudgeLogState.afterFirstRun {
uiLog.info("\("nudgeRefreshCycle: \(nudgeRefreshCycle)", privacy: .public)")
if !DNDServer {
uiLog.error("\("acceptableScreenSharingUsage is set but DoNotDisturbServer framework is unavailable", privacy: .public)")
}
}
let timerController = Utils().getTimerController()

Expand Down Expand Up @@ -172,9 +174,11 @@ func needToActivateNudge() -> Bool {
}

// Don't nudge if screen sharing and prior to requiredInstallationDate
if (nudgePrimaryState.isScreenSharing && acceptableScreenSharingUsage) && !pastRequiredInstallationDate {
uiLog.info("\("Ignoring Nudge activation - Screen sharing is currently active and not pastRequiredInstallationDate", privacy: .public)")
return false
if DNDServer && acceptableScreenSharingUsage && !pastRequiredInstallationDate {
if (DNDConfig().rawValue.value(forKey: "isScreenShared") as? Bool) == true && !pastRequiredInstallationDate {
uiLog.info("\("Ignoring Nudge activation - Screen sharing is currently active and not pastRequiredInstallationDate", privacy: .public)")
return false
}
}

// Don't nudge if assertions are set and prior to requiredInstallationDate
Expand Down Expand Up @@ -283,3 +287,12 @@ extension NSWorkspace {
return false
}
}

// Return nil if a key does not exist in a Dictionary, rather than completely crash the app
// Comparable to aDictionary.get("something", None) in Python
extension NSObject {
@objc
func value(forUndefinedKey key: String) -> String? {
nil
}
}

0 comments on commit a0bdd7b

Please sign in to comment.