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

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.

Related

Parse Server - How to delete image file from the server using cloud code

How can I delete an image's file from the server using Parse Cloud Code. I am using back4app.com
After Deleting Image Row
I am getting the images urls, then calling a function to delete the image using its url
Parse.Cloud.afterDelete("Image", function(request) {
// get urls
var imageUrl = request.object.get("image").url();
var thumbUrl = request.object.get("thumb").url();
if(imageUrl!=null){
//delete
deleteFile(imageUrl);
}
if(thumbUrl!=null){
//delete
deleteFile(thumbUrl);
}
});
Delete the image file from the server
function deleteFile(url){
Parse.Cloud.httpRequest({
url: url.substring(url.lastIndexOf("/")+1),
method: 'DELETE',
headers: {
'X-Parse-Application-Id': 'xxx',
'X-Parse-Master-Key': 'xxx'
}
}).then(function(httpResponse) {
console.log(httpResponse.text);
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
}
for security reasons, not is posible to delete directly the image from Back4App, using DELETE from SDK or REST API. I believe that you can follow the guide below:
https://help.back4app.com/hc/en-us/articles/360002327652-How-to-delete-files-completely-
After struggling with this for a while it seems to be possible through cloud function as mentioned here. One need to use MasterKey in the cloud code:
Parse.Cloud.define('deleteGalleryPicture', async (request) => {
const {image_id} = request.params;
const Gallery = Parse.Object.extend('Gallery');
const query = new Parse.Query(Gallery);
try {
const Image = await query.get(image_id);
const picture = Image.get('picture');
await picture.destroy({useMasterKey: true});
await Image.destroy();
return 'Image removed.';
} catch (error) {
console.log(error);
throw new Error('Error deleting image');
}
});
For me it was first confusing since I could open the link to that file even after I deleted the reference object in the dashboard, but then I found out that the dashboard is not calling Parse.Cloud.beforeDelete() trigger for some reason.
Trying to download the data from the url after deleting the file through the cloud code function returns 0kB data and therefore confirms that they were deleted.

dropzone js use $.Ajax and not inbuilt functions

I am planning to use dropzone and I am new to it, I am reading some documents
I am planning to use dropzone for the UI and uploading into server, using some other API's, so how do I tell dropzone to use my custom method and pass the success or failure to the UI
I found some other interesting posts like thisenter link description here
You could set the init() function and wait for the response:
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
var res = JSON.parse(data.xhr.responseText);
//use the request's statusCode anyway you want to
if(data.xhr.status === 200)
{
//modify the UI
}
});
}
dictResponseError: "error message when failed"
};
HTTP Status Codes

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.

titanium android custom redirection on notification

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

ElasticSearch real time GET API doesn't seem to work

I'm trying to access a doc using the GET API of ElasticSearch but eventhough the documentation claims to be real time I cannot seem to make it work.
Here's what I tried:
Indexing an event with a custom id:
POST: http://hostname.com:9200/events/purchase/<custom_id>
Immediatedly retrieving the doc using:
GET: http://hostname.com:9200/events/purchase/<custom_id>
The problem is that the document is not found.
UPDATE:
It seems that the problem only occurs if the index is initially empty and that's the first doc to be written. Subsequent requests are indexed and retrieved just fine.
this might not be the best code but I think this shows what you want. If possible switch to the elasticsearch.js client. That is what is used in this sample code.
var elasticsearch = require('elasticsearch');
var config = {host:'localhost:9200'};
var client = new elasticsearch.Client({
host: config.host,
log:'trace'
});
storeEvent({"title":"My Event"}, 1);
function storeEvent(myEvent, id) {
client.create({
"index":"events",
"type":"purchase",
"id":id,
"body":myEvent
}, function(error,response) {
if (error) {
console.log("Error during creating event");
console.log(error);
} else {
console.log("Submitted event");
}
client.get({
"index":"events",
"type":"purchase",
"id":id
}, function (error,response) {
if (error) {
console.log("Error during obtaining event");
console.log(error);
} else {
console.log(response);
}
})
});
}
Which version are you using? 1.2.0 had a bug involving routing: http://www.elasticsearch.org/blog/elasticsearch-1-2-1-released/
If you fixed things by reindexing your data it's worth noting that it won't be compatible with future versions.

Resources