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
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
@OmgImAlexis
Copy link
Author

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
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