titanium android custom redirection on notification - appcelerator

I am developing an android application that includes gcm push notifications via ti.cloudpush module.
I would like to launch specific windows for certain type of push notifications.
Is theere any proper way to acieve this.
Following are my workouts.
CloudPush.addEventListener('callback', function(evt) {
alert("Notification received: " + evt.payload);
//-------------------launch code
var win=Ti.UI.createWindow({
url:'music.js',
exitOnClose:true,
});
});
i also tried by creating pending intent.It was also not failure.
thanks in advance

In the callback you'll have a payload sent back.
alert(evt.payload);
CloudPush.addEventListener('callback', function(evt) {
Ti.API.debug(evt.payload);
}
The payload is a JSON string of your data payload. Use JSON.parse to turn this in to an object you can use.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
You can use this payload to base the check on what intent, window or action you would like to fire.
var payload = JSON.parse(evt.payload);
if (payload... ) {
// Do first option
} else {
// Do fallback option
}
Inside your callback eventEventLister from cloudPush once you have parsed the payload you could load something similar to this:
CloudPush.addEventListener('callback', function(evt) {
... Do payload check if statement from evt.payload...
// Or this could be a new window, alert, etc,
Titanium.Android.NotificationManager.notify(0,
Ti.Android.createNotification({
contentTitle : "title",
contentText : "text",
tickerText : "custom notification!",
contentIntent : Titanium.Android.createPendingIntent({
intent : Titanium.Android.createIntent({
url : 'foo.js'
})
})
})
);
});
If you want to switch out a different window, set the url object in the intent to a custom variable that is set depending on what the evt.payload is that's sent back.
eg
intent : Titanium.Android.createIntent({
url : presetWindowUrl
})

Related

How can I access `figma.clientStorage` in a Figma Plugin UI?

In my plugin code (code.ts), I am using the ClientStorage Figma Plugin API to store some state.
How can I read data from clientStorage from UI code (ui.html)?
I am not sure that you can access clientStorage directly from the UI, but you can pass the stored value from code.ts to ui.html using figma.ui.postMessage.
Here is an example of code that is retrieving a value from clientStorage, and sending it to the UI:
function retrieveFromStorage() {
(async () => {
try {
var item = await figma.clientStorage.getAsync('item');
figma.ui.postMessage({ type: 'send-item', payload: item);
} catch (err) {
console.log(err);
}
}})();
}
And then you can access it in the UI like so:
if(event.data.pluginMessage.type == 'send-item') {
var item = event.data.pluginMessage.payload
}
In this example I am also using "type" to make sure I am receiving the correct message.

Get current mailbox from Outlook web addin

I just found this: https://learn.microsoft.com/en-us/office/dev/add-ins/reference/manifest/supportssharedfolders . Which tells me there is a way to load an addin into a postbox from another user. I have activated the feature via manifest, which is working fine.
To let the server know where to find the mail, I am currently working with, I need the postbox name, that I am currently in. So I went through the properties I get within Office.context. There seems to be no reference to the current mailbox. Just Office.context.mailbox.userProfile.emailAddress which is referring to my signed in user.
Since I need the current postbox to access the mail via Graph / EWS, there has to be a way to read it, else the SupportsSharedFolders would be senseless. How would I get the current postbox name/ID?
You can get an item's shared properties in Compose or Read mode by calling the item.getSharedPropertiesAsync method. This returns a SharedProperties object that currently provides the user's permissions, the owner's email address, the REST API's base URL, and the target mailbox.
The following example shows how to get the shared properties of a message or appointment, check if the delegate or shared mailbox user has Write permission, and make a REST call.
function performOperation() {
Office.context.mailbox.getCallbackTokenAsync({
isRest: true
},
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded && asyncResult.value !== "") {
Office.context.mailbox.item.getSharedPropertiesAsync({
// Pass auth token along.
asyncContext: asyncResult.value
},
function (asyncResult1) {
let sharedProperties = asyncResult1.value;
let delegatePermissions = sharedProperties.delegatePermissions;
// Determine if user can do the expected operation.
// E.g., do they have Write permission?
if ((delegatePermissions & Office.MailboxEnums.DelegatePermissions.Write) != 0) {
// Construct REST URL for your operation.
// Update <version> placeholder with actual Outlook REST API version e.g. "v2.0".
// Update <operation> placeholder with actual operation.
let rest_url = sharedProperties.targetRestUrl + "/<version>/users/" + sharedProperties.targetMailbox + "/<operation>";
$.ajax({
url: rest_url,
dataType: 'json',
headers:
{
"Authorization": "Bearer " + asyncResult1.asyncContext
}
}
).done(
function (response) {
console.log("success");
}
).fail(
function (error) {
console.log("error message");
}
);
}
}
);
}
}
);
}

socket.io - how to access unhandled messages?

How can you detect that you received a message on a socket.io connection that you do not have a handler for?
example:
// client
socket.emit('test', 'message');
// server
io.on('connection', function (socket) {
console.log('connection received...');
// logs all messages
socket.conn.on('message', function(data) {
console.log('this gets every message.');
console.log('how do I get just the ones without explicit handlers?');
});
socket.on('other' function(data) {
console.log('expected message');
});
}
By accessing the internals of the socket object you can determine what events it is currently listening for. You can use this server-side code to see if the current message is being handled.
io.on('connection', (socket) => {
console.log('A user connected.');
socket.on('disconnect', () => {
console.log('A user disconnected.');
});
socket.on('chat', (msg) => {
console.log('message: ' + msg);
io.emit('chat', msg);
});
socket.conn.on('message', (msg) => {
if(!Object.keys(socket._events).includes(msg.split('"')[1])) {
console.log(`WARNING: Unhandled Event: ${msg}`);
}
});
}
Once connected I am handling two events, 'disconnect' and 'chat'. After that I define a handler that catches all messages with socket.conn.on(...).
The message it receives is going to be a string that looks something like this: '2["myEventName","param1","param2"]'. By splitting it along the double quotes we can get the event name.
We then peek into the internals of socket to find all the keys of socket._events, which happen to be the event name strings. If this collection of strings includes our event name, then another handler will take care of it, and we don't have to.
You can test it from the console in the browser. Run socket.emit('some other event') there and you should see your warning come up in the server console.
IMPORTANT NOTE: Normally you should not attempt to externally modify any object member starting with an underscore. Also, expect that any data in it is unstable. The underscore indicates it is for internal use in that object, class or function. Though this object is not stable, it should be up to date enough for us to use it, and we aren't modifying it directly.
Tested with SocketIO version 2.2.0 on Chrome.
I didn't find a way to do it like socket.io, but using a simple js function to transform message into json it's doing the same job. Here you can try this:
function formatMessage(packetType, data) {
var message = {'packetType': packetType, 'data': data}
return JSON.stringify(message)
}
With:
socket.on('message', function(packet){
packet = JSON.parse(packet)
switch (packet.packetType) {
case 'init':
...
and
socket.send(formatMessage('init', {message}));
I would do so, of course it is the abstract code ... you would have to implement all the listeners and the logic to get the ids of the users to work
Client
var currentUser = {
id: ? // The id of current user
};
var socketMessage = {
idFrom: currentUser.id,
idTo: ?, // Some user id value
message: 'Hello there'
};
socket.emit('message', socketMessage);
socket.on('emitedMessage' + currentUser.id, function(message) {
// TODO: handle message
});
Server
io.on('connection', function (socket) {
// Handle emit messages
socket.on('message', function(socketMessage) {
// With this line you send the message to a specific user
socket.emit('emitedMessage-' + socketMessage.idTo, {
from: socketMessage.idFrom,
message: socketMessage.message
});
});
});
More info: http://socket.io/docs/

YouTube Data API: add a subscription

I'm using YouTube's V3 Data API to add a subscription to a channel. This occurs on a Wordpress installation.
I added Google APIs (for oauth) on Wordpress theme functions:
wp_enqueue_script( 'googleapi', 'https://apis.google.com/js/client.js?onload=googleApiClientReady', array(), '1.0.0', true );
I added in the same way the oauth javascript file, which is the first one here: https://developers.google.com/youtube/v3/code_samples/javascript.
Following this guide(https://developers.google.com/youtube/v3/docs/subscriptions/insert (Apps Script)), I extended the OAuth js with the addSubscription method.
Google Client API seems to be loaded and working as it calls correctly googleApiClientReady on the oauth javascript.
So, this is how the subscription is being inserted:
OAUTH JAVASCRIPT
... ... ...
// After the API loads
function handleAPILoaded() {
addSubscription();
}
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
var channelId = 'this is filled with the channel ID';
var resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelId
}
}
};
try {
var response = YouTube.Subscriptions.insert(resource, 'snippet');
jQuery('#success').show();
} catch (e) {
if(e.message.match('subscriptionDuplicate')) {
jQuery('#success').show();
} else {
jQuery('#fail').show();
alert("Please send us a mail () with the following: ERROR: " + e.message);
}
}
So, the first error comes with
YouTube.Subscriptions.insert(resource, 'snippet')
It says YouTube is not defined. I replaced it with:
gapi.client.youtube.subscriptions.insert(resource, 'snippet');
And that error went away. When checking response, as the subscription isn't completed, this is what I get
{"wc":1,"hg":{"Ph":null,"hg":{"path":"/youtube/v3/subscriptions","method":"POST","params":{},"headers":{},"body":"snippet","root":"https://www.googleapis.com"},"wc":"auto"}}
So, I would like to know what's happening on that POST request and what's the solution to this.
I can post the full OAuth file, but it's just as in the example, plus that addSubscription method at the end.
Okay, I got it working, the problem was on the POST request. Here is the full method working:
// Subscribes the authorized user to the channel specified
function addSubscription(channelSub) {
var resource = {
part: 'id,snippet',
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelSub
}
}
};
var request = gapi.client.youtube.subscriptions.insert(resource);
request.execute(function (response) {
var result = response.result;
if (result) {
// alert("Subscription completed");
}
} else {
// alert("Subscripion failed");
// ...
}
});
}
Also make sure to load Google Apps API (in fact without it the authorize/login button won't work) and jQuery.
Any chance you can post everything that made this work...all the JS entire auth.js save for your private keys, im working on this exact problem.

Receiving binary data using request module in Firefox Add-on SDK

I am using the Add-on builder and I need to receive binary data (image). I would like to do this using the request module but as you can see from the documentation:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/packages/addon-kit/docs/request.html
There are only text and json properties and raw is absent.
How should I receive binary data in the add-on script?
You cannot do this using the request module, you will have to use the regular XMLHttpRequest via chrome authority. Something like this should work:
var {Cc, Ci} = require("chrome");
var request = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIJSXMLHttpRequest);
request.open("GET", "...");
request.onload = function()
{
onUnload.unload();
var arrayBuffer = request.response;
if (arrayBuffer)
{
var byteArray = new Uint8Array(arrayBuffer);
...
}
};
request.onerror = function()
{
onUnload.unload();
}
request.send(null);
var onUnload = {
unload: function()
{
// Make sure to abort the request if the extension is disabled
try
{
request.abort();
}
catch (e) {}
}
};
require("unload").ensure(onUnload);
The mechanism to ensure that the request is aborted if your extension is suddenly disabled is rather awkward, that's the main reason the request module exists rather than simply giving you XMLHttpRequest. Note that it is important to call onUnload.unload() once the request finishes, otherwise the Add-on SDK will keep it in the list of methods to be called on unload (a memory leak). See documentation of unload module.

Resources