Skip to content

Commit

Permalink
fix privacy on logging
Browse files Browse the repository at this point in the history
  • Loading branch information
erikng committed Jan 9, 2024
1 parent f3b2ef3 commit bfc2c07
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 125 deletions.
4 changes: 2 additions & 2 deletions Nudge/UI/Defaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,13 @@ class DNDConfig {
self.rawValue = rawType.init()
} else {
self.rawValue = nil
utilsLog.error("DNDSAuxiliaryStateMonitor class could not be found.")
LogManager.error("DNDSAuxiliaryStateMonitor class could not be found.", logger: utilsLog)
}
}

required init?(rawValue: NSObject?) {
guard let rawType = Self.rawType, let unwrappedRawValue = rawValue, unwrappedRawValue.isKind(of: rawType) else {
utilsLog.error("Initialization with rawValue failed.")
LogManager.error("Initialization with rawValue failed.", logger: utilsLog)
return nil
}
self.rawValue = unwrappedRawValue
Expand Down
62 changes: 31 additions & 31 deletions Nudge/UI/Main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
return .terminateNow
} else {
// Log the attempt to exit the application if it should not exit yet
uiLog.warning("Attempt to exit Nudge was prevented.")
LogManager.warning("Attempt to exit Nudge was prevented.", logger: uiLog)
return .terminateCancel
}
}
Expand Down Expand Up @@ -186,7 +186,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

@objc func logHiddenApplication(_ notification: Notification) {
utilsLog.info("Application hidden")
LogManager.info("Application hidden", logger: utilsLog)
}

@objc func scheduleLocal(applicationIdentifier: String) {
Expand All @@ -199,46 +199,46 @@ class AppDelegate: NSObject, NSApplicationDelegate {
switch settings.authorizationStatus {
case .authorized, .provisional:
center.add(request)
uiLog.info("Scheduled notification for terminated application \(applicationIdentifier)")
LogManager.info("Scheduled notification for terminated application \(applicationIdentifier)", logger: uiLog)
case .denied:
uiLog.info("Notifications are denied; cannot schedule notification for \(applicationIdentifier)")
LogManager.info("Notifications are denied; cannot schedule notification for \(applicationIdentifier)", logger: uiLog)
case .notDetermined:
uiLog.info("Notification status not determined; cannot schedule notification for \(applicationIdentifier)")
LogManager.info("Notification status not determined; cannot schedule notification for \(applicationIdentifier)", logger: uiLog)
@unknown default:
uiLog.info("Unknown notification status; cannot schedule notification for \(applicationIdentifier)")
LogManager.info("Unknown notification status; cannot schedule notification for \(applicationIdentifier)", logger: uiLog)
}
}
}

// Observe screen locking. Maybe useful later
@objc func screenLocked(_ notification: Notification) {
nudgePrimaryState.screenCurrentlyLocked = true
utilsLog.info("Screen was locked")
LogManager.info("Screen was locked", logger: utilsLog)
}

@objc func screenParametersChanged(_ notification: Notification) {
utilsLog.info("Screen parameters changed - Notification Center")
LogManager.info("Screen parameters changed - Notification Center", logger: utilsLog)
UIUtilities().centerNudge()
}

@objc func screenProfileChanged(_ notification: Notification) {
utilsLog.info("Display has changed profiles - Notification Center")
LogManager.info("Display has changed profiles - Notification Center", logger: utilsLog)
UIUtilities().centerNudge()
}

@objc func screenUnlocked(_ notification: Notification) {
nudgePrimaryState.screenCurrentlyLocked = false
utilsLog.info("Screen was unlocked")
LogManager.info("Screen was unlocked", logger: utilsLog)
}

@objc func spacesStateChanged(_ notification: Notification) {
UIUtilities().centerNudge()
utilsLog.info("Spaces state changed")
LogManager.info("Spaces state changed", logger: utilsLog)
nudgePrimaryState.afterFirstStateChange = true
}

@objc func terminateApplicationSender(_ notification: Notification) {
utilsLog.info("Application launched - checking if application should be terminated")
LogManager.info("Application launched - checking if application should be terminated", logger: utilsLog)
terminateApplications()
}

Expand All @@ -252,15 +252,15 @@ class AppDelegate: NSObject, NSApplicationDelegate {
private func applyRandomDelayIfNecessary() {
if UserExperienceVariables.randomDelay {
let delaySeconds = Int.random(in: 1...UserExperienceVariables.maxRandomDelayInSeconds)
uiLog.notice("Delaying initial run (in seconds) by: \(delaySeconds)")
LogManager.notice("Delaying initial run (in seconds) by: \(delaySeconds)", logger: uiLog)
sleep(UInt32(delaySeconds))
}
}

private func checkForBadProfilePath() {
let badProfilePath = "/Library/Managed Preferences/com.github.macadmins.Nudge.json.plist"
if FileManager.default.fileExists(atPath: badProfilePath) {
prefsProfileLog.warning("Found bad profile path at \(badProfilePath)")
LogManager.warning("Found bad profile path at \(badProfilePath)", logger: prefsProfileLog)
exit(1)
}
}
Expand Down Expand Up @@ -293,35 +293,35 @@ class AppDelegate: NSObject, NSApplicationDelegate {
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
// Disable CMD + W - closes the Nudge window and breaks it
case [.command] where event.charactersIgnoringModifiers == "w":
utilsLog.warning("Nudge detected an attempt to close the application via CMD + W shortcut key.")
LogManager.warning("Nudge detected an attempt to close the application via CMD + W shortcut key.", logger: utilsLog)
return true
// Disable CMD + N - closes the Nudge window and breaks it
case [.command] where event.charactersIgnoringModifiers == "n":
utilsLog.warning("Nudge detected an attempt to close the application via CMD + N shortcut key.")
LogManager.warning("Nudge detected an attempt to close the application via CMD + N shortcut key.", logger: utilsLog)
return true
// Disable CMD + Q - fully closes Nudge
case [.command] where event.charactersIgnoringModifiers == "q":
utilsLog.warning("Nudge detected an attempt to quit the application via CMD + Q shortcut key.")
LogManager.warning("Nudge detected an attempt to quit the application via CMD + Q shortcut key.", logger: utilsLog)
return true
// Disable CMD + M - Minimizes Nudge
case [.command] where event.charactersIgnoringModifiers == "m":
utilsLog.warning("Nudge detected an attempt to minimize the application via CMD + M shortcut key.")
LogManager.warning("Nudge detected an attempt to minimize the application via CMD + M shortcut key.", logger: utilsLog)
return true
// Disable CMD + H - Hides Nudge
case [.command] where event.charactersIgnoringModifiers == "h":
utilsLog.warning("Nudge detected an attempt to hide the application via CMD + H shortcut key.")
LogManager.warning("Nudge detected an attempt to hide the application via CMD + H shortcut key.", logger: utilsLog)
return true
// Disable CMD + Option + Esc (Force Quit Applications)
case [.command, .option] where event.charactersIgnoringModifiers == "\u{1b}": // Escape key
utilsLog.warning("Nudge detected an attempt to open Force Quit Applications via CMD + Option + Esc.")
LogManager.warning("Nudge detected an attempt to open Force Quit Applications via CMD + Option + Esc.", logger: utilsLog)
return true
// Disable CMD + Option + M - Minimizes Nudge
case [.command, .option] where event.charactersIgnoringModifiers == "µ":
utilsLog.warning("Nudge detected an attempt to minimise the application via CMD + Option + M shortcut key.")
LogManager.warning("Nudge detected an attempt to minimise the application via CMD + Option + M shortcut key.", logger: utilsLog)
return true
// Disable CMD + Option + N - Add tabs to Nudge window
case [.command, .option] where event.charactersIgnoringModifiers == "~":
utilsLog.warning("Nudge detected an attempt to add tabs to the application via CMD + Option + N shortcut key.")
LogManager.warning("Nudge detected an attempt to add tabs to the application via CMD + Option + N shortcut key.", logger: utilsLog)
return true
default:
// Don't care about any other shortcut keys
Expand All @@ -345,15 +345,15 @@ class AppDelegate: NSObject, NSApplicationDelegate {

private func handleAttemptToFetchMajorUpgrade() {
if GlobalVariables.fetchMajorUpgradeSuccessful == false && !majorUpgradeAppPathExists && !majorUpgradeBackupAppPathExists {
uiLog.error("Unable to fetch major upgrade and application missing, exiting Nudge")
LogManager.error("Unable to fetch major upgrade and application missing, exiting Nudge", logger: uiLog)
nudgePrimaryState.shouldExit = true
exit(1)
}
}

private func handleNoAttemptToFetchMajorUpgrade() {
if !majorUpgradeAppPathExists && !majorUpgradeBackupAppPathExists {
uiLog.error("Unable to find major upgrade application, exiting Nudge")
LogManager.error("Unable to find major upgrade application, exiting Nudge", logger: uiLog)
nudgePrimaryState.shouldExit = true
exit(1)
}
Expand Down Expand Up @@ -385,7 +385,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
handleNoAttemptToFetchMajorUpgrade()
}
} else {
prefsProfileLog.warning("actionButtonPath is nil or empty - actionButton will be unable to trigger any action required for major upgrades")
LogManager.warning("actionButtonPath is nil or empty - actionButton will be unable to trigger any action required for major upgrades", logger: prefsProfileLog)
return
}
}
Expand Down Expand Up @@ -429,11 +429,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
utilsLog.info("User granted notifications - application blocking status now available")
LogManager.info("User granted notifications - application blocking status now available", logger: utilsLog)
} else if let error = error {
utilsLog.error("Error requesting notifications authorization: \(error.localizedDescription)")
LogManager.error("Error requesting notifications authorization: \(error.localizedDescription)", logger: utilsLog)
} else {
utilsLog.info("User denied notifications - application blocking status will be unavailable")
LogManager.info("User denied notifications - application blocking status will be unavailable", logger: utilsLog)
}
}
}
Expand Down Expand Up @@ -511,10 +511,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {

private func terminateApplication(_ application: NSRunningApplication) {
guard application.terminate() else {
utilsLog.error("Failed to terminate application: \(application.bundleIdentifier ?? "")")
LogManager.error("Failed to terminate application: \(application.bundleIdentifier ?? "")", logger: utilsLog)
return
}
utilsLog.info("Successfully terminated application: \(application.bundleIdentifier ?? "")")
LogManager.info("Successfully terminated application: \(application.bundleIdentifier ?? "")", logger: utilsLog)
}

private func terminateApplications() {
Expand All @@ -529,7 +529,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
continue
}
if OptionalFeatureVariables.blockedApplicationBundleIDs.contains(appBundleID) {
utilsLog.info("Found \(appBundleID), terminating application")
LogManager.info("Found \(appBundleID), terminating application", logger: utilsLog)
terminateApplication(runningApplication)
}
}
Expand Down
22 changes: 21 additions & 1 deletion Nudge/Utilities/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,26 @@ struct LogManager {
static func createLogger(category: String) -> Logger {
return Logger(subsystem: bundleID, category: category)
}

static func debug(_ message: String, logger: Logger) {
logger.debug("\(message, privacy: .public)")
}

static func error(_ message: String, logger: Logger) {
logger.error("\(message, privacy: .public)")
}

static func info(_ message: String, logger: Logger) {
logger.info("\(message, privacy: .public)")
}

static func notice(_ message: String, logger: Logger) {
logger.notice("\(message, privacy: .public)")
}

static func warning(_ message: String, logger: Logger) {
logger.warning("\(message, privacy: .public)")
}
}

// Usage of Logger Manager
Expand Down Expand Up @@ -45,6 +65,6 @@ class LogState {
// NudgeLogger
class NudgeLogger {
init() {
loggingLog.debug("Starting log events")
LogManager.debug("Starting log events", logger: loggingLog)
}
}
2 changes: 1 addition & 1 deletion Nudge/Utilities/Preferences.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func getOptionalFeaturesProfile() -> [String: Any]? {
private func logEmptyKey(_ key: String, forJSON: Bool) {
if !nudgeLogState.afterFirstLaunch {
let log = forJSON ? prefsJSONLog : prefsProfileLog
log.info("\(key) key is empty")
LogManager.info("\(key) key is empty", logger: log)
}
}

Expand Down
26 changes: 13 additions & 13 deletions Nudge/Utilities/SoftwareUpdate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,59 +13,59 @@ class SoftwareUpdate {
let (output, error, exitCode) = runProcess(launchPath: "/usr/sbin/softwareupdate", arguments: ["--list", "--all"])

if exitCode != 0 {
softwareupdateListLog.error("Error listing software updates: \(error)")
LogManager.error("Error listing software updates: \(error)", logger: softwareupdateListLog)
return error
} else {
softwareupdateListLog.info("\(output)")
LogManager.info("\(output)", logger: softwareupdateListLog)
return output
}
}

func download() {
softwareupdateDownloadLog.notice("enforceMinorUpdates: \(OptionalFeatureVariables.enforceMinorUpdates)")
LogManager.notice("enforceMinorUpdates: \(OptionalFeatureVariables.enforceMinorUpdates)", logger: softwareupdateDownloadLog)

if DeviceManager().getCPUTypeString() == "Apple Silicon" && !AppStateManager().requireMajorUpgrade() {
softwareupdateListLog.debug("Apple Silicon devices do not support automated softwareupdate downloads for minor updates. Please use MDM for this functionality.")
LogManager.debug("Apple Silicon devices do not support automated softwareupdate downloads for minor updates. Please use MDM for this functionality.", logger: softwareupdateListLog)
return
}

if AppStateManager().requireMajorUpgrade() {
guard FeatureVariables.actionButtonPath == nil else { return }

if OptionalFeatureVariables.attemptToFetchMajorUpgrade, !majorUpgradeAppPathExists, !majorUpgradeBackupAppPathExists {
softwareupdateListLog.notice("Device requires major upgrade - attempting download")
LogManager.notice("Device requires major upgrade - attempting download", logger: softwareupdateListLog)
let (output, error, exitCode) = runProcess(launchPath: "/usr/sbin/softwareupdate", arguments: ["--fetch-full-installer", "--full-installer-version", OSVersionRequirementVariables.requiredMinimumOSVersion])

if exitCode != 0 {
softwareupdateDownloadLog.error("Error downloading software update: \(error)")
LogManager.error("Error downloading software update: \(error)", logger: softwareupdateDownloadLog)
} else {
softwareupdateDownloadLog.info("\(output)")
LogManager.info("\(output)", logger: softwareupdateDownloadLog)
GlobalVariables.fetchMajorUpgradeSuccessful = true
// Update the state based on the download result
}
} else {
softwareupdateListLog.notice("Found major upgrade application or backup - skipping download")
LogManager.notice("Found major upgrade application or backup - skipping download", logger: softwareupdateListLog)
}
} else {
if OptionalFeatureVariables.disableSoftwareUpdateWorkflow {
softwareupdateListLog.notice("Skipping running softwareupdate because it's disabled by a preference.")
LogManager.notice("Skipping running softwareupdate because it's disabled by a preference.", logger: softwareupdateListLog)
return
}
let softwareupdateList = self.list()
let updateLabel = extractUpdateLabel(from: softwareupdateList)

if !softwareupdateList.contains(OSVersionRequirementVariables.requiredMinimumOSVersion) || updateLabel.isEmpty {
softwareupdateListLog.notice("Software update did not find \(OSVersionRequirementVariables.requiredMinimumOSVersion) available for download - skipping download attempt")
LogManager.notice("Software update did not find \(OSVersionRequirementVariables.requiredMinimumOSVersion) available for download - skipping download attempt", logger: softwareupdateListLog)
return
}

softwareupdateListLog.notice("Software update found \(updateLabel) available for download - attempting download")
LogManager.notice("Software update found \(updateLabel) available for download - attempting download", logger: softwareupdateListLog)
let (output, error, exitCode) = runProcess(launchPath: "/usr/sbin/softwareupdate", arguments: ["--download", updateLabel])

if exitCode != 0 {
softwareupdateDownloadLog.error("Error downloading software updates: \(error)")
LogManager.error("Error downloading software updates: \(error)", logger: softwareupdateDownloadLog)
} else {
softwareupdateDownloadLog.info("\(output)")
LogManager.info("\(output)", logger: softwareupdateDownloadLog)
}
}
}
Expand Down
Loading

0 comments on commit bfc2c07

Please sign in to comment.