Fetch all emails across all Gmail contact groups - javascript

I am trying to fetch all the emails from the user contacts using JS library.
Setup
1.) Initialised the gapi client using
gapi.client.init({
apiKey: config['google']['apiKey'],
discoveryDocs:
["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"],
clientId: config['google']['appId'],
scope: "https://www.googleapis.com/auth/contacts.readonly"
})
2.) After the user grants permission, I try to fetch the contact details
gapi.client.people.people.connections.list({
'resourceName': 'people/me',
'pageSize': 500,
'personFields': 'names,emailAddresses'
}).then((response) => {
let connections = response.result.connections;
console.warn(connections);
})
3.) From step 2, I get zero connections.
However, when I perform
gapi.client.people.contactGroups.list()
I get following response
{
"contactGroups": [
{
"resourceName": "contactGroups/all",
"groupType": "SYSTEM_CONTACT_GROUP",
"name": "all",
"formattedName": "All Contacts",
"memberCount": 13
},
...
],
"totalItems": 9,
"nextSyncToken": "EJjRiq3lnNYC"
}
From the response, I can see that in contactGroups/all group, I have 13 contacts and in my account i can see the same number of contacts.
So, what is the proper way to get all the contacts across all the contact groups using JS library?

I've tried using gapi.client.people.people.connections.list and successfully got 200 response. I also don't get equal values.
Using gapi.client.people.people.connections.list, here is the response:
....
],
"nextSyncToken": "^***",
"totalPeople": 19,
"totalItems": 19
}
While in gapi.client.people.contactGroups.list(),
{
"resourceName": "contactGroups/all",
"groupType": "SYSTEM_CONTACT_GROUP",
"name": "all",
"formattedName": "All Contacts",
"memberCount": 155
},
Be noted that people.connections.list only provides a list of the authenticated user's contacts merged with any connected profiles. While contactGroups.list lists all contact groups owned by the authenticated user. Members of the contact groups are not populated.

Related

How to access data ID in fIrebase

I am working with Firebase Firestore using Nuxt js and I want to retrieve data from my database. I am using firebase with NuxtFirebase, the official plugin for firebase.
I need to access the ID property from my firebase database
Here is my store
const actions = {
// The Post list API
async postList({ commit }) {
try {
const req = await this.$fire.firestore.collection('Post').get()
const posts = req.docs.map((doc) => doc.data());
console.log(posts)
commit("SET_POST", posts)
} catch (e) {
console.log(e)
}
}
};
export default {
state,
getters,
mutations,
actions,
}
Looking at my console I get the following data
[
{
"title": "Bitcoin is the Detector of Imbeciles",
"created_at": {
"seconds": 1672921367,
"nanoseconds": 80000000
},
"featured_image": "https://firebasestorage.googleapis.com/v0/b/newsly-df76d.appspot.com/o/photo-1565402170291-8491f14678db.jpg?alt=media&token=535d7444-15ad-4f28-af8b-4e3918794c86",
"content": "Last year, 2022 was not of much respite for cryptocurrencies. While bitcoin has lost more than 60% of its value, the entire sector is in crisis, punctuated by various bankruptcies such as those of Terra and FTX.",
"tag": "Business"
},
{
"featured_image": "https://firebasestorage.googleapis.com/v0/b/newsly-df76d.appspot.com/o/photo-1519311965067-36d3e5f33d39.jpg?alt=media&token=4d49b9db-ec6b-4443-81a1-c52bc71bbd06",
"title": "How senior product managers think differently",
"created_at": {
"seconds": 1672921319,
"nanoseconds": 639000000
},
"content": "I often got asked how a product manager could get promoted to a more senior level. The truth is, getting a promotion is often a complicated game. Yes, your skills and achievements play a role, but so do other factors such as how much your manager cares about developing talents, how good and tenured your peers are, how political the company is, etc.",
"tag": "Business"
},
{
"content": "ChatGPT is blowing up. Twitter is inundated with screenshots of the app, coding sites like Stack Overflow are already banning answers produced with it, and over 1 million people have played with it. It’s a sensation. As a professional AI researcher, I wouldn’t have called that. ChatGPT is trained specifically to act as a chat bot, but fundamentally it’s using the same GPT-3 technology that’s been available for over two years now.",
"created_at": {
"seconds": 1672921101,
"nanoseconds": 807000000
},
"title": "ChatGPT Is Having a Thomas Edison Moment",
"tag": "Technology",
"featured_image": "https://firebasestorage.googleapis.com/v0/b/newsly-df76d.appspot.com/o/istockphoto-178586669-170667a.jpg?alt=media&token=f8c15944-080b-40f7-a926-589a8ff07bb4"
}
]
I need to access the ID
The req is a QuerySnapshot and every doc in the map is a QueryDocumentSnapshot that has id property. Try:
const posts = req.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
console.log(posts)

Teams botframework send proactive message REST api

I Try to create new converation and send proactive message with teams bot (botfreamwork).
I used this document to do that.
I POST to : SERVICE_URL/v3/conversations/
BODY:
{
"bot": {
"id": BOT_ID
},
"members": [
{
"id": USER_ID
}
],
"channelData": {
"tenant": {
"id": TENANT_ID
}
}
}
BOT_ID - I put the app id of the bot (with a prefix of "28:")
USERֹ_ID - I copied the USER_ID from a message I received from the user (not in a proactive message)
TENANT_ID - I took the tenant id from the link of the teams
I get this error:
{
"error": {
"code": "BadSyntax",
"message": "Invalid user identity in provided tenant"
}
}
I made several attempts to change the user ID: I changed to a user that appears in ADD, I changed with a prefix of 29: and without a prefix of 29: - nothing helped, this error continues to appear.
What am I missing?

Publish and Subscribe do not work correctly

Publish and Subscribe did not work. Please find the solution as an answer down below.
Initial question:
I am trying to publish the facebook first_name which is automatically retrieved when logging in with the accounts facebook package in Meteor (stored in the user collection under services.facebook). I have autopublish and insecure removed.
What I have tried so far looks like this:
Server side
Meteor.publish("facebook_name", function() {
return Meteor.users.find({_id: this.userId},
{fields: {'services.facebook.first_name' : true} });
});
Client side
Meteor.subscribe('facebook_name');
What I am using in my template to display it is this
<div class="Name"><p>{{currentUser.services.facebook.first_name}}</p></div>
Before removing autopublish the name showed up in the template.
Found the solution to my problem:
When setting up your meteor project in your client/main.js it will show import './main.html'; if you are working with routing and templates and not the main.html template this will prevent publish and subscribe to work correctly.
When user is logged in via facebook oauth API and the authentication was implemented using meteor accounts-facebook, then all needed data is stored in current user object ( Meteor.user() ).
So, the schema of user in your case looks similar to this:
{
"_id": "Ap85ac4r6Xe3paeAh",
"createdAt": "2015-12-10T22:29:46.854Z",
"services": {
"facebook": {
"accessToken": "XXX",
"expiresAt": 1454970581716,
"id": "XXX",
"email": "ada#lovelace.com",
"name": "Ada Lovelace",
"first_name": "Ada",
"last_name": "Lovelace",
"link": "https://www.facebook.com/app_scoped_user_id/XXX/",
"gender": "female",
"locale": "en_US",
"age_range": {
"min": 21
}
},
"resume": {
"loginTokens": [
{
"when": "2015-12-10T22:29:46.858Z",
"hashedToken": "XXX"
}
]
}
},
"profile": {
"name": "Sashko Stubailo"
}
}
Thus, if you want to retrieve a name of a user, all you need to do is to publish current user to a client and then get username from user object.
// server
Meteor.publish("userData", function () {
return Meteor.users.find({_id: this.userId});
});
// client
Meteor.subscribe("userData");
Template.templateName.helpers({
// this function returns username
Username : function(){
// if user is logged in using facebook; otherwise user is logged in using password
if (Meteor.user().profile.name)
return Meteor.user().profile.name;
else
return Meteor.user().username;
}
Now you can display a name of a user in your view: {{Username}}
Here is more info...

Redirection after the login succeeds or fails in loopback framework

I have recently started with loopback framework and made a simple login functionality by creating a 'customer' model inheriting from base 'User' like this:
CUSTOMER.JSON
{
"name": "customer",
"base": "User",
"idInjection": true,
"properties": {
"email":{
"type":"string",
"required":false
},
"username":{
"type":"string",
"required":false
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
CUSTOMER.JS
module.exports = function(customer){
}
I then made a entry in model-config.json like this:
"customer": {
"dataSource": "mango-database",
"public": true
}
And yes I was able to login and logout easily. I have a login screen with fields username and password. I submit this form to customers/login and as soon as it gets the login, I get a screen:
{
id: "lvrTjKBKXCFPTMFej6AyegQUFYe5mSc1BiYbROZwCBM0jqae7kZ7v8ZfGujfDGgy",
ttl: 1209600,
created: "2014-12-07T08:12:17.572Z",
userId: "5483e88b5e9cf2fe0c64dd6c"
}
Now I want that instead of this screen, I should be able to redirect user to some other page (dashboard) and if the login fails, it should go back to the login screen.
I googled up a lot on this and all i found was the suggestions to use hooks. But hooks doesn't have such event. Where do I write the redirection functionality? My guess is CUSTOMER.JS
I found the documentation quiet confusing !
Use context.res provided in a remote hook. For example:
Customer.afterRemote('create', function(context, customer, next) {
var res = context.res; //this is the same response object you get in Express
res.send('hello world');
})
Basically, you have access to request and response objects, so just respond as you would in Express. See http://expressjs.com/4x/api.html for more info.

how to check if database needs auth or not

I'm working on a project which allows user to login to a mongodb database. Basically I have
db.authenticate(username, password, function(err, isAuthPass) {...}
to check if the user pass the authentication. However, sometimes the server doesn't need authentication. If I provide username/password, it will fail. So I need to know how to check auth mode with mongo-native-client. Any idea?
Well I suppose you could just interrogate the database for the config information. This does come with the caveat that you should also be using the "test/fail" methods as discussed before as you would not be able to get this information from a server with authentication enabled that is not running on localhost:
var mongo = require('mongodb'),
MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://localhost:30000/test',function(err,db) {
var adminDb = db.admin();
adminDb.command({ "getCmdLineOpts": 1 },function(err,result) {
console.log( JSON.stringify( result, undefined, 4 ) );
});
});
That shows the "parsed" options, and it does not matter whether they are actually sent from the command line or picked up from a config file as the output here suggests:
{
"documents": [
{
"argv": [
"mongod",
"--config",
"mongod.conf"
],
"parsed": {
"config": "mongod.conf",
"net": {
"bindIp": "0.0.0.0",
"port": 30000
},
"security": {
"authorization": "enabled"
},
"storage": {
"dbPath": "data"
},
"systemLog": {
"destination": "file",
"logAppend": true,
"path": "log/mongod.log"
}
},
"ok": 1
}
],
"index": 338,
"messageLength": 338,
"requestId": 25,
"responseTo": 3,
"responseFlag": 8,
"cursorId": "0",
"startingFrom": 0,
"numberReturned": 1
}
So here the presence of "security.authorization.enabled": true tells you that further operations are going to require authorized credentials to be supplied.
Also see getCmdLineOpts and other diagnostic information commands that should be useful for your tool.
Sometimes? always use a password. and if you don't need one, like your local environment, you should use a config file for that environment like ./config/dev.js which has the credentials for that environment.

Categories

Resources