Skip to content

Instantly share code, notes, and snippets.

@OmgImAlexis
Forked from suhajdab/nodejs-unlock
Last active August 29, 2015 14:16
Show Gist options
  • Save OmgImAlexis/1519cc5fa1ac392fb2d1 to your computer and use it in GitHub Desktop.
Save OmgImAlexis/1519cc5fa1ac392fb2d1 to your computer and use it in GitHub Desktop.
Lock and unlock OSX from http request.
var applescript = require('applescript');
var http = require('http');
require('shelljs/global');
var script =
'tell application "System Events"\n\
if name of every process contains "ScreenSaverEngine" then \n\
tell application "ScreenSaverEngine"\n\
quit\n\
end tell\n\
delay 0.2\n\
else \n\
tell application "Terminal"\n\
do shell script "caffeinate -u -t 1"\n\
end tell\n\
delay 0.5\n\
end if\n\
keystroke "YOUR_PASSWORD"\n\
keystroke return\n\
get computer name of (system info)\n\
end tell';
function onRequest(req, res) {
if (req.url == '/unlock') {
if (!exec('python -c \'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); sys.exit(d and d.get("CGSSessionScreenIsLocked", 0) == 0 and d.get("kCGSSessionOnConsoleKey", 0) == 1)\'')['code']){
applescript.execString(script, function(err, rtn) {
if (err) console.error(err);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write( err ? 'something went wrong while unlocking' : 'unlocked ' + rtn );
res.end();
});
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('OSX isn\'t currently locked.');
res.end();
}
} else if (req.url == '/lock') {
applescript.execString('do shell script "open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app"');
} else {
console.log('WHAT?');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('WHAT?');
res.end();
}
}
http.createServer(onRequest).listen(9091);
@suhajdab
Copy link

No reason to go to shell from applescript to activate screensaver.
'tell application "System Events"\n
start current screen saver\n
end tell'

And thanks for the solution around lock screen detection! 😄

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