Youtube Live API get game information - java

I would like to integrate with the youtube livestream api.
I noticed that many live streams on youtube show the game the streamer is currently playing when their stream is open in the browser. however, when looking at the api documentation, it seems that this information is missing.
Looking at other similar apis from streaming companies such as the Twitch and Mixer, this data is retrievable. I was hoping that someone could point me in the direction of how i can find it when dealing with youtube, or how i can put in a request to get this information added as i feel it would make the api more complete.
Here is a code example that illustrates what i am trying to do:
// This OAuth 2.0 access scope allows for read-only access to the
// authenticated user's account, but not other types of account access.
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "listbroadcasts");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
.setApplicationName("youtube-cmdline-listbroadcasts-sample").build();
// Create a request to list broadcasts.
YouTube.LiveBroadcasts.List liveBroadcastRequest =
youtube.liveBroadcasts().list("id,snippet");
// Indicate that the API response should not filter broadcasts
// based on their type or status.
liveBroadcastRequest.setBroadcastType("all").setBroadcastStatus("all");
// Execute the API request and return the list of broadcasts.
LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
List<LiveBroadcast> returnedList = returnedListResponse.getItems();
// TODO: Get the name of the game the broadcasts are associated with
}
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
As you can see, the TODO in the snippet above highlights what I am trying to do.
To make it more clear, here is an example of a broadcast in the browser. Please make note that it displays the name of the game "Fortnite":
https://imgur.com/a/xzMim6v

Related

Get Member details using Java in Microsoft Bot Framework SDK

I am currently working on delivering 1:1 messages to the users in Teams.
Problem Statement: I am having trouble trying to get the member details to populate the Channel Account to set the ConverstationParameters object to create conversation if the user is not part of a team. Is there a way I could get the details of the user without having the user part of a Team. I wasn't able to find any reference documentation to how to get this information for Java.
Below is my code snippet:
Setup credentials and initialize a connection using Connector Client.
Populate Channel account with recipient details for set members on Conversation Parameters Object.
Activity message = MessageFactory.text("Hello World");
MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appClientID, appClientSecret);
try (ConnectorClient client = new RestConnectorClient(serviceUrl, credentials)) {
logger.info("** Connector Client Set: {} **", client);
ConversationParameters conversationParameters = new ConversationParameters();
conversationParameters.setIsGroup(false);
CompletableFuture<ChannelAccount> user = ((Conversations) client.getConversations())
.getConversationMember(recipient, teamsInternalId); // Don't want to use this because the user has to be part of the same team which is not true in our case.
logger.info("** Aysnc get User details call **");
logger.info("** AAID: {} **", user.get().getAadObjectId());
try {
conversationParameters.setMembers(Collections.singletonList(user.get()));
} catch (ErrorResponseException e) {
logger.error("** User Error : {}**", e.getMessage());
}
conversationParameters.setTenantId(tenantId);
TenantInfo tenantInfo = new TenantInfo(tenantId);
TeamsChannelData channelData = new TeamsChannelData();
channelData.setTenant(tenantInfo);
conversationParameters.setChannelData(channelData);
CompletableFuture<ConversationResourceResponse> conversationResourceResponse = new CompletableFuture<ConversationResourceResponse>();
try {
conversationResourceResponse = client.getConversations()
.createConversation(conversationParameters);
logger.info("** Create Conversation: {} **", conversationResourceResponse.get().getId());
} catch (ErrorResponseException e) {
logger.error("** Create Conversation : {} **", e.getMessage());
}
CompletableFuture<ResourceResponse> response = client.getConversations()
.sendToConversation(conversationResourceResponse.get().getId(), message);
logger.info("** Send Conversation **", response.get().getId());
I solved the above requirement following these steps:
Check if my app is installed for the user using Graph API.
If not installed, force install the app for the user using Graph API.
Then retrieve the conversation chat id.
Use this chat id to send the message to the user.
There steps are outline here on the MSFT reference page:
https://learn.microsoft.com/en-us/microsoftteams/platform/graph-api/proactive-bots-and-messages/graph-proactive-bots-and-messages?tabs=dotnet
I hope this answer helps anyone in the same boat who would like to send messages directly 1:1 from an app to a Teams user without any mutual Team condition.

How do I create an Alfresco site programmatically from a repository webscript?

I've implemented an Alfresco repository webscript (in Java) to programmatically create a new site.
I notice that there's a SiteService interface which I thought could be used to do this -
SiteInfo site = siteService.createSite("site-dashboard", "mySite",
"mySite", "", SiteVisibility.PUBLIC);
However, this results in the creation of a non-functional site, and although it's visible within the Alfresco Share dashboard, I'm not able to use it.
I then came across this code sample, which is doing exactly what I want. BUT the code includes a section to do authentication, involving sending the user's login and password details to a dologin web service. Don't really want to do this.
But as the user has already logged in via Alfresco Share, they should already be authenticated.
If I call the create-site webscript from my code, as shown in the example (without the initial call to dologin), I'm getting a 401 (unauthorised) return code.
So my question is, how do I tell the create-site webscript about my authentication?
I read about using an authentication ticket here. Is this ticket stored in the session, and if so, how do I access it within my Java code? If I could get the ticket, then this would be sufficient to invoke the create-site webscript.
Update: I've added the alf_ticket parameter as suggested by the comment, but I'm still getting a 401 response.
My current code is:
public NodeRef createServiceChange(String serviceChangeName) {
HttpClient client = new HttpClient();
String ticket = authService.getCurrentTicket();
PostMethod createSitePost = new PostMethod("http://localhost:8081/share/service/modules/create-site");
JSONObject siteObject = new JSONObject();
try {
siteObject.put("shortName", serviceChangeName);
siteObject.put("visiblity", "Public");
siteObject.put("sitePreset", "site-dashboard");
siteObject.put("title", serviceChangeName);
siteObject.put("description", serviceChangeName);
siteObject.put("alf_ticket", ticket);
createSitePost.setRequestHeader("Content-Type", "application/json");
createSitePost.setRequestHeader("Accept", "application/json");
createSitePost.setRequestEntity(new StringRequestEntity(siteObject.toString(), "application/json", "UTF-8"));
int status = client.executeMethod(createSitePost);
System.out.println("create a site script status :: " + status);
if (status == HttpStatus.SC_OK) {
System.out.println("Site created OK");
}
else{
System.out.println("There is error in site creation");
}
} catch (JSONException err) {
err.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So I've managed to successfully create a site, programmatically, and here's what I did:
First, forget about writing a repository (platform) webscript. Creation of sites in Alfresco is done by invoking a Share module, so you'll need to implement either a page, or custom menu item to create a site. I was also getting a lot of problems with authentication, but if you log in to the system via Alfresco Share, and in your Javascript, use the provided Alfresco Ajax request, then authentication shouldn't be a problem.
Here are the components I used:-
Create a Share page to create your site. In the Freemarker template (.ftl) add a form to collect the site details.
Attach a button on the form to the following Javascript function. Note that I cobbled this together from various code fragments on the web, so it could use some cleaning up. But it basically works for me -
function create_site()
{
var sc_form = document.forms.namedItem('sc_form');
var name = sc_form.elements.namedItem('name').value;
var url = Alfresco.constants.URL_CONTEXT + "service/modules/create-site";
Alfresco.util.Ajax.request({
method : Alfresco.util.Ajax.POST,
url : url,
dataObj: {
sitePreset: "site-dashboard",
visibility: "PUBLIC",
title: name,
shortName: name,
description: name
},
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
}

Google Analytics Java API Filter Update error

I'm working on using the Google Analytics Management API for Filter Update. I have been trying to use this method to update my filter, but apparently it does not work.
Below is a snippet of my update code:
private static void updateFilter(Analytics analytics, String accountID) {
FilterExpression details = new FilterExpression();
details.setField("GEO_DOMAIN");
details.setMatchType("EQUAL");
details.setExpressionValue(".example.com");
details.setCaseSensitive(false);
// Construct the body of the request.
Filter body = new Filter();
body.setName("My Domain Filter");
body.setType("EXCLUDE");
body.setExcludeDetails(details);
try {
analytics.management().filters().update("<valid GA ID>", "<valid filter ID>", body).execute();
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: "
+ e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
The error code I'm getting is 400 : Field id is required. To my knowledge, everything that is required of a filter has been initialized in the method. I do not know what "Field id is required" is supposed to mean.
Thanks for any help rendered.
I cant help to much with the Java. I have done this before with C#.
When using Update everthing is updated. So it is best to do a get on the filter which returns a Filter body change that then use that as the update.
But it is even easer if you are only changing a few things to use Patch. Patch will update only what you send it instead of updating everything.

How can I pass data returned from Facebook when Request.callback onCompleted() method is called, to my fragment in Android?

I'm currently trying to integrate Facebook into my Android application. I've had no problems getting the app to connect and authenticate. But I'm having a little trouble understanding how I can handle data once the onCompleted(Response response) callback method is executed.
The method below works:
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
new Request(session, "/me", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
JSONObject data = graphObject.getInnerJSONObject();
Log.i(TAG, "My DETAILS: ");
try {
Log.i(TAG, "ID: " + data.getLong("id"));
Log.i(TAG, "Name: " + data.getString("name"));
Log.i(TAG, "Email: " + data.getString("email"));
Log.i(TAG,
"Gender: " + data.getString("gender"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
When I run my application, Facebook authenticates, the data is retrieved and successfully outputs to the Logcat window. However, I'm at a loss to understand how I can pass the JSONObject back to my fragment for further processing.
Most examples I've looked at online simply set the JSONObject content to views in the fragment, or even less helpful simply say /* Handle response here */ or something similar.
I have another similar method where I want to get a profile image url and download the image, but I can't get the url back to my fragment for further processing.
Should I do something like develop a runnable class that accepts a JSONObject as a parameter and start a separate thread from the onCompleted() method to process it the way I want?
My current goal is to get a list of the users friends who use my app and save their profile pictures for use within the app. Am I going about this the wrong way?
SO if I understand you properly, you are getting all data, you are able to parse the JSON but you are not able to pass the data to your other fragment? Why dont you write to a file, which can be accessible from anywhere?
Why do you want to "DOWNLOAD" the images, that will increase your processing time. Just use this URL: https://graph.facebook.com/"+uid.trim()+"/picture?type=normal Where uid is your users id. Use this in Conjunction with Universal Image Loader to asynchronously load your images in image view. You save your time - you save a headache of manually caching files or saving them on the SD.
But bro, the problem here is that Facebook will stop support to the API you are using by April of 2015. Start porting your app to use the latest facebook API; which however is not so useful in getting users information. Cheers and keep on coding :)

Google Drive for Android SDK Doesn't List Files

I've got a really odd problem with the Google Drive Android SDK. I've been using it for several months now, and until last week it performed perfectly. However, there is now a really odd error, which doesn't occur all the time but does 9 out of 10 times.
I'm trying to list the user's files and folders stored in a particular Google Drive folder. When I'm trying to use the method Drive.files().list().execute(), 9 out of 10 times literally nothing happens. The method just hangs, and even if I leave it for an hour, it just remains doing... nothing.
The code I'm using is below - all of this being run within the doInBackground of an AsyncTask. I've checked credentials - they are all fine, as is the app's certificate's SHA1 hash. No exceptions are thrown. Google searches have yielded nothing. Here is the particular bit of code that's bothering me:
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
SettingsActivity.this, Arrays.asList(DriveScopes.DRIVE));
if (googleAccountName != null && googleAccountName.length() > 0) {
credential.setSelectedAccountName(googleAccountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
service.files().list().execute(); // Google Drive fails here
} else {
// ...
}
} catch (final UserRecoverableAuthIOException e) {
// Authorisation Needed
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
startActivityForResult(e.getIntent(), REQUEST_AUTHORISE_GDRIVE);
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account due to Exception after trying to show the Google Drive authroise request intent, as the UserRecoverableIOException was originally thrown. Error message:\n" + e.getMessage());
}
}
});
Log.d("SettingsActivity: Google Drive", "UserRecoverableAuthIOException when trying to add Google Drive account. This is normal if this is the first time the user has tried to use Google Drive. Error message:\n" + e.getMessage());
return;
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account. Error message:\n" + e.getMessage());
return;
}
I'm using Drive API v2. Thanks everyone!
Edit
Having played around a bit more, it turns out this isn't for just listing files. Trying to interact with any file on Google Drive behaves the same way - deleting, downloading, creating... Anything! I have also noticed that putting the device in aeroplane mode so it has not internet access makes no difference either: Google Drive doesn't throw an exception, or even return, it just freezes the thread it's on.
I've updated to the very latest Drive API lib but that hasn't helped. I remembered that the error happened soon after I added the JSch SSH library to the project, so I removed that, but it made no difference. Removing and re-adding the Drive API v2 has made no difference either, and nor has cleaning the project.
Edit 2
I've found something which may be significant. On the Google Developer console, I had some Drive errors recorded as follows:
TOP ERRORS:
Requests % Requests Methods Error codes
18 38.30% drive.files.list 400
14 29.79% drive.files.insert 500
11 23.40% drive.files.update 500
4 8.51% drive.files.get 400
Do you reckon these are the errors? How could I fix them? Thanks
This is my code and it's work
new AsyncTask<Void, Void, List<File>>() {
#Override
protected List<File> doInBackground(Void... params) {
List<File> result = new ArrayList<File>();
try {
com.google.api.services.drive.Drive.Files.List list = service.files().list();
list.setQ("'" + sourcePath + "' in parents");
FileList fileList = list.execute();
result = fileList.getItems();
if(result != null) {
return result;
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<File> result) {
//This is List file from Google Drive
};
}.execute();
I've come up with a solution which does work, and thought I'd post it so others could see it if they happen to come across the problem.
Luckily, I had backed up all of the previous versions of the app. So I restored the whole project to how it was two weeks ago, copied and pasted all changes from the newer version which had been made since then, and it worked. I don't see why this should work, since the end result is the same project, but it does!
Google Drive List Files
This might help you.. Try to display it in ListView u will see all fetched folders
public void if_db_updated(Drive service)
{
try {
Files.List request = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'");
FileList files = request.execute();
for(File file : files.getItems())
{
String title = file.getTitle();
showToast(title);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});

Categories