Skip to content

Instantly share code, notes, and snippets.

@drewkerr
Last active Nov 21, 2021
Embed
What would you like to do?
Read the current Focus mode on macOS Monterey (12.0+) using JavaScript for Automation (JXA)
const app = Application.currentApplication()
app.includeStandardAdditions = true
function getJSON(path) {
const fullPath = path.replace(/^~/, app.pathTo('home folder'))
const contents = app.read(fullPath)
return JSON.parse(contents)
}
function run() {
let focus = "No focus" // default
const assert = getJSON("~/Library/DoNotDisturb/DB/Assertions.json").data[0].storeAssertionRecords
const config = getJSON("~/Library/DoNotDisturb/DB/ModeConfigurations.json").data[0].modeConfigurations
if (assert) { // focus set manually
const modeid = assert[0].assertionDetails.assertionDetailsModeIdentifier
focus = config[modeid].mode.name
} else { // focus set by trigger
const date = new Date
const now = date.getHours() * 60 + date.getMinutes()
for (const modeid in config) {
const triggers = config[modeid].triggers.triggers[0]
if (triggers && triggers.enabledSetting == 2) {
const start = triggers.timePeriodStartTimeHour * 60 + triggers.timePeriodStartTimeMinute
const end = triggers.timePeriodEndTimeHour * 60 + triggers.timePeriodEndTimeMinute
if (start < end) {
if (now >= start && now < end) {
focus = config[modeid].mode.name
}
} else if (start > end) { // includes midnight
if (now >= start || now < end) {
focus = config[modeid].mode.name
}
}
}
}
}
return focus
}
@drewkerr
Copy link
Author

drewkerr commented Nov 5, 2021

Discussion on Automators forum and Six Colors.

Loading

@diogocampos
Copy link

diogocampos commented Nov 6, 2021

You could avoid using the Objective-C bridge in your getJSON function by doing something like this:

const app = Application.currentApplication()
app.includeStandardAdditions = true

function getJSON(path) {
  const fullPath = path.replace(/^~/, app.pathTo('home folder'))
  const contents = app.read(fullPath)
  return JSON.parse(contents)
}

Loading

@drewkerr
Copy link
Author

drewkerr commented Nov 7, 2021

Thanks @diogocampos! I was working from the JXA Cookbook for that. I've updated the gist.

Loading

@tjluoma
Copy link

tjluoma commented Nov 18, 2021

I'm wondering if this could be done in shell if I had access to jq for parsing json. Unfortunately, I don't really know how to read this code as I don't real AppleJavaScript.

EDITED TO ADD: I remembered that I could do a HEREDOC with this in it…

CURRENT=$(/usr/bin/osascript -l JavaScript <<EOT
....

EOT
)

and the variable $CURRENT would have the result of the JavaScript. That will work for me, unless there's a pure bash/zsh/shell option out there that someone can come up with.

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment