I want to get all the uploaded photos of the logged in user that was uploaded today. I could fetch all the photos and filter it with the created_time field. But I would like to make the request to Facebook api to just send me todays photos.
This is the code I am using to get users uploaded photos
fun getAllPhotos() {
val bundle =Bundle()
bundle.putString(
"fields",
"album,alt_text,created_time,event,place,alt_text_custom,name,name_tags,target,source"
)
tempPhotos.clear()
val request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/photos/uploaded",
object : GraphRequest.Callback {
override fun onCompleted(response: GraphResponse) {
val type = object : TypeToken<ApiResponseObject>() {}.type
val respJSON = response.getJSONObject()
val item: ApiResponseObject = Gson().fromJson(respJSON.toString(), type)
item.data.forEach {
if (UtilityFunctions.checkIfToday(it.createdTime)) {
tempPhotos.add(it)
} else {
return#forEach
}
}
}
})
request.parameters = bundle
request.executeAsync()
}
As you can see I request for all photos to "/me/photos/uploaded/" I would like to only request for photos on a certain date ( or just today )
I saw that the response came sorted by created time so I returned from the loop whenever I saw some picture that was out of date.
Hey can you provide some more information regarding the issue you are facing with your code.
eg. some examples of how facebook api response structure is, some code snippets etc.
Edited response:
I crawled a while for the internet to search for your problem as it is difficult to create custom query in graph api and I have never used it before. What you are doing in your code is not bad either but if you insist on creating a custom query to api then I have found a github repository that might help you
Facebook Graph API query builder
I found the solution. I just needed to look into the pagination documentation
I found that just as fields I could also send since and a unix timestamp and it would return the photos uploaded since that timestamp
Related
eventHandler = object : IRtcEngineEventHandler() {
override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
Log.d("VideoCall1", "channel:$channel,uid:$uid,elapsed:$elapsed")
openScreen(ScreenType.VIDEO_CALL_SCREEN)
}
override fun onUserJoined(uid: Int, elapsed: Int) {
Log.d("VideoCall1", "onUserJoined:$uid")
viewModel.onUserJoined(uid)
}
override fun onUserOffline(uid: Int, reason: Int) {
Log.d("VideoCall1", "onUserOffline:$uid")
viewModel.onUserOffline(uid)
}
}
rtcEngine = RtcEngine.create(this, AppConstants.AGORA_APP_ID, eventHandler)
rtcEngine.apply {
enableVideo()
setClientRole(0)
// setChannelProfile(Constants.CHANNEL_PROFILE_COMMUNICATION)
joinChannel(token, channelName, "", userId.toInt())
}
Mobile user able to see web user but web user not able to see mobile user. Also I am getting callback of onUserJoined when web user joined channel.
I am using io.agora.rtc:full-sdk:3.5.0 and it works with
https://webdemo.agora.io/agora-web-showcase/examples/Agora-Web-Tutorial-1to1-Web/
Anyone have a suggestion or idea ?
Okay, so this took me hours of try and error to figure out a solution. I believe it's a bug in AgoraRTC but I didn't dive deep to figure out what's happening. Anyway, the hack I found goes like this:
In the Agora RTM script on the Web side, use a string uid while logging in:
this.client.login({ uid, token }); // uid had to be a string in my case
However, it says in the Agora documentation that the types of uid must match on web and mobile, since you are using int on mobile you might need to use an int on the web too, however when I tried to use an int, the login method threw an invalid uid type error!
But then again, it only worked if when joining the channel I supply the AgoraRTC client join method a null uid:
// uid (last argument) must be null
client.join(options.appid, options.channel, options.token, null);
It also works if the uid in the join function is the same uid in the login function but parsed to a number, but it doesn't if both are strings. And it also doesn't work if both are numbers, the login method throws an invalid uid variable type error...
Hope this helps anyone facing the same issue since it's a very weird error with no answers found anywhere else on the internet.
I set up a connection between Android and AWS Lambda which has the endpoint set to SageMaker. I am using the REST API during the connection, the AWS Cognito plug is set to be accessed without authorization.
I make a connection as described here:
https://aws.amazon.com/blogs/machine-learning/call-an-amazon-sagemaker-model-endpoint-using-amazon-api-gateway-and-aws-lambda/
My question is how to send this data:
{"data":"13.49,22.3,86.91,561.0,0.08752,0.07697999999999999,0.047510000000000004,0.033839999999999995,0.1809,0.057179999999999995,0.2338,1.3530000000000002,1.735,20.2,0.004455,0.013819999999999999,0.02095,0.01184,0.01641,0.001956,15.15,31.82,99.0,698.8,0.1162,0.1711,0.2282,0.1282,0.2871,0.06917000000000001"}
And how to view the received response later. Anyone know how to do it or where I can find tips on how to do it?
If I understand correctly, this is your system flow:
POST some data from your Android device
It gets received by API Gateway
And continues through to AWS Lambda
In AWS Lambda the data is extracted, and passed to Sage Maker
Creating a POST using AWS Amplify
To POST data form the Android device, follow the Amplify API (REST) category documentation.
Specifically, you can do something like:
val options = RestOptions.builder()
.addPath("/prod/predictbreastcancer")
.addBody("{\"data\":\"13.49,22.3,86.91,561.0,0.08752,0.07697999999999999,0.047510000000000004,0.033839999999999995,0.1809,0.057179999999999995,0.2338,1.3530000000000002,1.735,20.2,0.004455,0.013819999999999999,0.02095,0.01184,0.01641,0.001956,15.15,31.82,99.0,698.8,0.1162,0.1711,0.2282,0.1282,0.2871,0.06917000000000001\"}".toByteArray())
.build()
Amplify.API.post(options,
{ Log.i("Demo", "POST response = $it") },
{ Log.e("Demo", "POST failed", it) }
)
Creating POST body from EditText content
You mentioned you're using an EditText widget to gather the input data. I assume a user can enter a comma-separated list of values like 0.44, 6.11, etc.
To extract it's content and build the POST body, you can do:
val input = findViewById(R.id.input) as EditText
val body = JSONObject()
.put("data", input.text)
.toString()
.replaceAll("\"", "\\\"")
Displaying response in another Activity
Skimming the blog you referenced, I can't see an example of the response body content. But, here's how you can retrieve response JSON and pass it to a new activity.
Amplify.API.post(options,
{ response ->
val intent = Intent(this, YourOtherActivity::class.java)
intent.putExtra("json", response.data.asString())
runOnUiThread { startActivity(intent) }
},
{ /* handle error ... */ }
)
In YourOtherActivity, access the extra data in onCreate() like so:
val json = intent.getStringExtra("json")
I am currently working on creating a custom authentication for a Xamarin.Android app using Azure. I have successfully created my API and it is properly returning values when submitting a raw payload using Advanced REST Client.
I am now trying to implement this on Xamarin.Android using Azure's MobileServiceClient SDK and when using the invokeApi method as demonstrated below in my code, I am getting an exception indicating that it is calling GET instead of POST. Is anyone aware of what I might be doing wrong?
ex.Message returns
"Cannot GET /api/register?username=azureAccountTest&password=testingpassword"
public async Task RegisterAsync()
{
Dictionary<string, string> user = new Dictionary<string, string>
{
{ "username", username },
{ "password", password }
};
try
{
CancellationToken ct;
var result = await client.InvokeApiAsync("register", HttpMethod.Post, user, ct);
}
catch(Exception ex)
{
var message = ex.Message;
}
}
According to your description, I tested this issue on my local side and I could retrieve the authenticationToken as follows:
You used the following method for InvokeApiAsync:
public Task<JToken> InvokeApiAsync(string apiName, HttpMethod method, IDictionary<string, string> parameters, CancellationToken cancellationToken = default(CancellationToken));
Note: It summarizes that the Additional data will sent to through the query string.
Per my understanding, you could refer to the following method for sending additional data though the HTTP content as follows:
JObject user = new JObject();
user.Add("username", "bruce");
user.Add("password", "123456");
var result = await App.MobileService.InvokeApiAsync("/.auth/login/custom", HttpMethod.Post, user, ct);
Additionally, you need to specific the mobileAppUri with https endpoint when deploy to azure side. Here is a similar issue, you could refer to here. Moreover, I would recommend you refer to adrian hall's book about Custom Authentication.
UPDATE:
Based on your comment, I checked the custom authentication and found the following note from adrian hall's book about Custom Authentication:
You must turn on Authentication / Authorization in your App Service. Set the Action to take when request is not authenticated to Allow Request (no action) and do not configure any of the supported authentication providers.
I'm developing an Android App based on Outlook-SDK-Android. The App talks with Outlook Calendar REST API to retrieve, book and delete events (see code examples here and here). Now I need to read someone else's calendar and I've been provided an Office365 account with delegate access (author permission level) towards other users.
I've registered my app using the provided account on the new portal. In my App I use the scope "https://outlook.office.com/Calendars.ReadWrite".
(The scope is used in com.microsoft.aad.adal.AuthenticationContext.acquireToken() to initialize an Office REST Client for Android OutlookClient, a shared client stack provided by orc-for-android)
When I try to read another user's calendar on which I have delegate access I just receive back a 403 response:
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again."
}
}
Any help?
Is it a limitation of the API? If so why is the following method invocation chain provided then?
outlookClient.getUsers()
.getById("meetingRoom#company.com")
.getCalendarView()
UPDATE:
It seems like there are works in progress that will allow this scenario, as reported here: Office 365 REST API - Access meeting rooms calendars
So if progress in that direction has been made can I achieve my goal without using an "admin service app"? (see Office 365 API or Azure AD Graph API - Get Someone Elses Calendar)
Can I use basic authentication as suggested here?
Calendar delegation is a feature of Exchange, the Graph API and Outlook API do not allow the user to access the delegated calendar.
Currently, the alternative workaround could be use the EWS. And here is an sample for your reference:
static void DelegateAccessSearchWithFilter(ExchangeService service, SearchFilter filter)
{
// Limit the result set to 10 items.
ItemView view = new ItemView(10);
view.PropertySet = new PropertySet(ItemSchema.Subject,
ItemSchema.DateTimeReceived,
EmailMessageSchema.IsRead);
// Item searches do not support deep traversal.
view.Traversal = ItemTraversal.Shallow;
// Define the sort order.
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
try
{
// Call FindItems to find matching calendar items.
// The FindItems parameters must denote the mailbox owner,
// mailbox, and Calendar folder.
// This method call results in a FindItem call to EWS.
FindItemsResults<Item> results = service.FindItems(
new FolderId(WellKnownFolderName.Calendar,
"fx#msdnofficedev.onmicrosoft.com"),
filter,
view);
foreach (Item item in results.Items)
{
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Id: {0}", item.Id.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("Exception while enumerating results: { 0}", ex.Message);
}
}
private static void GetDeligateCalendar(string mailAddress, string password)
{
ExchangeService service = new ExchangeService();
service.Credentials = new WebCredentials(mailAddress, password);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl(mailAddress, RedirectionUrlValidationCallback);
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(AppointmentSchema.Subject, "Discuss the Calendar REST API"));
DelegateAccessSearchWithFilter(service, sf);
}
And if you want the Outlook and Graph API to support this feature, you can try to contact the Office developer team from link below:
https://officespdev.uservoice.com/
FindMeetingTimes is currently in preview! To view the details, use this link and then change it to view the Beta version of the article (top right in the main column): https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations#Findmeetingtimespreview
Details below from the article, but please use the link to get the latest:
Find meeting times (preview)
Find meeting time suggestions based on organizer and attendee availability, and time or location constraints.
This operation is currently in preview and available in only the beta version.
All the supported scenarios use the FindMeetingTimes action. FindMeetingTimes accepts constraints specified as parameters in the request body, and checks the free/busy status in the primary calendars of the organizer and attendees. The response includes meeting time suggestions, each of which is defined as a MeetingTimeCandidate, with attendees having on the average a confidence level of 50% chance or higher to attend.
I have an Android application with GAE server. I tried to authenticate the user as described on developers.google.com, I added the user parameter to the endpoint methods etc. I get a User which is not null, but this method getUserId() returns null. It is similar to this, rather old problem:
Function User.getUserId() in Cloud endpoint api returns null for a user object that is not null
But I still don't know how to work around it. How do you handle this error? Have you ever encountered it?
In android client here's what I did (its simplified) :
credentials = GoogleAccountCredential.usingAudience(getApplicationContext(), "server:client_id:" + WEB_CLIENT_ID);
credentials.setSelectedAccountName(accountName);
WarriorEntityEndpoint.Builder endpointBuilder = new WarriorEntityEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credentials);
warriorEntityEndpoint = endpointBuilder.build();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
warriorEntityEndpoint.getWarrior().execute();
} catch (Exception e) {
}
return null;
}
}.execute();
And on GAE:
#Api(name = "warriorEntityEndpoint", namespace = #ApiNamespace(ownerDomain = "szpyt.com", ownerName = "szpyt.com", packagePath = "mmorpg.monsters"),
version = "version1",
scopes = {"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"},
clientIds = {Constants.ANDROID_CLIENT_ID, Constants.WEB_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE})
public class WarriorEntityEndpoint {
private static final Logger log = Logger.getLogger(WarriorEntityEndpoint.class.getName());
#ApiMethod(name = "getWarrior")
public WarriorEntity getWarrior(User user) throws OAuthRequestException, IOException {
log.log(Level.SEVERE, "this gives correct email: " + user.getEmail());
log.log(Level.SEVERE, "this is null: " + user.getUserId());
I have also another very important question: is this user authenticated, if getMail() gives me correct account, but getUserId() gives null? I read that user object should be null if it was not authenticated but I am not sure any more...
I'm using App engine SDK 1.8.7. I'm testing on a real device and backend deployed to GAE.
I asked the same question a while ago and got an answer. See link:
Function User.getUserId() in Cloud endpoint api returns null for a user object that is not null
The cause is a bug on appengine.
I guess there is no good solution for it right now. I store e-mail as a normal property and remove it from default fetch group, I use long as a primary key (generated by AppEngine) and I query the entity by the e-mail property. I don't like my solution, I'll accept ( and implement :) ) a better one if anyone can provide.
This is a known issue which has been filed with google, I've attached the issue link below.
There are two workarounds (1) save the user and read back from the store, if it refers to a valid account the user id will be populated (this sucks because you pay the saving / loading / deletion cost for each API access that is authenticated even if it is tiny, and obviously some performance cost) and (2) you could use the google+ ID but that is NOT the same as the user id.
This is extremely frustrating and there is currently no ETA as they are working on some fundamental issues with the auth design as far as I understand.
Please, vote for that issue by starring it. You can find all the information here
https://code.google.com/p/googleappengine/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Component%20Status%20Stars%20Summary%20Language%20Priority%20Owner%20Log&groupby=&sort=&id=8848
And here is the current formally approved workaround [(1) above], which you can also find in the link above, but for ease it's here: How can I determine a user_id based on an email address in App Engine?
For workaround (2) mentioned above, you can look at the first link, and go to post #39.