Integrating JavaScript web plugin in Ionic 2 - javascript

Im trying to integrate Applozic chat platform to my Ionic 2 project, which I wish to export to Web, Android and iOS. Using the sample as a base and created the applozic.d.ts & applozichv.js for the Javascript integration process.
applozic.d.ts
interface AppLozicStatic {
initPlugin(): any;
}
declare var AppLozic : AppLozicStatic;
export = AppLozic;
applozichv.js
(function () {
var root = this;
var AppLozic = function (obj) {
if (obj instanceof AppLozic) return obj;
if (!(this instanceof AppLozic)) return new AppLozic(obj);
// this.EXIFwrapped = obj;
};
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = AppLozic;
}
exports.AppLozic = AppLozic;
} else {
root.AppLozic = AppLozic;
}
AppLozic.initPlugin = function () {
var $original;
// var $applozic = "";
var $applozic;
console.log("initPlugin");
$original = jQuery.noConflict(true);
$ = $original;
jQuery = $original;
if (typeof jQuery !== 'undefined') {
console.log("initPlugin 1");
$applozic = jQuery.noConflict(true);
$applozic.fn
.applozic({
baseUrl : 'https://apps.applozic.com',
userId : 'debug454545', //TODO: replace userId with actual UserId
userName : 'test', //TODO: replace userId with actual UserName
appId : 'applozic-sample-app',
// accessToken: 'suraj', //TODO: set user access token.for new user it will create new access token
ojq: $original,
// obsm: oModal,
//optional, leave it blank for testing purpose, read this if you want to add additional security by verifying password from your server https://www.applozic.com/docs/configuration.html#access-token-url
// authenticationTypeId: 1, //1 for password verification from Applozic server and 0 for access Token verification from your server
// autoTypeSearchEnabled : false,
// messageBubbleAvator: true,
notificationIconLink: "https://www.applozic.com/resources/images/applozic_icon.png",
notificationSoundLink: "",
readConversation: readMessage, // readMessage function defined above
onInit: onInitialize, //callback function execute on plugin initialize
maxAttachmentSize: 25, //max attachment size in MB
desktopNotification: true,
locShare: true,
video: true,
topicBox: true,
// mapStaticAPIkey: "AIzaSyCWRScTDtbt8tlXDr6hiceCsU83aS2UuZw",
// googleApiKey: "AIzaSyDKfWHzu9X7Z2hByeW4RRFJrD9SizOzZt4" // replace it with your Google API key
// initAutoSuggestions : initAutoSuggestions // function to enable auto suggestions
});
}
var oModal = "";
/*if (typeof $original !== 'undefined') {
$ = $original;
jQuery = $original;
if (typeof $.fn.modal === 'function') {
oModal = $.fn.modal.noConflict();
}
} else {
$ = $applozic;
jQuery = $applozic;
if (typeof $applozic.fn.modal === 'function') {
oModal = $applozic.fn.modal.noConflict();
}
}*/
//Sample json contains display name and photoLink for userId
function readMessage() {
//console.log(userId);
}
//callback function execute after plugin initialize.
function onInitialize(response, data) {
if (response.status === 'success') {
// $applozic.fn.applozic('loadContacts', {'contacts':contactsJSON});
// $applozic.fn.applozic('loadTab', 'shanki.connect');
//write your logic exectute after plugin initialize.
alert("success");
} else {
alert(response.errorMessage);
}
}
// init();
};
})();
I added all the above created files including applozic.common.js, applozic.fullview.js and jquery.min.js to the assets/js folder and linked them in my index.html. This was the only way I could get the JavaScript method in applozic.js to execute from my chat.ts.
The problem that i'm now facing is the I get the error:
TypeError: Cannot read property 'noConflict' of undefined` in `applozic.js`
on the line
$original = jQuery.noConflict(true);
and consequently the rest of the if block is also not executing.
In an attempt to make jQuery work in the project I tried to install it via NPM by executing the following commands:
npm install jquery --save
npm install #types/jquery --save
But this led to issue in ionic serve giving the following error:
JavaScript heap out of memory
I really need help in executing my applozic.js file to initialize and call the chat plugin functions.

You should first identify the actual problem.
If problem is in jquery installation, then you can debug it using following line.
console.log("Jwuery Text : " , $('.testClassName'));
If below log is completely printed in the console then there is no mistake in jquery.
This memory size issue is resolved using reInitialize memory heap by using this command :
set NODE_OPTIONS=--max_old_space_size=4096
or
node --max_old_space_size=4096
After this command run into the command prompt, try to serve project or build a project.

Related

How can I close the client-side JavaScript 'Hub' connection in SignalR?

I have followed this tutorial.
But there is no hint how to close the Websocket connection via the HubConnection class in signalr.js-file. The file is V1.0.4.
This solution does not resolve my problem because I am using the microsofts javascript-library.
Here ist the code:
var lHubConnection = null;
var Init = function () {
// create instance
lHubConnection = new signalR.lHubConnectionBuilder().withUrl("/chatHub").build();
// receive message
lHubConnection.on("ReceiveMessage", function (pMessage) {
// show message
console.log(JSON.parse(pMessage));
});
// [...]
};
// close websocket connection
var CloseConnection = function(){
if (lHubConnection !== null && lHubConnection.connection.connectionState === 1) {
// lHubConnection.invoke("?"); ???
}
};
Here is an console output of the lHubConnection instance:
According to Microsoft the JavaScript client contains a stop function.
https://learn.microsoft.com/en-us/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#stop
In addition, you can find the .stop()-Method in the prototype of the framework:

Permissions error when running another JS AppleScript from another JSAppleScript

I am trying to separate out my .applescript files into different ones to tidy things up.
I have a JS AppleScript file called Test.applescript that tries to run the JS AppleScript file Group Tracks Dependency.applescript and what I want to do is pass in a parameter into the dependency script and get a return value out of it. (It creates an array of arrays of iTunes tracks).
Test.applescript
(function() {
var app = Application('iTunes');
app.includeStandardAdditions = true;
app.doShellScript('Group Tracks Dependency.applescript');
return "Done";
})();
// For quick logging
function log(obj) {
this.console.log(obj);
}
Group Tracks Dependency.applescript
(function(selection) {
return getGroupsOfTracks(selection);
function getGroupsOfTracks(originalTracksArray) {
if (originalTracksArray == null || originalTracksArray.length == 0)
return null;
var tracks = originalTracksArray.slice();
var groups = [];
while (true) {
var group = [];
group.push(tracks[0]);
tracks = tracks.slice(1);
while (true) {
if (!tracks[0]) break;
if (tracks[0].album() != group[0].album())
break;
if (tracks[0].artist() != group[0].artist())
break;
if (tracks[0].discNumber() != group[0].discNumber())
break;
group.push(tracks[0]);
tracks = tracks.slice(1);
}
groups.push(group);
if (!tracks[0]) break;
}
return groups;
}
})();
When I try to run the Test script I get this error (line 5 is the app.doShellScript line):
Error on line 5: Error: A privilege violation occurred.
Is there any way to get around this? I should also note that I want other people to be able to download these scripts and run them on their own iTunes libraries in the future (currently it's not user-friendly though).
If there's no way to get around this then would importing another JS AppleScript file work?
I think you may be fighting a battle that you can’t win using .doShellScript.
The Apple way is to use a Script Library as defined on https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-11.html#//apple_ref/doc/uid/TP40014508-CH110-SW1
Unfortunately a script library has constraints where you can only pass simple variables.
Another way is to use require, which can be defined with code like https://github.com/dtinth/JXA-Cookbook/wiki/Importing-Scripts
I'm not sure what you are trying to accomplish, but this works for me using Script Editor 2.8.1 (183.1) on OSX 10.11.4:
Create a main JXA Script file
Create a JXA Script Library file
BOTH of these MUST be saved as compiled script files (.scpt)
It is INCORRECT that "Unfortunately a script library has constraints where you can only pass simple variables."
You can call any of the functions in the Script Library file from any JXA script.
In your MAIN script file, which I will call "Get iTunes Group Selection.scpt":
var app = Application('iTunes');
app.includeStandardAdditions = true;
var myLib = Library("My JXA Lib")
var selectionArr = app.selection() // ### Change as needed ###
var groupArr = myLib.getGroupsOfTracks(selectionArr)
groupArr
~~~~~~~~~~~~~~~~~~~~~
And then in a separate script file, saved as:
~/Library/Script Libraries/My JXA Lib.scpt
function getGroupsOfTracks(originalTracksArray) {
if (originalTracksArray == null || originalTracksArray.length == 0)
return null;
var tracks = originalTracksArray.slice();
var groups = [];
while (true) {
var group = [];
group.push(tracks[0]);
tracks = tracks.slice(1);
while (true) {
if (!tracks[0]) break;
if (tracks[0].album() != group[0].album())
break;
if (tracks[0].artist() != group[0].artist())
break;
if (tracks[0].discNumber() != group[0].discNumber())
break;
group.push(tracks[0]);
tracks = tracks.slice(1);
}
groups.push(group);
if (!tracks[0]) break;
}
return groups;
}
Well, it's been a few years...
I ran into errors with JXA and doShellScript when I tried to run with Application("Finder"). These errors went away when I instead ran the script from Application.currentApplication(). So for my script, I used const finder = Application("Finder") for Finder specific stuff, then const app = Application.currentApplication() for running the script.
For example:
//test1.scpt
function run() {
const app = Application.currentApplication()
app.includeStandardAdditions = true
app.doShellScript("osascript ~/Desktop/test2.scpt")
}
//test2.scpt
function run() {
const app = Application.currentApplication()
app.includeStandardAdditions = true
app.displayDialog("foo")
app.doShellScript("osascript -e 'display dialog \"bar\"'")
}
As expected, running test1.scpt gives me two dialogs: foo and `bar.

How to create a Node.js module from Asynchronous Function response?

This problem is in regards the creation of a Node module that depends on a async function to return the content. For instance, "src/index.js" is the following:
GOAL
The module A, implemented from "src/index" must be resolved and must not depend on promises, or anything else... It will just return a JSON object of computed values.
var a = require("./src/index");
// should be resolved already.
console.log(a.APP_NAME)
src/index.js
"use strict";
var CoreClass = require("./core-class");
var coreInstance = new CoreClass();
coreInstance.toJson(function(err, coreData) {
if (err) {
console.log("Error while loading " + __filename);
console.log(err);
return;
}
console.log(coreData);
// Export the data from the core.
module.exports = coreData;
});
src/core-class.js
The implementation of the method "toJson()", defined in the class in the file "src/core-class.js" is as follows:
/**
* #return {string} Overriding the toStrng to return the object properties.
*/
ISPCore.prototype.toJson = function toJson(callback) {
var result = {
// From package.json
APP_NAME: this.appPackageJson.name.trim(),
APP_VERSION: this.appPackageJson.version.trim(),
APP_CONFIG_DIR: this.APP_DIR + "/config",
APP_DOCS_DIR: this.APP_DIR + "/docs",
APP_TESTS_DIR: this.APP_DIR + "/tests",
};
// TODO: Remove this when we have a registry
if (!this.pom) {
// Let's verify if there's a pom.xml file in the roort APP_DIR
var _this = this;
this.APP_POM_PATH = this.APP_DIR + "/pom.xml";
// Check first to see if the file exists
fs.stat(this.APP_POM_PATH, function(err, fileStats) {
// The file does not exist, so we can continue with the current result.
if (err) {
return callback(null, result);
}
_this._loadPomXmlSettings(function pomXmlCallback(err, pomObject) {
if (err) {
return callback(err);
}
_this.pom = pomObject;
// Update the result with the pom information
result.POM_GROUPID = _this.pom.groupid || "undefined";
result.POM_ARTIFACTID = _this.pom.artifactid || "undefined";
result.POM_VERSION = _this.pom.version || "undefined";
// Callback with the updated version.
return callback(null, result);
});
});
} else {
result.POM_GROUPID = this.pom.groupid || "undefined";
result.POM_ARTIFACTID = this.pom.artifactId || "undefined";
result.POM_VERSION = this.pom.version || "undefined";
// Return just what's been collected so far, including the pom.
return callback(null, result);
}
};
Test class
Requiring this and trying to use the library just returns an empty object. Here's the test class...
// describing the method to get the instance.
describe("require(sp-core) with pom.xml", function() {
var core = null;
before(function(done) {
// Copy the fixture pom.xml to the APP_DIR
fs.writeFileSync(__dirname + "/../pom.xml", fs.readFileSync(__dirname + "/fixture/pom.xml"));
// Load the library after the creation of the pom
core = require("../src/");
console.log("TEST AFTER CORE");
console.log(core);
done();
});
after(function(done) {
// Delete the pom.xml from the path
fs.unlinkSync(__dirname + "/../pom.xml");
done();
});
it("should load the properties with pom properties", function(done) {
expect(core).to.be.an("object");
console.log("Loaded pom.xml metadata");
console.log(core);
expect(core.POM_ARTIFACTID).to.exist;
expect(core.POM_VERSION).to.exist;
done();
});
});
Execution of the tests
However, after a while, the output from the library shows up in the console.
SPCore with pom.xml
require(sp-core) with pom.xml
TEST AFTER CORE
{}
Loaded pom.xml metadata
{}
1) should load the properties with pom properties
{ APP_NAME: 'sp-core',
APP_VERSION: '0.3.5',
ENV: 'development',
NODE_ENV: 'development',
IS_PROD: false,
APP_DIR: '/home/mdesales/dev/isp/sp-core',
APP_CONFIG_DIR: '/home/mdesales/dev/isp/sp-core/config',
APP_DOCS_DIR: '/home/mdesales/dev/isp/sp-core/docs',
APP_TESTS_DIR: '/home/mdesales/dev/isp/sp-core/tests',
POM_GROUPID: 'com.mycompany',
POM_ARTIFACTID: 'my-service',
POM_VERSION: '1.0.15-SNAPSHOT' }
0 passing (142ms)
1 failing
1) SPCore with pom.xml require(sp-core) with pom.xml should load the properties with pom properties:
AssertionError: expected undefined to exist
How to properly create a module that depends on an Async call?
I'm sure this is due to the asynchronous call, but I was thinking that the module would not return {}, but wait until the callback returns.
I tried using:
Async.waterfall
Deasync (does not work)
Async.waterfall attempt
"use strict";
var async = require("async");
var CoreClass = require("./core-class");
var coreInstance = new CoreClass();
async.waterfall([
function(cb) {
coreInstance.toJson(cb);
},
function(coreData) {
console.log(coreData);
module.exports = coreData;
}
]);
Please please help!
Following the comments, I revisited the attempt of using "deasync" module, and it WORKS! YES WE CAN! Cheating with the hack of "deasync" :D
Runnable instance
The runnable solution is at http://code.runnable.com/VbCksvKBUC4xu3rd/demo-that-an-async-method-can-be-returned-before-a-module-exports-is-resolved-for-node-js-deasync-pom-parser-and-stackoverflow-31577688
Type "npm test" in the terminal box and hit "ENTER" (always works).
Just click in the "Run" button to see the execution of the code. All the source code is available. (Sometimes the container gets corrupted and the test fails).
Solution
Here's the implementation of the "GOAL" module.
/** #module Default Settings */
"use strict";
var CoreClass = require("./core-class");
var merge = require("merge");
var deasync = require("deasync");
// Core properties needed.
var coreInstance = new CoreClass();
var coreProperties = coreInstance.toJson();
// Pom properties temporary support, deasync the async call
var loadPom = deasync(coreInstance.loadPomXmlSettings);
var pomObject = loadPom(coreProperties.APP_POM_PATH);
// Merge them all.
var allProperties = merge(coreProperties, pomObject);
module.exports = allProperties;
With that, all the code is returned as expected for the module.exports!

Cordova Mms Plugin Error : mms_config.xml missing uaProfUrl setting

I want to send the MMS to some "anyemail#gmail.com", I tried my device mms service (using device sms app) and it worked. So now I'am tring to do the same using myapp. So, I landed up to cordova-MMS-Plugin.
But it gave some error MmsConfig.loadMmsSettings mms_config.xml missing uaProfUrl setting. So I looked in res/xml there was no mms_config.xml. So I downloaded it from git repo here, and put it in res/xml folder. But still the same error.
Here is My Code, this code contains only javascript I used to call send() for sending MMS with some arguments.
sendSMS = function (phoneNo, data) {
var that = this;
window.module.exports.send(phoneNo,data,undefined,undefined,function () {
that.smsSent();
},function (e) {
that.failed(e);
});
}
Here is MMS-PLUGIN js File sms.js
var sms = {
send: function(phone, message, imageFile, method, success, failure) {
phone = sms.convertPhoneToArray(phone);
cordova.exec(
success,
failure,
'Sms',
'send',
[phone, message, imageFile, method]
);
},
convertPhoneToArray: function(phone) {
if(typeof phone === 'string' && phone.indexOf(',') !== -1) {
phone = phone.split(',');
}
if(Object.prototype.toString.call(phone) !== '[object Array]') {
phone = [phone];
}
return phone;
}
};
sms.install = function () {
window.module.exports = sms;
}
cordova.addConstructor(sms.install);
Any body have any idea what I'm missing here.
One more thing it works when I send to a mobileNo instead of email.

BreezeJs with dedicated web worker

I am trying to initialize a Breeze manager inside a 'Web Worker'.
RequireJs, knockout, q, breeze are being imported inside the worker.
After a call to:EntityQuery.from('name').using(manager).execute(),
the following error appears:
Uncaught Error: Q is undefined. Are you missing Q.js? See https://github.com/kriskowal/q.
A live preview is uploaded here http://plnkr.co/edit/meXjKa?p=preview
(plunk supports downloading for easier debug).
EDIT -- relevant code
Worker.js
importScripts('knockout.js', 'q.js', 'breeze.js', 'require.js');
define('jquery', function () { return jQuery; });
define('knockout', ko);
define('q', Q); //Just trying to assign q since breeze requests Q as q
require(function () {
var self = this;
this.q = this.Q; //Just trying to assign q since breeze requests Q as q
breeze.NamingConvention.camelCase.setAsDefault();
var manager = new breeze.EntityManager("breeze/Breeze");
var EntityQuery = breeze.EntityQuery;
// Q or q here is defined (TESTED)
var test = function (name) {
return EntityQuery.from(name)
.using(manager).execute() // <-- Here q/Q breaks (I think on execute)
};
var primeData = function () {
return test('Languages')
.then(test('Lala'))
.then(test('Lala2'))
};
primeData();
setTimeout(function () { postMessage("TestMan"); }, 500);
});
Worker will be initialized on main page as:
var myWorker = new Worker("worker.js");
Ok here it goes:
Create a new requireJs and edit the
isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document)
to
isBrowser = false
Create a new Jquery so it uses nothing related to window and generally anything that a WebWorker cannot access. Unfortunatelly i can't remember where i got this Custom JQueryJs but i have uploaded it here "https://dl.dropboxusercontent.com/u/48132252/jqueydemo.js".
Please if you find the author or the original change link and give credit.
My workerJs file looks like:
importScripts('Scripts/test.js', 'Scripts/jqueydemo.js', 'Scripts/q.js', 'Scripts/breeze.debug.js', 'Scripts/require2.js');
define('jquery', function () { return jQuery; });
require(
{
baseUrl: "..",
},
function () {
var manager = new breeze.EntityManager("breeze/Breeze");
var EntityQuery = breeze.EntityQuery;
var primeData = function () {
return EntityQuery.from(name)
.using(manager).execute() // Get my Data
.then(function (data) {
console.log("fetced!\n" + ((new Date()).getTime()));
var exportData = manager.exportEntities(); // Export my constructed entities
console.log("created!\n" + ((new Date()).getTime()));
var lala = JSON.stringify(exportData)
postMessage(lala); // Send them as a string to the main thread
})
};
primeData();
});
Finally on my mainJs i have something like:
this.testWorker = function () {
var myWorker = new Worker("worker.js"); // Init Worker
myWorker.onmessage = function (oEvent) { // On worker job finished
toastr.success('Worker finished and returned');
var lala = JSON.parse(oEvent.data); // Reverse string to JSON
manager.importEntities(lala); // Import the pre-Constructed Entities to breezeManager
toastr.success('Import done');
myWorker.terminate();
};
};
So we have managed to use breeze on a WebWorker enviroment to fetch and create all of our entities, pass our exported entities to our main breeze manager on the main thread(import).
I have tested this with 9 tables fully related to each other and about 4MB of raw data.
PROFIT: UI stays fully responsive all the time.
No more long execution script, application not responding or out of memory errors) at least for chrome
*As it makes sense breeze import entities is way more faster than the creation a full 4MB raw data plus the association process following for these entities.
By having all the heavy work done on the back, and only use import entities on the front, breeze allows you to handle large datasets 'like a breeze'.

Categories

Resources