Google picker open multiple views on subsequent calls for folder selection - google-picker

I am using the following filepicker.js code,it works fine for displaying documents and folders. When I open the google picker for displaying the folder,on subsequent calls multiple picker will open.
(function() {
/**
* Initialise a Google Driver file picker
*/
var myType = 'empty';
var FilePicker = window.FilePicker = function (options) {
// Config
this.apiKey = options.apiKey;
this.clientId = options.clientId;
this.accesstoken = options.accesstoken;
myType = options.dType;
// Elements
this.buttonEl = options.buttonEl;
// Events
this.onSelect = options.onSelect;
this.buttonEl.addEventListener('click', this.open.bind(this));
// Disable the button until the API loads, as it won't work properly until then.
this.buttonEl.disabled = true;
// Load the drive API
gapi.client.setApiKey(this.apiKey);
gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this));
google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
}
FilePicker.prototype = {
/**
* Open the file picker.
*/
open: function() {
// Check if the user has already authenticated
var token = gapi.auth.getToken();
if (token) {
// alert(JSON.stringify(token) + " token status");
this._showPicker();
} else {
// The user has not yet authenticated with Google
// We need to do the authentication before displaying the Drive picker.
this._doAuth(true, function () {
// alert('in the doAuth ')
this._showPicker();
}.bind(this));
}
},
/**
* Show the file picker once authentication has been done.
* #private
*/
_showPicker: function () {
var view = null;
if (myType == "Folder") {
view = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
.setIncludeFolders(true)
.setMimeTypes('application/vnd.google-apps.folder')
.setSelectFolderEnabled(true);
}
if (myType=="DOC") {
view = google.picker.ViewId.DOCUMENTS;
}
if (myType == "PPT") {
view = google.picker.ViewId.PRESENTATIONS;
}
// alert("Final access token "+ this.accesstoken);
// alert(this.picker);
this.picker = new google.picker.PickerBuilder().
addView(view).
setAppId(this.clientId).
setOAuthToken(this.accesstoken).
setCallback(this._pickerCallback.bind(this)).
build().
setVisible(true);
console.log(view);
},
/**
* Called when a file has been selected in the Google Drive file picker.
* #private
*/
_pickerCallback: function (data) {
if (myType == "DOC" || myType == "PPT") {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var file = data[google.picker.Response.DOCUMENTS][0];
url = file[google.picker.Document.URL];
this._fileGetCallback(url);
}
}
if (myType == "Folder") {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
console.log(google.picker);
var url = JSON.stringify(data.docs[0]);
this._fileGetCallback(url);
}
}
},
/**
* Called when file details have been retrieved from Google Drive.
* #private
*/
_fileGetCallback: function (abc) {
if (this.onSelect) {
this.onSelect(abc);
}
},
/**
* Called when the Google Drive file picker API has finished loading.
* #private
*/
_pickerApiLoaded: function() {
this.buttonEl.disabled = false;
},
/**
* Called when the Google Drive API has finished loading.
* #private
*/
_driveApiLoaded: function() {
this._doAuth(true);
},
/**
* Authenticate with Google Drive via the Google JavaScript API.
* #private
*/
_doAuth: function (immediate, callback) {
gapi.auth.authorize({
client_id: this.clientId,
scope: 'https://www.googleapis.com/auth/drive',
immediate: immediate
}, callback);
}
};
How can I stop making mutiple google views?

For my use I moved the var picker = line out of the function and into the global scope then checked in createPicker() if the picker var was null. If it was then I did the whole create, if not then just the setVisible(). Seems to work here, hope this helps.
var picker = null;
function createPicker() {
if (pickerApiLoaded && oauthToken && picker === null) {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document');
picker = new google.picker.PickerBuilder().
addView(view).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
} else if(pickerApiLoaded && oauthToken && picker !== null) {
picker.setVisible(true);
}
}

You can disable feature for various views. Use PickerBuilder.enableFeature and PickerBuilder.disableFeature to turn on/off views.
Below is a sample code for disabling multiple selection view:
var picker = new google.picker.PickerBuilder().disableFeature(google.picker.Feature.MULTISELECT_ENABLED)

Related

how to integrate google-recaptcha in oracle-jet

I am trying to integrate google-recaptcha but no success.
Getting error
feedback.js:39 Uncaught TypeError: grecaptcha.render is not a function
main.js
'googlerecaptcha':'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit',
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'ckeditor', 'googlerecaptcha', 'ojs/ojlabel',
'ojs/ojknockout', 'ojs/ojinputtext', 'ojs/ojformlayout'],
function (oj, ko, $, app, ckeditor, grecaptcha) {
/**
* The view model for the main content view template
*/
function feedbackViewModel() {
var self = this;
// For small screens: labels on top
// For medium screens and up: labels inline
this.labelEdge = ko.computed(function () {
return app.smScreen ? "top" : "start";
}, this);
onloadCallback = function (a) {
grecaptcha.render('submit', {
'sitekey': 'YOUR_API_KEY',
'callback': self.onSubmit
}, true);
};
this.handleActivated = function (info) {
};
self.onSubmit = function (token) {
console.info("google recatpcha onSubmit", token)
//do validation/application code using token
var data = {secret: grecaptcha, response: recaptchaToken};
$.post({
url: "https://www.google.com/recaptcha/api/siteverify",
form: data
}).then(function (e) {
//recaptcha service called...check result
var resp = JSON.parse(e);
if (resp.success == false) {
console.info("recaptcha token outcome is false")
} else {
console.info("recaptcha token validated")
}
});
};
}
return feedbackViewModel;
});
Do you have a mapping for 'googlerecaptcha' in src/js/path_mapping.json? If I go to https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit, I do not see that it is returning any valid object. So most likely 'grecaptcha' variable is undefined.
reCaptcha + RequireJS
Looks like reCaptcha is a function that has to be executed vs an object that can be interacted with directly. So you may need a different approach, something mentioned in this thread.

How to register Window phone with notification hub in app-backend

Hello friends i am trying to implement the app-backend registration of app with notification hub.for implementing it i am following this notify user with notification hub but i wanted to do registration for windows phone so i have tried to do it and write this code in mobile service Api
exports.post = function(request, response) {
// Use "request.service" to access features of your mobile service, e.g.:
// var tables = request.service.tables;
// var push = request.service.push;
var azure = require('azure');
var hub = azure.createNotificationHubService('samplenotificationhub',
'full access key');
var platform = request.body.platform;
var installationId = request.header('X-ZUMO-INSTALLATION-ID');
var registrationComplete = function(error, registration) {
if (!error) {
// Return the registration.
response.send(200, registration);
} else {
response.send(500, 'Registration failed!');
}
}
// Function called to log errors.
var logErrors = function(error) {
if (error) {
console.error(error)
}
}
hub.listRegistrationsByTag(installationId, function(error, existingRegs) {
var firstRegistration = true;
if (existingRegs.length > 0) {
for (var i = 0; i < existingRegs.length; i++) {
if (firstRegistration) {
// Update an existing registration.
if (platform === 'wp') {
existingRegs[i].ChannelUri = request.body.channelUri;
hub.updateRegistration(existingRegs[i], registrationComplete);
} else {
response.send(500, 'Unknown client.');
}
firstRegistration = false;
} else {
// We shouldn't have any extra registrations; delete if we do.
hub.deleteRegistration(existingRegs[i].RegistrationId, logErrors);
}
}
} else {
// Create a new registration.
if (platform === 'wp') {
hub.mpns.createNativeRegistration(request.body.channelUri,
[request.body.CurrentDate], registrationComplete);
}
else {
response.send(500, 'Unknown client.');
}
}
});
};
i am able to get the api call from this code in my app..
private async Task AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("mychannel");
string message;
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("mychannel");
CurrentChannel.Open();
CurrentChannel.BindToShellTile();
CurrentChannel.BindToShellToast();
}
var body = new NotificationRequest
{
channelUri = CurrentChannel.ChannelUri.ToString(),
platform = "wp",
CurrentDate = "1",
};
try
{
// Call the custom API POST method with the supplied body.
var result = await App.MobileService
.InvokeApiAsync<NotificationRequest,
RegistrationResult>("registrationapi", body,
System.Net.Http.HttpMethod.Post, null);
// Set the response, which is the ID of the registration.
message = string.Format("Registration ID: {0}", result.RegistrationId);
registrationid = result.RegistrationId;
}
catch (MobileServiceInvalidOperationException ex)
{
message = ex.Message;
}
i have seen an active api call on mobile service dashboard but not able to get response from API..
i have written this code in my table scripts so that i can send push notification to my phone it..also take a look if anything is wrong in it.
function insert(item, user, request) {
var azure = require('azure');
var hub = azure.createNotificationHubService('samplenotificationhub',
'listen signature string');
// Create the payload for a Windows Store app.
var wnsPayload = '<toast><visual><binding template="ToastText02"><text id="1">New item added:</text><text id="2">' + "tanuj" + '</text></binding></visual></toast>';
var Toasttemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" +"<wp:Toast>" +"<wp:Text1>$(" + "1" + ")</wp:Text1>" +"</wp:Toast> " +"</wp:Notification>";
// Execute the request and send notifications.
request.execute({
success: function() {
// Write the default response and send a notification
// to the user on all devices by using the userId tag.
request.respond();
hub.wpns.send("1", Toasttemplate, 'wpns/toast', function(error) {
if (error) {
console.log(error);
}
});
}
});
i know this is lot of code i am putting this because the link is not mentioned for wp so just wanted to make sure i am doing right.
also please let me know first what is INSTALATIONID in var installationId = request.header('X-ZUMO-INSTALLATION-ID'); hope to get some response. any help ,idea or suggestion is appreciated.

Telerik RadEditor: Overriding Media Manager 'Save'

Searched for a similar question but cannot find anything as yet.
I have a RadEditor set up and I would like to override the event after the MediaManager file upload finishes so I can get the file and process it as i like. The FileBrowser I am using already has a 'prototype' but this is not leading me anywhere. I'm thinking it will be a JQuery/Javascript calls but I can't seem to find anything on the Telerik website.
Telerik.Web.UI.Editor.DialogControls.FileBrowser.prototype = {
initialize: function () {
this.set_insertButton($get("InsertButton"));
this.set_cancelButton($get("CancelButton"));
var previewer = this.get_previewerType();
var previewerType = eval("Telerik.Web.UI.Widgets." + previewer);
$create(previewerType, { "browser": this }, null, null, $get(previewer));
this.set_filePreviewer($find(previewer));
this.set_fileBrowser($find("RadFileExplorer1"));
Telerik.Web.UI.Editor.DialogControls.FileBrowser.callBaseMethod(this, 'initialize');
},
dispose: function () {
Telerik.Web.UI.Editor.DialogControls.FileBrowser.callBaseMethod(this, 'dispose');
this._insertButton = null;
this._cancelButton = null;
}
}
Fine the solution through http://demos.telerik.com/aspnet-ajax/editor/examples/onclientpastehtml/defaultcs.aspx
On the OnClientPasteHtml i do the following:
function OnClientPasteHtml(sender, args) {
var commandName = args.get_commandName();
var value = args.get_value();
if (commandName == "FlashManager") {
var object = document.createElement("object");
Telerik.Web.UI.Editor.Utils.setElementInnerHtml(object, value);
var movieObject = object.firstChild;
//object.firstChild.Movie //this is the url of the file just uploaded
args.set_value('Write custom html here');
}
else if (commandName == "MediaManager") {
}
}

JsonLogOn via https

I've just introduced SSL to my MVC website. I made the whole default AccountContorller use it. It works fine unless I'm currently on http page and try to log on with ajax (the logon action is vredirected to httpS). This popup logon window doesn't even show up.
For the controller a used a custom attribute:
public class RequireSSL : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.IsDefined(typeof(NoSSL), true) ||
filterContext.ActionDescriptor.IsDefined(typeof(OptionalSSL), true))
{
base.OnActionExecuting(filterContext);
return;
}
HttpRequestBase req = filterContext.HttpContext.Request;
HttpResponseBase res = filterContext.HttpContext.Response;
//Check if we're secure or not and if we're on the local box
if (!req.IsSecureConnection && (!req.IsLocal || Properties.Settings.Default.UseSSLForLocalRequests))
{
var builder = new UriBuilder(req.Url)
{
Scheme = Uri.UriSchemeHttps,
Port = Properties.Settings.Default.HttpsPort,
};
res.Redirect(builder.Uri.ToString());
}
base.OnActionExecuting(filterContext);
}
}
How can I make it work?
EDIT
The whole rest was generated by MVC. (Project with built in authentications)
That's the link.
#Html.ActionLink(#Labels.LogOn, "LogOn", "Account", routeValues: null, htmlAttributes: new { id = "logonLink", data_dialog_title = "Identification" })
JS somehow hooks into that link and performs ajax logon . Probably with this code: (JajaxLogin.js - also out of the box)
/// <reference path="jquery-1.6.2.js" />
/// <reference path="jquery.validate.js" />
$(function () {
// Cache for dialogs
var dialogs = {};
var getValidationSummaryErrors = function ($form) {
// We verify if we created it beforehand
var errorSummary = $form.data('validation-summary-errors');
if (!errorSummary) {
errorSummary = $('<div class="validation-summary-errors"><span>Please correct the errors and try again.</span><ul></ul></div>')
.insertBefore($form);
// Remember that we created it
$form.data('validation-summary-errors', errorSummary);
}
return errorSummary;
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr('action'), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
location = json.redirect || location.href;
} else if (json.errors) {
var errorSummary = getValidationSummaryErrors($form);
var items = $.map(json.errors, function (error) {
return '<li>' + error + '</li>';
}).join('');
var ul = errorSummary
.find('ul')
.empty()
.append(items);
}
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
var loadAndShowDialog = function (id, link, url) {
var separator = url.indexOf('?') >= 0 ? '&' : '?';
// Save an empty jQuery in our cache for now.
dialogs[id] = $();
// Load the dialog with the content=1 QueryString in order to get a PartialView
$.get(url + separator + 'content=1')
.done(function (content) {
dialogs[id] = $('<div class="modal-popup">' + content + '</div>')
.hide() // Hide the dialog for now so we prevent flicker
.appendTo(document.body)
.filter('div') // Filter for the div tag only, script tags could surface
.dialog({ // Create the jQuery UI dialog
title: link.data('dialog-title'),
modal: true,
resizable: true,
draggable: true,
width: link.data('dialog-width') || 300
})
.find('form') // Attach logic on forms
.submit(formSubmitHandler)
.end();
});
};
// List of link ids to have an ajax dialog
var links = ['logonLink', 'registerLink'];
$.each(links, function (i, id) {
$('#' + id).click(function (e) {
var link = $(this),
url = link.attr('href');
if (!dialogs[id]) {
loadAndShowDialog(id, link, url);
} else {
dialogs[id].dialog('open');
}
// Prevent the normal behavior since we use a dialog
e.preventDefault();
});
});
});

Firefox, Mozilla validator error

I am getting this one error when I use the Mozilla validator:
This is the JS file:
const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
// Version changes:
// It used to get the lists from a PHP file, but that was putting too much of a strain on the servers
// now it uses xml files.
// Randomizes the servers to load balance
// Mozilla editor suggested no synchronous file gets, so changed it to asynchronous
// Added one more server to help with the updates (Ilovemafiaafire.net)
// Edited some redirect code that some idiots were spreading FUD about.
var xmlDoc = null;
var quickFilter_100_count_redirect_url='http://www.mafiaafire.com/help_us.php';
var countXmlUrl = 0;
//var xmlUrl = 'http://elxotica.com/xml-update/xml-list.php';
var xmlUrl = new Array(4);
xmlUrl[0] = 'http://mafiaafire.com/xml-update/mf_xml_list.xml';
xmlUrl[1] = 'http://ifucksexygirls.com/xml-update/mf_xml_list.xml';
xmlUrl[2] = 'http://ezee.se/xml-update/mf_xml_list.xml';
xmlUrl[3] = 'http://ilovemafiaafire.net/mf_xml_list.xml';
xmlUrl.sort(function() {return 0.5 - Math.random()})
var realXmlUrl = xmlUrl[countXmlUrl];
var notificationUrl = 'http://mafiaafire.com/xml-update/click_here_for_details.php';
var root_node = null;
var second_node = null;
var timervar = null;
var mafiaafireFilterUrl = '';
//Calling the interface for preferences
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var quickfilter_mafiaafire =
{
// get the domain name from the current url
get_domain_name:function()
{
var urlbar = window.content.location.href;
domain_name_parts = urlbar.match(/:\/\/(.[^/]+)/)[1].split('.');
if(domain_name_parts.length >= 3){
domain_name_parts[0] = '';
}
var dn = domain_name_parts.join('.');
if(dn.indexOf('.') == 0)
return dn.substr(1);
else
return dn;
},
// send ajax request to server for loading the xml
request_xml:function ()
{
//alert(countXmlUrl);
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request)
{
return false;
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
},
// receive the ajax response
response_xml:function ()
{
if (http_request.readyState == 4)
{
if(http_request.status == 404 && countXmlUrl<=3)
{
countXmlUrl++;
//alert(xmlUrl[countXmlUrl]);
realXmlUrl = xmlUrl[countXmlUrl];
quickfilter_mafiaafire.request_xml();
}
if (http_request.status == 200)
{
xmlDoc = http_request.responseXML;
}
}
},
filterUrl:function()
{
var urlBar = window.content.location.href;
//check if url bar is blank or empty
if (urlBar == 'about:blank' || urlBar == '' || urlBar.indexOf('http')<0)
return false;
//1. get domain
processing_domain = this.get_domain_name();
//alert(processing_domain);
//Couldn't fetch the XML config, so returning gracefully
if(xmlDoc == null)
return false;
try
{
root_node = '';
// Parsing the xml
root_node = xmlDoc.getElementsByTagName('filter');
for(i=0;i<=root_node.length;i++)
{
second_node = '';
second_node = root_node[i];
if(second_node.getElementsByTagName('realdomain')[0].firstChild.nodeValue == processing_domain)
{
this.notificationBox();
mafiaafireFilterUrl = '';
mafiaafireFilterUrl = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
timervar = setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
//window.content.location.href = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
//this.redirectToAnotherUrl(this.filterUrl);
//timervar = setInterval("quickfilter_mafiaafire.redirectToAnotherUrl(quickfilter_mafiaafire.filterUrl)",1000);
}
}
}
catch(e){
//alert(e.toString());
}
},
// This function is called for showing the notification
notificationBox:function()
{
try{
// Firefox default notification interface
var notificationBox = gBrowser.getNotificationBox();
notificationBox.removeAllNotifications(false);
notificationBox.appendNotification('You are being redirected', "", "chrome://quickfilter/content/filter.png", notificationBox.PRIORITY_INFO_HIGH, [{
accessKey: '',
label: ' click here for details',
callback: function() {
// Showing the notification Bar
window.content.location.href = notificationUrl;
}
}]);
}catch(e){}
},
redirectToAnotherUrl:function()
{
var qucikFilterRedirectCount = '';
//Read the value from preferrences
qucikFilterRedirectCount = prefManager.getCharPref("extensions.quickfilter_redirect_count");
//alert(qucikFilterRedirectCount);
if(qucikFilterRedirectCount % 15 == 0)
{
// Disable for now, can comment this entire section but this is the easier fix incase we decide to enable it later
//window.content.location.href = quickFilter_100_count_redirect_url+"?d="+mafiaafireFilterUrl;
window.content.location.href = mafiaafireFilterUrl;
}
else
{
window.content.location.href = mafiaafireFilterUrl;
}
qucikFilterRedirectCount = parseInt(qucikFilterRedirectCount)+1;
prefManager.setCharPref("extensions.quickfilter_redirect_count",qucikFilterRedirectCount);
}
}
var quickfilter_urlBarListener = {
QueryInterface: function(aIID)
{
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
//Called when the location of the window being watched changes
onLocationChange: function(aProgress, aRequest, aURI)
{
// This fires when the location bar changes; that is load event is confirmed
// or when the user switches tabs. If you use myListener for more than one tab/window,
// use aProgress.DOMWindow to obtain the tab/window which triggered the change.
quickfilter_mafiaafire.filterUrl();
},
//Notification indicating the state has changed for one of the requests associated with aWebProgress.
onStateChange: function(aProgress, aRequest, aFlag, aStatus)
{
if(aFlag & STATE_START)
{
// This fires when the load event is initiated
}
if(aFlag & STATE_STOP)
{
// This fires when the load finishes
}
},
//Notification that the progress has changed for one of the requests associated with aWebProgress
onProgressChange: function() {},
//Notification that the status of a request has changed. The status message is intended to be displayed to the user.
onStatusChange: function() {},
//Notification called for security progress
onSecurityChange: function() {},
onLinkIconAvailable: function() {}
};
var quickfilter_extension = {
init: function()
{
//Initiating the progressListerner
gBrowser.addProgressListener(quickfilter_urlBarListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
//Load the block list xml form server
quickfilter_mafiaafire.request_xml();
},
uninit: function()
{
// Remove the progressListerner
gBrowser.removeProgressListener(quickfilter_urlBarListener);
}
};
// window.addEventListener("load", function () { TheGreatTest1.onFirefoxLoad(); }, false);
// this function is Called on window Onload event
window.addEventListener("load", function(e) {
quickfilter_extension.init();
}, false);
window.addEventListener("unload", function(e) {
quickfilter_extension.uninit();
}, false);
Can you tell me how to squash that error please?
It looks like the offending line is setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
The setTimeout function can take a string (which then essentially gets eval'd) or a function (which gets called). Using a string is not recommended, for all the same reasons that using eval is not recommended. See https://developer.mozilla.org/en/DOM/window.setTimeout
In this case, the simplest fix would be to change it to setTimeout(function() { quickfilter_mafiaafire.redirectToAnotherUrl(); },1500);

Resources