Skip to content
This repository has been archived by the owner on Oct 1, 2023. It is now read-only.

Commit

Permalink
Updating Search functionality to use YTGBSS service.
Browse files Browse the repository at this point in the history
  • Loading branch information
MarconiGRF committed Jun 22, 2020
1 parent c7fd209 commit 01e3e60
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 72 deletions.
77 changes: 52 additions & 25 deletions MainPage.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
Expand All @@ -23,6 +24,7 @@ public sealed partial class MainPage : Page
public MainPage()
{
this.search = new Search();
this.search.FinishedFetchingResults += PresentResults;
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Enabled;
}
Expand Down Expand Up @@ -53,7 +55,7 @@ private void HandlePlayButton(object sender, RoutedEventArgs eventArgs)

if (list != null && list.Count > 0)
{
SetAsMediaURL(list.ElementAt(0).VideoId);
SetAsMediaURL(list.ElementAt(0).MediaUrl);
PrepareToPlay();
}
else
Expand Down Expand Up @@ -266,6 +268,7 @@ await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
LoadingRing.IsActive = true;
inputBox.IsSuggestionListOpen = false;
ErrorMessage.Visibility = Visibility.Collapsed;
}
);
Expand Down Expand Up @@ -296,36 +299,60 @@ private async void inputBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTex
SetAsMediaURL(inputBox.Text);
PrepareToPlay();
}
else
{
await DoSearch();
}
}
else
{
if (this.inLoadingState == false)
{
this.inLoadingState = true;
RunUIUpdateByMethod(WeakLoading);
}

try
{
await this.search.ByTerm(inputBox.Text);
}
catch
{
InLoadingState(false);

ShowErrorMessage("Search is not available now, please use links.");
return;
}
await DoSearch();
}
}
}

if (this.inLoadingState == true)
{
InLoadingState(false);
}
/// <summary>
/// Does the search using the text available on inputBox.
/// </summary>
/// <returns></returns>
private async Task DoSearch()
{
if (this.inLoadingState == false)
{
this.inLoadingState = true;
RunUIUpdateByMethod(WeakLoading);
}

sender.ItemsSource = this.search.Retreive();
inputBox.IsSuggestionListOpen = true;
try
{
await this.search.ByTerm(inputBox.Text);
}
catch (Exception ex)
{
if (!(ex is NotSupportedException))
{
InLoadingState(false);
ShowErrorMessage("Search is not available now, please use links.");
}

}
}

/// <summary>
/// Presents the results on AutoSuggestBox when the results are ready.
/// This function is triggered by the Search's FinishedFetchingResults event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PresentResults(Object sender, EventArgs e)
{
if (this.inLoadingState == true)
{
InLoadingState(false);
}

inputBox.ItemsSource = this.search.Retreive();
inputBox.IsSuggestionListOpen = true;
}

/// <summary>
Expand All @@ -339,7 +366,7 @@ private void inputBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQueryS
{
InLoadingState(true);
ListItem chosenItem = (ListItem)args.ChosenSuggestion;
SetAsMediaURL("https://www.youtube.com/watch?v=" + chosenItem.VideoId);
SetAsMediaURL(chosenItem.MediaUrl);

PrepareVideoUI();
}
Expand Down
2 changes: 1 addition & 1 deletion Package.appxmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<Identity
Name="7772MarconiGomes.YoutubeGameBarOverlay"
Publisher="CN=898CB6EC-BE9E-4A4A-B6D2-AF2A55B4118F"
Version="1.3.0.0" />
Version="1.4.1.0" />

<mp:PhoneIdentity PhoneProductId="e3aa7c77-81b5-4b21-a173-a7e411312ab5" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

Expand Down
15 changes: 5 additions & 10 deletions Search/ListItems.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace YoutubeGameBarWidget.Search
{
Expand All @@ -19,19 +14,19 @@ public class ListItem
{
public string VideoTitle { get; set; }
public string ChannelTitle { get; set; }
public string VideoId { get; set; }
public string MediaUrl { get; set; }

/// <summary>
/// A list item object.
/// </summary>
/// <param name="videoTitle">The video title of the item.</param>
/// <param name="channelTitle">The channel title of the item.</param>
/// <param name="videoId">The video ID of the item.</param>
public ListItem(string videoTitle, string channelTitle, string videoId)
/// <param name="mediaUrl">The Media URL of the item.</param>
public ListItem(string videoTitle, string channelTitle, string mediaUrl)
{
this.VideoTitle = videoTitle;
this.ChannelTitle = channelTitle;
this.VideoId = videoId;
this.MediaUrl = mediaUrl;
}
}
}
84 changes: 48 additions & 36 deletions Search/Search.cs
Original file line number Diff line number Diff line change
@@ -1,64 +1,76 @@
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System;
using System;
using System.Net;
using System.Threading.Tasks;
using Windows.Data.Json;

namespace YoutubeGameBarWidget.Search
{
/// <summary>
/// Implements a Data Retriever using Google's Youtube API.
/// Implements a Data Retriever using Youtube GameBar Search Server's service.
///
/// For more details, see: https://developers.google.com/youtube/v3/docs/search/list
/// For more API details, see: https://github.com/MarconiGRF/YoutubeGameBarSearchServer
/// </summary>
class Search
{
private YouTubeService _youtubeService;
private SearchResource.ListRequest _listRequest;
private SearchListResponse _listResponse;
private WebClient client;
private string ytgbssEndPoint;
public ListItems parsedResults;
public event EventHandler FinishedFetchingResults;

/// <summary>
/// A simple constructor setting the common parameters for every request.
/// The FinishedFetchingResults event method manager.
/// </summary>
/// <param name="e"></param>
protected virtual void OnFinishedFetchingResults(EventArgs e)
{
EventHandler handler = FinishedFetchingResults;
handler?.Invoke(this, e);
}

/// <summary>
/// A simple constructor setting the common parameters for every search request.
/// </summary>
public Search()
{
_youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = Environment.GetEnvironmentVariable("YT_DATA_API_KEY"),
ApplicationName = "YoutubeGameBarWidget"
});
this.ytgbssEndPoint = "http://"
+ Environment.GetEnvironmentVariable("YTGBSS_ADDRESS") + ":"
+ Environment.GetEnvironmentVariable("YTGBSS_PORT") + "/search/";

this._listRequest = this._youtubeService.Search.List("snippet");
_listRequest.Type = "video";
_listRequest.MaxResults = 5;
_listRequest.SafeSearch = SearchResource.ListRequest.SafeSearchEnum.None;
this.client = new WebClient();
this.client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
this.client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ParseResults);
}

/// <summary>
/// Performs a search request on Data API by the given term, parsing the response into a ListItems object.
/// Performs a search (GET) request on YTGBSS by the given term, raising events when the raw data is ready.
/// </summary>
/// <param name="term">The term to compose the request.</param>
/// <returns></returns>
public async Task ByTerm(string term)
/// <param name="givenTerm">The term to compose the request.</param>
/// <returns></returns>0
public async Task ByTerm(string givenTerm)
{
this._listRequest.Q = term;
this._listResponse = await _listRequest.ExecuteAsync();
this.client.DownloadStringAsync(new Uri(ytgbssEndPoint + givenTerm));
}

/// <summary>
/// Parses the raw data into a ListItems object, raising FinishedFetchingResults event when finished.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ParseResults(Object sender, DownloadStringCompletedEventArgs e)
{
this.parsedResults = new ListItems();
foreach (SearchResult resultItem in this._listResponse.Items)

JsonArray jArray = JsonArray.Parse((string)e.Result);
foreach (JsonValue jValue in jArray)
{
switch (resultItem.Id.Kind)
{
case "youtube#video":
this.parsedResults.Add(new ListItem(
resultItem.Snippet.Title,
resultItem.Snippet.ChannelTitle,
resultItem.Id.VideoId)
);
break;
}
JsonObject jObject = jValue.GetObject();
this.parsedResults.Add(new ListItem(
jObject.GetNamedString("videoTitle"),
jObject.GetNamedString("channelTitle"),
jObject.GetNamedString("mediaUrl")));
}

this.OnFinishedFetchingResults(EventArgs.Empty);
}

/// <summary>
Expand Down

0 comments on commit 01e3e60

Please sign in to comment.