(sorry my english is poor)
Hi, i'm new with electron.js i'm building an app can get temp mails ... the app is working but the problem is the content not updating. when i send a email to the temp-mail this not appairs but if i close and open the app the inbox appairs... i don't know what is the problem.
Here is the code:
renderer.js
input_inbox.addEventListener("click", async () => {
const email_inbox = input_email.value; // get mail generate randomly and pass
window.TempMail.getInbox(email_inbox); // to the main process
window.TempMail.send('sending', (data) => {console.log(data)});
});
main.js
ipcMain.on("getInbox", (event, arg) => {
var address = new TempMail(arg); // get from renderer and create email
address.fetchEmails(function (err, body) {
console.log(body) // show the content in console.
mainWindow.webContents.send('sending', body.messages[0].from)
if (!body.messages[0]?.from === undefined) {
console.log(body.messages[0].from);
}
});
});
At this point, if i send an email to the generate email this not have inbox until close and open the app.
console.log before close and open the app.. :
{
address: 'PjrlERcEoEPU#1secmail.com#1secmail.com',
messageCount: 0,
messages: []
}
console.log after close and open the app:
{
address: 'PjrlERcEoEPU#1secmail.com',
messageCount: 1,
messages: [
{
from: 'my-email#gmail.com',
timestamp: '2022-09-04 20:03:04',
subject: 'skajj',
message: 'kjkjkj\n'
}
]
}
Related
What I'd like to do is to:
Popup Send Data Request to Content -> Content Receive Request, Send Data (listData) -> Popup Receive Data.
Then, if content change its elements,
Content Send Message -> Popup Receive Message, Send Request Data -> Content Receive Request, Send Data (listData) -> Popup Receive Data
I have this code in Content.tsx
new MutationObserver(() => {
var dataImage: any = document.getElementsByClassName('image');
var dataName: any = document.getElementsByClassName('name');
var dataTitle: any = document.getElementsByClassName('title');
var listData: Array<any> = [];
for (let x = 0; x < dataImage.length; x++) {
const image = dataImage[x]?.firstElementChild?.src;
const name = dataName[x]?.innerText;
const title = dataTitle[x]?.firstElementChild?.innerText;
const web = dataName[x]?.firstElementChild?.href;
listData.push({
image: image,
name: name,
title: title,
web: web,
});
}
chrome.runtime.onMessage.addListener(function (request, sender, sendMessage) {
if (request.greeting === 'hello') {sendMessage(listData)};
});
chrome.runtime.sendMessage(listData)
}).observe(document, { subtree: true, childList: true });
And this in Popup.tsx
getLeadList(query: Object): Promise<LeadResult[]> {
return new Promise<LeadResult[]>(
(resolve: (value: LeadResult[]) => void) => {
chrome.tabs.query(
{ active: true, currentWindow: true },
function (tabs: any) {
chrome.tabs.sendMessage(
tabs[0].id,
{ greeting: 'hello' },
function (response) {
if (response) {
resolve(response);
}
}
);
}
);
chrome.runtime.onMessage.addListener((request: LeadResult[]) => {
if (request) {
resolve(request);
}
});
}
);
}
What is happening right now is that Popup only send message once. So if you close the Popup and the url in content wasn't reload, Popup wont get the new content from Content.tsx and it only has the initial data from content. Also as you can see, I used direct sendMessage since if Content have changes, it passes the listdata in realtime. Although I'm not yet familiar with the proper use of chrome.runtime, so I'm open with correction in my misused code.
What I'd like to do is to Popup get the updated listdata when scrolled by MutationObserver. Then, if the Popup was closed, it will retrieve the latest scrolled data from MutationObserver. Also, make the Popup reload the Content Page when it clicked to open. (Like window.reload or soemthing)
Hope you could help me figure this thing.
Thank you very much.
I'm using react-native-contacts inside my react native app to save a contact.
Before saving I request WRITE permission from android.
It works, I open the contact form through my app and save it using the contact form. The contact is saving properly. But, after I have saved the contact, it goes to the home screen, not to my app.
I want to return to my app after the contact is saved.
here is my code,
saveContact = user => {
var newPerson = {
emailAddresses: [
{
label: "work",
email: user.email
}
],
phoneNumbers: [
{
label: "mobile",
number: user.mobileNumber
}
],
displayName: user.firstName + " " + user.lastName
};
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS, {
title: "Contacts",
message: "This app would like to write contacts.",
buttonPositive: "Please accept bare mortal"
}).then(() => {
Contacts.openContactForm(newPerson, (err, contact) => {
if (err) throw err;
// contact has been saved
});
});
};
So I think you are talking about Callback when openContactForm when creation screen is closed
This issue is still OPEN on their github issue page and this feature is still not given by package owner.
For instance, you can see for iOS this thread
I think for now you need to add event listeners for both android and ios separately.
For more information about handling event listeners here
I want to save the chat history in the database. Is there any inbuilt functions for that ?
chat.controller('chat', ['Messages', '$scope', function(Messages, $scope) {
// Message Inbox
$scope.chats = {};
Messages.user({id: "support-agent", name: "Support Agent"});
// Receive Messages
Messages.receive(function(message, isPrivate) {
// isPrivate is always true
// create a new chat if doesn't exist
if(!$scope.chats[message.user.id]) {
$scope.chats[message.user.id] = {
user: message.user,
messages: []
};
}
// add messages to the chat
$scope.chats[message.user.id].messages.push(message);
});
// Send Messages
$scope.send = function(to, text) {
var message = {
to: to,
data: text,
user: Messages.user()
};
Messages.send(message);
// because we are sending a message to a user's personal channel,
// but not subscribing to it we need to keep track of sent messages
// ourselves
$scope.chats[to].messages.push(message);
};
}]);
Where to add the history function in the code ?
GCM Cloud messaging notifications for my Ionic Android app are not appearing in my device's home screen, despite the notification registering in the app itself.
I'm using the npm module node-gcm to send push notifications.
var gcm = require('node-gcm');
var message = new gcm.Message({
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 10,
dryRun: false,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP."
}
});
var regIds = ['*device id*'];
var sender = new gcm.Sender('*api key*');
sender.send(message, { registrationIds: regIds }, function (err, result) {
if(err) console.error(err);
else console.log(result);
});
When I send a push notification to my device's ID, I get a successful response:
{ multicast_id: 8406385547051869000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1441962697347777%b67ee170f9fd7ecd' } ] }
I then get the following message in my Android Studio console:
V/GCMBroadcastReceiver﹕ onReceive: com.google.android.c2dm.intent.RECEIVE
V/GCMBroadcastReceiver﹕ GCM IntentService class: com.plugin.gcm.GCMIntentService
V/GCMBaseIntentService﹕ Acquiring wakelock
V/GCMBaseIntentService﹕ Intent service name: GCMIntentService-GCMIntentService-5
D/GCMIntentService﹕ onMessage - context: android.app.Application#2dc6dbff
V/GCMBaseIntentService﹕ Releasing wakelock
In the Google Play Developer Console GCM Debugger, my notifications also to appear to have been confirmed.
0: 1441899623073525% b67ee170f9fd7ecd Confirmed
Other than this I receive no error message in the Android Studio console when a notification has been received.
The Ionic app itself registers the notification once I've sent one. However when I'm out of the app. no notification is displayed in the home screen.
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
alert(notification);
if (ionic.Platform.isAndroid() && notification.event == "registered") {
window.localStorage['token'] = notification.regid;
var params = {
deviceType: 'android',
tokenId: notification.regid
};
NotificationService.registerDevice(params);
}
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge);
}
//notifications payload
if (notification.foreground == '0') {
if (notification.view) {
$timeout(function () {
$state.go('app.notifications');
});
} else {
if (notification.id) {
NotificationService.markNotificationAsRead(notification.id).success(function () {
$rootScope.$emit('notifications-read');
});
}
if (notification.chat) {
$timeout(function () {
$state.go('app.message', {id: notification.chat});
});
} else if (notification.post) {
$timeout(function () {
$state.go('app.singlePost', {id: notification.post});
});
} else if (notification.group) {
$timeout(function () {
$state.go('app.group', {id: notification.group});
});
}
}
}
});
You must add icon field in your notification block:
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP.",
icon: "#drawable/ic_launcher"
}
I was having the same issue, using the sample provided at the node-gcm page. After struggling for quite some time i came across this blogpost: http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
and modified my code according to the example provided in the blog post.
i guess there is an issue with "notification" object on node-gcm code, using message.addData seems to make it work,
in short replacing the message creation and sending logic as below worked for my application :
// For Android
if (row.device === "Android" && row.deviceToken) {
console.log(row.deviceToken);
var sender = new gcm.Sender(serverApiKey);
var message = new gcm.Message();
message.addData('title','İş Geliştirme Platformu');
message.addData('message','Yeni İleti');
message.addData('msgcnt','1');
//message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
var registrationIds = [];
registrationIds.push(row.deviceToken);
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
res.send(200,result);
});
}
add your server IP to white list and try again:
console.developers.google.com > APIs & auth > credential > select your server key > and add your server IP
I need to test a protractor test case in which a user signs up, receives an email, goes to the link provided in the email and fills up his/her details in activation signup form.
The problem is how can I get the redeem token from the email. My email has a link to the activation page which has the auth token like following:
http://127.0.0.1:3000/#/signup/redeem/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJlOTRhYzY3MC1kYTNlLTQyYTUtODVkZS02NDU4ZjVmZGMwYjAiLCJzdWIiOiJ0ZXN0QGNvZWYuY28iLCJpYXQiOjE0Mjc0OTM5MDMsImV4cCI6MTQyODA5ODcwM30.
But how do I fetch that token so that I can build the url or how can I click that button in my email so that I can complete the flow ? I am using mailcatcher to simulate email.
This is something I've solved recently. Hope the solution would also apply for your use-case.
Prerequisites:
mail-listener2 package
understanding of the concept of promises
Step by step instructions:
Install mail-listener2:
npm install mail-listener2 --save-dev
In your protractor config initialize Mail Listener and make it available globally:
onPrepare: function () {
var MailListener = require("mail-listener2");
// here goes your email connection configuration
var mailListener = new MailListener({
username: "imap-username",
password: "imap-password",
host: "imap-host",
port: 993, // imap port
tls: true,
tlsOptions: { rejectUnauthorized: false },
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments
});
mailListener.start();
mailListener.on("server:connected", function(){
console.log("Mail listener initialized");
});
global.mailListener = mailListener;
}),
onCleanUp: function () {
mailListener.stop();
},
Create a helper getLastEmail() function which would wait for an email to be retrieved:
function getLastEmail() {
var deferred = protractor.promise.defer();
console.log("Waiting for an email...");
mailListener.on("mail", function(mail){
deferred.fulfill(mail);
});
return deferred.promise;
};
Example test case:
describe("Sample test case", function () {
beforeEach(function () {
browser.get("/#login");
browser.waitForAngular();
});
it("should login with a registration code sent to an email", function () {
element(by.id("username")).sendKeys("MyUserName");
element(by.id("password")).sendKeys("MyPassword");
element(by.id("loginButton")).click();
browser.controlFlow().await(getLastEmail()).then(function (email) {
expect(email.subject).toEqual("New Registration Code");
expect(email.headers.to).toEqual("myemail#email.com");
// extract registration code from the email message
var pattern = /Registration code is: (\w+)/g;
var regCode = pattern.exec(email.text)[1];
console.log(regCode);
});
});
});
The solution I implemented was using mailcatcher API, if you scroll down a bit you'll find the following about the API:
A fairly RESTful URL schema means you can download a list of messages
in JSON from /messages, each message's metadata with
/messages/:id.json, and then the pertinent parts with
/messages/:id.html and /messages/:id.plain for the default HTML and
plain text version, /messages/:id/:cid for individual attachments by
CID, or the whole message with /messages/:id.source.
So we first fetched the whole json response, parse it and fetch the latest email id:
// Returns the last email id
function(emails, user) {
var email, recipient;
for(var i = emails.length - 1; i >= 0; i--) {
email = emails[i];
for(var j = 0; j < email.recipients.length ; j++) {
recipient = email.recipients[j];
if(recipient == "<"+user+">") {
return email.id;
}
}
}
};
using that email id we can get the body of the email by hitting /messages/:id.plain(of course there are more variants like fetching the email source code or email rendered html, we only needed the message) then we can just parse the body to fetch what we want, following is the code:
browser.driver.get(mailcatcherUrl+"/messages");
browser.driver.findElement(by.tagName('body')).getText().then(function(response) {
var emails, lastEmailId, partialTokens ;
emails = JSON.parse(response);
lastEmailId = getLastEmailId(emails, user);
browser.driver.get(mailcatcherUrl+"/messages/"+lastEmailId+".plain");
browser.driver.findElement(by.tagName('body')).getText().then(function(lastEmail) {
// use latestEmail to get what you want.
});
});
And Cheers!
I had to do the same thing but the mail testing server we were using did not have imap support.
So in case anyone runs into the same issue, I achieved a similar solution as alecxe using mailpop3 npm library.
The thing with the pop3 client, however, was that it doesn't act as a listener so we had to define a helper function that would connect, login and fetch the latest email when we needed to test the latest email.
Something like this:
function getLastEmail() {
var deferred = protractor.promise.defer();
var POP3Client = require("mailpop3");
var client = new POP3Client(port, host, {
tlserrs: false,
enabletls: true,
debug: false
});
client.on("connect", function() {
console.log("CONNECT success");
client.login(username, password);
});
client.on("login", function(status, rawdata) {
if (status) {
console.log("LOGIN/PASS success");
client.retr(1);
} else {
console.log("LOGIN/PASS failed");
client.quit();
}
});
client.on("retr", function(status, msgnumber, data, rawdata) {
if (status === true) {
console.log("RETR success for msgnumber " + msgnumber);
deferred.fulfill(data);
} else {
console.log("RETR failed for msgnumber " + msgnumber);
}
client.quit();
});
return deferred.promise;
}