I have simple deposit calc. Here is the code.
app.js:
el: '#calcbox',
data: {
newCalc: {
summ: '50000',
currency: 'USD',
duration: '',
percents: '',
},
calcResult: '',
},
computed: {
percents() {
var id = $("#deposit_id").val();
var url = "/get_percent/"+ id + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.newCalc.percents = response;
});
},
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.calcResult = response;
});
}
},
frontend:
<span>#{{newCalc.percents}}%:</span>
<span>#{{calcResult}}:</span>
So the problem is that result isn't appears in frontend, console.log shows the correct result.
Percentage value is showing well.
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.calcResult = response;
});
}
add .bind(this)
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.calcResult = response;
}.bind(this));
}
Or use fat arrow notation since you're using ES6 syntax
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, response => {
return this.calcResult = response;
});
}
the this in the .then callback is not the same context as the one outside or within your vue method
Related
*FrontEnd
As you can see in the code. I'm trying to make a Chat Application. The Message I'm sending is triggered and my Event is being Processed. But the problem is I'm not able to catch message from receiver side. I'm a stage Beginner developer and making application via youtube tutorials. Thankyou...
<script>
$(function (){
let $chatInput = $(".chat-input");
let $chatInputToolbar = $(".chat-input-toolbar");
let $chatBody = $(".chat-body");
let $messageWrapper = $("#messageWrapper");
let user_id = "{{ auth()->user()->id }}";
let ip_address = 'http://127.0.0.1';
let socket_port = '8005';
let socket = io(ip_address + ':' + socket_port);
let friendId = "{{ $friendInfo->id }}";
socket.on('connect', function() {
socket.emit('user_connected', user_id);
});
socket.on('updateUserStatus', (data) => {
let $userStatusIcon = $('.user-status-icon ');
$userStatusIcon.removeClass('text-success');
$userStatusIcon.attr('title', 'Away');
$.each(data, function (key, val) {
if (val !== null && val !== 0) {
let $userIcon = $(".user-icon-"+key);
$userIcon.addClass('text-success');
$userIcon.attr('title','Online');
}
});
});
$chatInput.keypress(function (e) {
let message = $(this).html(); //text
if (e.which === 13 && !e.shiftKey) {
$chatInput.html("");
sendMessage(message);
return false;
}
});
function sendMessage(message) {
let url = "{{ route('message.send-message') }}";
let form = $(this);
let formData = new FormData();
let token = "{{ csrf_token() }}";
formData.append('message', message);
formData.append('_token', token);
formData.append('receiver_id', friendId);
appendMessageToSender(message);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'JSON',
success: function (response) {
if (response.success) {
console.log(response.data);
}
}
});
}
function appendMessageToSender(message) {
let name = '{{ $myInfo->name }}';
let image = '{!! makeImageFromName($myInfo->name) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500"
title="'+getCurrentDateTime()+'">\n' +
getCurrentTime()+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' +
message +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-item-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
function appendMessageToReceiver(message) {
let name = '{{ $friendInfo->name }}';
let image = '{!! makeImageFromName($friendInfo->name) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500"
title="'+dateFormat(message.created_at)+'">\n' +
timeFormat(message.created_at)+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' + message.content +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
{
appendMessageToReceiver(message);
});
I think I'm missing something in the socket.on function:
socket.on("private-channel:App\Events\PrivateMessageEvent", function (message)
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message)
{
appendMessageToReceiver(message);
});
});
BackEnd Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, {
cors: {
origin: "*",
}
});
var Redis = require('ioredis');
var redis = new Redis();
var users = [];
http.listen(8005, function() {
console.log('Listening to port 8005');
});
redis.subscribe('private-channel', function() {
console.log('subscribed to private channel');
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(message);
if (channel == 'private-channel') {
let data = message.data.data;
let receiver_id = data.receiver_id;
let event = message.event;
io.to('${users[receiver_id]}').emit(channel + ':' + event, data);
}
});
io.on('connection', function (socket) {
socket.on("user_connected", function (user_id) {
users[user_id] = socket.id;
io.emit('updateUserStatus', users);
console.log("user connected "+ user_id);
});
socket.on('disconnect', function() {
var i = users.indexOf(socket.id);
users.splice(i, 1, 0);
io.emit('updateUserStatus', users);
console.log('users');
});
});
PrivateMessageEvent
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PrivateMessageEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
Public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('private-channel');
}
.env
Here's is my .env file.
APP_NAME=chat_application
APP_ENV=local
//App_key
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=chat_application
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=redis
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}
"
I've noticed one issue in the event emitting in your server side code, here is the code which emits the socket events
io.to('${users[receiver_id]}').emit(channel + ':' + event, data);
So, you trying to use string interpolation and above syntax is incorrect. Basically, this is just a string '${users[receiver_id]}'. This need to be changed to `${users[receiver_id]}`, and below is the updated code
io.to(`${users[receiver_id]}`).emit(channel + ':' + event, data);
So, when using string interpolation you need to use back ticks instead of single quotes.
And another point is make sure, your channel + ':' + event in io.to('${users[receiver_id]}').emit(channel + ':' + event, data); is same as the client event in your client side code - "private-channel:App\\Events\\PrivateMessageEvent",
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message) {
appendMessageToReceiver(message);
});
My problem is that I am trying to get an access token from Spotify, but my window.addEventListener("message, function() {...}") is never triggered. Refer to the code below:
mounted(){
this.$nextTick(function() {
function login(callback) {
var CLIENT_ID = 'd3ebae5610894ca48c9f66794214252b';
var REDIRECT_URI = 'http://localhost:8080/spotify';
function getLoginURL(scopes) {
console.log('url')
return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID +
'&redirect_uri=' + encodeURIComponent(REDIRECT_URI) +
'&scope=' + encodeURIComponent(scopes.join(' ')) +
'&response_type=token';
}
var url = getLoginURL([
'user-read-email'
]);
var width = 450,
height = 730,
left = (screen.width / 2) - (width / 2),
top = (screen.height / 2) - (height / 2);
var w = window.open(url,
'Spotify',
'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left
);
window.addEventListener("message", function(event) {
var hash = JSON.parse(event.data);
console.log(JSON.parse(event.data))
if (hash.type == 'access_token') {
callback(hash.access_token);
}
}, false);
}
var loginButton = document.getElementById('btn-login');
loginButton.addEventListener('click', function() {
console.log('click the button')
login(function(accessToken) {
console.log(accessToken)
});
});
})}
I'm using FormData() in my React app. I was going to use it for registration and login too. I have a working passport.js registration piece of code and was going to use it with busboy but it looks like it reads fields one by one whenever there is one and it seems like I can't use it with Account.register.
I've inserted Account.register in busboy.on('field') but then realized it won't work. I didn't change req.body.username etc in my original code, ignore them.
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
Account.register(new Account({ nickname: req.body.username, email: req.body.email }), req.body.passwordOne, (err, user) => {
if(err){
helpers.errors(err, res);
} else {
helpers.registerSuccess(res);
}
});
});
busboy.on('finish', function() {
console.log('Done parsing form!');
//res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
I'm using nickname instead of username in passport.js because I'm using email as the username field. Working code:
router.post('/register', (req, res, next)=>{
var busboy = new Busboy({ headers: req.headers });
let nickname = '';
let email = '';
let password = '';
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
if(fieldname == 'username') { nickname = val; }
if(fieldname == 'email') { email = val; }
if(fieldname == 'password') { password = val; }
});
busboy.on('finish', function() {
console.log('Done parsing form!');
console.log('email: ' + email + 'password: ' + password + 'username: ' + nickname);
Account.register(new Account({ nickname: nickname, email: email }), password, (err, user) => {
if(err){
helpers.errors(err, res);
} else {
helpers.registerSuccess(res);
}
});
});
req.pipe(busboy);
});
I am trying to create a PDF from HTML text using PhantomJS (version 1.9.7). I've written a very simple script (made more complicated by error callbacks etc.)
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stdout.write(msgStack.join('\n'));
phantom.exit(1);
};
var page = require('webpage').create();
page.viewportSize = { width: 800, height: 600 };
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' };
page.onResourceRequested = function(requestData, networkRequest) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
page.render('tmp.pdf');
setTimeout(function() {
phantom.exit();
}, 5000);
I set up the page, assign the simple HTML string to the content property and render it to a PDF.
This script doesn't produce any output.
I've narrowed the problem down to the <img> element, when that is removed a PDF is generated as expected. I can see from the callback functions that the image is requested, a response is received, and there are no errors reported. I've tried rendering to a PNG which also yields no output.
I've explored the possibility of this being a proxy issue, however the raserize.js example works without any problems.
You have to call render when the page is fully loaded. Remember that loading a page via page.open or page.content is always async.
Change your code to this
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
setTimeout(function() {
page.render('tmp.pdf');
phantom.exit();
}, 5000);
Can someone helps me with some example using haraka librairy?
We use Haraka as our application mail server. We have written a simple plugin which takes any incoming mail and post it to our application web server.
Here is the plugin script. Just save it to a file do the necessary name changes and add the path to Harakas config/plugins file.
var
fs = require('fs'),
query_string = require('querystring'),
logger = require('./logger'),
DROP_DIRECTORY_PATH = '/path/haraka/drop/',
RETRY_DIRECTORY_PATH = '/path/haraka/retry/',
HOST_NAME = 'this_haraka_servers_name';
exports.hook_queue = function (next, connection, params) {
'use strict';
function haraka_log(function_name_in, section_in, text_in) {
var log_text = '[HttpMail]';
log_text += ' [' + function_name_in + ']';
log_text += ' [' + section_in + ']';
log_text += ' ' + text_in;
logger.lognotice(log_text);
}//function haraka_log
function move_file(filename_in) {
fs.rename(DROP_DIRECTORY_PATH + filename_in, RETRY_DIRECTORY_PATH + filename_in, function (err) {
if (err) {
//throw err;
haraka_log('move_file', 'fs.rename ... failed', filename_in + '\n' + JSON.stringify(err));
} else {
haraka_log('move_file', 'fs.rename ... success', filename_in);
}
});
}//function move_file
function delete_file(filename_in) {
fs.unlink(DROP_DIRECTORY_PATH + filename_in, function (err) {
if (err) {
//throw err;
haraka_log('delete_file', 'fs.unlink ... failed', filename_in + '\n' + JSON.stringify(err));
} else {
haraka_log('delete_file', 'fs.unlink ... success', filename_in);
}
});
}//function delete_file
function http_post_file(filename_in) {
var
http = require('http'),
post_options = {
host: 'my.server.com',
port: 80,
path: '/http_mail/' + HOST_NAME + '?' + query_string.stringify({FileName: filename_in}),
method: 'POST',
headers: {'Content-Type': 'text/plain'}
},
post_request,
read_stream;
haraka_log('http_post_file', 'Before http.request', filename_in);
post_request = http.request(post_options, function (post_response) {
haraka_log('http_post_file', 'post_response', ' post_response.statusCode = ' + post_response.statusCode + ' : ' + filename_in);
if (post_response.statusCode === 200) {
delete_file(filename_in);
} else {
move_file(filename_in);//Posted later by retry script;
}
post_response.resume();
});//post_request = http.request(post_options, function(post_response) {
post_request.on('error', function (err) {
haraka_log('http_post_file post_request.on(\'error\' ...)', err.message, filename_in);
move_file(filename_in);
});//post_request.on('error', function(err) {
read_stream = fs.createReadStream(DROP_DIRECTORY_PATH + filename_in);
read_stream.pipe(post_request);
}//function http_post_file
var
x_sender = connection.transaction.mail_from,
x_receiver_list = connection.transaction.rcpt_to,
filename = x_sender + '_' + new Date().toISOString() + '_' + connection.uuid,
writeStream;
filename = filename.replace(/\//g, '');
connection.transaction.add_header('x-sender', x_sender.toString());
x_receiver_list.forEach(function (value) {
connection.transaction.add_header('x-receiver', value.toString());
});
haraka_log('main', 'filename', filename);
writeStream = fs.createWriteStream(DROP_DIRECTORY_PATH + filename);
//connection.transaction.message_stream.pipe(writeStream, {dot_stuffing: true, ending_dot: true});
connection.transaction.message_stream.pipe(writeStream, {dot_stuffing: true});
writeStream.on("close", function () {
haraka_log('main writeStream.on("close"...', 'File Saved!', filename);
http_post_file(filename);
next(OK);
});//writeStream.on("close", function()
};//exports.hook_queue = function(next, connection, params) {