I have integrated branch.io deeplink in my ionic 3 application. I have successfully generated the link and the link opens up the app. But, I wanted to open a particular page instead of the homepage of the app.
So, I integrated the below code to the desired page:
dl(){
// only on devices
if (!this.platform.is('cordova')) { return }
const Branch = window['Branch'];
//only canonicalIdentifier is required
let properties = {
canonicalIdentifier: 'content/123',
canonicalUrl: 'https://example.com/content/123',
title: 'Content 123 Title',
contentDescription: 'Content 123 Description ' + Date.now(),
price: 12.12,
currency: 'GBD',
contentIndexingMode: 'private',
contentMetadata: {
custom: 'data',
testing: 123,
this_is: true
}
}
//create a branchUniversalObj variable to reference with other Branch methods
let branchUniversalObj = null
Branch.createBranchUniversalObject(properties).then(function (res) {
branchUniversalObj = res
//alert(JSON.stringify(res));
// optional fields
}).catch(function (err) {
alert('Error: ' + JSON.stringify(err))
})
let message = 'Check out this link'
Branch.initSession(function(data) {
if (data['+clicked_branch_link']) {
// read deep link data on click
alert('Deep Link Data: ' + JSON.stringify(data))
}
}).then(function(res) {
// create deep link
var analytics = {
channel: Date.now()
}
var properties = {}
branchUniversalObj.generateShortUrl(analytics, properties).then(function (res) {
alert('Response: ' + JSON.stringify(res.url))
}).catch(function (err) {
alert('Error: ' + JSON.stringify(err))
})
branchUniversalObj.onLinkShareResponse(function (res) {
alert('Goosebumps:' + JSON.stringify(res))
})
});
}
And I added the function to a button click. But, still it opens up the app home page when I click the created link.
It doesn't looks like you are using the correct setup for your deep link routing. Please reference this Branch documentation for best results: https://docs.branch.io/pages/deep-linking/routing/
Related
I have been trying to extend magento 2's $.mage.loader widget. I have have a requirejs-config.js file with the following lines
var config = {
map: {
'*': {
'mage/loader' : 'Youssuph_Bakerscheckout/js/custom-mage-loader'
}
}
};
And the content of custom-mage-loader.js file is
define([
'jquery',
'mage/template',
'jquery/ui',
'mage/translate'],
function ($, mageTemplate) {
'use strict';
$.widget("bakers.loader", $.mage.loader, {
options: {
icon: '',
texts: {
loaderText: $.mage.__('Please wait...'),
imgAlt: $.mage.__('Loading...')
},
template:
'<div class="loading-mask" data-role="loader">' +
'<div class="loader">' +
'<img alt="<%- data.texts.imgAlt %>" src="'+loadingBakersLogo+'">' +
'<p><%- data.texts.loaderText %></p>' +
'</div>' +
'</div>'
}
});
return $.bakers.loader;
});
i have confirmed that this file loads in the browser but it just doesn't work. The loader works normally during page load and I see error message -
Base is not a function
What am I doing wrong?
Your requirejs-config.js it's right, but your js file no, change the params like this:
define([
'jquery',
'jquery/ui',
'mage/loader'],
function ($) {
$.widget('your_namespace.loader', $.mage.loader, {
options: {
texts: {
loaderText: $.mage.__('Foo')
},
template:
'<div>Your template</div>'
}
});
return $.your_namespace.loader;
});
Now use: jQuery('body').loader('show') and see your new custom loader!
Its been a while but if anybody else stumbles upon this answer.
vjurado is not correct. The mistake lays in requirejs-config.js. Correct will be a reference withouth the "mage/", like this:
var config = {
map: {
'*': {
'loader' : 'Youssuph_Bakerscheckout/js/custom-mage-loader'
}
}
};
The custom-mage-loader.js is correct as posted in the initial question.
I am a novice in chatbot development and I would like some help.
While it seems quite simple to connect botkit with facebook messenger and wit.ai in orger to use NLP. I haven't managed to do so. My initial goal is to have a simple conversation like hello-hello but using wit.ai as middleware.
Below I attach the code. What it should do is receive a "hello" message, pass it to wit.ai and then respond "I heard hello!" as a reply (without using wit at this stage). Instead I just receive
debug: RECEIVED MESSAGE
debug: CUSTOM FIND CONVO XXXXXXXXXXXXXX XXXXXXXXXXXXXX
debug: No handler for message_received
after every message I send to facebook messenger bot. In wit it seems like I am getting the messages since I receive messages in my inbox to update the intents.
If there is any code much simpler than the one below I would be very happy to have it so that I can start with something much simpler :).
Thanks
<pre><code>
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.verify_token) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}
if (!process.env.app_secret) {
console.log('Error: Specify app_secret in environment');
process.exit(1);
}
var Botkit = require('./lib/Botkit.js');
var wit = require('./node_modules/botkit-middleware-witai')({
token: process.env.wit,
minConfidence: 0.6,
logLevel: 'debug'
});
var os = require('os');
var commandLineArgs = require('command-line-args');
var localtunnel = require('localtunnel');
const ops = commandLineArgs([
{name: 'lt', alias: 'l', args: 1, description: 'Use localtunnel.me to make your bot available on the web.',
type: Boolean, defaultValue: false},
{name: 'ltsubdomain', alias: 's', args: 1,
description: 'Custom subdomain for the localtunnel.me URL. This option can only be used together with --lt.',
type: String, defaultValue: null},
]);
if(ops.lt === false && ops.ltsubdomain !== null) {
console.log("error: --ltsubdomain can only be used together with --lt.");
process.exit();
}
var controller = Botkit.facebookbot({
debug: true,
log: true,
access_token: process.env.page_token,
verify_token: process.env.verify_token,
app_secret: process.env.app_secret,
validate_requests: true, // Refuse any requests that don't come from FB on your receive webhook, must provide FB_APP_SECRET in environment variables
});
var bot = controller.spawn({
});
controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
controller.createWebhookEndpoints(webserver, bot, function() {
console.log('ONLINE!');
if(ops.lt) {
var tunnel = localtunnel(process.env.port || 3000, {subdomain: ops.ltsubdomain}, function(err, tunnel) {
if (err) {
console.log(err);
process.exit();
}
console.log("Your bot is available on the web at the following URL: " + tunnel.url + '/facebook/receive');
});
tunnel.on('close', function() {
console.log("Your bot is no longer available on the web at the localtunnnel.me URL.");
process.exit();
});
}
});
});
controller.middleware.receive.use(wit.receive);
controller.hears(['hello'], 'direct_message', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}
Make sure you have a few conversations in Wit.ai beforehand so for example hello there and highlight the hello in that statement as something like, greetings.
Now i'm not sure what your intents are called in wit.ai but in your statement controller.hears(['hello'] you're actually listening to the wit.ai intents. So in the example i mentioned above, we'd be using hears(['greetings']) since that's the intent in wit.ai.
Also, instead of using direct_message use message_received this is what it should look like:
controller.hears(['hello'], 'message_received', wit.hears, function(bot, message) {
bot.reply(message, 'I heard hello!');
});
If you're struggling tracking down the problem you can stick a console statement in your controller so something like console.log("Wit.ai detected entities", message.entities); and see what you get back from that.
Let me know if you're still having any issues :)
I must be missing something patently obvious here, but I cannot for the life of me figure out what. I have configured Restivus like this:
Projects = new Mongo.Collection('projects');
Skills = new Mongo.Collection('skills');
Causes = new Mongo.Collection('causes');
Meteor.startup(() => {
let Api = new Restivus({
apiPath: 'api/',
auth: {
token: 'auth.apiKey',
user: function () {
return {
userId: this.request.headers['user-id'],
token: this.request.headers['login-token']
};
}
},
defaultHeaders: {
'Content-Type': 'application/json'
},
onLoggedIn: function () {
console.log(this.user.username + ' (' + this.userId + ') logged in');
},
onLoggedOut: function () {
console.log(this.user.username + ' (' + this.userId + ') logged out');
},
prettyJson: true,
useDefaultAuth: true,
version: 'v1'
});
// Add core models
Api.addCollection(Skills);
Api.addCollection(Causes);
Api.addCollection(Projects);
Api.addRoute('custom', {
get: function () {
return {
status: 'success',
data: 'get something different'
};
}
});
});
This is essentially copy-pasted from the documentation. The problem is that when trying to access either any of the auto-generated endpoints, or the custom endpoint custom, all I get is the HTML of the Meteor app itself (i.e. same as if I had navigated to the root URL of the app).
It is as if Restivus simply is not being run at all, yet a console.log at the end of the code block above verifies that it is at least being run. What am I doing wrong?
As I expected, it was something patently obvious. I am leaving this here just in case anyone else makes the same mistake.
The key is this line in the config:
version: 'v1'
this means that you will need to append /v1/ to your API path, so that the call itself has the format (for example):
mydomain.com/api/v1/myresource
Currently I am capturing the image of the camera, this Base64 format,and I'm sending through ajax.
xhr({
uri: 'http://localhost:1337/file/upload',
method: 'post',
body:'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...'
}
0 file(s) uploaded successfully!
Here is a nice link that will guide you to do send an image from an Ajax Client to an ajax server.
http://www.nickdesteffen.com/blog/file-uploading-over-ajax-using-html5
You can read this sails documentation to receive files on a sails server :
http://sailsjs.org/documentation/reference/request-req/req-file
You can do as the following example :
Client side ( ajax ):
var files = [];
$("input[type=file]").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
};
reader.readAsDataURL(file);
});
});
$("form").submit(function(form) {
$.each(files, function(index, file) {
$.ajax({url: "/ajax-upload",
type: 'POST',
data: {filename: file.filename, data: file.data}, // file.data is your base 64
success: function(data, status, xhr) {}
});
});
files = [];
form.preventDefault();
});
Server side ( sails ) :
[let's say you have a model Picture that take an ID and a URL]
[here is a sample of Picture controller, just to give you an idea]
module.exports = {
uploadPicture: function(req, res) {
req.file('picture').upload({
// don't allow the total upload size to exceed ~10MB
maxBytes: 10000000
},
function onDone(err, uploadedFiles) {
if (err) {
return res.negotiate(err);
}
// If no files were uploaded, respond with an error.
if (uploadedFiles.length === 0){
return res.badRequest('No file was uploaded');
}
// Save the "fd" and the url where the avatar for a user can be accessed
Picture
.update(777, { // give real ID
// Generate a unique URL where the avatar can be downloaded.
pictureURL: require('util').format('%s/user/pictures/%s', sails.getBaseUrl(), 777), // GIVE REAL ID
// Grab the first file and use it's `fd` (file descriptor)
pictureFD: uploadedFiles[0].fd
})
.exec(function (err){
if (err) return res.negotiate(err);
return res.ok();
});
});
}
};
Hope this will help in your research.
I also recommand you to use Postman to test your API first, then code your client.
i'm currently trying to migrate my site to yii. (still new to it too) in my site i have a facebook login code that looks like this
function updateButton(response) {
var b = document.getElementById("{$this->fbLoginButtonId}");
b.onclick = function(){
$("#{$this->fbLoginButtonId}").button("loading");
FB.login(function(response) {
if(response.authResponse) {
$('#processing').modal({show: true, backdrop: 'static', keyboard: false});
FB.api('/me', function(user) {
$.ajax({ type : 'post'
, url: '{$this->facebookLoginUrl}'
, data: ({ user: user })
, dataType: 'json'
, success: function(data){
if(data.error == 0){
window.location.href = data.success;
} else {
$('#processing').modal('hide');
showError(data.error);
$("#{$this->fbLoginButtonId}").button("reset");
}
}
});
});
} else { $("#{$this->fbLoginButtonId}").button("reset"); }
}, {scope: '{$this->facebookPermissions}'});
}
}
the line url: '{$this->facebookLoginUrl}' basically points to the file that does the authentication. in Yii, i put that file in protected/controllers/facebookcontroller.php
class FacebookController extends Controller {
public $defaultAction = 'facebook';
public function actionFacebook() {
if (app()->request->isAjaxRequest) {
$user = app()->request->getParam('user');
Shared::debug($user);
// verify one last time that facebook knows this guy
if($user['id'] === app()->facebook->getUser()){
$model = User::model()->findByEmail($user['email']);
if(!empty($model)){
// facebook email matches one in the user database
$identity = new UserIdentity( $model->email , null );
$identity->_ssoAuth = true;
$identity->authenticate();
if($identity->errorCode === UserIdentity::ERROR_NONE){
app()->user->login($identity, null);
echo json_encode(array('error' => false, 'success' => url('/')));
app()->end();
} else {
echo json_encode(array('error' => 'System Authentication Failed', 'code' => 'auth'));
app()->end();
}
} else {
// nothing found, this person should register
// write query to input into database!!!
}
} else {
// fb user id past from ajax does not match who facebook says they are...
echo json_encode(array('error' => 'Facebook Authentication Failed', 'code' => 'fb_auth'));
app()->end();
}
} else {
throw new CHttpException(403);
}
}
}
basically what do i put here url: '{$this->facebookLoginUrl}' ?? i tried http://localhost/facebook.html but doesn't work. i get this error on firebug
<h1>PHP Error [8]</h1>
<p>Undefined index: email (/Applications/XAMPP/xamppfiles/htdocs/protected/controllers/FacebookController.php:13)</p>
<pre>#0 /Applications/XAMPP/xamppfiles/htdocs/protected/controllers/FacebookController.php(13): CWebApplication->handleError()
#1 /Applications/XAMPP/xamppfiles/htdocs/yii/web/actions/CInlineAction.php(49): FacebookController->actionFacebook()
#2 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CController.php(308): CInlineAction->runWithParams()
#3 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CController.php(286): FacebookController->runAction()
#4 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CController.php(265): FacebookController->runActionWithFilters()
#5 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CWebApplication.php(282): FacebookController->run()
#6 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CWebApplication.php(141): CWebApplication->runController()
#7 /Applications/XAMPP/xamppfiles/htdocs/yii/base/CApplication.php(180): CWebApplication->processRequest()
#8 /Applications/XAMPP/xamppfiles/htdocs/index.php(25): CWebApplication->run()
</pre>
the ajax post response looks like this..
user[birthday] MM/DD/YYYY
user[first_name] name
user[gender] male
user[hometown][id] 106031246101856
user[hometown][name] CITY, STATE
user[id] 598482999
user[last_name] LASTNAME
user[link] https://www.facebook.com/ID
user[locale] en_US
user[location][id] 106031246101856
user[location][name] CITY, STATE
user[middle_name] MIDDLENAME
user[name] FULLNAME
user[timezone] -8
user[updated_time] 2013-12-15T16:43:03+0000
user[username] USERNAME
user[verified] true
Yii generates url as http://www.example.com/index.php?r={controller_id}/{action_id}.
So in your case url will be http://www.example.com/index.php?r=facebook/facebook.
Learn how yii manges url's here.