Detect lock screen or running screensaver with Firefox/OS X - javascript

I'm creating an extension for Firefox (SDK Add-on) in which I'll need to detect screensaver and lock-screen events so that I can set a user's availability status in a web-app.
I've managed to do this already for Windows and now need to port to OS X. For the Windows version, I was using calls to native API to find out if screen was locked, etc. Is there a similar way of getting OS information from a Firefox extension on OS X? I've tried Googling this and haven't found a solid answer - any help appreciated!

On OSX you can query a locked screen/screensaver using CGSessionCopyCurrentDictionary and looking for the presence and value of the "CGSSessionScreenIsLocked" key.
This is platform API, so one will have to use js-ctypes again and write a bunch of code to get that working.
I did get it working: The following code is a working example you can run in a privileged Scratchpad. To get a privileged one, open a pad for e.g. about:newtab.
Components.utils.import("resource://gre/modules/ctypes.jsm");
var CoreFoundation = new (function() {
this.CFNumberRef = ctypes.voidptr_t;
this.CFStringRef = ctypes.voidptr_t;
this.CFDictionaryRef = ctypes.voidptr_t;
var lib = ctypes.open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");
this.CFRelease = lib.declare(
"CFRelease",
ctypes.default_abi,
ctypes.void_t,
ctypes.voidptr_t);
var CFStringCreateWithCharacters = lib.declare(
"CFStringCreateWithCharacters",
ctypes.default_abi,
this.CFStringRef,
ctypes.voidptr_t,
ctypes.jschar.ptr,
ctypes.int32_t);
this.CFStringCreateWithCharacters = function(str) {
var rv = CFStringCreateWithCharacters(null, str, str.length);
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, this.CFRelease);
};
var CFDictionaryGetValue = lib.declare(
"CFDictionaryGetValue",
ctypes.default_abi,
this.CFNumberRef,
this.CFDictionaryRef,
this.CFStringRef);
this.CFDictionaryGetInt = function(dict, str) {
var rv = CFDictionaryGetValue(dict, this.CFStringCreateWithCharacters(str));
if (!rv || rv.isNull()) {
return null;
};
return this.CFNumberGetValue(rv);
};
var CFNumberGetValue = lib.declare(
"CFNumberGetValue",
ctypes.default_abi,
ctypes.bool,
this.CFNumberRef,
ctypes.int32_t,
ctypes.int32_t.ptr);
this.CFNumberGetValue = function(num) {
var rv = new ctypes.int32_t();
CFNumberGetValue(num, 3, rv.address());
console.log("CFNumberGetValue", rv, rv.value);
return rv.value;
};
this.close = function() {
lib.close();
};
})();
var ApplicationServices = new (function() {
var lib = ctypes.open("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices");
var CGSessionCopyCurrentDictionary = lib.declare(
"CGSessionCopyCurrentDictionary",
ctypes.default_abi,
CoreFoundation.CFDictionaryRef);
this.CGSessionCopyCurrentDictionary = function() {
var rv = CGSessionCopyCurrentDictionary();
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, CoreFoundation.CFRelease);
};
this.close = function() {
lib.close();
};
})();
setInterval(function() {
var dict = ApplicationServices.CGSessionCopyCurrentDictionary();
if (dict) {
var locked = CoreFoundation.CFDictionaryGetInt(dict, "CGSSessionScreenIsLocked");
console.log("rv", locked);
if (locked) {
// do something;
}
}
}, 500);

Related

How to save mxworkflow editor as Xml using javascript

Iam using mxWorkflow -Editor to draw workflow process
then i tried to save the workflow as xml but it is not working
i tried this
function GetXML(container)
{
var graph = new mxGraph(container);
var enc = new mxCodec();
var node = enc.encode(graph.getModel());
var model = graph.getModel();
try
{
// var graph = new mxGraph(container);
graph.model.addListener(mxEvent.CHANGE, function (sender, evt) {
var changes = evt.getProperty('edit').changes;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change instanceof mxChildChange &&
change.change.previous == null) {
graph.startEditingAtCell(change.child);
break;
}
}
});
}
finally
{
// Updates the display
model.endUpdate();
// graph.getModel().endUpdate();
}
// Adds an option to view the XML of the graph
document.body.appendChild(mxUtils.button('View XML', function()
{
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
mxUtils.popup(mxUtils.getXml(node), true);
}));
I've looked at few posts & documentation , but didn't find anything
use function mxUtils.getPrettyXml
var button = mxUtils.button('View XML', function() {
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
mxUtils.popup(mxUtils.getPrettyXml(node), true);
});
document.appendChild(button);

Sketch JS, how to use AWS pre-signed URL on audio tag?

Quick look
I'm using Sketch.js plugin in this example. I
would like to use my pre-signed urls as well but they don't work.
Expiration time is set long enough (1 day) so there's something wrong
with the JS itself.
I have an S3 bucket where I store some music public protected.
Using the official AWS SDK I can generate urls like:
https://d225******.cloudfront.net/song.m4a?Expires=1493381986&Signature=***&Key-Pair-Id=***
I'm using pre-signed urls over my website without any problem, but in this script won't work:
<script>
var ALPHA, AudioAnalyser, COLORS, MP3_PATH, NUM_BANDS, NUM_PARTICLES, Particle, SCALE, SIZE, SMOOTHING, SPEED, SPIN;
MP3_PATH = 'my_presigned_url';
AudioAnalyser = (function() {
AudioAnalyser.AudioContext = self.AudioContext || self.webkitAudioContext;
AudioAnalyser.enabled = AudioAnalyser.AudioContext != null;
function AudioAnalyser(audio, numBands, smoothing) {
var src;
this.audio = audio != null ? audio : new Audio();
this.numBands = numBands != null ? numBands : 256;
this.smoothing = smoothing != null ? smoothing : 0.3;
if (typeof this.audio === 'string') {
src = this.audio;
this.audio = new Audio();
this.audio.crossOrigin = "anonymous";
this.audio.controls = true;
this.audio.src = src;
}
this.context = new AudioAnalyser.AudioContext();
this.jsNode = this.context.createScriptProcessor(2048, 1, 1);
this.analyser = this.context.createAnalyser();
this.analyser.smoothingTimeConstant = this.smoothing;
this.analyser.fftSize = this.numBands * 2;
this.bands = new Uint8Array(this.analyser.frequencyBinCount);
this.audio.addEventListener('canplay', (function(_this) {
return function() {
_this.source = _this.context.createMediaElementSource(_this.audio);
_this.source.connect(_this.analyser);
_this.analyser.connect(_this.jsNode);
_this.jsNode.connect(_this.context.destination);
_this.source.connect(_this.context.destination);
return _this.jsNode.onaudioprocess = function() {
_this.analyser.getByteFrequencyData(_this.bands);
if (!_this.audio.paused) {
return typeof _this.onUpdate === "function" ? _this.onUpdate(_this.bands) : void 0;
}
};
};
})(this));
}
AudioAnalyser.prototype.start = function() {
return this.audio.play();
};
AudioAnalyser.prototype.stop = function() {
return this.audio.pause();
};
return AudioAnalyser;
})();
Sketch.create({
particles: [],
setup: function() {
var analyser, error, i, intro, j, particle, ref, warning, x, y;
for (i = j = 0, ref = NUM_PARTICLES - 1; j <= ref; i = j += 1) {
x = random(this.width);
y = random(this.height * 2);
particle = new Particle(x, y);
particle.energy = random(particle.band / 256);
this.particles.push(particle);
}
if (AudioAnalyser.enabled) {
try {
analyser = new AudioAnalyser(MP3_PATH, NUM_BANDS, SMOOTHING);
analyser.onUpdate = (function(_this) {
return function(bands) {
var k, len, ref1, results;
ref1 = _this.particles;
results = [];
for (k = 0, len = ref1.length; k < len; k++) {
particle = ref1[k];
results.push(particle.energy = bands[particle.band] / 256);
}
return results;
};
})(this);
analyser.start();
document.getElementById('player-container').appendChild(analyser.audio);
document.getElementsByTagName("audio")[0].setAttribute("id", "dy_wowaudio");
intro = document.getElementById('intro');
intro.style.display = 'none';
} catch (_error) {
error = _error;
}
}
}
});
// generated by coffee-script 1.9.2
</script>
The script works fine (as you can see in the example above) without a pre-signed url, so what can I do to use my pre-signed urls inside AudioAnalyser function?
I've seen html5 video tags make multiple requests. I assume to fetch some meta-data like play length and the first frame of video to use as a thumbnail. You might try playing with the preload attribute to prevent this.
Specifically, if the clip is small, preload="auto" might be everything you need. If the browser has to make follow requests you're gonna have a hard time I think. Here's some relevant info
Another way to go about this that I think may work more reliably is to generate temporary credentials as needed.
See the docs for more on this:
- Requesting temp creds
- Accessing resources with temp creds
Combined with a JS package for signing AWS requests like binoculars/aws-sigv4 or copy someone else who's doing this in-browser.
Share your browser error message if any. It may by problem related to cross origin for S3 bucket data.

WebCL doesn't fill global table

I started using Nokia WebCL implementation for Mozilla Firefox.
I'm testing my application on Firefox version 32.0 (which is version for which Nokia binding was implemented).
This is my code (for simplicity and to show you what my issue is I've simplified the kernel code to minimum):
Kernel code:
<script id="julia_set" type="text/x-opencl">
__kernel void julia_set(__global int* pix)
{
pix[0]=5;
}
</script>
My Javascript code:
function loadKernel(id){
var kernelElement = document.getElementById(id);
var kernelSource = kernelElement.text;
if (kernelElement.src != "") {
var mHttpReq = new XMLHttpRequest();
mHttpReq.open("GET", kernelElement.src, false);
mHttpReq.send(null);
kernelSource = mHttpReq.responseText;
}
return kernelSource;
}
var platforms = webcl.getPlatforms();
var width = 2;
var height = 2;
var ctx = webcl.createContext(platforms[2],WebCL.DEVICE_TYPE_GPU);
var length = 4*width*height;
var bufSize = 4*length;
var bufferC = ctx.createBuffer (WebCL.MEM_WRITE_ONLY, bufSize);
var kernelSrc = loadKernel("julia_set");
var program = ctx.createProgram(kernelSrc);
var device = ctx.getInfo(WebCL.CONTEXT_DEVICES)[0];
try {
program.build ([device], "");
} catch(e) {
alert ("Failed to build WebCL program. Error "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_STATUS)
+ ": "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_LOG));
throw e;
}
var kernel = program.createKernel ("julia_set");
kernel.setArg (0, bufferC);
var cmdQueue = ctx.createCommandQueue (device);
var local = [16,16];
var global = [32,32];
cmdQueue.enqueueNDRangeKernel(kernel, 2, null,global, local);
var outBuffer = new Uint32Array(length);
cmdQueue.enqueueReadBuffer (bufferC, false, 0, bufSize, outBuffer);
cmdQueue.finish ();
console.log(outBuffer);
It's the most simple OpenCL application I could imagine. I expect my outBuffer to be filled with 0's and first element to be 5, but all the elements are 0. Whatever I try to do in kernel, my array seems untouched.
The device I'm using is NVidia GeForce GT 750M.
What can be possibly wrong in my code?
if(get_global_id(0)==0 && get_global_id(1)==0)
pix[0]=5;
should fix the issue, without race condition.

Hsts firefox addon

i 'm writing a firefox addon! i would like to know if the website use hsts, so i call the function isSecureURI() from https://dxr.mozilla.org/comm-central/source/mozilla/security/manager/ssl/nsISiteSecurityService.idl but,always, when i check it return as result false!
here is my code
var activeBrowserWindow = require("sdk/window/utils").getMostRecentBrowserWindow();
Cu.import("resource://gre/modules/Services.jsm");
var gSSService = Cc["#mozilla.org/ssservice;1"]
.getService(Ci.nsISiteSecurityService);
// For now, STS data gets stored in permissions.sqlite.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=775370.
var permissionManager = Cc["#mozilla.org/permissionmanager;1"]
.getService(Ci.nsIPermissionManager);
// We should not store anything permanent in permissions.sqlite in private
// browsing mode.
var FLAGS = require("sdk/private-browsing").isPrivate(activeBrowserWindow) ?
Ci.nsISocketProvider.NO_PERMANENT_STORAGE : 0;
var STS_TYPE = Ci.nsISiteSecurityService.HEADER_HSTS;
var tabs = require("sdk/tabs");
tabs.on('ready', function(tab) {
var URL = tab.url;
var url = require("sdk/url").URL(URL);
var hostname = url.hostname;
//console.log(hostname);
function isSecureUri(hostname) {
var uri = Services.io.newURI("https://" + hostname, null, null);
var resultURI = gSSService.isSecureURI(STS_TYPE, uri, FLAGS);
return resultURI;
}
thank you very much for your time!
ps sorry for my english!

NodeJS some modules not working

I'm making a game with socket.io and nodejs, and I'm making a module called rooms.js, this module require users.js module and fiveSocket.js module
but when I call Rooms.New from the main server file, it says that fiveSocket is undefined, same problem when Rooms.New calls a users.js function, I got TypeError: Cannot read property 'getSocketIDbyId' of undefined
rooms.js:
var mysql = require('../mysql/mysql.js');
var headers = require('./headers.js');
var users = require('./users.js');
var fiveSocket = require('./sockets.js');
var Rooms = {
Obj: {},
Room: function(data) {
var room = this;
this.name = data.name;
this.users = [];
this.floorCode = data.floor;
this.description = data.desc;
this.maxUsers = data.maxUsers;
this.owner = data.owner;
this.setTime = new Date().getTime();
this.dbID = data.dbID;
this.doorx = data.doorx;
this.doory = data.doory;
this.doordir = data.doordir;
},
New: function(socketID, roomID) {
var keys = Object.keys(Rooms.Obj).length;
var id = keys + 1;
var callback = function(row) {
fiveSocket.emitClient(socketID, headers.roomData, {
title: row.title,
desc: row.description,
mapStr: row.floorCode,
doorx: row.doorx,
doory: row.doory,
doordir: row.doordir
});
var uid = users.getIdBySocketID(socketID);
users.Obj[uid].curRoom = roomID;
var rid = Rooms.getIdByDbID(roomID);
Rooms.Obj[rid].users.push(uid);
}
if(Rooms.getIdByDbID(roomID) != false) {
var room = Rooms.getIdByDbID(roomID);
var row = { title: room.name, description: room.description, floorCode: room.foorCode, doorx: room.doorx, doory: room.doory, doordir: room.doordir };
callback(row);
} else {
mysql.Query('SELECT * FROM rooms WHERE id = ? LIMIT 1', roomID, function(rows) {
if(rows.length > 0) {
var row = rows[0];
Rooms.Obj[id] = new Rooms.Room({name: row.title, floorCode: row.floorCode, desc: row.description, maxUsers: row.maxUsers, owner: row.owner, dbID: row.id, doorx: row.doorx, doory: row.doory, doordir: row.doordir});
callback(row);
}
});
}
},
removeUser: function(DBroomID, userID) {
var rid = Rooms.getIdByDbID(DBroomID);
var room = Rooms.Obj[rid];
var index = room.indexOf(userID);
if (index > -1) array.splice(index, 1);
},
Listener: function(users) {
setInterval(function(){
for(var roomID in Rooms.Obj) {
var room = Rooms.Obj[roomID];
// send users coordinates
room.users.forEach(function(uid) {
var socketID = users.getSocketIDbyId(uid);
var data = Rooms.getUsersInRoomData(roomID);
fiveSocket.emitClient(socketID, headers.roomUsers, data);
});
// unload inactive rooms (no users after 10 seconds)
var activeUsers = room.users.length;
var timestamp = room.setTime;
var t = new Date(); t.setSeconds(t.getSeconds() + 10);
var time2 = t.getTime();
if(activeUsers <= 0 && timestamp < time2) {
Rooms.Remove(roomID);
}
}
}, 1);
},
getUsersInRoomData: function(roomID) {
var room = Rooms.Obj[roomID];
var obj = {};
room.users.forEach(function(uid) {
var user = users.Obj[uid];
obj[uid] = {
username: user.username,
position: user.position,
figure: user.figure
};
});
return obj;
},
Remove: function(id) {
delete Rooms.Obj[id];
},
getIdByDbID: function(dbID) {
var result = null;
for(var room in Rooms.Obj) {
var u = Rooms.Obj[room];
if(u.dbID == dbID) var result = room;
}
if(result == null) return false;
else return result;
},
getDbIDbyId: function(id) {
return Rooms.Obj[id].dbID;
}
}
Rooms.Listener();
module.exports = Rooms;
EDIT: (if it can be helpful)
When I console.log fiveSocket on the main file
When I console.log fiveSocket on the rooms.js file
EDIT2: When I've removed var users = require('./users.js'); from fiveSocket, when I console.log it in rooms.js it works, why ?
EDIT3: I still have the problem
If you need the others modules sources:
Users.JS: http://pastebin.com/Ynq9Qvi7
sockets.JS http://pastebin.com/wpmbKeAA
"Rooms" requires "Users" and vice versa, so you are trying to perform "circular dependency".
Quick search for node.js require circular dependencies gives a lot of stuff, for example :
"Circular Dependencies in modules can be tricky, and hard to debug in
node.js. If module A requires('B') before it has finished setting up
it's exports, and then module B requires('A'), it will get back an
empty object instead what A may have intended to export. It makes
logical sense that if the export of A wasn't setup, requiring it in B
results in an empty export object. All the same, it can be a pain to
debug, and not inherently obvious to developers used to having those
circular dependencies handled automatically. Fortunately, there are
rather simple approaches to resolving the issue."
or
How to deal with cyclic dependencies in Node.js

Categories