moved to subfolder

This commit is contained in:
2018-12-09 23:24:53 +01:00
parent fd86f3e9c7
commit 02aad5f41d
25 changed files with 0 additions and 0 deletions

9
Tv7Playlist/AppConfig.cs Normal file
View File

@@ -0,0 +1,9 @@
namespace Tv7Playlist
{
public class AppConfig
{
public string TV7Url { get; set; }
public string UdpxyUrl { get; set; }
public string DownloadFileName { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Tv7Playlist.Models;
namespace Tv7Playlist.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

View File

@@ -0,0 +1,122 @@
using System;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Tv7Playlist.Controllers
{
[Route("api/playlist")]
[ApiController]
public class PlayListController : ControllerBase
{
private const string PlayListContentType = "audio/mpegurl";
/// <summary>
/// This is the regex used to build up the proxy url.
/// The first part (udp://@) is ignored while generating the final url
/// The multicast address is expected to be a ip-address with a port and is reused
/// </summary>
private static readonly Regex MultiCastRegex = new Regex(@"(udp\:\/\/@)([0-9.:]+)",
RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
private readonly string _downloadFileName;
private readonly ILogger<PlayListController> _logger;
private readonly string _proxyUrl;
private readonly string _tv7Url;
public PlayListController(ILogger<PlayListController> logger, IConfiguration configuration)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
var appConfig = configuration.Get<AppConfig>();
_tv7Url = GetTv7Url(appConfig);
_proxyUrl = GetProxyUrl(appConfig);
_downloadFileName = GetDownloadFileName(appConfig);
}
[HttpGet]
public async Task<ActionResult> Get()
{
using (var httpClient = new HttpClient())
{
_logger.LogInformation(LoggingEvents.Playlist, "Downloading playlist from {tv7url}", _tv7Url);
var tv7Response = await httpClient.GetAsync(_tv7Url);
if (!tv7Response.IsSuccessStatusCode)
{
_logger.LogWarning(LoggingEvents.PlaylistNotFound,
"Could not download playlist from {tv7url}. The StatusCode was: {StatusCode}", _tv7Url,
tv7Response.StatusCode);
return StatusCode((int) tv7Response.StatusCode);
}
var modifiedPlaylist = await BuildProxyPlaylist(tv7Response);
_logger.LogInformation(LoggingEvents.Playlist, "Sending updated playlist {filename}",
_downloadFileName);
return new FileStreamResult(modifiedPlaylist, PlayListContentType)
{
FileDownloadName = _downloadFileName
};
}
}
private async Task<MemoryStream> BuildProxyPlaylist(HttpResponseMessage tv7Response)
{
var outStream = new MemoryStream();
var outWriter = new StreamWriter(outStream);
_logger.LogInformation(LoggingEvents.Playlist, "Building m3u file content");
using (var tv7ReadStream = await tv7Response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(tv7ReadStream))
{
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
var proxyLine = MultiCastRegex.Replace(line, $"{_proxyUrl}/$2/");
outWriter.WriteLine(proxyLine);
_logger.LogDebug(LoggingEvents.Playlist, "Transformed {src} to {dst}", line, proxyLine);
}
await outWriter.FlushAsync();
}
outStream.Seek(0, SeekOrigin.Begin);
return outStream;
}
private string GetTv7Url(AppConfig configuration)
{
var tv7Url = configuration.TV7Url;
if (!Uri.IsWellFormedUriString(tv7Url, UriKind.Absolute))
throw new ApplicationException($"The TV7Url is set to {tv7Url}. This is not a well formed uri!");
return tv7Url;
}
private string GetProxyUrl(AppConfig configuration)
{
var proxyUrl = configuration.UdpxyUrl;
if (!Uri.IsWellFormedUriString(proxyUrl, UriKind.Absolute))
throw new ApplicationException($"The proxyUrl is set to {proxyUrl}. This is not a well formed uri!");
return proxyUrl;
}
private string GetDownloadFileName(AppConfig configuration)
{
var downloadFileName = configuration.DownloadFileName;
if (string.IsNullOrEmpty(downloadFileName)) downloadFileName = "playlist.m3u";
return downloadFileName;
}
}
}

View File

@@ -0,0 +1,11 @@
namespace Tv7Playlist
{
public class LoggingEvents
{
public const int Startup = 1000;
public const int Playlist = 1001;
public const int ParsingM3uPlayList = 1002;
public const int PlaylistNotFound = 4000;
}
}

View File

@@ -0,0 +1,11 @@
using System;
namespace Tv7Playlist.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@@ -0,0 +1,11 @@
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Tv7Playlist.Parser
{
public interface IPlaylistParser
{
Task<IReadOnlyCollection<ParsedTrack>> ParseFromStream(Stream stream);
}
}

View File

@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.Logging;
namespace Tv7Playlist.Parser
{
internal class M3UParser : IPlaylistParser
{
private const string ExtInfStartTag = "#EXTINF:";
private const string ExtFileStartTag = "#EXTM3U";
private readonly ILogger<M3UParser> _logger;
public M3UParser(ILogger<M3UParser> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<IReadOnlyCollection<ParsedTrack>> ParseFromStream(Stream stream)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
_logger.LogInformation(LoggingEvents.ParsingM3uPlayList, "Parsing m3u file content");
EnsureStreamIsAtBeginning(stream);
using (var reader = new StreamReader(stream))
{
var tracks = await ParseTracksFromStreamAsync(reader);
_logger.LogInformation(LoggingEvents.ParsingM3uPlayList, "Parsing m3u file finished");
return tracks;
}
}
private async Task<IReadOnlyCollection<ParsedTrack>> ParseTracksFromStreamAsync(StreamReader reader)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
if (!await StreamHasValidStartTagAsync(reader))
{
_logger.LogError(LoggingEvents.ParsingM3uPlayList, $"Could not parse stream as it did not start with {ExtFileStartTag}");
return new List<ParsedTrack>(300);
}
var tracks = new List<ParsedTrack>(300);
var currentId = 1000;
while (!reader.EndOfStream)
{
await ParseTracksAsync(reader, tracks, currentId);
currentId++;
}
return tracks;
}
private static async Task<bool> StreamHasValidStartTagAsync(StreamReader reader)
{
var startLine = await ReadLineSafeAsync(reader);
var stramHasValidStartTag = !startLine.Trim().ToUpper().Equals(ExtInfStartTag);
return stramHasValidStartTag;
}
private void EnsureStreamIsAtBeginning(Stream stream)
{
if (stream.Position == 0) return;
_logger.LogWarning(LoggingEvents.ParsingM3uPlayList, "Stream not positioned at the beginning. Repositioning!");
stream.Position = 0;
}
private async Task ParseTracksAsync(TextReader reader, ICollection<ParsedTrack> tracks, int currentId)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
if (tracks == null) throw new ArgumentNullException(nameof(tracks));
if (currentId <= 0) throw new ArgumentOutOfRangeException(nameof(currentId));
var metaLine = await ReadLineSafeAsync(reader);
if (!metaLine.StartsWith(ExtInfStartTag))
{
_logger.LogDebug(LoggingEvents.ParsingM3uPlayList,
"Line {lineNumber} {metaLine} is not a valid start channel start line",
currentId.ToString(), metaLine);
return;
}
var url = await ReadLineSafeAsync(reader);
var track = CreateTrack(currentId, metaLine, url);
if (track != null)
{
tracks.Add(track);
_logger.LogDebug(LoggingEvents.ParsingM3uPlayList, "Parsed track {track}", track);
}
else
{
_logger.LogWarning(LoggingEvents.ParsingM3uPlayList,
"Could not parse lines {metaLine} with url {url}", metaLine, url);
}
}
private static async Task<string> ReadLineSafeAsync(TextReader reader)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
var line = await reader.ReadLineAsync();
return line ?? string.Empty;
}
private ParsedTrack CreateTrack(int currentId, string metaLine, string url)
{
if (string.IsNullOrWhiteSpace(metaLine))
return null;
if (string.IsNullOrWhiteSpace(url))
return null;
var fields = metaLine.Replace(ExtInfStartTag, string.Empty).Split(",");
var name = fields.Length >= 2 ? fields[1] : $"{currentId}-unknown";
return new ParsedTrack(currentId, name, url);
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Diagnostics;
namespace Tv7Playlist.Parser
{
[DebuggerDisplay("ParsedTrack-{Id}(Name:{Name}, Url:{Url})")]
public class ParsedTrack
{
public ParsedTrack(int id, string name, string url)
{
Id = id;
Name = name;
Url = url ?? throw new ArgumentNullException(nameof(url));
}
public int Id { get; }
public string Name { get; }
public string Url { get; }
protected bool Equals(ParsedTrack other)
{
return Id == other.Id && string.Equals(Name, other.Name) && string.Equals(Url, other.Url);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((ParsedTrack) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Id;
hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Url != null ? Url.GetHashCode() : 0);
return hashCode;
}
}
public override string ToString()
{
return $"{nameof(Id)}: {Id}, {nameof(Name)}: {Name}, {nameof(Url)}: {Url}";
}
}
}

30
Tv7Playlist/Program.cs Normal file
View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Tv7Playlist
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();
}
}

View File

@@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:18699",
"sslPort": 44374
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"tv7playlist": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

9
Tv7Playlist/README.md Normal file
View File

@@ -0,0 +1,9 @@
# tv7playlist
This little application is used to rewrite the TV7 multicast channel list by fiber7 m3u.
The updated list will proxy the multicast stream through udpxy and builds a stream that plex can handle.
Others have changed the code in telly. As I did not want to change any external source, I just
wrote this little program.
This is licenced under GPLv2. See License file.

74
Tv7Playlist/Startup.cs Normal file
View File

@@ -0,0 +1,74 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Tv7Playlist
{
public class Startup
{
private readonly ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
LogConfiguration();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
private void LogConfiguration()
{
var appConfig = Configuration.Get<AppConfig>();
_logger.LogInformation(LoggingEvents.Startup, "Using TV7 URL: {TV7Url}", appConfig.TV7Url);
_logger.LogInformation(LoggingEvents.Startup, "Using Udpxy URL: {UdpxyUrl}", appConfig.UdpxyUrl);
_logger.LogInformation(LoggingEvents.Startup, "Using DownloadFileName: {DownloadFileName}",
appConfig.DownloadFileName);
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,8 @@
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

View File

@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@@ -0,0 +1,25 @@
@using Microsoft.AspNetCore.Http.Features
@{
var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
var showBanner = !consentFeature?.CanTrack ?? false;
var cookieString = consentFeature?.CreateConsentCookie();
}
@if (showBanner)
{
<div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
Use this space to summarize your privacy and cookie use policy.
<button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
<span aria-hidden="true">Accept</span>
</button>
</div>
<script>
(function () {
var button = document.querySelector("#cookieConsent button[data-cookie-string]");
button.addEventListener("click", function (event) {
document.cookie = button.dataset.cookieString;
}, false);
})();
</script>
}

View File

@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>@ViewData["Title"] - Tv7Playlist</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css"/>
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"/>
</environment>
<link rel="stylesheet" href="~/css/site.css"/>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Tv7Playlist</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<partial name="_CookieConsentPartial"/>
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2018 - Tv7Playlist
</div>
</footer>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</environment>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", false)
</body>
</html>

View File

@@ -0,0 +1,8 @@
<environment include="Development">
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
</environment>

View File

@@ -0,0 +1,3 @@
@using Tv7Playlist
@using Tv7Playlist.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"System": "Information",
"Microsoft": "Information"
}
},
"AllowedHosts": "*",
"TV7Url": "https://api.init7.net/tvchannels.m3u",
"UdpxyUrl": "http://192.168.15.2:4022/udp",
"DownloadFileName": "PlaylistTV7udpxy.m3u"
}

View File

@@ -0,0 +1,56 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
/* Set the fixed height of the footer here */
height: 60px;
line-height: 60px; /* Vertically center the text there */
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@@ -0,0 +1,4 @@
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.