Skip to content

Instantly share code, notes, and snippets.

@OhkuboSGMS
Created July 17, 2018 06:13
Show Gist options
  • Save OhkuboSGMS/e51cf03d545a4de416e5161d62b9a574 to your computer and use it in GitHub Desktop.
Save OhkuboSGMS/e51cf03d545a4de416e5161d62b9a574 to your computer and use it in GitHub Desktop.
Youtube Live Streaming APIのコメント取得をUniTask を使用して書き直し
using System;
using System.Collections;
using MiniJSON;
using UniRx.Async;
using UnityEngine;
using UnityEngine.Networking;
namespace VirtualComment
{
/// <summary>
/// 元コード:https://qiita.com/platoronical/items/cd793e54a50274f2ff1f
/// UniTaskの使い方がこれでいいのかわからない…
/// </summary>
public class YoutubeLiveCommentFetcher : MonoBehaviour
{
//コメントがほしい処理はこれに登録
public delegate void OnGetComment(object comments);
public event OnGetComment OnGetCommentListener;
//ここから使う
[SerializeField] protected bool displayName = false;
[SerializeField] string apikey = string.Empty;
private string searchBaseURI =
"https://www.googleapis.com/youtube/v3/search?key=AIzaSyC8TVCz4d-0cUtWXjAGBQEqzOnifiklMrw&part=snippet&channelId=";
[Tooltip("ライブ放送をしているチャンネルのUIDを入力")] [SerializeField]
public string searchBaseChannnel;
private string searchBaseStr = "&eventType=live&type=video";
private string videoId;
private const string youtubeAPIbase = "https://www.googleapis.com/youtube/v3/";
private const string channnelSearch = "videos?part=liveStreamingDetails&id=";
private string chatId;
private const string pagetoken = "&pageToken=";
private const string chatURIUp = "liveChat/messages?liveChatId=";
private bool connectionflag = false;
private string nextPageTokenstr = null;
private string jsontext;
//コメントと投稿時間だけ出るやつ
private string chatURIbottom =
"&part=snippet&hl=ja&maxResults=2000&fields=items/snippet/displayMessage,items/snippet/publishedAt,items/authorDetails/displayName&key=";
//&part=snippet&hl=ja&maxResults=2000&fields=items/snippet/displayMessage,items/snippet/publishedAt&key=
//全部出るやつ
private string chatURIbottom2 = "&part=snippet,authorDetails&key=";
private bool end = false;
// Use this for initialization
void Start()
{
end = false;
print("Get Youtube Comment From:" + searchBaseChannnel);
//GetYoutubeAPI->GetChatID->GetComment
CommentAsync(5);
}
private void OnDestroy()
{
end = true;
}
async UniTask CommentAsync(float waitTimeSec = 2)
{
try
{
while (enabled && !end)
{
string videoId = await GetYoutubeAPI(searchBaseURI + searchBaseChannnel + searchBaseStr); print("GET Youtube API");
string chatId = await GetChatId(youtubeAPIbase + channnelSearch + videoId + "&key=" + apikey);print("GET Chat ID")
var comments = await GetComment(
youtubeAPIbase + chatURIUp + chatId + pagetoken + nextPageTokenstr + chatURIbottom2 +apikey);print("GET Comment");
print("Spawn Comment");
this.videoId = videoId;
this.chatId = chatId;
if (comments != null && !end)
foreach (var c in comments)
{
if (OnGetCommentListener != null) OnGetCommentListener(c);
await UniTask.Yield(PlayerLoopTiming.Update);
}
await UniTask.Delay(TimeSpan.FromSeconds(waitTimeSec));
if (end) break;
}
}
catch (Exception e)
{
Debug.LogError(e.Message+"\n"+e.StackTrace);
}
}
private async UniTask<string> GetYoutubeAPI(string url)
{
if (url == null) return null;
Debug.LogFormat("Youtbe URL:{0}", url);
var liverequest = UnityWebRequest.Get(url);
var op = await liverequest.SendWebRequest();
if (op.isHttpError || op.isNetworkError)
{
Debug.LogError(op.error+"\n"+op.downloadHandler.text);
return null;
}
jsontext = liverequest.downloadHandler.text;
var mjson = (IDictionary) MiniJSON.Json.Deserialize(jsontext);
var mitems = (IList) mjson["items"];
var mid = (IDictionary) mitems[0];
var sid = (IDictionary) mid["id"];
//videoIdを取得
var videoId = (string) sid["videoId"];
return videoId;
}
private async UniTask<string> GetChatId(string channel)
{
if (channel == null) return null;
UnityWebRequest channelrequest = UnityWebRequest.Get(channel);
var op = await channelrequest.SendWebRequest();
if (op.isHttpError || op.isNetworkError)
{
Debug.LogError(op.error);
return null;
}
var mchanjson = (IDictionary) Json.Deserialize(op.downloadHandler.text);
var citems = (IList) mchanjson["items"];
var cslsd = (IDictionary) citems[0];
var clad = (IDictionary) cslsd["liveStreamingDetails"];
//chatIdを取得
var chatId = (string) clad["activeLiveChatId"];
return chatId;
}
private async UniTask<IList> GetComment(string chatURI)
{
if (chatURI == null) return null;
//チャットを取りに行く!!!
UnityWebRequest connectChatrequest = UnityWebRequest.Get(chatURI);
var op = await connectChatrequest.SendWebRequest();
if (op.isHttpError || op.isNetworkError)
{
Debug.LogError(op.error);
return null;
}
var commentlogjson = (IDictionary) Json.Deserialize(connectChatrequest.downloadHandler.text);
// Debug.Log("commentjson:"+connectChatrequest.downloadHandler.text );
try
{
if (nextPageTokenstr == (string) commentlogjson["nextPageToken"])
{
Debug.Log("sameToken");
return null;
}
else
{
nextPageTokenstr = (string) commentlogjson["nextPageToken"];
print("nextPageToken");
var pageinfo = (IDictionary) commentlogjson["pageInfo"];
print("PageInfo");
//var totalResults = (IDictionary)pageinfo[0];
var commentList = (IList) commentlogjson["items"];
if (commentlogjson.Contains("items"))
{
print("Items:" + commentlogjson["items"].ToString());
print("Return Comment");
return commentList;
}
return null;
}
}
catch (Exception e)
{
Debug.LogError(e.Message + "\n" + e.StackTrace);
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment