flutter_socket_io : My event triggers, my JSON is OK, but the message is not sent - flutter

I have a problem using flutter_socket_io. My event triggers, my message is OK, all seems to be OK, but the message is not published.
Here is my log :
D/FlutterSocketIoPlugin: FlutterSocketIoPlugin(22753): onMethodCall: socketSendMessage - domain:
<MY_URL> - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: (22753): 1
D/FlutterSocketIoPlugin: SocketIO(22753): socket id: <MY_URL> is connected: true
D/FlutterSocketIoPlugin: sendMessage(22753): Event: chat.sendMessage - with message: {"chat": "5da02fec8216246456198e19", "sender": {"id": "5c014a1d43b6804ed7b642b1", "username": "Yowims", "image": {"url": "<IMAGE_URL>"}}, "state": "send", "message": "zahtrz", "sendDate": "2020-04-03T17:04:58.203404"}
D/FlutterSocketIoPlugin: FlutterSocketIoPlugin(22753): onMethodCall: socketSendMessage - domain:
<MY_URL> - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: (22753): 1
D/FlutterSocketIoPlugin: SocketIO(22753): socket id: <MY_URL> is connected: true
D/FlutterSocketIoPlugin: sendMessage(22753): Event: chat.receiveMessage - with message: {"chat": "5da02fec8216246456198e19", "sender": {"id": "5c014a1d43b6804ed7b642b1", "username": "Yowims", "image": {"url": "<IMAGE_URL>"}}, "state": "send", "message": "zahtrz", "sendDate": "2020-04-03T17:04:58.203404"}
Here are the methods I call :
SocketIO socketIO;
_connectSocket() {
socketIO = SocketIOManager().createSocketIO(wsAdd, "/");
socketIO.init();
_subscribes();
socketIO.connect();
}
_subscribes() {
if (socketIO != null) {
socketIO.subscribe('chat.sendMessage', _onSendChatMessage);
socketIO.subscribe("chat.receiveMessage", _onReceiveChatMessage);
}
}
void _onReceiveChatMessage(dynamic message) {
print("--- Message reçu! Actualisation... ---");
_getMessagesByChatId(chatStateId);
}
void _onSendChatMessage(String msg) async {
if (socketIO != null) {
Map<String,dynamic> chatUser = ({
'"id"': '"${user.id}"',
'"username"': '"${user.username}"',
'"image"': {
'"url"':'"${user.image.url}"'
}
});
String currentDate = DateTime.now().toIso8601String();
Map<String,dynamic> thisJson = {
'"chat"': '"${this.chatStateId}"',
'"sender"': chatUser,
'"state"': '"send"',
'"message"': '"$msg"',
'"sendDate"': '"$currentDate"'
};
socketIO.sendMessage("chat.sendMessage", thisJson.toString());
socketIO.sendMessage("chat.receiveMessage", thisJson.toString());
sendController.clear();
}
}
My formating is quite gross, but I have to do it like this otherwise my program doesn't add quotes at the right spots.
And here is the widget where I call the method to send my message :
SizedBox(
width: 50,
child: FlatButton(
child: Icon(Icons.send),
onPressed: (){
_onSendChatMessage(sendController.text);
},
),
)

Finally I managed to find what the problem was: my message was correctly sent, but the server wasn't able to process it because my server wasn't prepared to receive messages from mobile devices.
Some modifications within the server's code were able to solve my problem.

Related

How to catch Next-Auth Email Provider's sign in errors in the client with redirect property set to 'false'?

I added Next-Auth's Email provider to my app, and having issues with catching signIn errors in the client. According to documentation as well as this answer, when using signIn with 'redirect: false' it will return a Promise, that resolves to the following:
{
error: string | undefined;
status: number;
ok: boolean;
url: string | null;
}
In case of errors, however, the 'error' property of the response object has only 'EmailSignin' value, and contains no other information about the kind of error. Instead, more detailed errors are printed in the terminal.
I have the following basic setup:
[...nextauth].js
EmailProvider({
name: "Email",
server: {
host: "smtp.gmail.com",
port: "587",
auth: {
user: "myusername",
pass: "mypassword",
},
},
from: "My App",
}),
And the code of my custom sign in form (modal window):
const handleSignInClick = async () => {
const { email } = formData;
const response = await signIn("email", {
redirect: false,
email,
});
...
...
...
};
Is there any way to catch the errors that are printing in the console, and send them to client instead?
Ok, after playing a little bit with the code + additional reading of the documentation I came up with a solution.
Basically, when you add normalizeIdentifier method to EmailProvider, it overrides the default normalization mechanism. In the method I return 'identifier' without any changes. This stops Next-Auth's logger from throwing 'invalid email' errors to the console. Here is the code:
'normalizeIdentifier' method
EmailProvider({
name: "Email",
server: {
host: "smtp.gmail.com",
port: "587",
auth: {
user: "myusername",
pass: "mypassword",
},
},
from: "My App",
normalizeIdentifier(identifier) {
// return indentifier as is, to avoid next auth logger to log failure for invalid email
return identifier;
},
})
In addition to that, I added 'signIn' callback. Which as per documentation runs 2 times. First when verification request is sent, and second after a user has clicked on a sign-in link. In the first run, you can check 'verificationRequest' which will be 'true'. And here you can do validation of the email, as well and throw an error (which will be sent to client).
'signIn' callback
callbacks: {
async signIn({ user: { email }, email: { verificationRequest } }) {
if (verificationRequest) {
try {
// validate email here
validateEmail(email);
} catch {
//thrown error will be sent to client
throw "Email is invalid";
}
}
},
},
Here is response for invalid request:
{
"error": "Email is invalid",
"status": 200,
"ok": true,
"url": null
}
NOTE: There is only one case in which this solution will not work, and it is when email is not provided at all (normalizeIdentifier and signIn will not be triggered). So default 'EmailSignin' error is sent to client. IMO this is still OK, because logger does not pollute the console, and you know that if it's not a custom error, then there was no email provided.

Unable to deploy smart contract to testnet (Ropsten) using Truffle Infura

I'm trying to deploy a simple smart contract to Testnet Ropsten but always fails with the following error:
Error: *** Deployment Failed ***
"Migrations" -- Transaction was not mined within 750 seconds, please
make sure your transaction was properly sent. Be aware that it might
still be mined!.
I've searched in many places, and it says to change the gas value, I tried almost every value but still got the same error. Sometimes it says that the gas value is not enough and sometimes it's too much.
This is my code:
require("dotenv").config();
const HDWalletProvider = require("truffle-hdwallet-provider");
const MNEMONIC = process.env.MNEMONIC;
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*",
},
ropsten: {
provider: function () {
return new HDWalletProvider(
MNEMONIC,
`https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`
);
},
network_id: 3,
gas: 5500000, // Here I tried from 1000000 to 5500000
},
},
compilers: {
solc: {
version: "0.8.10",
},
},
};
Contract:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.3;
contract HelloWorld {
function sayHello() public pure returns(string memory){
return("hello world");
}
}
Migrations:
const Migrations = artifacts.require("Migrations");
module.exports = function (deployer) {
deployer.deploy(Migrations);
};
const HelloWorld = artifacts.require("HelloWorld");
module.exports = function (deployer) {
deployer.deploy(HelloWorld, "hello");
};
I have my metamask wallet with 1 ether in red ropstem
Any idea on how to deploy a smart contract in a testnet?
It might be because, you are not speciying address and gasPrice. gasPrice varies depending on network activities. You can get the current gasPrice here : https://ethgas.watch/
ropsten: {
provider: () =>
new HDWalletProvider({
mnemonic: {
phrase: MENMONICS,
},
providerOrUrl: `https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`,
// first address
addressIndex: 0,
}),
network_id: 3,
gas: 5500000,
// this might varies depending on the network activity
gasPrice: 20000000000,
confirmations: 2, // number of blocks to wait between deployment
timeoutBlocks: 200, // number of blocks before deployment times out
},

Create Payment Request API

I am trying to integrate the Payment Request API for the Google Pay for Payments using javascript but my code returns a PaymentRequest is not defined error.
Here is my code.
CODE:
const supportedInstruments = [
{
supportedMethods: ['https://tez.google.com/pay'],
data: {
pa: 'abc#gmail.com',
pn: 'abc',
tr: '1234ABCD', // your custom transaction reference ID
url: 'http://url/of/the/order/in/your/website',
mc: '1234', // your merchant category code
tn: 'Purchase in Merchant',
},
}
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: '10.01', // sample amount
},
},
displayItems: [{
label: 'Original Amount',
amount: {
currency: 'INR',
value: '10.01',
},
}],
};
let request = null;
try {
request = new PaymentRequest(supportedInstruments, details);
}
catch (e) {
console.log('Payment Request Error: ' + e.message);
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
Error Message:
Payment Request Error: PaymentRequest is not defined
Sounds to me like you are testing it in an older browser that simply doesn't support it. Browser support is pretty good these days, but not universal. You just need to do a simple bit of feature detection and wrap your code in an if statement to check the browser supports it:
if (window.PaymentRequest) {
// your payment request code here
}

How to read mail text in mail listener 2?

conf.js
var MailListener = require("mail-listener2");
var mailListener = new MailListener({
username: "*****#office365.com",
password: "******",
host: "outlook.office365.com",
port: 993, // imap port
tls: true,
fetchUnreadOnStart: true,
tlsOptions: {rejectUnauthorized: false},
mailbox: "INBOX",
searchFilter: "UNSEEN",
markSeen: true
});
mailListener.on("server:connected", function () {
console.log("imapConnected");
});
mailListener.on("server:disconnected", function () {
console.log("imapDisconnected");
});
(function () {
var count = 0;
mailListener.on("mail", function (mail, seqno, attributes) {
var mailuid = attributes.uid,
toMailbox = 'Inbox',
i = ++count;
if (i > 1) {
mailListener.stop(); // start listening
return;
}
console.log('email parsed', {
i: i,
subject: mail.subject,
from: mail.from,
text:mail.text,
seqno: seqno,
uid: attributes.uid,
attributes: attributes
});
expect(mail.subject).toEqual("FW: Secure One-Time-Password for Account Login");
var pattern = new RegExp(/Please use (\w+)/g);
var regCode = pattern.exec(mail.text)[1];
console.log(regCode);
console.log('attempting to mark msg read/seen');
mailListener.imap.addFlags(mailuid, '\\Seen', function (err) {
if (err) {
console.log('error marking message read/SEEN');
return;
}
//console.log('moving ' + (seqno || '?') + ' to ' + toMailbox);
//mailListener.imap.move(mailuid, toMailbox, function (err) {
if (err) {
console.log('error moving message');
return;
}
console.log('moved ' + (seqno || '?'), mail.subject);
});
});
});
})
();
mailListener.start(); // start listening
setTimeout(function () {
mailListener.stop(); // start listening
}, 60 * 1000);
I am reading all the details except text and the text is in html table format.
Instead of text i am getting undefined message.If needed i will add html code also.
If i am forwarding the same mail to gmail from office 365 and reading the mail from gmail i am able to get text.
Error:
subject: 'test mail',
from: [ { address: 'otp#gmail.com', name: 'gmail.com' } ],
body: undefined,
seqno: 2,
uid: 18,
attributes:
{ date: 2017-06-14T16:22:06.000Z,
flags: [ '\\Seen' ],
uid: 18,
modseq: '3914',
'x-gm-labels': [],
'x-gm-msgid': '1570197813730673685',
'x-gm-thrid': '1570197813730673685' } }
[21:56:13] E/launcher - Cannot read property '1' of null
[21:56:13] E/launcher - TypeError: Cannot read property '1' of null
I see that this is an old issue, but I am facing the same problem and using the nearly the same function.
I want to get the content of the e-mail with a link and the email is in HTML. So: mail.text doesn't and won't work in this case.
Solution is really simple and it works for me straight forward: mail.html

Shippo API - Multipiece shipment returns empty rates_list

Attempting to create a multi-piece shipment per https://goshippo.com/docs/multipiece
I'm specifying async = false in my request, but I'm getting back an empty rates_list in the response. EDIT to add that the to and from address I redacted are both valid (home and office) and I've been able to successfully do single-piece test shipments using them before, just not multi-piece ones.
Request payload (I apologize if these are a mess, I can't get SO to format JSON):
{
"object_purpose": "PURCHASE",
"address_from": {
"object_state":null,
"object_purpose":"PURCHASE",
"object_source":null,
"object_created":null,
"object_updated":null,
"object_owner":null,
"name":"REDACTED",
"company":"REDACTED",
"street1":"REDACTED",
"street_no":"",
"street2":"",
"city":"REDACTED",
"state":"REDACTED",
"zip":"REDACTED",
"country":"US",
"phone":"REDACTED",
"email":"REDACTED",
"ip":null,
"metadata":null,
"is_residential":null,
"validate":false,
"object_id":null,
"object":"unknown"
},
"address_to": {
"object_state":null,
"object_purpose":"PURCHASE",
"object_source":null,
"object_created":null,
"object_updated":null,
"object_owner":null,
"name":"Tony Stark",
"company":"Stark Enterprises",
"street1":"REDACTED",
"street_no":null,
"street2":"",
"city":"REDACTED",
"state":"REDACTED",
"zip":"REDACTED",
"country":"US",
"phone":null,
"email":"REDACTED",
"ip":null,
"metadata":null,
"is_residential":null,
"validate":false,
"object_id":null,
"object":"unknown"
},
"parcel": [
{
"object_state":null,
"object_created":null,
"object_updated":null,
"object_owner":null,
"length":"20",
"width":"20",
"height":"20",
"distance_unit":"in",
"weight":1.5,
"mass_unit":"lb",
"metadata":null,
"object_id":null,
"object":"unknown"
},
{
"object_state":null,
"object_created":null,
"object_updated":null,
"object_owner":null,
"length":"20",
"width":"20",
"height":"20",
"distance_unit":"in",
"weight":1.5,
"mass_unit":"lb",
"metadata":null,
"object_id":null,
"object":"unknown"
},
{
"object_state":null,
"object_created":null,
"object_updated":null,
"object_owner":null,
"length":"20",
"width":"20",
"height":"20",
"distance_unit":"in",
"weight":2.6,
"mass_unit":"lb",
"metadata":null,
"object_id":null,
"object":"unknown"
}
],
"async": false
}
Response:
`{
"async":null,
"object_state":"VALID",
"object_status":"SUCCESS",
"object_purpose":"PURCHASE",
"object_created":"2016-12-13T20:33:20.318Z",
"object_updated":"2016-12-13T20:33:20.318Z",
"object_owner":"REDACTED",
"address_from":"e0633e8c3f3a4a19ba6a83998906da02",
"address_to":"b48de7caf2624803adba6cac2b10e1f5",
"address_return":"e0633e8c3f3a4a19ba6a83998906da02",
"parcel":[
"ec25a9566fdd47ef9d728307b76eca35",
"be5e95a487644abd875f6049a32621fc",
"de942d19ef8046e49011c3b1971c2dc8"
],
"submission_type":"PICKUP",
"submission_date":"2016-12-13T15:33:18Z",
"insurance_amount":"0.0",
"insurance_currency":"USD",
"extra":{
},
"customs_declaration":null,
"reference_1":"",
"reference_2":"",
"rates_url":"https://api.goshippo.com/shipments/4f1e4a275ca341dda8cb31eed746720f/rates/",
"rates_list":[
],
"metadata":"",
"messages":[
],
"object_id":"4f1e4a275ca341dda8cb31eed746720f",
"object":"unknown"
}`
The rates_url similarly gives no results:
{"count": 0, "next": null, "previous": null, "results": []}
I am a support engineer here at Shippo. I looked up the API call you made to our servers and it looks like the TO and FROM addresses are the same. You're getting a blank response in return because those two fields cannot be the same, even for testing purposes. We're aware that we need to have better error messages and we're working on it. If you get any more errors or blank responses, email support#goshippo.com.
Ben