How to make Google Contact API work with AngularJS? - javascript

I have been trying to get the data from response and add it to controller, but no luck.
Here is my previous question.
How is it done in AngularJS?

The code that I used for this is like this:
invitePeersController.getGmailContacts = function(){
console.log("I come in gmail contacts");
var clientId = "contact key";
var apiKey = "apiKey";
var scopes = "https://www.googleapis.com/auth/contacts.readonly";
authorize();
function authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult){
invitePeersController.gmailContacts = [];
var gmailData = [];
if (authorizationResult && !authorizationResult.error){
var urlContact = "https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0";
var promiseGoogleData = HttpService.httpGetExternalLink(urlContact);
promiseGoogleData.then(function (response) {
var jsonChildData = response.data.feed.entry;
for(var i=0; i<jsonChildData.length ;i++){
var item = {};
try{
var name = jsonChildData[i].title.$t;
var email = jsonChildData[i].gd$email[0].address;
if(name.substring(1, name.length-1) && email.substring(1, email.length-1)){
item ["name"] = name.substring(1, name.length-1);
item ["email"] = email.substring(1, email.length-1);
item ["id"] = email.substring(1, email.length-1).replace(/[^a-zA-Z ]/g, "");
invitePeersController.gmailContacts.push(item);
gmailData.push(item);
}
}catch(error){
console.log("Error is thrown while trying to read gmail resposne");
}
}
$state.go("app.inviteContacts");
InvitePeersService.setGmailContactsData( invitePeersController.gmailContacts);
return response;
})
.catch(function (error) {
console.log("Something went terribly wrong while trying to get Gmail Data.");
});
}
}
}
Also don't forget to add the domain names in the credentials:

Related

How to fetch email thread by messageId using IMAP in NodeJS?

I want to fetch whole reply thread using the particular messageId something like this 2a2b0f84-261c-ecd5-33bf-919548b76000#hotmail.com.
I have tried this:
const getInbox = () => {
return new Promise((resolve, reject) => {
imaps.connect(config).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['ALL'];
var fetchOptions = {
bodies: ['HEADER', 'TEXT', ''],
};
return connection.search(searchCriteria, fetchOptions).then(async function (messages) {
let promises = messages.map(item=>{
return new Promise((resolve,reject)=>{
var all = _.find(item.parts, { "which": "" })
var id = item.attributes.uid;
var idHeader = "Imap-Id: " + id + "\r\n";
simpleParser(idHeader + all.body, (err, mail) => {
resolve(mail);
});
});
});
Promise.all(promises).then(data=>{
let d = data.filter(obj=>obj.me).map(obj=>{
return {
from:obj.from.value.map(obj=>obj.address).join(','),
to:obj.to.value.map(obj=>obj.address).join(','),
subject:obj.subject,
attachments:obj.attachments,
message_id:obj.messageId,
date:obj.date
}
});
resolve(d);
})
});
});
});
}); }
I have tried this , it is returning whole inbox, I want particular message thread.
I tried this
var searchCriteria = [['HEADER','IN-REPLY-TO',messageId]];
it is working perfectly.
This line in your code means to search for all messages:
var searchCriteria = ['ALL'];
Really quite clear code, don't you agree? If you try something more like
var searchCriteria = ['OR HEADER "Message-ID" "' + id + '" HEADER "References" "' + id + '"'];
then you'll search for just the messages you want, and then you can retrieve their headers and bodies and do whatever you want.

Parse Cloud code query.withinKilometers

(Edit 1)
I'm trying to work with the cloud code and GeoPoint. With the function "query.withinKilometers" I have a pointer to the Location Class but when I try to call the function I get the error "invalid key name". What is the right way to do this? I could not find anything in the documentation, here is a file of the cloud function.
Error: "code":105,"message":"Invalid key name: [object Object]"
here de documentation: http://parseplatform.org/Parse-SDK-JS/api/v1.11.1/Parse.html
Parse.Cloud.define("getCloseFindings", function(request, response){
var query = new Parse.Query("findings");
var locQuery = query.include("location");
var LocQuery = locQuery.get("geoLocation");
var Loc_Lat = request.params.Latitude;
var Loc_Long = request.params.Longitude;
var UserLocation = new Parse.GeoPoint(Loc_Lat,Loc_Long);
var RadiusLocation = request.params.Radius;
query.equalTo("isDeleted", false);
query.withinKilometers(locQuery, UserLocation, 100);
query.find({
success: function(results){
if(results === undefined){
var response_jsonArr = {
code : 404,
message : "Not Found"
};
response.success(response_jsonArr);
}else{
var jsonArr = [];
for ( var i = 0; i < results.length; ++i ) {
var finding_location = results[i].get("location");
jsonArr.push({
name: results
});
}
response.success(jsonArr);
}
}, error: function(error){
response.error(error);
}
});
You are passing an object to query.withinKilometers as the first parameter when you should be passing a String. Try using the key from your query.include call instead, like this:
query.withinKilometers("location", userLocation, 100);

Parse : Retrieving properties from an object that is related

So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?
i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.

Parse Cloud Code save() doesn't seem to save a field

I'm trying to run save() on a retrieved _User object, but it doesn't seems to save the field I've modified ("ignoredUsers"), which is an array. Although I can see that the save actually went through, as updatedAt does change.
Here is the code:
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", userid1);
query.first({
success: function(result){
var ignored = result.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userid2);
result.set("ignoredUsers", ignored);
result.save();
}
});
function appendUser(toUser, userId) {
return toUser.fetch({
success: function(user) {
var ignored = user.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userId);
user.set("ignoredUsers", ignored);
user.save();
}
});
}
Parse.Cloud.job("ignoredUsers", function(request, status) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Conversation");
return query.each(function(conversation) {
var participants = conversation.get("participants");
var userid1 = participants[0].id;
var userid2 = participants[1].id;
var user1 = participants[0];
var user2 = participants[1];
return appendUser(user1, userid2).then(function() {
return appendUser(user2, userid1); });
});
status.success();
});
The problem was that the cloud function returned before waiting for the callbacks to finish

Updating outside variables inside a javascript function in Node.js

I am developing a NodeJS application and encountered following problem:
I am using node module node-rest-client to issue REST requests using an API. I use post method provided by the module for my purpose. I need to fetch the json response and write it to seperate variables and return them.
I have defined returnData variable outside the client.post method. I need to update this returnData variable inside the function which is passed as a parameter to the client.post method.
But I have a scope issue here. Although I try to update the returnData variable inside that function, when execution returns from client.post function, I see that the same values I have set (in this case null, but may be any value) before calling client.post function still persists in the variable.
How can I define scope well so that I can update an outside variable inside the function which I pass as a parameter to another function? Any help would be greatly appreciated.
Following is my Code:
module.exports = function(){
require("../config");
var restClient = require('node-rest-client').Client;
var client = new restClient();
var sessionID = null,
reqID = 1;
var login = function(username, password){
var requestParams = {};
var apiParams = {};
requestParams.jsonrpc = "2.0";
requestParams.method = ZABBIX_API_METHODS.login;
apiParams.user = username;
apiParams.password = password;
requestParams.params = apiParams;
requestParams.id = reqID;
requestParams.auth = null;
var args = {
data: requestParams,
headers:{"Content-Type": "application/json-rpc"} // ask response type to be application/json-rpc
};
var returnData = {};
returnData.status = null;
returnData.data = null
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
console.log(returnData.data);
});
console.log("SessionID:"+getSessionID());
return returnData;
}
var functions = {
login: login
}
return functions;
}
Thank you.
.post is Async, you should do it like this,
var login = function(username, password, callback){
..................
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
return {login: returnData};
});
//remove all below return statements

Categories

Resources