Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
@OmgImAlexis

This comment has been minimized.

Copy link
Owner Author

commented Mar 8, 2015

To use this run the following line in terminal.
You must have node.js or a fork like io.js installed.

curl -o app.js https://gist.githubusercontent.com/OmgImAlexis/1519cc5fa1ac392fb2d1/raw/ce73a885e976e510e35f67af4629d3ad352ea233/nodejs-unlock && npm install -g nodemon && npm install shelljs && npm install applescript && clear && echo 'Install done'

Make sure to replace YOUR_PASSWORD in app.js with your own password and then run forever start app.js, to stop the process use forever stop 0.

@suhajdab

This comment has been minimized.

Copy link

commented Mar 13, 2015

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
You can’t perform that action at this time.