Using ctypes function in firefox ChromeWorker - firefox

I am trying to use a ChromeWorker to launch a background process, like so:
var worker = new ChromeWorker(data.url("stun-manager.js"));
worker.addEventListener('message', function(e) {
console.log(e.data);
}, false);
worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
But where exactly do I declare all my ctypes and such? Interestingly, in stun-manager.js, if I have the following:
dump ("Message 1");
var {Cu} = require("chrome");
dump ("Message 2");
/*import js-ctypes */
var {ctypes} = Cu.import("resource://gre/modules/ctypes.jsm")
var stun_driver = ctypes.open("C:\\Users\\derek_000\\Documents\\Visual Studio 2012\\Projects\\stunnel507\\stunnel507\\bin\\win32\\stun_driver.dll");
const launch_stun = stun_driver.declare("launch_stun", ctypes.default_abi, ctypes.int32_t, ctypes.int32_t, ctypes.char.ptr.ptr);
let argv_t = ctypes.ArrayType(ctypes.char.ptr);
let argc = 2;
let argv = new argv_t(argc);
var conf_path = "C:\\Users\\derek_000\\Documents\\Visual Studio 2012\\Projects\\stunnel507\\stunnel507\\stunnel.conf";
argv[0] = ctypes.char.array()(conf_path);
argv[1] = ctypes.char.array()(conf_path);
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'start':
self.postMessage("Value of launch_stun " + self.launch_stun);
self.postMessage('WORKER STARTED: ' + data.msg);
self.postMessage("debug" + self.argv_t);
self.postMessage("test: " + self.argv_t);
self.postMessage(self.argv[0].readString());
launch_stun(argc, argv );
break;
case 'stop':
self.postMessage('WORKER STOPPED: ' + data.msg +
'. (buttons will no longer work)');
self.close(); // Terminates the worker.
break;
default:
self.postMessage('Unknown command: ' + data.msg);
};
}, false);
"Message 2" is never printed to the screen, and "Message 1" is. It's almost like I am getting a silent fail from one of those other lines, but this is the exact code I have used to launch this from main.js, before I tried to use ChromeWorker.
Any ideas? I guess it seems like stun-manager.js is failing silently, and on a related note, I can't even find it in the Browser Toolbox to debug, but I do see my main.js file there.

Two simple examples of using ChromeWorker (and also an advancement of ChromeWorker, PromiseWorker, which rocks by the way):
GitHub :: Noitidart / ChromeWorker
GitHub :: Noitidart / PromiseWorker
You can't do var {ctypes} = Cu.import("resource://gre/modules/ctypes.jsm") in the worker (your worker is stun-manager.js). That's causing an error, remove that. You can just use ctypes without importing anything, ChromeWorker's autoamtically have it. That should fix it.
I'll look more over your code, but definitely check out the ChromeWorker repo it will help a lot, its a very basic messaging thing between worker and main.

Related

Discord.js Announce Command Slice Issue with Args

iv made an announce command for my bot, i have it outputting the contents of the message to a RichEmbed.
I have it set in IF statement
If users mentioned first then it removes the mention and sends it to the channel and displays embed with contents (args.slice(2))
ELSE just send the embed with args.slice(1) removing the command.
My problem is that they either both slice(1) or both slice(2) , despite me having them set differently
if (!user);
const embed = new Discord.MessageEmbed()
.setTitle(`${(args.slice(1).join(" "))}`, 'https://i.gyazo.com/898806671312f3585209cf0fd69341006.jpg')
.setColor(0x320b52)
.setTimestamp()
.setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/898806671312f3585209cf0fd69341006.jpg')
message.channel.send(embed);
}
else {
message.channel.send("<#" + user.id + ">")
const embed = new Discord.MessageEmbed()
.setTitle(`${(args.slice(2).join(" "))}`, 'https://i.gyazo.com/898806671312f358509cf0fd69341006.jpg')
.setColor(0x320b52)
.setTimestamp()
.setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/898806671312f358509cf0fd69341006.jpg')
message.channel.send(embed);
}
Replace the ; in your first line with a {:
if (!user) {

Apps Script Exceeded MAXIMUM_RUNNING_TIME Workaround

First of all, I am continuing an old thread at this link that I am unable to comment on due to being a newbie.
I have a situation that an answer in that thread given by user Br. Sayan would really improve my Spreadsheet Google App Script. I am making calls to Google Url Shortener API, which puts quotas at 1 call per user per second. I have slowed my script down enough to accommodate this quota, but I then I run over the MAX_RUNNING_TIME for App Scripts execution due to the extended number of calls I need to make, so I need to break the loop when the execution time is exceeded and pick up where I left off.
Here is the code of his answer:
function runMe() {
var startTime= (new Date()).getTime();
//do some work here
var scriptProperties = PropertiesService.getScriptProperties();
var startRow= scriptProperties.getProperty('start_row');
for(var ii = startRow; ii <= size; ii++) {
var currTime = (new Date()).getTime();
if(currTime - startTime >= MAX_RUNNING_TIME) {
scriptProperties.setProperty("start_row", ii);
ScriptApp.newTrigger("runMe")
.timeBased()
.at(new Date(currTime+REASONABLE_TIME_TO_WAIT))
.create();
break;
} else {
doSomeWork();
}
}
//do some more work here
}
My Questions:
Is MAX_RUNNING_TIME a global variable with a value set by Apps Script that I can leave that reference as-is, or must I replace it with a value equalling the 6 minutes listed as the quota for run time on the Google API Console?
How can I place the bulk of my function within this script so that a loop that runs inside my function (say var i = 0; i < data.length; i++) will be synchronized with the loop in the portion given in the above code?
Clarification: when i is incremented up by 1, I need ii to increment by 1.
Does this happen automatically? Do I need one loop nested inside the other? Does the bulk of my function go in the first '//do some work here' or the second '//do some work here' or possibly even doSomeWork()?
#tehhowch agreed! However, HOW I need to adapt my code depends on where I need to put it in the above snippet.
Here is what I have so far:
'function short() {
var = startTime = (new Date()).getTime();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var run = 0;
var finc = 50;
var istart = run * finc;
var iLen = (run + 1) * finc;
var startRow = 2 + istart;
var endRow = startRow + finc;
var data = sheet.getSheetValues(startRow,2,endRow,1);
var shortUrl = new Array();
for (var i=istart; i < iLen; i++) {
Utilities.sleep(1100);
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
shortUrl.push([url.id]);
Logger.log([url.id]);
}
var t = ss.setActiveSheet(ss.getSheets()[0]);
t.getRange(startRow,4,finc,data[0].length).clearContent();
t.getRange(startRow,4,finc,data[0].length).setValues(shortUrl);'
So if I update the code after each subsequent run to manually increase the variable 'run' by 1, and manually run the code again, this works.
I have also tried break it down into multiple functions by updating the i= and i < parts for each subsequent function, which also works, but requires much more manual work.
I have also tried, unsuccessfully, to use a prompt with a button press that continues the function, which would be better than the other attempts, but would still require a button press to resume the code after each run.
I want to automate the function as much as possible.

Google spreadsheet script very slow

I've got a script that i run each day. it's incredibly slow and i can't figure out what's slowing it down. Anyone have any suggestions? I originally wrote a function to do one sheet, then i added a function to loop and call it on every sheet.
function addAllLog() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var allSheets = ss.getSheets();
// build array of all sheets
for (var i in allSheets) {
if (i == 0) { continue;} // skip first sheet
var tmpName = allSheets[i].getName();
if (tmpName == "Print Sheet") break; //stop at this tab
var tmpName = ss.getSheetByName(allSheets[i].getName());
ss.setActiveSheet(ss.getSheetByName(allSheets[i].getName()));
addLog();
}
}
function addLog () {
var sheet = SpreadsheetApp.getActiveSheet();
var numLastRow = sheet.getLastRow();
var numThisRow = numLastRow+1;
today = new Date();
today.setDate(today.getDate()-1);
today = Utilities.formatDate(today,"EDT","MM/DD/YYYY");
if (sheet.getMaxRows() == numLastRow) sheet.insertRowAfter(numLastRow);
var range = sheet.getRange(numLastRow,2,1,16); // last row, column b, 1 row of 16 columns
var data = range.getValues();
range.copyTo(sheet.getRange(numLastRow+1, 2,1,16)); //you will need to define the size of the copied data see getRange()
sheet.getRange(numThisRow, 1).setValue(today);
sheet.getRange(numThisRow, 4).setValue('Log');
sheet.getRange(numThisRow, 5).setValue(''); //erase copied value if there was anything there
sheet.getRange(numThisRow, 7).setValue(''); //erase copied value if there was anything there
sheet.getRange(numThisRow, 6).setValue('=GoogleFinance(C' + numThisRow + ',"price")');
sheet.getRange(numThisRow, 6).setValues(sheet.getRange(numThisRow,6).getValues());
}
Any suggestions on speeding it up would be greatly appreciated!
Each time you set a value in a range directly over the Spreadsheet, it takes at least 800ms to do it, so the best way to face this problem is create an Object[][] with the values and set it with sheet.getRange(range).setValues(Object[][]), being sure that Object[][] has the same width-height of the range.
In this post, Best Practices | Apps Script, Google explains the difference.
Also, an interesting solution is make an Spreadsheet abstraction in memory. I make my own MemsheetApp, based in this approach and it works very nice. I'm receiving pull request if you want to improve it.
This version doesn't require that you activate each sheet so it may take a little less time.
function addAllLog() {
var ss=SpreadsheetApp.getActive();
var allSheets = ss.getSheets();
for (var i=1;i<allSheets.length;i++){
var shtname = allSheets[i].getName();
if (shtname == "Print Sheet"){
break; //stop at this tab
}else{
addLog(shtname);
}
}
}
function addLog (shtname) {
var sheet = SpreadsheetApp.getSheetByName(shtname);
var numLastRow = sheet.getLastRow();
var numThisRow = numLastRow+1;
today = new Date();
today.setDate(today.getDate()-1);
today = Utilities.formatDate(today,"EDT","MM/DD/YYYY");
if (sheet.getMaxRows() == numLastRow) sheet.insertRowAfter(numLastRow);
var range = sheet.getRange(numLastRow,2,1,16);
range.copyTo(sheet.getRange(numLastRow+1, 2,1,16));
sheet.getRange(numThisRow, 1).setValue(today);
sheet.getRange(numThisRow, 4).setValue('Log');
sheet.getRange(numThisRow, 5).setValue('');
sheet.getRange(numThisRow, 7).setValue('');
sheet.getRange(numThisRow, 6).setFormula('=GoogleFinance(C' + numThisRow + ',"price")');
}
It appears to be Google's fault. Even SpreadsheetApp.getSheetByName() is bottlenecking the script by a minute or so, in my tests.

Script Works on Win 7, Not on Server 2003

I have a script that is rather simple, it boots up WinSCP and checks the directory for a file that starts with "TSA". If the file exists, it exits, if it does not exist, it transfers over a new file.
Its up and running on my Windows 7 machine, that is where i created it - but when i transfer it over to my server [windows server 2003] it never finds the file.
My script:
var FILEPATH = "../zfinance/TSA";
// Session to connect to
var SESSION = "someplace#somewhere.com";
// Path to winscp.com
var WINSCP = "c:\\program files\\winscp\\winscp.com";
var filesys = WScript.CreateObject("Scripting.FileSystemObject");
var shell = WScript.CreateObject("WScript.Shell");
var logfilepath = filesys.GetSpecialFolder(2) + "\\" + filesys.GetTempName() + ".xml";
var p = FILEPATH.lastIndexOf('/');
var path = FILEPATH.substring(0, p);
var filename = FILEPATH.substring(p + 1);
var exec;
// run winscp to check for file existence
exec = shell.Exec("\"" + WINSCP + "\" /log=\"" + logfilepath + "\"");
exec.StdIn.Write(
"option batch abort\n" +
"open \"" + SESSION + "\"\n" +
"ls \"" + path + "\"\n" +
"exit\n");
// wait until the script finishes
while (exec.Status == 0)
{
WScript.Sleep(100);
WScript.Echo(exec.StdOut.ReadAll());
}
if (exec.ExitCode != 0)
{
WScript.Echo("Error checking for file existence");
WScript.Quit(1);
}
// look for log file
var logfile = filesys.GetFile(logfilepath);
if (logfile == null)
{
WScript.Echo("Cannot find log file");
WScript.Quit(1);
}
// parse XML log file
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.load(logfilepath);
doc.setProperty("SelectionNamespaces",
"xmlns:w='http://winscp.net/schema/session/1.0'");
doc.setProperty("SelectionLanguage", "XPath");
var nodes = doc.selectNodes("//w:file/w:filename[starts-with(#value, '" + filename + "')]");
if (nodes.length > 0)
{
WScript.Echo("File found");
WScript.Quit(0);
}
else
{
WScript.Echo("File not found");
WScript.Quit(1);
}
After much investigation, i think i've found the piece of code that does not function properly:
// parse XML log file
var doc = new ActiveXObject("MSXML2.DOMDocument.6.0");
doc.async = false;
doc.load(logfilepath);
doc.setProperty("SelectionNamespaces",
"xmlns:w='http://winscp.net/schema/session/1.0'");
The only problem is, i have no idea why. The log file at this point should be written over with the xml code, but this does not happen.
Thanks in advance for any help.
And the answer is........... WinSCP on Windows Server 2003 was WAY out of date. So out of date that the log was completely different from one version to the next. Updated and VIOLA! Problem solved. Thanks for your help.
Maybe you need to install MSXML2.DOMDocument.6.0
http://msdn.microsoft.com/en-us/library/windows/desktop/cc507436%28v=vs.85%29.aspx
If you open up regedit and look for "MSXML2.DOMDocument.6.0" does it find it? If so maybe security settings for the script need to be set in order to be able to create an activeX object.
What can you see when you put some stuff in try catch?
try{
//stuff
}catch(e){
WScript.Echo(e.message);
}

How do I poke the flag in a win32 PE that controls console window display

I have an executable which is part of a batch process. This one executable opens a console window, which is annoying since it's useless to the end user and steals focus away from their active task.
We can't compile a new version from of this EXE from source (easily). Is there an easy way to twiddle this setting in the PE?
Found it.
editbin.exe /subsystem:windows foo.exe
editbin.exe is part of MSVC
I have wrote it with python based on the PE specification
http://msdn.microsoft.com/en-us/library/windows/hardware/gg463119.aspx
I'm not sure that Windows EXE binaries with console|windows subsystem have same
Entry Point Format (with same arguments), but it seem that it is so.
Python Code:
import sys
import struct
if len(sys.argv) < 4:
print "Change Exe Run Mode Application by burlachenkok#gmail.com\nNot sufficient parametrs. 'exe_src_name.exe' 'exe_dest_name.exe' 'to_console' or 'to_windows'"
sys.exit(-1)
source = open(sys.argv[1], "rb")
dest = open(sys.argv[2], "w+b")
dest.write(source.read())
dest.seek(0x3c)
(PeHeaderOffset,)=struct.unpack("H", dest.read(2))
dest.seek(PeHeaderOffset)
(PeSignature,)=struct.unpack("I", dest.read(4))
if PeSignature != 0x4550:
print "Error in Find PE header"
dest.seek(PeHeaderOffset + 0x5C)
if sys.argv[3].strip() == "to_console":
# console mode
dest.write(struct.pack("H", 0x03))
elif sys.argv[3].strip() == "to_windows":
# window mode
dest.write(struct.pack("H", 0x02))
else:
print "Wrong Format: '" + sys.argv[3] + "'"
source.close()
dest.close()
print "Completed succesfully.."
Here is a node version of the Python code :)
const fs = require('fs');
const bufferpack = require('bufferpack');
if(process.argv.length < 4) {
console.log("Change Exe Run Mode Application \nNot sufficient parameters. 'exe_src_name.exe' 'exe_dest_name.exe' 'to_console' or 'to_windows'");
process.exit(-1);
}
function read(f, size, offset) {
if(typeof size == 'undefined') size = 1;
if(typeof offset == 'undefined') offset = -1;
const buffer = Buffer.alloc(size);
fs.readSync(f, buffer, 0, size, offset);
return buffer;
}
const source = fs.openSync(process.argv[2], "r");
const dest = fs.openSync(process.argv[3], "w+");
fs.writeSync(dest, read(source, fs.statSync(process.argv[2]).size, 0));
const PeHeaderOffset = bufferpack.unpack('<H', read(dest, 2, 0x3c)).pop();
const PeSignature = bufferpack.unpack('<I', read(dest, 4, PeHeaderOffset)).pop();
if(PeSignature != 0x4550) {
console.log("Error in Find PE header");
process.exit(-1);
}
if(process.argv[4] == "to_console") {
// console mode
fs.writeSync(dest, bufferpack.pack('<H', [0x03]), 0, 1, PeHeaderOffset + 0x5C);
} else if(process.argv[4] == "to_windows") {
// window mode
fs.writeSync(dest, bufferpack.pack('<H', [0x02]), 0, 1, PeHeaderOffset + 0x5C);
} else {
console.log("Wrong Format: '" + process.argv[4] + "'");
}
fs.closeSync(source);
fs.closeSync(dest);
console.log("Completed succesfully.");

Resources