WordPress media library with metadata limit - javascript

I want to create a media library window. attachment should filter with mime types and metadata.
the mime-type filter is done. How can I build a metadata filter just for this?
function upload_image_tinymce(e) {
e.preventDefault();
var $input_field = $('.mce-my_input_image');
var custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Add Video',
button: {
text: 'Add Video'
},
library: {
type: [
'video/MP4',
'video/quicktime',
'video/x-m4v',
],
},
multiple: false
});
custom_uploader.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$input_field.val(attachment.id);
});
custom_uploader.open();
}

I cant help you with the whole filter code (not enoth knowlage ...)
But you can use the hook wp_get_attachment_metadata('attachment id') to get an array with the whole metadata of the attachment.
$meta = wp_get_attachment_metadata(126);
Will produce an array with the metadata from the attachment 126.
$cam = $meta[camera]
$cam will then hold the camera string from the metadata ...
Not much but maybe it will lead you a little bit in the right direction.

Related

Filters in Power BI embed report

I developed a few months ago a NodeJS API to get embed reports from Power BI (using a tenant). I consume this API from an Angular app. Now I want to get the report filtered, and I don't know if this is possible with my actual code.
I used the PowerBI rest API to get the embed report. Reading the docs of microsoft, I see lots of docs like this one, where says that I should create an object with the filters that I want. This is not a problem, but I don't know if this is compatible with mi actual Node API or I should develop a new solution.
My API follows the sample provided by Microsoft, and the code is:
async function getEmbedParamsForSingleReport(
workspaceId,
reportId,
additionalDatasetId
) {
const reportInGroupApi = `https://api.powerbi.com/v1.0/myorg/groups/${workspaceId}/reports/${reportId}`;
const headers = await getRequestHeader();
// Get report info by calling the PowerBI REST API
const result = await axios.get(reportInGroupApi, { headers });
if (result.status !== 200) {
throw result;
}
// Convert result in json to retrieve values
const resultJson = result.data;
// Add report data for embedding
const reportDetails = new PowerBiReportDetails(
resultJson.id,
resultJson.name,
resultJson.embedUrl
);
const reportEmbedConfig = new EmbedConfig();
// Create mapping for report and Embed URL
reportEmbedConfig.reportsDetail = [reportDetails];
// Create list of datasets
let datasetIds = [resultJson.datasetId];
// Append additional dataset to the list to achieve dynamic binding later
if (additionalDatasetId) {
datasetIds.push(additionalDatasetId);
}
// Get Embed token multiple resources
reportEmbedConfig.embedToken =
await getEmbedTokenForSingleReportSingleWorkspace(
reportId,
datasetIds,
workspaceId
);
return reportEmbedConfig;
}
With this I obtain the embed report and send back to my app. Is this solution compatible with filters?
Thanks in advance!
Finally, I came out with a solution. In mi Angular app, I use the library powerbi-client-angular. That allows me to define some configuration in the embed report:
basicFilter: models.IBasicFilter = {
$schema: 'http://powerbi.com/product/schema#basic',
target: {
table: 'items',
column: 'id',
},
operator: 'In',
values: [1,2,3],
filterType: models.FilterType.Basic,
requireSingleSelection: true,
displaySettings: {
/** Hiding filter pane */
isLockedInViewMode: true,
isHiddenInViewMode: true,
},
};
reportConfig: IReportEmbedConfiguration = {
type: 'report',
id: cuantitativeReportID,
embedUrl: undefined,
tokenType: models.TokenType.Embed,
filters: [this.basicFilter],
accessToken: undefined,
settings: undefined,
};
With this, I can avoid passing information to the NodeJS API
Yes, It will work fine with this solution. Please find the relevant code below:
Create a filter object:
const filter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Geo",
column: "Region"
},
operator: "In",
values: ["West", "Central"]
};
Add the filter to the report's filters:
await report.updateFilters(models.FiltersOperations.Add, [filter]);
You can refer sample NodeJS application to get embed reports from Power BI.
Please find the the reference here:
https://github.com/microsoft/PowerBI-Developer-Samples/tree/master/NodeJS

How get image from FormData to Rails API and saves in ActiveStorage

I am trying to send a FormData object from my React Native app to my Rails API.
I am using react-native-image-crop-picker to pick the image from gallery and store the image object in my state:
ImagePicker.openPicker({
multiple: true,
cropping: true,
includeBase64: true,
compressImageMaxHeight: 1080,
compressImageMaxWidth: 1080,
})
.then(selectedImages => {
selectedImages.map(image => {
let prefix;
let ext;
[prefix, ext] = image.filename.split(".");
ext = ext.toLowerCase() === "heic" ? "jpg" : ext;
const upload = {
uri: image.path,
type: image.mime,
name: `${prefix}.${ext}`,
};
this.setState(prevState => ({
event: {
...prevState.event,
images: [...prevState.event.images, upload],
},
}));
});
})
.catch(error => {
});
Then i create a FormData object to send yo my Rails API:
const data = new FormData();
data.append("name", event.name);
data.append("description", event.description);
data.append("date", event.date);
data.append("time", event.time);
data.append("images", event.images[0]);
My api successfully receives que request:
Parameters: {"event"=>{"_parts"=>[["event[name]", ""], ["event[description]", ""], ["event[date]", ""], ["event[time]", ""], ["event[images]", {"uri"=>"/private/var/mobile/Containers/Data/Application/6226B812-CDEC-4994-A864-0A91EE8C44B3/tmp/react-native-image-crop-picker/BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg", "type"=>"image/jpeg", "name"=>"IMG_7142.jpg"}]]}}
Now, how can i recover this image and saves directly in my Rails ActiveStorage?
I am trying to directly attach the image object: {"uri"=>"/private/var/mobile/Containers/Data/Application/6226B812-CDEC-4994-A864-0A91EE8C44B3/tmp/react-native-image-crop-picker/BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg", "type"=>"image/jpeg", "name"=>"IMG_7142.jpg"} to my model, but i am getting the current exception: ActiveRecord::RecordNotSaved (Failed to save the new associated avatar_attachment.):
I see that you have multiple images to attach.
If you've already gone through the documentation, I believe you must have already setup active storage by now.
In your model do you have has_many_attached :images? note that images could've been something else or just about any name.
I was able to retrieve the image name by doing the following (but I doubt if it will work for your purpose):
hash = {"uri"=>"/private/var/mobile/Containers/Data/Application/6226B812-CDEC-4994-A864-0A91EE8C44B3/tmp/react-native-image-crop-picker/BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg", "type"=>"image/jpeg", "name"=>"IMG_7142.jpg"}
hash['uri'].split('/')[-1]
=> "BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg"
If the above route is how you want to go and you are sure that it will work this way, then you need to do something like:
#your_model.images.attach(io: File.open("#{hash['uri']}"), filename: "#{hash['uri'].split('/')[-1]}")
You can find here a complete tutorial on how this should actually work here - https://medium.com/#ashley_foster/react-native-image-uploads-with-activestorage-ec4898317a82
Give it a try and if you get stuck along the way, you can drop a comment or edit/update your question.

What does the filebrowser field actually do in CKEditor?

The upload tab of image2 plugin looks like this -
{
id: 'Upload',
hidden: false,
filebrowser: 'uploadButton',
label: lang.uploadTab,
elements: [
{
type: 'file',
id: 'upload',
label: lang.btnUpload,
style: 'height:40px',
onChange: function(evt){
alert('file uploaded');
}
},
{
type: 'fileButton',
id: 'uploadButton',
filebrowser: 'info:src',
label: lang.btnUpload,
'for': [ 'Upload', 'upload' ]
}
]
}
Here in the 'tab' details there is filebrowser field which is equal to 'uploadButton' and filebrowser field is also in UI element object where it is equal to 'info:src'.
I am not implementing Browse Server functionality, only upload functionality. I have implemented it but I want to understand how filebrowser plugin and filebrowser fields are facilitating it?
Can anyone here explain here a little bit in detail as CKEditor documentation does not tell much?
The ck_config.js file has settings which determine the URL of the file browser for various purposes:
config.filebrowserBrowseUrl = '';
config.filebrowserImageBrowseUrl = '';
config.filebrowserFlashBrowseUrl = '';
config.filebrowserUploadUrl = '';
config.filebrowserImageUploadUrl = '';
config.filebrowserFlashUploadUrl = '';
Basically this will be a webpage which appears in a roughly 600px-wide popup.
One of the GET parameters of this URL (automatically added) will be CKEditorFuncNum which determines the callback function for sending the results back to CK.
On selection of a file/path, you would typically do:
window.opener.CKEDITOR.tools.callFunction(ck_callback,pathrel2page);
where ck_callback is the CKEditorFuncNum value and pathrel2page is the selected file.
HTH.

ExtJS 4 - How to download a file using Ajax?

I have a form with various textfields and two buttons - Export to Excel and Export to CSV.
The user can provide the values to different fields in the form and click one of the buttons.
Expected behaviour is that an Ajax request should be fired carrying the values of fields as parameters and the chosen file (Excel/CSV as per the button click) should get downloaded (I am not submitting the form as there needs to be done some processing at the values before submit).
I have been using the following code in success function of Ajax request for the download:
result = Ext.decode(response.responseText);
try {
Ext.destroy(Ext.get('testIframe'));
}
catch(e) {}
Ext.core.DomHelper.append(document.body, {
tag: 'iframe',
id:'testIframe',
css: 'display:none;visibility:hidden;height:0px;',
src: result.filename,
frameBorder: 0,
width: 0,
height: 0
});
The above code has been working fine in the case when the file is created physically at the server. But in my current project, the file is not created at the server, rather the contents are just streamed to the browser with proper headers.
Thus, is there a way to download a file using Ajax when the file is not present at the server physically? Just to add that I have a long list of parameters which I need to send to the server and hence can not add them all to the src of iframe.
Could anyone guide at this?
Thanks for any help in advance.
You may use component like this:
Ext.define('CMS.view.FileDownload', {
extend: 'Ext.Component',
alias: 'widget.FileDownloader',
autoEl: {
tag: 'iframe',
cls: 'x-hidden',
src: Ext.SSL_SECURE_URL
},
stateful: false,
load: function(config){
var e = this.getEl();
e.dom.src = config.url +
(config.params ? '?' + Ext.urlEncode(config.params) : '');
e.dom.onload = function() {
if(e.dom.contentDocument.body.childNodes[0].wholeText == '404') {
Ext.Msg.show({
title: 'Attachment missing',
msg: 'The document you are after can not be found on the server.',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.ERROR
})
}
}
}
});
Put it somewhere in viewport, for example:
{
region: 'south',
html: 'South',
items: [
{
xtype: 'FileDownloader',
id: 'FileDownloader'
}
]
}
Do not forget to require it in your viewport class:
requires: [
'CMS.view.FileDownload'
]
Action handler may look like this:
var downloader = Ext.getCmp('FileDownloader')
downloader.load({
url: '/attachments/' + record.get('id') + '/' + record.get('file')
});
It's very important to have Content-Disposition header in response, otherwise nothing is downloaded.
Regards go to http://www.quispiam.com/blog/post.php?s=2011-06-09-download-a-file-via-an-event-for-extjs4
This thing works for me.

Accessing Ext Designer JsonStore from another file

I want to access an JsonStore created from the ext designer from another panels user js file.
The file store file generated from the designer looks like this
myJsonStore = Ext.extend(Ext.data.JsonStore, {
constructor: function(cfg) {
cfg = cfg || {};
CoaJsonStore.superclass.constructor.call(this, Ext.apply({
storeId: 'myJsonStore',
url: '/server.json',
restful: true,
autoLoad: true,
autoSave: false,
fields: [
{
name: 'id'
},
{
name: 'code'
},
{
name: 'name'
}
]
}, cfg));
}
});
new myJsonStore();
what i am doing right now is using a hidden combo and assign the store to the combo, this allows me to access it via autoRef (with. combo.getStore(), it gives me an object type of Store). Ideally i want to be able to do it without the hidden combo.
i have tried referring to it with storeId, but it doesn't work, if i log the storeId to the console this is what i get.
function (cfg) {
cfg = cfg || {};
CoaJsonStore.superclass.constructor.call(this, Ext.apply({
storeId: 'myJsonStore',
url: '/coas.json',
restful: true,
........
so i was just wondering whether this is even possible. if so some direction on how to get it done would be greatly appreciated . thanks
The new myJsonStore(); only creates a new store. In order to reference the store elsewhere in your code ( same file or another file) you need to use a variable. Create the store like this:
var myStore = new myJsonStore();
And to bind it to the comobobox use the variable name myStore with the store property.

Categories

Resources