Obj C - I can't find the user location via the Facebook Graph API - objective-c

I'm building a iOS app with a Facebook login via the Facebook Graph API. So far the login works perfectly and I receive the users profile. I'm trying to display the location (place of residence, not his current location) of the user but can't seem to find it in the user data I get when the user is logging in.
This is the JSON I receive:
{
email = "";
"favorite_athletes" = (
{
id = 308994352528078;
name = "Belgian Falcon F16 Racing Team";
}
);
"first_name" = Bastiaan;
gender = male;
id = 10153090459134040;
"last_name" = Andriessen;
link = "https://www.facebook.com/app_scoped_user_id/10153090459134040/";
locale = "en_US";
name = "Bastiaan Andriessen";
timezone = 1;
"updated_time" = "2014-11-28T13:10:46+0000";
verified = 1;
}
The Facebook Docs says it does send the location with the profile but I as you can see I don't find it in the JSON:
https://developers.facebook.com/docs/reference/ios/current/protocol/FBGraphUser/
Does someone know how I could solve this?

Related

Using telebot register_next_step_handler structure I get error with mixed users' data

I want to get user's nickname and after that to get user's screenshot. Than all the data will be send to Google Sheet. But I have the problem. When multiple users(at least 2) are using bot at the same time, their data are mixed up. For example first user's nickname is second user's nickname or first user's id is second user's id. Can I make a unique user session to store data in unique user class. It means for each user it will be created their own user class. Here is the code:
#bot.message_handler(commands=['start'])
def send_hello(message):
bot.send_message(message.chat.id, "Hi! Let`s start verification.")
msg = bot.send_message(message.chat.id, "Enter your nickname:")
bot.register_next_step_handler(msg, process_nickname)
def process_nickname(message):
user.name=message.text
user.id=message.from_user.id
msg = bot.send_message(message.chat.id, 'Super! Now send screenshot:')
bot.register_next_step_handler(msg, process_screenshot)
def process_screenshot(message):
fileID = message.photo[-1].file_id
file = bot.get_file(fileID)
file_path=file.file_path
metadata = {
'name': user.name,
'parents':[folder_id]
}
url=(f"https://api.telegram.org/file/bot{token}/{file_path}")
response = requests.get(url)
image_data = BytesIO(response.content)
media=MediaIoBaseUpload(image_data, 'image/jpeg')
serviceDrive.files().create(body=metadata,media_body=media,fields='id').execute()

Google API for getting maximum number of licenses in a Google Apps domain

I have a Google Apps Script function used for setting up accounts for new employees in our Google Apps domain.
The first thing it does is makes calls to the Google Admin Settings API and retrieves the currentNumberOfUsers and maximumNumberOfUsers, so it can see if there are available seats (otherwise a subsequent step where the user is created using the Admin SDK Directory API would fail).
It's been working fine until recently when our domain had to migrate from Postini to Google Vault for email archiving.
Before the migration, when creating a Google Apps user using the Admin SDK Directory API, it would increment the currentNumberOfUsers by 1 and the new user account user would automatically have access to all Google Apps services.
Now after the migration, when creating a Google Apps user, they aren't automatically assigned a "license," so I modified my script to use the Enterprise License Manager API and now it assigns a "Google-Apps-For-Business" license. That works fine.
However, the currentNumberOfUsers is now different from the number of assigned licenses, and "Google-Apps-For-Business" is only one of several different types of licenses available.
I can get the current number of assigned "Google-Apps-For-Business" licenses by running this:
var currentXml = AdminLicenseManager.LicenseAssignments.listForProductAndSku('Google-Apps', 'Google-Apps-For-Business', 'domain.com', {maxResults: 1000});
var current = currentXml.items.toString().match(/\/sku\/Google-Apps-For-Business\/user\//g).length;
But the number that produces is different from currentNumberOfUsers.
All I really need to do now is get the maximum number of owned "Google-Apps-For-Business" licenses so the new employee setup script can determine whether there are any available.
I checked the API Reference documentation for the following APIs but...
Enterprise License Manager API → Doesn't have a method for getting the maximum or available number of licenses.
Google Admin Settings API → Doesn't deal with licenses, only "users."
Admin SDK Directory API User resource → Doesn't deal with licenses.
Google Apps Reseller API → This API seems to have what I need, but it's only for Reseller accounts.
I know I can program my new employee setup script to just have a try/catch seeing if it would be able to create the user and assign the license, and end the script execution gracefully if it can't, but that doesn't seem efficient.
Also, part of the old script was that if there were less than X seats available, it would email me a heads-up to order more. I can program a loop that attempts to repeatedly create dummy users and assign them licenses and count the number of times it can do that before it fails, then delete all the dummy users, but, once again, that's not efficient at all.
Any ideas?
Update 3/11/2020: Since the Admin Settings API had shut down a few years ago I've been using the Enterprise License Manager API to get the current number of used licenses, like this:
function getCurrentNumberOfUsedGoogleLicenses(skuId) {
var success = false, error = null, count = 0;
var adminEmail = 'admin#domain.com';
var gSuiteDomain = adminEmail.split('#')[1];
// for more information on the domain-wide delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
// the getDomainWideDelegationService() function uses this:
// https://github.com/gsuitedevs/apps-script-oauth2
var service = getDomainWideDelegationService('EnterpriseLicenseManager: ', 'https://www.googleapis.com/auth/apps.licensing', adminEmail);
if (skuId == 'Google-Apps-Unlimited') var productId = 'Google-Apps';
else return { success: success, error: "Unsupported skuId", count: count };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.method = "GET";
requestBody.muteHttpExceptions = false;
var data, pageToken, pageTokenString;
var maxAttempts = 5;
var currentAttempts = 0;
var pauseBetweenAttemptsSeconds = 3;
loopThroughPages:
do {
if (typeof pageToken === 'undefined') pageTokenString = "";
else pageTokenString = "&pageToken=" + encodeURIComponent(pageToken);
var url = 'https://www.googleapis.com/apps/licensing/v1/product/' + productId + '/sku/' + skuId + '/users?maxResults=1000&customerId=' + gSuiteDomain + pageTokenString;
try {
currentAttempts++;
var response = UrlFetchApp.fetch(url, requestBody);
var result = JSON.parse(response.getContentText());
if (result.items) {
var licenseAssignments = result.items;
var licenseAssignmentsString = '';
for (var i = 0; i < licenseAssignments.length; i++) {
licenseAssignmentsString += JSON.stringify(licenseAssignments[i]);
}
if (skuId == 'Google-Apps-Unlimited') count += licenseAssignmentsString.match(/\/sku\/Google-Apps-Unlimited\/user\//g).length;
currentAttempts = 0; // reset currentAttempts before the next page
}
} catch(e) {
error = "Error: " + e.message;
if (currentAttempts >= maxAttempts) {
error = 'Exceeded ' + maxAttempts + ' attempts to get license count: ' + error;
break loopThroughPages;
}
} // end of try catch
if (result) pageToken = result.nextPageToken;
} while (pageToken);
if (!error) success = true;
return { success: success, error: error, count: count };
}
However, there still does not appear to be a way to get the maximum number available to the domain using this API.
Use CustomerUsageReports.
jay0lee is kind enough to provide the GAM source code in Python. I crudely modified the doGetCustomerInfo() function into Apps Script thusly:
function getNumberOfLicenses() {
var tryDate = new Date();
var dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
while (true) {
try {
var response = AdminReports.CustomerUsageReports.get(dateString,{parameters : "accounts:gsuite_basic_total_licenses,accounts:gsuite_basic_used_licenses"});
break;
} catch(e) {
//Logger.log(e.warnings.toString());
tryDate.setDate(tryDate.getDate()-1);
dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
continue;
}
};
var availLicenseCount = response.usageReports[0].parameters[0].intValue;
var usedLicenseCount = response.usageReports[0].parameters[1].intValue;
Logger.log("Available licenses:" + availLicenseCount.toString());
Logger.log("Used licenses:" + usedLicenseCount.toString());
return availLicenseCount;
}
I would recommend exploring GAM which is a tool that gives command line access to the administration functions of your domain.

auth url doesn't work in yahoo

I am doing login with yahoo from my site.
I used the code given from https://github.com/yahoo/yos-social-php
snippet of sample code:
$hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);
if($hasSession == FALSE) {
// create the callback url,
$callback = YahooUtil::current_url()."?in_popup";
$sessionStore = new NativeSessionStore();
$auth_url = YahooSession::createAuthorizationUrl(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $callback, $sessionStore);
}
here the $auth_url gives empty value. its return null. Also I given correct consumer-key, secret-key and app-id.
You have to replace your current Yahoo Api library with the below github branch.
https://github.com/syamvilakudy/yos-social-php

Retrieving email-id from database and send mail to them

In yii i am creating sendemail functionality. I am using mailer extension and its working correctly after making all settings of SMTP. i had made method actionEmail in controller as-
public function actionEmail()
{
$model=new User;
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "abc#gmail.com";
$mailer->Password = "abc";
$mailer->From = "xyz#gmail.com";
$mailer->FromName = "Balaee.com";
$mailer->AddAddress('shilpa.kirad#shailani.com');
$mailer->Subject = "welcome to Balaee";
$mailer->IsHTML(true);
// $html = $this->renderPartial('myview',array('content'=>'Hello World'),true);
$mailer->Body = "Welcomeclick on link for other detail ".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {
echo "Please check mail";
//Yii::app()->user->setFlash('register','Thank you for contacting us. We will respond to you as soon as possible.');
// $this->refresh();
}
else {
echo "Fail to send your message!";
}
}
This method is implementing correctly.It is sending mail to address which is mentioned in mailer->AddAdress.But now i want to retrive email id's from database corresponding to specific user's id and send mail to him. i.e.I dont want to insert hard coded value for this field. So how can i do this. Please help me.
for fetch use id of user to get email address as
$user_model=User::model()->findByPk($id);
and set in email as
$mailer->AddAddress($user_model->email_id);
where id and email_id are the table column name.
check other ways .
http://www.yiiframework.com/doc/guide/1.1/en/database.dao
For this to be done, you can fetch email id from database using following query:
$email = SELECT email FROM USER WHERE user_id = "X";
Here X is user_id of user whom you want to send email.
And provide this $email in the receipient's email field. Thanks.

Error creating SalesForce users LICENSE_LIMIT_EXCEEDED:License Limit Exceeded

I want to create 5-6 SalesForce users programmatically in one go by using SOAP API. I am using Partner API and I have a Developer edition sandbox. I am retrieving users information from a database table and then by using API I want to create these 5-6 users at once. I can create one user however after creating another user it is throwing error LICENSE_LIMIT_EXCEEDED:License Limit Exceeded.
This is snapshot of my code which retrieves users information from database and then creates a user programmatically:
SObject user = new SObject();
user.setType("User");
while (rs.next()) {
user.setField("Alias", rs.getString("Alias"));
user.setField("Email", rs.getString("Email"));
user.setField("EmailEncodingKey", rs.getString("EmailEncodingKey"));
user.setField("LanguageLocaleKey", "En_US");
user.setField("LastName", rs.getString("LastName"));
user.setField("LocaleSidKey", rs.getString("LocaleSidKey"));
user.setField("TimeZoneSidKey", "America/Los_Angeles");
user.setField("Username", rs.getString("Username"));
user.setField("UserPermissionsCallCenterAutoLogin", "false");
user.setField("UserPermissionsMarketingUser", "false");
user.setField("UserPermissionsOfflineUser", "false");
user.setField("ProfileId", connection.getUserInfo().getProfileId());
SaveResult[] results = connection.create(new SObject[] { user });
System.out.println("Created user: " + results[0].getId());
if (results[0].isSuccess())
out.println("Created user: " + results[0].getId());
else
out.println("Error: " + results[0].getErrors()[0].getStatusCode() +
":" + results[0].getErrors()[0].getMessage());
}
QueryResult queryResults = connection
.query("SELECT Id, Name from User "
+ "ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
out.println("Id: " + s.getField("Id") + " - Name: "
+ s.getField("Name"));
}
}
Here I can create one user however after creating one user it is throwing error LICENSE_LIMIT_EXCEEDED:License Limit Exceeded.
These are the number of licenses available:
I can see that licenses remaining for SalesForce is 0. However, I just want to create some users that don't necessarily have to be SalesForce users. It can be any type of users which just should be able to login to my org. When I am trying to create some different type of users such as 'Chatter Free' which has 5000 licences by using user.setField("UserType", "CsnOnly") it is giving error INVALID_FIELD_FOR_INSERT_UPDATE:Unable to create/update fields: UserType
These are users in my SalesForce:
How to solve this problem? I just want to create some users from database which can then login to SalesForce. Its not necessary that they should be administrators. They can have minimum privileges but they should be able to login to SalesForce.
In a developer org, you won't be able to have more than two active users with Salesforce licenses. In order to create a user with a Chatter Free license, you should only need to assign them the profile of Chatter Free User - it will automatically set their license correctly based on the profile assigned to them (the UserType field is not editable).
Edit: to obtain the Chatter Free User's profile Id without hardcoding it (as it may change from org to org), you'll have to query it. I modified your code to include this query, as well as reworked it so that only a single callout to PartnerConnection.create is made (just a suggestion, as it will save overhead on your SOAP callouts):
QueryResult profileQuery = connection.query("select Id from Profile where Name = 'Chatter Free User' limit 1");
SObject chatterFreeProfile;
if ( profileQuery.getSize() > 0 ) {
chatterFreeProfile = profileQuery.getRecords()[0];
}
ArrayList<SObject> users = new ArrayList<SObject>();
while (rs.next()) {
SObject user = new SObject();
user.setType("User");
user.setField("Alias", rs.getString("Alias"));
user.setField("Email", rs.getString("Email"));
user.setField("EmailEncodingKey", rs.getString("EmailEncodingKey"));
user.setField("LanguageLocaleKey", "En_US");
user.setField("LastName", rs.getString("LastName"));
user.setField("LocaleSidKey", rs.getString("LocaleSidKey"));
user.setField("TimeZoneSidKey", "America/Los_Angeles");
user.setField("Username", rs.getString("Username"));
user.setField("UserPermissionsCallCenterAutoLogin", "false");
user.setField("UserPermissionsMarketingUser", "false");
user.setField("UserPermissionsOfflineUser", "false");
if ( chatterFreeProfile != null )
user.setField("ProfileId", chatterFreeProfile.getField("Id"));
else
user.setField("ProfileId", connection.getUserInfo().getProfileId());
users.add(user);
}
if ( users.size() > 0 ) {
SaveResult[] results = connection.create(users.toArray(new SObject[users.size()]));
for ( int i = 0; i < saveResults.length; i++ ) {
if (results[i].isSuccess())
out.println("Created user: " + results[i].getId());
else
out.println("Error: " + results[i].getErrors()[0].getStatusCode() + ":" + results[i].getErrors()[0].getMessage());
}
}
QueryResult queryResults = connection.query("SELECT Id, Name from User ORDER BY CreatedDate DESC LIMIT 5");
if ( queryResults.getSize() > 0 ) {
for ( SObject s : queryResults.getRecords() ) {
out.println("Id: " + s.getField("Id") + " - Name: " + s.getField("Name"));
}
}
You need to set ProfileId to a Profile associated with an available License Type, in your case to a Profile on the Chatter Free, Salesforce Platform, or one of your other available license types. Each Profile is tied to a particular UserLicense record, for example:
'SFDC' : Full Salesforce license
'CSN_User' : Chatter Free license
'AUL' : Salesforce Platform license
(To see more, do a Query All on the UserLicense object).
So you'll need to query for Profile records on available license types, and then associate this to your new users, e.g.
QueryResult profileQuery = connection.query(
"SELECT Id FROM Profile "
+ "WHERE UserLicense.Name = 'Chatter Free' LIMIT 1"
);
SObject chatterFreeProfile;
if ( profileQuery.getSize() > 0 ) {
chatterFreeProfile = profileQuery.getRecords()[0];
user.setField("ProfileId", chatterFreeProfile.getField("Id"));
}