1
0

Indetation formatting and unnecessary usings cleanup

This commit is contained in:
Michael Gordeev
2020-05-10 13:47:42 +03:00
parent f968c95ab1
commit 1d636120cc
20 changed files with 684 additions and 702 deletions
+13 -13
View File
@@ -4,16 +4,16 @@ using YouTube.Models;
namespace YouTube.API.Test namespace YouTube.API.Test
{ {
public class ClosedCaptionsTest public class ClosedCaptionsTest
{ {
[Test] [Test]
public void ValidCaptionsTest() public void ValidCaptionsTest()
{ {
ExtendedYouTubeService service = new ExtendedYouTubeService(); ExtendedYouTubeService service = new ExtendedYouTubeService();
ClosedCaptionInfo info = service.VideoPlayback.List("VC5-YkjMHuw").Execute().ClosedCaptions.FirstOrDefault(); ClosedCaptionInfo info = service.VideoPlayback.List("VC5-YkjMHuw").Execute().ClosedCaptions.FirstOrDefault();
ClosedCaptionTrack track = service.Captions.Load(info).Execute(); ClosedCaptionTrack track = service.Captions.Load(info).Execute();
Assert.IsNotNull(track); Assert.IsNotNull(track);
Assert.IsNotEmpty(track.Captions); Assert.IsNotEmpty(track.Captions);
} }
} }
} }
+13 -19
View File
@@ -5,23 +5,17 @@ using YouTube.Models;
namespace YouTube.API.Test namespace YouTube.API.Test
{ {
public class DashManifestTest public class DashManifestTest
{ {
[SetUp] [Test]
public void Setup() public void ValidManifestTest()
{ {
ExtendedYouTubeService service = new ExtendedYouTubeService();
} IReadOnlyList<DashManifest> manifests = service.DashManifests.List("NkGbcQwWxqk").Execute();
foreach (var i in manifests)
[Test] Console.WriteLine(i.Label);
public void ValidManifestTest() Assert.IsNotNull(manifests);
{ Assert.IsNotEmpty(manifests);
ExtendedYouTubeService service = new ExtendedYouTubeService(); }
IReadOnlyList<DashManifest> manifests = service.DashManifests.List("NkGbcQwWxqk").Execute(); }
foreach (var i in manifests)
Console.WriteLine(i.Label);
Assert.IsNotNull(manifests);
Assert.IsNotEmpty(manifests);
}
}
} }
+12 -15
View File
@@ -1,19 +1,16 @@
using System; using NUnit.Framework;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using YouTube.Models; using YouTube.Models;
namespace YouTube.API.Test namespace YouTube.API.Test
{ {
public class VideoPlaybackTest public class VideoPlaybackTest
{ {
[Test] [Test]
public void ValidVideoPlaybackTest() public void ValidVideoPlaybackTest()
{ {
ExtendedYouTubeService service = new ExtendedYouTubeService(); ExtendedYouTubeService service = new ExtendedYouTubeService();
VideoPlayback info = service.VideoPlayback.List("VC5-YkjMHuw").Execute(); VideoPlayback info = service.VideoPlayback.List("VC5-YkjMHuw").Execute();
Assert.NotNull(info); Assert.NotNull(info);
} }
} }
} }
+37 -40
View File
@@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Text;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services; using Google.Apis.Services;
using Google.Apis.YouTube.v3.Data; using Google.Apis.YouTube.v3.Data;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -11,44 +8,44 @@ using YouTube.Resources;
namespace YouTube.API.Test namespace YouTube.API.Test
{ {
public class WatchLaterTest public class WatchLaterTest
{ {
const string testVideoId = "NkGbcQwWxqk"; const string testVideoId = "NkGbcQwWxqk";
ExtendedYouTubeService service; ExtendedYouTubeService service;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
var task = AuthorizationHelpers.ExchangeToken(new ClientSecrets var task = AuthorizationHelpers.ExchangeToken(new Google.Apis.Auth.OAuth2.ClientSecrets
{ {
ClientId = "CLIENT_ID", ClientId = "CLIENT_ID",
ClientSecret = "CLIENT_SECRET" ClientSecret = "CLIENT_SECRET"
}, "SUCCESS_CODE"); }, "SUCCESS_CODE");
task.Wait(); task.Wait();
UserCredential credential = task.Result; UserCredential credential = task.Result;
service = new ExtendedYouTubeService(new BaseClientService.Initializer service = new ExtendedYouTubeService(new BaseClientService.Initializer
{ {
HttpClientInitializer = credential, HttpClientInitializer = credential,
ApplicationName = "FoxTube" ApplicationName = "FoxTube"
}); });
} }
[Test] [Test]
public void AddVideoTest() public void AddVideoTest()
{ {
WatchLaterResource.InsertRequest request = service.WatchLater.Insert(testVideoId, "snippet"); WatchLaterResource.InsertRequest request = service.WatchLater.Insert(testVideoId, "snippet");
PlaylistItem item = request.Execute(); PlaylistItem item = request.Execute();
Console.WriteLine(JsonConvert.SerializeObject(item)); Console.WriteLine(JsonConvert.SerializeObject(item));
Assert.IsNotNull(item); Assert.IsNotNull(item);
} }
[Test] [Test]
public void DeleteVideoTest() public void DeleteVideoTest()
{ {
WatchLaterResource.DeleteRequest request = service.WatchLater.Delete(testVideoId); WatchLaterResource.DeleteRequest request = service.WatchLater.Delete(testVideoId);
request.Execute(); request.Execute();
Assert.Pass(); Assert.Pass();
} }
} }
} }
+12 -12
View File
@@ -1,15 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<MPD minBufferTime="PT2S" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011" type="static"> <MPD minBufferTime="PT2S" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011" type="static">
<Period> <Period>
<AdaptationSet> <AdaptationSet>
<ContentComponent contentType="video" id="1"> <ContentComponent contentType="video" id="1">
</ContentComponent> </ContentComponent>
</AdaptationSet> </AdaptationSet>
<AdaptationSet> <AdaptationSet>
<ContentComponent contentType="audio" id="2"> <ContentComponent contentType="audio" id="2">
</ContentComponent> </ContentComponent>
</AdaptationSet> </AdaptationSet>
</Period> </Period>
</MPD> </MPD>
+18 -18
View File
@@ -2,22 +2,22 @@
namespace YouTube namespace YouTube
{ {
internal static class Extensions internal static class Extensions
{ {
internal static Uri ToUri(this string str) internal static Uri ToUri(this string str)
{ {
try { return new Uri(str); } try { return new Uri(str); }
catch { return null; } catch { return null; }
} }
internal static int RangeOffset(int value, int min, int max) internal static int RangeOffset(int value, int min, int max)
{ {
if (value < min) if (value < min)
return -1; return -1;
else if (value > max) else if (value > max)
return 1; return 1;
else else
return 0; return 0;
} }
} }
} }
+167 -167
View File
@@ -17,210 +17,210 @@ using YoutubeExplode.Models.MediaStreams;
namespace YouTube.Generators namespace YouTube.Generators
{ {
internal class ManifestGenerator internal class ManifestGenerator
{ {
IClientService ClientService { get; } IClientService ClientService { get; }
YoutubeClient Client { get; } YoutubeClient Client { get; }
string Id { get; } string Id { get; }
Video Meta { get; set; } Video Meta { get; set; }
MediaStreamInfoSet UrlsSet { get; set; } MediaStreamInfoSet UrlsSet { get; set; }
public ManifestGenerator(IClientService service, string id) public ManifestGenerator(IClientService service, string id)
{ {
ClientService = service; ClientService = service;
Id = id; Id = id;
Client = new YoutubeClient(service.HttpClient); Client = new YoutubeClient(service.HttpClient);
} }
public async Task<IReadOnlyList<DashManifest>> GenerateManifestsAsync() public async Task<IReadOnlyList<DashManifest>> GenerateManifestsAsync()
{ {
Meta = await Client.GetVideoAsync(Id); Meta = await Client.GetVideoAsync(Id);
if (Meta == null) if (Meta == null)
throw new FileNotFoundException("Video not found. Check video ID and visibility preferences"); throw new FileNotFoundException("Video not found. Check video ID and visibility preferences");
UrlsSet = await Client.GetVideoMediaStreamInfosAsync(Id); UrlsSet = await Client.GetVideoMediaStreamInfosAsync(Id);
if (!string.IsNullOrWhiteSpace(UrlsSet.HlsLiveStreamUrl)) if (!string.IsNullOrWhiteSpace(UrlsSet.HlsLiveStreamUrl))
throw new NotSupportedException("This is livestream. Use 'YouTubeClient.VideoPlayback.List()' to get playback URLs"); throw new NotSupportedException("This is livestream. Use 'YouTubeClient.VideoPlayback.List()' to get playback URLs");
List<DashManifest> list = new List<DashManifest> List<DashManifest> list = new List<DashManifest>
{ {
await GenerateManifest("Auto") await GenerateManifest("Auto")
}; };
foreach (string i in UrlsSet.GetAllVideoQualityLabels()) foreach (string i in UrlsSet.GetAllVideoQualityLabels())
list.Add(await GenerateManifest(i)); list.Add(await GenerateManifest(i));
return list.AsReadOnly();
}
async Task<DashManifest> GenerateManifest(string quality) return list.AsReadOnly();
{ }
XmlDocument manifest = new XmlDocument();
manifest.LoadXml(Properties.Resources.DashManifestTemplate);
manifest["MPD"].SetAttribute("mediaPresentationDuration", XmlConvert.ToString(Meta.Duration)); async Task<DashManifest> GenerateManifest(string quality)
{
XmlDocument manifest = new XmlDocument();
manifest.LoadXml(Properties.Resources.DashManifestTemplate);
StreamInfo streamInfo = await GetInfoAsync(quality); manifest["MPD"].SetAttribute("mediaPresentationDuration", XmlConvert.ToString(Meta.Duration));
foreach (var i in streamInfo.Video) StreamInfo streamInfo = await GetInfoAsync(quality);
{
string rep = GetVideoRepresentation(i);
manifest.GetElementsByTagName("ContentComponent")[0].InnerXml += rep;
}
foreach (var i in streamInfo.Audio) foreach (var i in streamInfo.Video)
manifest.GetElementsByTagName("ContentComponent")[1].InnerXml += GetAudioRepresentation(i); {
string rep = GetVideoRepresentation(i);
manifest.GetElementsByTagName("ContentComponent")[0].InnerXml += rep;
}
return new DashManifest(quality, manifest); foreach (var i in streamInfo.Audio)
} manifest.GetElementsByTagName("ContentComponent")[1].InnerXml += GetAudioRepresentation(i);
string GetVideoRepresentation(StreamInfo.VideoInfo info) => return new DashManifest(quality, manifest);
$@"<Representation bandwidth=""{GetBandwidth(info.Label)}"" id=""{info.Itag}"" mimeType=""{info.MimeType}"" codecs=""{info.Codecs}"" fps=""{info.Fps}"" height=""{info.Height}"" width=""{info.Width}""> }
string GetVideoRepresentation(StreamInfo.VideoInfo info) =>
$@"<Representation bandwidth=""{GetBandwidth(info.Label)}"" id=""{info.Itag}"" mimeType=""{info.MimeType}"" codecs=""{info.Codecs}"" fps=""{info.Fps}"" height=""{info.Height}"" width=""{info.Width}"">
<BaseURL>{WebUtility.UrlEncode(info.Url)}</BaseURL> <BaseURL>{WebUtility.UrlEncode(info.Url)}</BaseURL>
<SegmentBase indexRange=""{info.IndexRange}""> <SegmentBase indexRange=""{info.IndexRange}"">
<Initialization range=""{info.InitRange}""/> <Initialization range=""{info.InitRange}""/>
</SegmentBase> </SegmentBase>
</Representation>"; </Representation>";
string GetAudioRepresentation(StreamInfo.AudioInfo info) => string GetAudioRepresentation(StreamInfo.AudioInfo info) =>
$@"<Representation bandwidth=""200000"" id=""{info.Itag}"" sampleRate=""{info.SampleRate}"" numChannels=""{info.ChannelsCount}"" mimeType=""{info.MimeType}"" codecs=""{info.Codecs}""> $@"<Representation bandwidth=""200000"" id=""{info.Itag}"" sampleRate=""{info.SampleRate}"" numChannels=""{info.ChannelsCount}"" mimeType=""{info.MimeType}"" codecs=""{info.Codecs}"">
<BaseURL>{WebUtility.UrlEncode(info.Url)}</BaseURL> <BaseURL>{WebUtility.UrlEncode(info.Url)}</BaseURL>
<SegmentBase indexRange=""{info.IndexRange}""> <SegmentBase indexRange=""{info.IndexRange}"">
<Initialization range=""{info.InitRange}""/> <Initialization range=""{info.InitRange}""/>
</SegmentBase> </SegmentBase>
</Representation>"; </Representation>";
async Task<StreamInfo> GetInfoAsync(string quality) async Task<StreamInfo> GetInfoAsync(string quality)
{ {
StreamInfo info = new StreamInfo(); StreamInfo info = new StreamInfo();
string response = await ClientService.HttpClient.GetStringAsync($"https://youtube.com/watch?v={Id}&disable_polymer=true&bpctr=9999999999&hl=en"); string response = await ClientService.HttpClient.GetStringAsync($"https://youtube.com/watch?v={Id}&disable_polymer=true&bpctr=9999999999&hl=en");
IHtmlDocument videoEmbedPageHtml = new HtmlParser().ParseDocument(response); IHtmlDocument videoEmbedPageHtml = new HtmlParser().ParseDocument(response);
#region I don't know what the fuck is this #region I don't know what the fuck is this
string playerConfigRaw = Regex.Match(videoEmbedPageHtml.Source.Text, string playerConfigRaw = Regex.Match(videoEmbedPageHtml.Source.Text,
@"ytplayer\.config = (?<Json>\{[^\{\}]*(((?<Open>\{)[^\{\}]*)+((?<Close-Open>\})[^\{\}]*)+)*(?(Open)(?!))\})") @"ytplayer\.config = (?<Json>\{[^\{\}]*(((?<Open>\{)[^\{\}]*)+((?<Close-Open>\})[^\{\}]*)+)*(?(Open)(?!))\})")
.Groups["Json"].Value; .Groups["Json"].Value;
JToken playerConfigJson = JToken.Parse(playerConfigRaw); JToken playerConfigJson = JToken.Parse(playerConfigRaw);
var playerResponseRaw = playerConfigJson.SelectToken("args.player_response").Value<string>(); var playerResponseRaw = playerConfigJson.SelectToken("args.player_response").Value<string>();
JToken playerResponseJson = JToken.Parse(playerResponseRaw); JToken playerResponseJson = JToken.Parse(playerResponseRaw);
string errorReason = playerResponseJson.SelectToken("playabilityStatus.reason")?.Value<string>(); string errorReason = playerResponseJson.SelectToken("playabilityStatus.reason")?.Value<string>();
if (!string.IsNullOrWhiteSpace(errorReason)) if (!string.IsNullOrWhiteSpace(errorReason))
throw new InvalidDataException($"Video [{Id}] is unplayable. Reason: {errorReason}"); throw new InvalidDataException($"Video [{Id}] is unplayable. Reason: {errorReason}");
List<Dictionary<string, string>> adaptiveStreamInfosUrl = playerConfigJson.SelectToken("args.adaptive_fmts")?.Value<string>().Split(',').Select(SplitQuery).ToList(); List<Dictionary<string, string>> adaptiveStreamInfosUrl = playerConfigJson.SelectToken("args.adaptive_fmts")?.Value<string>().Split(',').Select(SplitQuery).ToList();
List<Dictionary<string, string>> video = List<Dictionary<string, string>> video =
quality == "Auto" ? quality == "Auto" ?
adaptiveStreamInfosUrl.FindAll(i => i.ContainsKey("quality_label")) : adaptiveStreamInfosUrl.FindAll(i => i.ContainsKey("quality_label")) :
adaptiveStreamInfosUrl.FindAll(i => i.ContainsValue(quality.Substring(0, quality.IndexOf('p')))); adaptiveStreamInfosUrl.FindAll(i => i.ContainsValue(quality.Substring(0, quality.IndexOf('p'))));
List<Dictionary<string, string>> audio = adaptiveStreamInfosUrl.FindAll(i => i.ContainsKey("audio_sample_rate")); List<Dictionary<string, string>> audio = adaptiveStreamInfosUrl.FindAll(i => i.ContainsKey("audio_sample_rate"));
#endregion #endregion
foreach (var i in video) foreach (var i in video)
info.Video.Add(new StreamInfo.VideoInfo info.Video.Add(new StreamInfo.VideoInfo
{ {
IndexRange = i["index"], IndexRange = i["index"],
Url = i["url"], Url = i["url"],
Itag = i["itag"], Itag = i["itag"],
Fps = i["fps"], Fps = i["fps"],
Height = i["size"].Split('x')[1], Height = i["size"].Split('x')[1],
Width = i["size"].Split('x')[0], Width = i["size"].Split('x')[0],
Codecs = i["type"].Split('"')[1], Codecs = i["type"].Split('"')[1],
MimeType = i["type"].Split(';')[0], MimeType = i["type"].Split(';')[0],
Label = i["quality_label"] Label = i["quality_label"]
}); });
foreach (var i in audio) foreach (var i in audio)
info.Audio.Add(new StreamInfo.AudioInfo info.Audio.Add(new StreamInfo.AudioInfo
{ {
ChannelsCount = i["audio_channels"], ChannelsCount = i["audio_channels"],
IndexRange = i["index"], IndexRange = i["index"],
SampleRate = i["audio_sample_rate"], SampleRate = i["audio_sample_rate"],
Codecs = i["type"].Split('"')[1], Codecs = i["type"].Split('"')[1],
MimeType = i["type"].Split(';')[0], MimeType = i["type"].Split(';')[0],
Url = i["url"], Url = i["url"],
Itag = i["itag"] Itag = i["itag"]
}); });
return info; return info;
} }
/// <summary> /// <summary>
/// I don't know what the fuck is this either /// I don't know what the fuck is this either
/// </summary> /// </summary>
public Dictionary<string, string> SplitQuery(string query) public Dictionary<string, string> SplitQuery(string query)
{ {
Dictionary<string, string> dic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); Dictionary<string, string> dic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
string[] paramsEncoded = query.TrimStart('?').Split('&'); string[] paramsEncoded = query.TrimStart('?').Split('&');
foreach (string paramEncoded in paramsEncoded) foreach (string paramEncoded in paramsEncoded)
{ {
string param = WebUtility.UrlDecode(paramEncoded); string param = WebUtility.UrlDecode(paramEncoded);
// Look for the equals sign // Look for the equals sign
int equalsPos = param.IndexOf('='); int equalsPos = param.IndexOf('=');
if (equalsPos <= 0) if (equalsPos <= 0)
continue; continue;
// Get the key and value // Get the key and value
string key = param.Substring(0, equalsPos); string key = param.Substring(0, equalsPos);
string value = equalsPos < param.Length string value = equalsPos < param.Length
? param.Substring(equalsPos + 1) ? param.Substring(equalsPos + 1)
: string.Empty; : string.Empty;
// Add to dictionary // Add to dictionary
dic[key] = value; dic[key] = value;
} }
return dic; return dic;
} }
string GetBandwidth(string quality) => string GetBandwidth(string quality) =>
quality.Split('p')[0] switch quality.Split('p')[0] switch
{ {
"4320" => "16763040", "4320" => "16763040",
"3072" => "11920384", "3072" => "11920384",
"2880" => "11175360", "2880" => "11175360",
"2160" => "8381520", "2160" => "8381520",
"1440" => "5587680", "1440" => "5587680",
"1080" => "4190760", "1080" => "4190760",
"720" => "2073921", "720" => "2073921",
"480" => "869460", "480" => "869460",
"360" => "686521", "360" => "686521",
"240" => "264835", "240" => "264835",
_ => "100000", _ => "100000",
}; };
class StreamInfo class StreamInfo
{ {
public class VideoInfo public class VideoInfo
{ {
public string IndexRange { get; set; } public string IndexRange { get; set; }
public string InitRange => $"0-{int.Parse(IndexRange.Split('-')[0]) - 1}"; public string InitRange => $"0-{int.Parse(IndexRange.Split('-')[0]) - 1}";
public string Itag { get; set; } public string Itag { get; set; }
public string Fps { get; set; } public string Fps { get; set; }
public string Url { get; set; } public string Url { get; set; }
public string Codecs { get; set; } public string Codecs { get; set; }
public string MimeType { get; set; } public string MimeType { get; set; }
public string Height { get; set; } public string Height { get; set; }
public string Width { get; set; } public string Width { get; set; }
public string Label { get; set; } public string Label { get; set; }
} }
public class AudioInfo public class AudioInfo
{ {
public string IndexRange { get; set; } public string IndexRange { get; set; }
public string InitRange => $"0-{int.Parse(IndexRange.Split('-')[0]) - 1}"; public string InitRange => $"0-{int.Parse(IndexRange.Split('-')[0]) - 1}";
public string SampleRate { get; set; } public string SampleRate { get; set; }
public string ChannelsCount { get; set; } public string ChannelsCount { get; set; }
public string Codecs { get; set; } public string Codecs { get; set; }
public string MimeType { get; set; } public string MimeType { get; set; }
public string Url { get; set; } public string Url { get; set; }
public string Itag { get; set; } public string Itag { get; set; }
} }
public List<VideoInfo> Video { get; } = new List<VideoInfo>(); public List<VideoInfo> Video { get; } = new List<VideoInfo>();
public List<AudioInfo> Audio { get; } = new List<AudioInfo>(); public List<AudioInfo> Audio { get; } = new List<AudioInfo>();
} }
} }
} }
+8 -8
View File
@@ -3,12 +3,12 @@ using YoutubeExplode.Models.ClosedCaptions;
namespace YouTube.Models namespace YouTube.Models
{ {
public class ClosedCaptionInfo public class ClosedCaptionInfo
{ {
public CultureInfo Language { get; set; } public CultureInfo Language { get; set; }
public string Url { get; set; } public string Url { get; set; }
public bool AutoGenerated { get; set; } public bool AutoGenerated { get; set; }
internal ClosedCaptionTrackInfo TrackInfo { get; set; } internal ClosedCaptionTrackInfo TrackInfo { get; set; }
} }
} }
+12 -12
View File
@@ -4,16 +4,16 @@ using System.Text;
namespace YouTube.Models namespace YouTube.Models
{ {
public class ClosedCaptionTrack public class ClosedCaptionTrack
{ {
public ClosedCaptionInfo Info { get; set; } public ClosedCaptionInfo Info { get; set; }
public IReadOnlyList<ClosedCaption> Captions { get; set; } public IReadOnlyList<ClosedCaption> Captions { get; set; }
public class ClosedCaption public class ClosedCaption
{ {
public TimeSpan Offset { get; set; } public TimeSpan Offset { get; set; }
public TimeSpan Duration { get; set; } public TimeSpan Duration { get; set; }
public string Content { get; set; } public string Content { get; set; }
} }
} }
} }
+18 -18
View File
@@ -4,22 +4,22 @@ using System.Xml;
namespace YouTube.Models namespace YouTube.Models
{ {
public class DashManifest public class DashManifest
{ {
public string Label { get; } public string Label { get; }
public DateTime ValidUntil { get; } public DateTime ValidUntil { get; }
public DashManifest(string label, XmlDocument doc) public DashManifest(string label, XmlDocument doc)
{ {
Label = label; Label = label;
Xml = doc; Xml = doc;
} }
public string ManifestContent => Xml.OuterXml; public string ManifestContent => Xml.OuterXml;
public XmlDocument Xml { get; } public XmlDocument Xml { get; }
public Uri WriteManifest(FileStream outStream) public Uri WriteManifest(FileStream outStream)
{ {
Xml.Save(outStream); Xml.Save(outStream);
return new Uri(outStream.Name); return new Uri(outStream.Name);
} }
} }
} }
+44 -46
View File
@@ -1,48 +1,46 @@
using System.Drawing; namespace YouTube.Models
namespace YouTube.Models
{ {
public enum VideoFormat public enum VideoFormat
{ {
/// <summary> /// <summary>
/// MPEG-4 Part 2. /// MPEG-4 Part 2.
/// </summary> /// </summary>
Mp4V = 0, Mp4V = 0,
H263 = 1, H263 = 1,
/// <summary> /// <summary>
/// MPEG-4 Part 10, H264, Advanced Video Coding (AVC). /// MPEG-4 Part 10, H264, Advanced Video Coding (AVC).
/// </summary> /// </summary>
H264 = 2, H264 = 2,
Vp8 = 3, Vp8 = 3,
Vp9 = 4, Vp9 = 4,
Av1 = 5 Av1 = 5
} }
public enum AudioFormat public enum AudioFormat
{ {
/// <summary> /// <summary>
/// MPEG-4 Part 3, Advanced Audio Coding (AAC). /// MPEG-4 Part 3, Advanced Audio Coding (AAC).
/// </summary> /// </summary>
Aac = 0, Aac = 0,
Vorbis = 1, Vorbis = 1,
Opus = 2 Opus = 2
} }
public enum AudioQuality { Low, Medium, High } public enum AudioQuality { Low, Medium, High }
public class VideoPlaybackUrl public class VideoPlaybackUrl
{ {
public string Quality { get; set; } public string Quality { get; set; }
public VideoFormat Format { get; set; } public VideoFormat Format { get; set; }
public string Url { get; set; } public string Url { get; set; }
public Size Resolution { get; set; } public System.Drawing.Size Resolution { get; set; }
public bool HasAudio { get; set; } public bool HasAudio { get; set; }
public int Bitrate { get; set; } public int Bitrate { get; set; }
} }
public class AudioPlaybackUrl public class AudioPlaybackUrl
{ {
public AudioQuality Quality { get; set; } public AudioQuality Quality { get; set; }
public AudioFormat Format { get; set; } public AudioFormat Format { get; set; }
public string Url { get; set; } public string Url { get; set; }
public int Bitrate { get; set; } public int Bitrate { get; set; }
} }
} }
+14 -14
View File
@@ -3,18 +3,18 @@ using System.Collections.Generic;
namespace YouTube.Models namespace YouTube.Models
{ {
public class VideoPlayback public class VideoPlayback
{ {
public string Id { get; set; } public string Id { get; set; }
public PlaybackUrlsData PlaybackUrls { get; set; } = new PlaybackUrlsData(); public PlaybackUrlsData PlaybackUrls { get; set; } = new PlaybackUrlsData();
public IReadOnlyList<ClosedCaptionInfo> ClosedCaptions { get; set; } public IReadOnlyList<ClosedCaptionInfo> ClosedCaptions { get; set; }
public class PlaybackUrlsData public class PlaybackUrlsData
{ {
public IReadOnlyList<VideoPlaybackUrl> Video { get; set; } public IReadOnlyList<VideoPlaybackUrl> Video { get; set; }
public IReadOnlyList<AudioPlaybackUrl> Audio { get; set; } public IReadOnlyList<AudioPlaybackUrl> Audio { get; set; }
public string LiveStreamUrl { get; set; } public string LiveStreamUrl { get; set; }
public DateTime ValidUntil { get; set; } public DateTime ValidUntil { get; set; }
} }
} }
} }
+43 -43
View File
@@ -6,52 +6,52 @@ using YoutubeExplode;
namespace YouTube.Resources namespace YouTube.Resources
{ {
public class CaptionsResource : Google.Apis.YouTube.v3.CaptionsResource public class CaptionsResource : Google.Apis.YouTube.v3.CaptionsResource
{ {
IClientService Service { get; } IClientService Service { get; }
public CaptionsResource(IClientService service) : base(service) => public CaptionsResource(IClientService service) : base(service) =>
Service = service; Service = service;
public LoadRequest Load(ClosedCaptionInfo captionInfo) => public LoadRequest Load(ClosedCaptionInfo captionInfo) =>
new LoadRequest(Service, captionInfo); new LoadRequest(Service, captionInfo);
public class LoadRequest public class LoadRequest
{ {
public ClosedCaptionInfo CaptionInfo { get; set; } public ClosedCaptionInfo CaptionInfo { get; set; }
IClientService Service { get; set; } IClientService Service { get; set; }
public LoadRequest(IClientService service, ClosedCaptionInfo captionInfo) public LoadRequest(IClientService service, ClosedCaptionInfo captionInfo)
{ {
CaptionInfo = captionInfo; CaptionInfo = captionInfo;
Service = service; Service = service;
} }
public async Task<ClosedCaptionTrack> ExecuteAsync() public async Task<ClosedCaptionTrack> ExecuteAsync()
{ {
YoutubeClient client = new YoutubeClient(Service.HttpClient); YoutubeClient client = new YoutubeClient(Service.HttpClient);
var response = await client.GetClosedCaptionTrackAsync(CaptionInfo.TrackInfo); var response = await client.GetClosedCaptionTrackAsync(CaptionInfo.TrackInfo);
List<ClosedCaptionTrack.ClosedCaption> captions = new List<ClosedCaptionTrack.ClosedCaption>(); List<ClosedCaptionTrack.ClosedCaption> captions = new List<ClosedCaptionTrack.ClosedCaption>();
foreach (var i in response.Captions) foreach (var i in response.Captions)
captions.Add(new ClosedCaptionTrack.ClosedCaption captions.Add(new ClosedCaptionTrack.ClosedCaption
{ {
Offset = i.Offset, Offset = i.Offset,
Duration = i.Duration, Duration = i.Duration,
Content = i.Text Content = i.Text
}); });
return new ClosedCaptionTrack return new ClosedCaptionTrack
{ {
Info = CaptionInfo, Info = CaptionInfo,
Captions = captions.AsReadOnly() Captions = captions.AsReadOnly()
}; };
} }
public ClosedCaptionTrack Execute() public ClosedCaptionTrack Execute()
{ {
Task<ClosedCaptionTrack> task = ExecuteAsync(); Task<ClosedCaptionTrack> task = ExecuteAsync();
task.Wait(); task.Wait();
return task.Result; return task.Result;
} }
} }
} }
} }
+30 -30
View File
@@ -6,39 +6,39 @@ using YouTube.Models;
namespace YouTube.Resources namespace YouTube.Resources
{ {
public class DashManifestsResource public class DashManifestsResource
{ {
IClientService Service { get; } IClientService Service { get; }
public DashManifestsResource(IClientService service) => public DashManifestsResource(IClientService service) =>
Service = service; Service = service;
public ListRequest List(string videoId) => public ListRequest List(string videoId) =>
new ListRequest(Service, videoId); new ListRequest(Service, videoId);
public class ListRequest public class ListRequest
{ {
public string Id { get; set; } public string Id { get; set; }
IClientService Service { get; set; } IClientService Service { get; set; }
public ListRequest(IClientService service, string id) public ListRequest(IClientService service, string id)
{ {
Id = id; Id = id;
Service = service; Service = service;
} }
public async Task<IReadOnlyList<DashManifest>> ExecuteAsync() public async Task<IReadOnlyList<DashManifest>> ExecuteAsync()
{ {
ManifestGenerator generator = new ManifestGenerator(Service, Id); ManifestGenerator generator = new ManifestGenerator(Service, Id);
return await generator.GenerateManifestsAsync(); return await generator.GenerateManifestsAsync();
} }
public IReadOnlyList<DashManifest> Execute() public IReadOnlyList<DashManifest> Execute()
{ {
Task<IReadOnlyList<DashManifest>> task = ExecuteAsync(); Task<IReadOnlyList<DashManifest>> task = ExecuteAsync();
task.Wait(); task.Wait();
return task.Result; return task.Result;
} }
} }
} }
} }
+24 -24
View File
@@ -6,31 +6,31 @@ using Google.Apis.YouTube.v3.Data;
namespace YouTube.Resources namespace YouTube.Resources
{ {
public class HistoryResource public class HistoryResource
{ {
public class ListRequest { } public class ListRequest { }
public class InsertRequest { } public class InsertRequest { }
public class DeleteRequest { } public class DeleteRequest { }
public class ClearRequest { } public class ClearRequest { }
public ListRequest List() public ListRequest List()
{ {
return new ListRequest(); return new ListRequest();
} }
public InsertRequest Insert(string videoId, TimeSpan? leftOn) public InsertRequest Insert(string videoId, TimeSpan? leftOn)
{ {
return new InsertRequest(); return new InsertRequest();
} }
public DeleteRequest Delete(string videoId) public DeleteRequest Delete(string videoId)
{ {
return new DeleteRequest(); return new DeleteRequest();
} }
public ClearRequest Clear() public ClearRequest Clear()
{ {
return new ClearRequest(); return new ClearRequest();
} }
} }
} }
+87 -87
View File
@@ -10,102 +10,102 @@ using YoutubeExplode.Models.MediaStreams;
namespace YouTube.Resources namespace YouTube.Resources
{ {
public class VideoPlaybackResource public class VideoPlaybackResource
{ {
IClientService ClientService { get; } IClientService ClientService { get; }
public VideoPlaybackResource(IClientService clientService) => public VideoPlaybackResource(IClientService clientService) =>
ClientService = clientService; ClientService = clientService;
public ListRequest List(string videoId) => public ListRequest List(string videoId) =>
new ListRequest(ClientService, videoId); new ListRequest(ClientService, videoId);
public class ListRequest public class ListRequest
{ {
IClientService Service { get; } IClientService Service { get; }
public string Id { get; set; } public string Id { get; set; }
public async Task<VideoPlayback> ExecuteAsync() public async Task<VideoPlayback> ExecuteAsync()
{ {
VideoPlayback item = new VideoPlayback(); VideoPlayback item = new VideoPlayback();
YoutubeClient client = new YoutubeClient(Service.HttpClient); YoutubeClient client = new YoutubeClient(Service.HttpClient);
MediaStreamInfoSet streamSet = await client.GetVideoMediaStreamInfosAsync(Id); MediaStreamInfoSet streamSet = await client.GetVideoMediaStreamInfosAsync(Id);
item.Id = Id; item.Id = Id;
item.PlaybackUrls.ValidUntil = streamSet.ValidUntil.DateTime; item.PlaybackUrls.ValidUntil = streamSet.ValidUntil.DateTime;
if(!string.IsNullOrWhiteSpace(streamSet.HlsLiveStreamUrl)) if (!string.IsNullOrWhiteSpace(streamSet.HlsLiveStreamUrl))
{ {
item.PlaybackUrls.LiveStreamUrl = streamSet.HlsLiveStreamUrl; item.PlaybackUrls.LiveStreamUrl = streamSet.HlsLiveStreamUrl;
return item; return item;
} }
List<AudioPlaybackUrl> audio = new List<AudioPlaybackUrl>(); List<AudioPlaybackUrl> audio = new List<AudioPlaybackUrl>();
foreach (AudioStreamInfo i in streamSet.Audio) foreach (AudioStreamInfo i in streamSet.Audio)
audio.Add(new AudioPlaybackUrl audio.Add(new AudioPlaybackUrl
{ {
Url = i.Url, Url = i.Url,
Bitrate = (int)i.Bitrate, Bitrate = (int)i.Bitrate,
Format = (AudioFormat)i.AudioEncoding, Format = (AudioFormat)i.AudioEncoding,
Quality = Extensions.RangeOffset((int)i.Bitrate / 1024, 128, 255) switch Quality = Extensions.RangeOffset((int)i.Bitrate / 1024, 128, 255) switch
{ {
-1 => AudioQuality.Low, -1 => AudioQuality.Low,
1 => AudioQuality.High, 1 => AudioQuality.High,
_ => AudioQuality.Medium _ => AudioQuality.Medium
} }
}); });
item.PlaybackUrls.Audio = audio.AsReadOnly(); item.PlaybackUrls.Audio = audio.AsReadOnly();
List<VideoPlaybackUrl> video = new List<VideoPlaybackUrl>(); List<VideoPlaybackUrl> video = new List<VideoPlaybackUrl>();
foreach (VideoStreamInfo i in streamSet.Video) foreach (VideoStreamInfo i in streamSet.Video)
video.Add(new VideoPlaybackUrl video.Add(new VideoPlaybackUrl
{ {
Format = (VideoFormat)i.VideoEncoding, Format = (VideoFormat)i.VideoEncoding,
HasAudio = false, HasAudio = false,
Quality = i.VideoQualityLabel, Quality = i.VideoQualityLabel,
Url = i.Url, Url = i.Url,
Resolution = new Size(i.Resolution.Width, i.Resolution.Height), Resolution = new Size(i.Resolution.Width, i.Resolution.Height),
Bitrate = (int)i.Bitrate Bitrate = (int)i.Bitrate
}); });
foreach (MuxedStreamInfo i in streamSet.Muxed) foreach (MuxedStreamInfo i in streamSet.Muxed)
video.Add(new VideoPlaybackUrl video.Add(new VideoPlaybackUrl
{ {
Format = (VideoFormat)i.VideoEncoding, Format = (VideoFormat)i.VideoEncoding,
HasAudio = true, HasAudio = true,
Quality = i.VideoQualityLabel, Quality = i.VideoQualityLabel,
Url = i.Url, Url = i.Url,
Resolution = new Size(i.Resolution.Width, i.Resolution.Height), Resolution = new Size(i.Resolution.Width, i.Resolution.Height),
Bitrate = 0 Bitrate = 0
}); });
item.PlaybackUrls.Video = video.AsReadOnly(); item.PlaybackUrls.Video = video.AsReadOnly();
var ccSet = await client.GetVideoClosedCaptionTrackInfosAsync(Id); var ccSet = await client.GetVideoClosedCaptionTrackInfosAsync(Id);
List<ClosedCaptionInfo> captions = new List<ClosedCaptionInfo>(); List<ClosedCaptionInfo> captions = new List<ClosedCaptionInfo>();
foreach (ClosedCaptionTrackInfo i in ccSet) foreach (ClosedCaptionTrackInfo i in ccSet)
captions.Add(new ClosedCaptionInfo captions.Add(new ClosedCaptionInfo
{ {
AutoGenerated = i.IsAutoGenerated, AutoGenerated = i.IsAutoGenerated,
Url = i.Url, Url = i.Url,
Language = new CultureInfo(i.Language.Code), Language = new CultureInfo(i.Language.Code),
TrackInfo = i TrackInfo = i
}); });
item.ClosedCaptions = captions.AsReadOnly(); item.ClosedCaptions = captions.AsReadOnly();
return item; return item;
} }
public VideoPlayback Execute() public VideoPlayback Execute()
{ {
Task<VideoPlayback> task = ExecuteAsync(); Task<VideoPlayback> task = ExecuteAsync();
task.Wait(); task.Wait();
return task.Result; return task.Result;
} }
public ListRequest(IClientService service, string id) public ListRequest(IClientService service, string id)
{ {
Id = id; Id = id;
Service = service; Service = service;
} }
} }
} }
} }
+82 -82
View File
@@ -13,97 +13,97 @@ using System.Threading.Tasks;
namespace YouTube.Resources namespace YouTube.Resources
{ {
public class WatchLaterResource public class WatchLaterResource
{ {
IClientService Service { get; } IClientService Service { get; }
public WatchLaterResource(IClientService service) => public WatchLaterResource(IClientService service) =>
Service = service; Service = service;
public ListRequest List() public ListRequest List()
{ {
return new ListRequest(); return new ListRequest();
} }
public InsertRequest Insert(string videoId, string part) => public InsertRequest Insert(string videoId, string part) =>
new InsertRequest(Service, videoId, part); new InsertRequest(Service, videoId, part);
public DeleteRequest Delete(string videoId) => public DeleteRequest Delete(string videoId) =>
new DeleteRequest(Service, videoId); new DeleteRequest(Service, videoId);
public class ListRequest { } public class ListRequest { }
public class InsertRequest public class InsertRequest
{ {
IClientService Service { get; set; } IClientService Service { get; set; }
public string Id { get; set; } public string Id { get; set; }
public string Part { get; set; } public string Part { get; set; }
public InsertRequest(IClientService service, string videoId, string part) public InsertRequest(IClientService service, string videoId, string part)
{ {
Service = service; Service = service;
Id = videoId; Id = videoId;
Part = part; Part = part;
} }
public async Task<PlaylistItem> ExecuteAsync() public async Task<PlaylistItem> ExecuteAsync()
{ {
PlaylistItem playlist = new PlaylistItem PlaylistItem playlist = new PlaylistItem
{ {
Snippet = new PlaylistItemSnippet Snippet = new PlaylistItemSnippet
{ {
PlaylistId = "WL", PlaylistId = "WL",
ResourceId = new ResourceId ResourceId = new ResourceId
{ {
VideoId = Id, VideoId = Id,
Kind = "youtube#video" Kind = "youtube#video"
} }
} }
}; };
PlaylistItemsResource.InsertRequest request = (Service as YouTubeService).PlaylistItems.Insert(playlist, Part); PlaylistItemsResource.InsertRequest request = (Service as YouTubeService).PlaylistItems.Insert(playlist, Part);
return await request.ExecuteAsync(); return await request.ExecuteAsync();
} }
public PlaylistItem Execute() public PlaylistItem Execute()
{ {
Task<PlaylistItem> task = ExecuteAsync(); Task<PlaylistItem> task = ExecuteAsync();
task.Wait(); task.Wait();
return task.Result; return task.Result;
} }
} }
public class DeleteRequest public class DeleteRequest
{ {
IClientService Service { get; set; } IClientService Service { get; set; }
public string Id { get; set; } public string Id { get; set; }
public DeleteRequest(IClientService service, string videoId) public DeleteRequest(IClientService service, string videoId)
{ {
Service = service; Service = service;
Id = videoId; Id = videoId;
} }
public async Task ExecuteAsync() public async Task ExecuteAsync()
{ {
ConfigurableHttpClient client = Service.HttpClient; ConfigurableHttpClient client = Service.HttpClient;
string data = await client.GetStringAsync($"https://youtube.com/watch?v={Id}&disable_polymer=true&bpctr=9999999999&hl=en"); string data = await client.GetStringAsync($"https://youtube.com/watch?v={Id}&disable_polymer=true&bpctr=9999999999&hl=en");
string plid = Regex.Match(data, @"(?<=plid=).?\w+").Value; string plid = Regex.Match(data, @"(?<=plid=).?\w+").Value;
IHtmlDocument html = await new HtmlParser().ParseDocumentAsync(data); IHtmlDocument html = await new HtmlParser().ParseDocumentAsync(data);
string sessionToken = html.GetElementsByTagName("input").FirstOrDefault(i => i.GetAttribute("name") == "session_token")?.GetAttribute("value"); string sessionToken = html.GetElementsByTagName("input").FirstOrDefault(i => i.GetAttribute("name") == "session_token")?.GetAttribute("value");
Dictionary<string, string> body = new Dictionary<string, string> Dictionary<string, string> body = new Dictionary<string, string>
{ {
{ "video_ids", Id }, { "video_ids", Id },
{ "full_list_id", "WL" }, { "full_list_id", "WL" },
{ "plid", plid }, { "plid", plid },
{ "session_token", sessionToken } { "session_token", sessionToken }
}; };
HttpResponseMessage response = await client.PostAsync("https://www.youtube.com/playlist_video_ajax?action_delete_from_playlist=1", new FormUrlEncodedContent(body)); HttpResponseMessage response = await client.PostAsync("https://www.youtube.com/playlist_video_ajax?action_delete_from_playlist=1", new FormUrlEncodedContent(body));
string responseStr = await response.Content.ReadAsStringAsync(); string responseStr = await response.Content.ReadAsStringAsync();
if (!responseStr.Contains("SUCCESS")) if (!responseStr.Contains("SUCCESS"))
throw new Exception(responseStr); throw new Exception(responseStr);
} }
public void Execute() => public void Execute() =>
ExecuteAsync().Wait(); ExecuteAsync().Wait();
} }
} }
} }
+36 -40
View File
@@ -1,42 +1,38 @@
using System; namespace YouTube
using System.Collections.Generic;
using System.Text;
namespace YouTube
{ {
public static class VideoQuality public static class VideoQuality
{ {
public static string Auto => QualityConstants.Auto; public static string Auto => QualityConstants.Auto;
public static string Low144 => QualityConstants.Low144; public static string Low144 => QualityConstants.Low144;
public static string Low240 => QualityConstants.Low240; public static string Low240 => QualityConstants.Low240;
public static string Medium360 => QualityConstants.Medium360; public static string Medium360 => QualityConstants.Medium360;
public static string Meduim480 => QualityConstants.Meduim480; public static string Meduim480 => QualityConstants.Meduim480;
public static string High720 => QualityConstants.High720; public static string High720 => QualityConstants.High720;
public static string High720p60 => QualityConstants.High720p60; public static string High720p60 => QualityConstants.High720p60;
public static string High1080 => QualityConstants.High1080; public static string High1080 => QualityConstants.High1080;
public static string High1080p60 => QualityConstants.High1080p60; public static string High1080p60 => QualityConstants.High1080p60;
public static string High1440 => QualityConstants.High1440; public static string High1440 => QualityConstants.High1440;
public static string High2160 => QualityConstants.High2160; public static string High2160 => QualityConstants.High2160;
public static string High2880 => QualityConstants.High2880; public static string High2880 => QualityConstants.High2880;
public static string High3072 => QualityConstants.High3072; public static string High3072 => QualityConstants.High3072;
public static string High4320 => QualityConstants.High4320; public static string High4320 => QualityConstants.High4320;
public static class QualityConstants public static class QualityConstants
{ {
public const string Auto = "auto"; public const string Auto = "auto";
public const string Low144 = "144p"; public const string Low144 = "144p";
public const string Low240 = "240p"; public const string Low240 = "240p";
public const string Medium360 = "360p"; public const string Medium360 = "360p";
public const string Meduim480 = "480p"; public const string Meduim480 = "480p";
public const string High720 = "720p"; public const string High720 = "720p";
public const string High720p60 = "720p60"; public const string High720p60 = "720p60";
public const string High1080 = "1080p"; public const string High1080 = "1080p";
public const string High1080p60 = "1080p60"; public const string High1080p60 = "1080p60";
public const string High1440 = "1440p"; public const string High1440 = "1440p";
public const string High2160 = "2160p"; public const string High2160 = "2160p";
public const string High2880 = "2880p"; public const string High2880 = "2880p";
public const string High3072 = "3072p"; public const string High3072 = "3072p";
public const string High4320 = "4320p"; public const string High4320 = "4320p";
} }
} }
} }
+1 -1
View File
@@ -26,7 +26,7 @@
<PackageReference Include="Google.Apis.Auth" Version="1.45.0" /> <PackageReference Include="Google.Apis.Auth" Version="1.45.0" />
<PackageReference Include="Google.Apis.Core" Version="1.45.0" /> <PackageReference Include="Google.Apis.Core" Version="1.45.0" />
<PackageReference Include="Google.Apis.Oauth2.v2" Version="1.45.0.1869" /> <PackageReference Include="Google.Apis.Oauth2.v2" Version="1.45.0.1869" />
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.45.0.1918" /> <PackageReference Include="Google.Apis.YouTube.v3" Version="1.45.0.1929" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" /> <PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="all" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="all" />
<PackageReference Include="YoutubeExplode" Version="4.7.16" /> <PackageReference Include="YoutubeExplode" Version="4.7.16" />
+13 -13
View File
@@ -2,17 +2,17 @@
namespace YouTube namespace YouTube
{ {
public partial class ExtendedYouTubeService : Google.Apis.YouTube.v3.YouTubeService public partial class ExtendedYouTubeService : Google.Apis.YouTube.v3.YouTubeService
{ {
public DashManifestsResource DashManifests => new DashManifestsResource(this); public DashManifestsResource DashManifests => new DashManifestsResource(this);
public VideoPlaybackResource VideoPlayback => new VideoPlaybackResource(this); public VideoPlaybackResource VideoPlayback => new VideoPlaybackResource(this);
public new CaptionsResource Captions => new CaptionsResource(this); public new CaptionsResource Captions => new CaptionsResource(this);
public HistoryResource History { get; } public HistoryResource History { get; }
public WatchLaterResource WatchLater => new WatchLaterResource(this); public WatchLaterResource WatchLater => new WatchLaterResource(this);
// TODO: Add Activities override for recomendations and subscriptions // TODO: Add Activities override for recomendations and subscriptions
public ExtendedYouTubeService() : base() { }
public ExtendedYouTubeService(Initializer initializer) : base(initializer) { } public ExtendedYouTubeService() : base() { }
}
} public ExtendedYouTubeService(Initializer initializer) : base(initializer) { }
}
}