Rebase all

This commit is contained in:
Laura Hausmann 2021-01-24 04:04:16 +01:00
commit 978a00cf8d
80 changed files with 41333 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
/.idea/
bin/
obj/
/packages/
/data/
app.db

View file

@ -0,0 +1,30 @@
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using RTMPDash.DataModels;
namespace RTMPDash.Controllers {
[ApiController, Route("/api/authenticate")]
public class RtmpAuthController : ControllerBase {
[HttpGet]
public string Get() {
var db = new AppDb.DbConn();
if (!db.Users.Any(p => p.StreamKey == Request.Query["name"])) {
Response.StatusCode = 403;
return "unauthorized";
}
var user = db.Users.FirstOrDefault(p => p.StreamKey == Request.Query["name"]);
Response.Headers.Add("x-rtmp-user", user!.Username);
if (!user!.AllowRestream || string.IsNullOrWhiteSpace(user.RestreamTargets))
Response.Headers.Add("x-rtmp-target", "rtmp://127.0.0.1/src/" + user!.Username);
else
Response.Headers.Add("x-rtmp-target",
"rtmp://127.0.0.1/src/" + user!.Username + "," + user.RestreamTargets);
Response.StatusCode = 302;
return "authorized as " + user!.Username;
}
}
}

39
DataModels/AppDb.cs Normal file
View file

@ -0,0 +1,39 @@
using System.Collections.Generic;
using System.Linq;
using LinqToDB;
using LinqToDB.Configuration;
using LinqToDB.Data;
using RTMPDash.DataModels.Tables;
namespace RTMPDash.DataModels {
public class AppDb {
public class ConnectionStringSettings : IConnectionStringSettings {
public string ConnectionString { get; set; }
public string Name { get; set; }
public string ProviderName { get; set; }
public bool IsGlobal => false;
}
public class Settings : ILinqToDBSettings {
public IEnumerable<IDataProviderSettings> DataProviders => Enumerable.Empty<IDataProviderSettings>();
public string DefaultConfiguration => "SQLite";
public string DefaultDataProvider => "SQLite";
public IEnumerable<IConnectionStringSettings> ConnectionStrings {
get {
yield return new ConnectionStringSettings {
Name = "db", ProviderName = "SQLite", ConnectionString = @"Data Source=app.db;"
};
}
}
}
public class DbConn : DataConnection {
public DbConn() : base("db") { }
public ITable<User> Users => GetTable<User>();
public ITable<Invite> Invites => GetTable<Invite>();
}
}
}

View file

@ -0,0 +1,8 @@
using LinqToDB.Mapping;
namespace RTMPDash.DataModels.Tables {
[Table(Name = "Invites")]
public class Invite {
[Column(Name = "Code"), PrimaryKey, NotNull] public string Code { get; set; }
}
}

19
DataModels/Tables/User.cs Normal file
View file

@ -0,0 +1,19 @@
using LinqToDB.Mapping;
namespace RTMPDash.DataModels.Tables {
[Table(Name = "Users")]
public class User {
[Column(Name = "Username"), PrimaryKey] public string Username { get; set; }
[Column(Name = "Password")] public string Password { get; set; }
[Column(Name = "IsAdmin")] public bool IsAdmin { get; set; }
[Column(Name = "AllowRestream")] public bool AllowRestream { get; set; }
[Column(Name = "StreamKey")] public string StreamKey { get; set; }
[Column(Name = "PronounSubject")] public string PronounSubject { get; set; }
[Column(Name = "PronounPossessive")] public string PronounPossessive { get; set; }
[Column(Name = "ChatUrl")] public string ChatUrl { get; set; }
[Column(Name = "AnnouncementUrl")] public string AnnouncementUrl { get; set; }
[Column(Name = "SrcRes")] public string SrcRes { get; set; }
[Column(Name = "RestreamTargets")] public string RestreamTargets { get; set; }
[Column(Name = "RestreamUrls")] public string RestreamUrls { get; set; }
}
}

7
LICENSE.md Normal file
View file

@ -0,0 +1,7 @@
Copyright 2021 Laura Hausmann
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

135
Pages/Admin.cshtml Normal file
View file

@ -0,0 +1,135 @@
@page
@inject IAntiforgery Antiforgery
@using Microsoft.AspNetCore.Antiforgery
@using Microsoft.AspNetCore.Http
@using RTMPDash.DataModels
@model AdminModel
@{
ViewData["Title"] = "Admin";
var db = new AppDb.DbConn();
var tokenSet = Antiforgery.GetAndStoreTokens(HttpContext);
if (string.IsNullOrEmpty(HttpContext.Session.GetString("authenticatedUser")) || !new AppDb.DbConn().Users.First(p => p.Username == HttpContext.Session.GetString("authenticatedUser")).IsAdmin) {
Response.Redirect("/");
return;
}
}
<h2>Users</h2>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Username</th>
<th scope="col">Stream status</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var user in db.Users) {
<tr>
<th scope="row">@user.Username</th>
<td>
@if (StreamUtils.IsLive(user.Username)) {
/*if (StreamUtils.IsLive(user.Username, "1080")) {
<button class="btn btn-dark" role="button" style="width:13ch" disabled>Restreaming</button>
}
else {*/
<button class="btn btn-success" role="button" style="width:13ch" disabled>Live</button>
//}
//kept around for
//TODO Restreaming & direct stats support
}
else {
<button class="btn btn-danger" role="button" style="width:13ch" disabled>No data</button>
}
</td>
<td>
@if (user.IsAdmin) {
if (user.Username != HttpContext.Session.GetString("authenticatedUser")) {
<button onclick="ajax_and_reload('admin_revoke', '@user.Username')" class="btn btn-warning">Revoke Admin</button>
}
else {
<button class="btn btn-warning" disabled>Revoke Admin</button>
}
}
else {
<button onclick="ajax_and_reload('admin_grant', '@user.Username')" class="btn btn-primary">Grant Admin</button>
}
@if (user.AllowRestream) {
<button onclick="ajax_and_reload('restream_revoke', '@user.Username')" class="btn btn-secondary">Revoke Restreams</button>
}
else {
<button onclick="ajax_and_reload('restream_allow', '@user.Username')" class="btn btn-info">Allow Restreams</button>
}
@if (user.IsAdmin) {
<button class="btn btn-dark" disabled>Set Password</button>
<button class="btn btn-danger" disabled>Delete</button>
}
else {
<button class="btn btn-dark" onclick="prepareSetPasswordModal('@user.Username')">Set Password</button>
<button onclick="ajax_and_reload('user_delete', '@user.Username')" class="btn btn-danger">Delete</button>
}
</td>
</tr>
}
</tbody>
</table>
<h2>Invites</h2>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Code</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var invite in db.Invites) {
<tr>
<td>@invite.Code</td>
<td>
<button onclick="copyToClipboard('@invite.Code')" class="btn btn-sm btn-secondary">Copy</button>
<button onclick="ajax_and_reload('invite_revoke', '@invite.Code')" class="btn btn-sm btn-danger">Revoke</button>
</td>
</tr>
}
</tbody>
</table>
<button onclick="ajax_and_reload('invite_generate')" class="btn btn-dark">Generate New Invite</button>
<script>
function ajax_and_reload(action, target, value) {
$.ajax({method: 'POST', data: {action: action, target: target, value: value, '__RequestVerificationToken' : '@tokenSet.RequestToken'}, success: function () { location.reload() }})
}
function prepareSetPasswordModal(target) {
document.getElementById('setPasswordModalLabel').innerHTML = 'Set password for: ' + target;
document.getElementById('setPasswordTarget').value = target;
$('#setPasswordModal').modal();
}
</script>
<div class="modal fade" id="setPasswordModal" tabindex="-1" aria-labelledby="setPasswordModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="setPasswordModalLabel">Set password for</h5>
<button role="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<form method="POST">
<div class="modal-body">
<div class="form-group">
<input type="password" class="form-control" id="InputPassword" placeholder="New Password" name="value" required>
<input type="hidden" value="user_setpass" name="action">
<input type="hidden" value="" name="target" id="setPasswordTarget">
</div>
</div>
<div class="modal-footer">
<button role="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>

67
Pages/Admin.cshtml.cs Normal file
View file

@ -0,0 +1,67 @@
using System;
using System.Linq;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RTMPDash.DataModels;
using RTMPDash.DataModels.Tables;
namespace RTMPDash.Pages {
public class AdminModel : PageModel {
public void OnGet() { }
public void OnPost() {
if (string.IsNullOrEmpty(HttpContext.Session.GetString("authenticatedUser"))
|| !new AppDb.DbConn().Users
.First(p => p.Username == HttpContext.Session.GetString("authenticatedUser"))
.IsAdmin)
return;
if (!Request.HasFormContentType || string.IsNullOrWhiteSpace(Request.Form["action"]))
return;
var db = new AppDb.DbConn();
if (Request.Form["action"] == "invite_generate")
db.Insert(new Invite {Code = Guid.NewGuid().ToString().Substring(9, 14)});
if (Request.Form["action"] == "invite_revoke")
db.Delete(db.Invites.First(p => p.Code == Request.Form["target"]));
if (Request.Form["action"] == "restream_allow") {
var user = db.Users.First(p => p.Username == Request.Form["target"]);
user.AllowRestream = true;
db.Update(user);
}
if (Request.Form["action"] == "restream_revoke") {
var user = db.Users.First(p => p.Username == Request.Form["target"]);
user.AllowRestream = false;
db.Update(user);
}
if (Request.Form["action"] == "admin_grant") {
var user = db.Users.First(p => p.Username == Request.Form["target"]);
user.IsAdmin = true;
db.Update(user);
}
if (Request.Form["action"] == "admin_revoke") {
var user = db.Users.First(p => p.Username == Request.Form["target"]);
user.IsAdmin = false;
db.Update(user);
}
if (Request.Form["action"] == "user_delete") {
var user = db.Users.First(p => p.Username == Request.Form["target"]);
db.Delete(user);
}
if (Request.Form["action"] == "user_setpass") {
var user = db.Users.First(p => p.Username == Request.Form["target"]);
user.Password = Request.Form["value"].ToString().Sha256();
db.Update(user);
}
}
}
}

15
Pages/Credits.cshtml Normal file
View file

@ -0,0 +1,15 @@
@page
@model CreditsModel
@{
ViewData["Title"] = "Credits";
}
<h1>@ViewData["Title"]</h1>
<p>
All streamed content belongs to the respective content creators. We do not record or otherwise store streamed materials.
</p>
<p>
Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a>
</p>
<p>If you have any further questions, contact us at <a href="mailto:@Program.CopyrightEmail">@Program.CopyrightEmail</a></p>

7
Pages/Credits.cshtml.cs Normal file
View file

@ -0,0 +1,7 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
public class CreditsModel : PageModel {
public void OnGet() { }
}
}

195
Pages/Dashboard.cshtml Normal file
View file

@ -0,0 +1,195 @@
@page
@inject IAntiforgery Antiforgery
@using Microsoft.AspNetCore.Antiforgery
@using Microsoft.AspNetCore.Http
@using RTMPDash.DataModels
@model DashboardModel
@{
ViewData["Title"] = "Dashboard";
var tokenSet = Antiforgery.GetAndStoreTokens(HttpContext);
}
@if (string.IsNullOrWhiteSpace(HttpContext.Session.GetString("authenticatedUser"))) {
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>If you have an invite, <a asp-page="/Register">sign up</a> here. If you already have an account, <a asp-page="/Login">sign back in</a>.</p>
</div>
}
else {
var db = new AppDb.DbConn();
var user = db.Users.First(p => p.Username == HttpContext.Session.GetString("authenticatedUser"));
<div class="alert alert-success" role="alert">
<h4 class="alert-heading">Welcome back!</h4>
<p>Thanks for using @Program.SiteName. If you have any issues, please contact me on <a href="https://t.me/zotan">Telegram</a>, <a href="https://threema.id/S59S9U8J">Threema</a>, or via <a href="mailto:zotan@zotan.pw">email</a>.</p>
<hr>
<p class="mb-0">When using OBS, the stream key and leading slash before it is to be left out in the RTMP url.</p>
<hr/>
<p class="mb-0">For low-latancy streams, please set your keyframe interval to 1-2 seconds. Otherwise, automatic or something in the range of 4-8 seconds is fine.</p>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Profile URL</span>
</div>
<input type="text" class="form-control" id="input-profileurl" value="@Program.RootDomain/profile/@user.Username" disabled>
<div class="input-group-append">
<button class="btn btn-outline-secondary" role="button" id="button-copy-profileurl" onclick="copyToClipboard(document.getElementById('input-profileurl').value);">Copy</button>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Player URL</span>
</div>
<input type="text" class="form-control" id="input-playerurl" value="@Program.PlayerDomain/@user.Username" disabled>
<div class="input-group-append">
<button class="btn btn-outline-secondary" role="button" id="button-copy-playerurl" onclick="copyToClipboard(document.getElementById('input-playerurl').value);">Copy</button>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Stream key</span>
</div>
<input type="text" class="form-control" id="input-streamkey" value="@user.StreamKey" disabled>
<div class="input-group-append">
<button onclick="ajax_and_reload('streamkey_reset')" class="btn btn-outline-danger" role="button" id="button-reset-streamkey">Reset</button>
<button class="btn btn-outline-secondary" role="button" id="button-copy-streamkey" onclick="copyToClipboard(document.getElementById('input-streamkey').value);">Copy</button>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Stream URL</span>
</div>
<input type="text" class="form-control" id="input-streamurl" value="@Program.IngressDomain/ingress/@user.StreamKey" disabled>
<div class="input-group-append">
@if (StreamUtils.IsLive(user.Username)) {
/*if (StreamUtils.IsLive(user.Username, "1080")) {
<button class="btn btn-dark" role="button" style="width:13ch" disabled>Restreaming</button>
}
else {*/
<button class="btn btn-success" role="button" style="width:13ch" disabled>Live</button>
//}
//kept around for
//TODO Restreaming & direct stats support
}
else {
<button class="btn btn-danger" role="button" style="width:13ch" disabled>No data</button>
}
<button class="btn btn-outline-secondary" role="button" id="button-copy-streamurl" onclick="copyToClipboard(document.getElementById('input-streamurl').value);">Copy</button>
</div>
</div>
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Chat URL</span>
</div>
<input type="hidden" value="chaturl_set" name="action">
<input type="text" class="form-control" name="value" placeholder="Leave empty to disable" value="@user.ChatUrl">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Announcement URL</span>
</div>
<input type="hidden" value="announceurl_set" name="action">
<input type="text" class="form-control" name="value" placeholder="Leave empty to disable" value="@user.AnnouncementUrl">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
if (user.SrcRes == "unspecified") {
<div class="alert alert-warning" role="alert">
<b>Hey, you!</b>
<span>You have not yet specified the resolution and bitrate in which you stream. Please do so below. Thank you!</span>
</div>
}
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Source Resolution</span>
</div>
<input type="hidden" value="srcres_set" name="action">
<input type="text" class="form-control" name="value" placeholder="example: 1080p60 @@ 10Mbit (Shown in profile page tooltip)" value="@(user.SrcRes == "unspecified" ? "" : user.SrcRes)">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@if (user.AllowRestream) {
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Restream targets</span>
</div>
<input type="hidden" value="restream_targets_set" name="action">
<input type="text" class="form-control" name="value" placeholder="rtmp://live-ber.twitch.tv/app/streamkey,rtmp://a.rtmp.youtube.com/live2/streamkey" value="@user.RestreamTargets">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Restream URLs</span>
</div>
<input type="hidden" value="restream_urls_set" name="action">
<input type="text" class="form-control" name="value" placeholder="https://twitch.tv/yourusername,https://youtube.com/c/channelid/live" value="@user.RestreamUrls">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
}
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Pronoun (subject)</span>
</div>
<input type="hidden" value="pronoun_subj_set" name="action">
<input type="text" class="form-control" name="value" placeholder="they" value="@user.PronounSubject">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<form method="POST">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" style="width:23ch">Pronoun (possessive)</span>
</div>
<input type="hidden" value="pronoun_poss_set" name="action">
<input type="text" class="form-control" name="value" placeholder="their" value="@user.PronounPossessive">
<div class="input-group-append">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<form method="POST">
<div class="form-group">
<label for="InputPassword">Change Password</label>
<input type="password" class="form-control" id="InputPassword" placeholder="New Password" name="pass" required>
<input type="hidden" value="password_change" name="action">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function ajax_and_reload(action, target, value) {
$.ajax({method: 'POST', data: {action: action, target: target, value: value, '__RequestVerificationToken' : '@tokenSet.RequestToken'}, success: function () { location.reload() }})
}
</script>
}

93
Pages/Dashboard.cshtml.cs Normal file
View file

@ -0,0 +1,93 @@
using System;
using System.Linq;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RTMPDash.DataModels;
namespace RTMPDash.Pages {
public class DashboardModel : PageModel {
public void OnGet() { }
public void OnPost() {
if (!Request.HasFormContentType
|| string.IsNullOrWhiteSpace(Request.Form["action"])
|| string.IsNullOrWhiteSpace(HttpContext.Session.GetString("authenticatedUser")))
return;
using var db = new AppDb.DbConn();
var user = db.Users.FirstOrDefault(p => p.Username == HttpContext.Session.GetString("authenticatedUser"));
if (Request.Form["action"] == "password_change") {
var newPass = Request.Form["pass"];
user!.Password = newPass.ToString().Sha256();
db.Update(user);
Response.Redirect("/Logout");
}
if (Request.Form["action"] == "chaturl_set") {
user!.ChatUrl = Request.Form["value"];
db.Update(user);
Response.Redirect("/Dashboard");
}
if (Request.Form["action"] == "announceurl_set") {
user!.AnnouncementUrl = Request.Form["value"];
db.Update(user);
Response.Redirect("/Dashboard");
}
if (user!.AllowRestream) {
if (Request.Form["action"] == "restream_urls_set") {
user!.RestreamUrls = Request.Form["value"];
db.Update(user);
Response.Redirect("/Dashboard");
}
if (Request.Form["action"] == "restream_targets_set") {
var newtgts = Request.Form["value"].ToString();
if (newtgts.Contains("localhost")
|| newtgts.Contains("127.0.0.1")
|| newtgts.Contains(user.StreamKey))
return;
user!.RestreamTargets = newtgts;
db.Update(user);
Response.Redirect("/Dashboard");
}
}
if (Request.Form["action"] == "pronoun_subj_set") {
var target = string.IsNullOrWhiteSpace(Request.Form["value"])
? "they"
: Request.Form["value"].ToString();
user!.PronounSubject = target.ToLowerInvariant();
db.Update(user);
Response.Redirect("/Dashboard");
}
if (Request.Form["action"] == "pronoun_poss_set") {
var target = string.IsNullOrWhiteSpace(Request.Form["value"])
? "their"
: Request.Form["value"].ToString();
user!.PronounPossessive = target.ToLowerInvariant();
db.Update(user);
Response.Redirect("/Dashboard");
}
if (Request.Form["action"] == "srcres_set") {
var target = string.IsNullOrWhiteSpace(Request.Form["value"])
? "unspecified"
: Request.Form["value"].ToString();
user!.SrcRes = target;
db.Update(user);
Response.Redirect("/Dashboard");
}
if (Request.Form["action"] == "streamkey_reset") {
user!.StreamKey = Guid.NewGuid().ToString().Substring(9, 14);
db.Update(user);
}
}
}
}

25
Pages/Error.cshtml Normal file
View file

@ -0,0 +1,25 @@
@page
@model ErrorModel
@{
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 the <strong>Development</strong> environment displays 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>

16
Pages/Error.cshtml.cs Normal file
View file

@ -0,0 +1,16 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true), IgnoreAntiforgeryToken]
public class ErrorModel : PageModel {
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet() {
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}

21
Pages/Index.cshtml Normal file
View file

@ -0,0 +1,21 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Home";
var liveUsers = StreamUtils.ListLiveUsers();
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
@if (liveUsers.Count > 0) {
<p>The following users are currently live:</p>
<div class="btn-group btn-group" role="group">
@foreach (var user in liveUsers) {
<a href="/profile/@user" class="btn btn-primary" role="button">@user</a>
}
</div>
}
else {
<p>At the moment, no users are live. Please check back later!</p>
}
</div>

7
Pages/Index.cshtml.cs Normal file
View file

@ -0,0 +1,7 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
public class IndexModel : PageModel {
public void OnGet() { }
}
}

25
Pages/Login.cshtml Normal file
View file

@ -0,0 +1,25 @@
@page
@using Microsoft.AspNetCore.Http
@model LoginModel
@{
ViewData["Title"] = "Login";
if (!string.IsNullOrWhiteSpace(HttpContext.Session.GetString("authenticatedUser"))) {
Response.Redirect("/Dashboard");
return;
}
}
<h3>@ViewData["Title"]</h3>
<form method="POST">
<div class="form-group">
<label for="InputUser">Username</label>
<input type="text" class="form-control" id="InputUser" name="user">
</div>
<div class="form-group">
<label for="InputPassword">Password</label>
<input type="password" class="form-control" id="InputPassword" name="pass">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

79
Pages/Login.cshtml.cs Normal file
View file

@ -0,0 +1,79 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RTMPDash.DataModels;
namespace RTMPDash.Pages {
public class LoginModel : PageModel {
public void OnPost() {
if (!Request.HasFormContentType
|| string.IsNullOrWhiteSpace(Request.Form["user"])
|| string.IsNullOrWhiteSpace(Request.Form["pass"]))
return;
using var db = new AppDb.DbConn();
var user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString()
&& p.Password == Request.Form["pass"].ToString().Sha256());
if (user == null)
return;
HttpContext.Session.SetString("authenticatedUser", user.Username);
}
}
public static class StringExtensions {
public static string Sha256(this string rawData) {
// Create a SHA256
using var sha256Hash = SHA256.Create();
// ComputeHash - returns byte array
var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
var builder = new StringBuilder();
for (var i = 0; i < bytes.Length; i++)
builder.Append(bytes[i].ToString("x2"));
return builder.ToString();
}
public static string FirstCharToUpper(this string input) => input switch {
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => input.First().ToString().ToUpper() + input.Substring(1)
};
public static string Base64Encode(this string plainText) {
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
public static string UrlEncode(this string plainText) => HttpUtility.UrlEncode(plainText);
public static string Delimit(this string input, int max) =>
input.PadRight(max, ' ').Substring(0, max).TrimEnd();
public static string Bash(this string cmd) {
var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
var result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}
}

7
Pages/Logout.cshtml Normal file
View file

@ -0,0 +1,7 @@
@page
@model LogoutModel
@{
Layout = null;
Response.Redirect("/");
}

9
Pages/Logout.cshtml.cs Normal file
View file

@ -0,0 +1,9 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
public class LogoutModel : PageModel {
public void OnGet() {
HttpContext.Session.Clear();
}
}
}

40
Pages/Privacy.cshtml Normal file
View file

@ -0,0 +1,40 @@
@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Last update: 2021-01-21 20:55 CET</p>
<p>The only cookies we store on your device is a session identifier, which is used to access information related to your session on the server, as well as CSRF antiforgery tokens.</p>
<p>We do not track you, nor use external services that do.</p>
<p>We do not save any data in your session unless you log in. For registered users, the following data associated with you is stored in our database:</p>
<ul>
<li>Your username and hashed password</li>
<li>Your stream key</li>
<li>Your configured pronouns</li>
<li>Your configured chat URL</li>
<li>Your configured announcements URL</li>
<li>Your configured resolution and bitrate</li>
<li>Your configured restream URLs (if applicable)</li>
</ul>
<p>Web server access logs are disabled. For registered users, we log the following data about RTMP sessions:</p>
<ul>
<li>Timestamp of session end</li>
<li>RTMP method</li>
<li>RTMP endpoint</li>
<li>RTMP streamkey</li>
<li>Bytes received during the streaming session</li>
<li>Duration of the session</li>
</ul>
<p>This data may be used for statistical purposes.</p>
<p>
When viewing a stream, the HLS playlist file as well as the MPEG-TS fragments are proxied through Cloudflare (US).
This could allow Cloudflare (US) to intercept all data to and from the streaming server.
This does not apply to the rest of the website.
</p>
<p>More detailed information about GDPR and Cloudflare can be found on the <a href="https://cloudflare.com/gdpr/introduction/">GDPR pages of Cloudflare</a>.</p>
<p>If you have any further questions, contact us at <a href="mailto:@Program.PrivacyEmail">@Program.PrivacyEmail</a></p>

7
Pages/Privacy.cshtml.cs Normal file
View file

@ -0,0 +1,7 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
public class PrivacyModel : PageModel {
public void OnGet() { }
}
}

41
Pages/Register.cshtml Normal file
View file

@ -0,0 +1,41 @@
@page
@using Microsoft.AspNetCore.Http
@model RegisterModel
@{
ViewData["Title"] = "Register";
if (!string.IsNullOrWhiteSpace(HttpContext.Session.GetString("authenticatedUser"))) {
Response.Redirect("/Dashboard");
return;
}
}
<h3>@ViewData["Title"]</h3>
@if (Request.Query.ContainsKey("e")) {
<div class="alert alert-warning" role="alert">
<h4 class="alert-heading">Sorry :(</h4>
@if (Request.Query["e"] == "user_exists") {
<p class="mb-0">The username you were attempting to register with is already in use. Please use a different username.</p>
}
else {
<p class="mb-0">An unknown error occoured. The error code was <b>@Request.Query["e"]</b>.</p>
}
</div>
}
<form method="POST">
<div class="form-group">
<label for="InputUser">Username</label>
<input type="text" class="form-control" id="InputUser" name="user">
</div>
<div class="form-group">
<label for="InputPassword">Password</label>
<input type="password" class="form-control" id="InputPassword" name="pass">
</div>
<div class="form-group">
<label for="InputCode">Invite Code</label>
<input type="text" class="form-control" id="InputCode" name="code">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

45
Pages/Register.cshtml.cs Normal file
View file

@ -0,0 +1,45 @@
using System;
using System.Linq;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RTMPDash.DataModels;
using RTMPDash.DataModels.Tables;
namespace RTMPDash.Pages {
public class RegisterModel : PageModel {
public void OnPost() {
if (!Request.HasFormContentType
|| string.IsNullOrWhiteSpace(Request.Form["user"])
|| string.IsNullOrWhiteSpace(Request.Form["pass"])
|| string.IsNullOrWhiteSpace(Request.Form["code"]))
return;
using var db = new AppDb.DbConn();
if (!db.Invites.Any(p => p.Code == Request.Form["code"]))
return;
var user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString());
if (user != null) {
//user already exists
Response.Redirect("/Register?e=user_exists");
return;
}
user = new User {
Username = Request.Form["user"].ToString(),
Password = Request.Form["pass"].ToString().Sha256(),
StreamKey = Guid.NewGuid().ToString().Substring(9, 14),
PronounSubject = "they",
PronounPossessive = "their",
SrcRes = "unspecified"
};
db.Insert(user);
db.Delete(db.Invites.First(p => p.Code == Request.Form["code"]));
HttpContext.Session.SetString("authenticatedUser", user.Username);
}
}
}

View file

@ -0,0 +1,69 @@
@using Microsoft.AspNetCore.Http
@using RTMPDash.DataModels
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>@ViewData["Title"] - @Program.SiteName</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"/>
<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 asp-area="" asp-page="/Index">
<img src="/favicon.ico" alt="Logo" style="width: 3.5ch; margin-right: 1ch"/>
</a>
<a class="navbar-brand" asp-area="" asp-page="/Index">@Program.SiteName</a>
<button class="navbar-toggler" role="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 justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Stats">Stats</a>
</li>
@if (!string.IsNullOrEmpty(Context.Session.GetString("authenticatedUser")) && new AppDb.DbConn().Users.First(p => p.Username == Context.Session.GetString("authenticatedUser")).IsAdmin) {
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Admin">Admin</a>
</li>
}
@if (!string.IsNullOrEmpty(Context.Session.GetString("authenticatedUser"))) {
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Dashboard">Dashboard</a>
</li>
}
</ul>
@if (Context.Request.Headers["ASP-Site-Type"] != "view") {
<partial name="_LoginPartial"/>
}
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container text-center">
<a href="https://git.zotan.services/zotan/rtmpdash">Source Code</a> - <a asp-area="" asp-page="/Privacy">Privacy</a> - <a href="mailto:@Program.AbuseEmail">Abuse</a> - <a asp-area="" asp-page="/Credits">Credits and Copyright</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", false)
</body>
</html>

View file

@ -0,0 +1,19 @@
@using Microsoft.AspNetCore.Http
<ul class="navbar-nav">
@if (!string.IsNullOrEmpty(Context.Session.GetString("authenticatedUser"))) {
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/Manage" title="Manage">Hello, @Context.Session.GetString("authenticatedUser")!</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/Logout">Logout</a>
</li>
}
else {
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/Register">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/Login">Login</a>
</li>
}
</ul>

View file

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

13
Pages/Stats.cshtml Normal file
View file

@ -0,0 +1,13 @@
@page
@model StatsModel
@{
ViewData["Title"] = "Stats";
}
<img src="@Program.StatsDomain/vnstat1.png" alt="stats image 1"/>
<br/>
<img src="@Program.StatsDomain/vnstat2.png" alt="stats image 2"/>
<br/>
<img src="@Program.StatsDomain/vnstat3.png" alt="stats image 3"/>
<br/>
<img src="@Program.StatsDomain/vnstat4.png" alt="stats image 4"/>

7
Pages/Stats.cshtml.cs Normal file
View file

@ -0,0 +1,7 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
public class StatsModel : PageModel {
public void OnGet() { }
}
}

View file

@ -0,0 +1,4 @@
@using Microsoft.AspNetCore.Identity
@using RTMPDash
@namespace RTMPDash.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

3
Pages/_ViewStart.cshtml Normal file
View file

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

47
Pages/profile.cshtml Normal file
View file

@ -0,0 +1,47 @@
@page "{user}"
@using RTMPDash.DataModels
@model ProfileModel
@{
ViewData["Title"] = "View";
var db = new AppDb.DbConn();
if (!db.Users.Any(p => p.Username == Model.User)) {
Response.Redirect("/");
return;
}
var user = db.Users.First(p => p.Username == Model.User);
var live = StreamUtils.IsLive(user.Username);
var pronounAdditional = user.PronounSubject == "they" ? "are" : "is"; // TODO make this configurable too
}
<div class="text-center">
<h3 class="display">Welcome to @Model.User's page!</h3>
@if (live) {
@if (!string.IsNullOrWhiteSpace(user.ChatUrl)) {
<p>@user.PronounSubject.FirstCharToUpper() @pronounAdditional currently live! @user.PronounPossessive.FirstCharToUpper() stream chat is located <a href="@user.ChatUrl" target="_blank">here</a>.</p>
}
else {
<p>@user.PronounSubject.FirstCharToUpper() @pronounAdditional currently live! @user.PronounSubject.FirstCharToUpper() have not specified a stream chat URL, so enjoy @user.PronounPossessive content!</p>
}
<div class="btn-group btn-group-lg" role="group">
<a href="@Program.PlayerDomain/@user.Username" target="_blank" role="button" class="btn btn-success" data-toggle="tooltip" data-placement="bottom" title="@user.SrcRes">Source</a>
@if (user.AllowRestream) {
if ((user.RestreamUrls ?? "").Contains(",")) {
<a href="@user.RestreamUrls!.Split(",")[0]" target="_blank" role="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="@user.SrcRes">Twitch Restream</a>
<a href="@user.RestreamUrls!.Split(",")[1]" target="_blank" role="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Source @@ 10Mbit VBR">YouTube Restream</a>
}
else if (!string.IsNullOrWhiteSpace(user.RestreamUrls)) {
<a href="@user.RestreamUrls" target="_blank" role="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="@user.SrcRes">Twitch Restream</a>
}
}
</div>
}
else {
if (!string.IsNullOrWhiteSpace(user.AnnouncementUrl)) {
<p>@user.PronounSubject.FirstCharToUpper() @pronounAdditional not currently live. @user.PronounSubject.FirstCharToUpper() have indicated that @user.PronounSubject will announce their streams <a href="@user.AnnouncementUrl" target="_blank">here</a>.</p>
}
else {
<p>@user.PronounSubject.FirstCharToUpper() @pronounAdditional not currently live. @user.PronounSubject.FirstCharToUpper() have not specified an announcement URL, so check back later!</p>
}
}
</div>

11
Pages/profile.cshtml.cs Normal file
View file

@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RTMPDash.Pages {
public class ProfileModel : PageModel {
public new string User { get; set; }
public void OnGet(string user) {
User = user;
}
}
}

28
Program.cs Normal file
View file

@ -0,0 +1,28 @@
using LinqToDB.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using RTMPDash.DataModels;
namespace RTMPDash {
public class Program {
public const string SiteName = "zotan.stream";
public const string IngressDomain = "rtmp://zotan.stream";
public const string RootDomain = "https://zotan.stream";
public const string PlayerDomain = "https://live.on.zotan.stream";
public const string FragmentDomain = "https://cdn.zotan.stream";
public const string StatsDomain = "https://stats.zotan.stream";
public const string PrivacyEmail = "stream-privacy@zotan.email";
public const string CopyrightEmail = "stream-copyright@zotan.email";
public const string AbuseEmail = "stream-abuse@zotan.email";
public static void Main(string[] args) {
DataConnection.DefaultSettings = new AppDb.Settings();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
}
}

View file

@ -0,0 +1,17 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
},
"profiles": {
"RTMPDash": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": false,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

11
README.md Normal file
View file

@ -0,0 +1,11 @@
# RTMPDash
[Production instance](https://zotan.stream)
## Installation
- Adjust all the `const`'s in Program.cs
- Copy example.db to app.db
- Create yourself a user using `sqlite3`
- Install [nginx-mod-rtmp](https://github.com/lhaus/nginx-mod-rtmp)
- Configure nginx-mod-rtmp (TODO: example config here)

18
RTMPDash.csproj Normal file
View file

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<UserSecretsId>aspnet-RTMPDash-F151ECC3-F8CD-4437-8BC6-55BCE2711D26</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="linq2db" Version="3.2.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="5.0.2" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.113.7" />
</ItemGroup>
<ItemGroup>
<_ContentIncludedByDefault Remove="Areas\Identity\Pages\_ViewStart.cshtml" />
</ItemGroup>
</Project>

16
RTMPDash.sln Normal file
View file

@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RTMPDash", "RTMPDash.csproj", "{BFB1DE56-0FF8-4137-AD48-485B902CBE0E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BFB1DE56-0FF8-4137-AD48-485B902CBE0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BFB1DE56-0FF8-4137-AD48-485B902CBE0E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BFB1DE56-0FF8-4137-AD48-485B902CBE0E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BFB1DE56-0FF8-4137-AD48-485B902CBE0E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,70 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CommonFormatter/SHOW_AUTODETECT_CONFIGURE_FORMATTING_TIP/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FIXED/@EntryValue">NotRequired</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_LOCK/@EntryValue">NotRequired</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_USING/@EntryValue">NotRequired</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/CONSTRUCTOR_OR_DESTRUCTOR_BODY/@EntryValue">ExpressionBody</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/FORCE_ATTRIBUTE_STYLE/@EntryValue">Join</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/LOCAL_FUNCTION_BODY/@EntryValue">ExpressionBody</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/METHOD_OR_OPERATOR_BODY/@EntryValue">ExpressionBody</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ACCESSOR_DECLARATION_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ACCESSOR_OWNER_DECLARATION_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_FIRST_ARG_BY_PAREN/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_LINQ_QUERY/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_ARGUMENT/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_CALLS_CHAIN/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_EXTENDS_LIST/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_FOR_STMT/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_PARAMETER/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTIPLE_DECLARATION/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTLINE_TYPE_PARAMETER_CONSTRAINS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTLINE_TYPE_PARAMETER_LIST/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_TUPLE_COMPONENTS/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGNMENT_TAB_FILL_STYLE/@EntryValue">OPTIMAL_FILL</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ANONYMOUS_METHOD_DECLARATION_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AFTER_CONTROL_TRANSFER_STATEMENTS/@EntryValue">1</s:Int64>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/CASE_BLOCK_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/EMPTY_BLOCK_STYLE/@EntryValue">TOGETHER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_PREPROCESSOR_IF/@EntryValue">USUAL_INDENT</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_PREPROCESSOR_OTHER/@EntryValue">USUAL_INDENT</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_STYLE/@EntryValue">Tab</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INITIALIZER_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_ASSIGNMENTS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_COMMENTS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_FIELDS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_METHODS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_NESTED_TERNARY/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_PARAMETERS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_PROPERTIES/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_SWITCH_EXPRESSIONS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_SWITCH_SECTIONS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INT_ALIGN_VARIABLES/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INVOCABLE_DECLARATION_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_CODE/@EntryValue">1</s:Int64>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_DECLARATIONS/@EntryValue">1</s:Int64>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_DECLARATION_PARENS_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_EMBEDDED_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_EXPR_MEMBER_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_INITIALIZER_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_INVOCATION_PARENS_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_USER_LINEBREAKS/@EntryValue">False</s:Boolean>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/MAX_ENUM_MEMBERS_ON_LINE/@EntryValue">1</s:Int64>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/OTHER_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_EXPR_ACCESSOR_ON_SINGLE_LINE/@EntryValue">ALWAYS</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_EXPR_METHOD_ON_SINGLE_LINE/@EntryValue">ALWAYS</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_EXPR_PROPERTY_ON_SINGLE_LINE/@EntryValue">ALWAYS</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_CASE_STATEMENT_ON_SAME_LINE/@EntryValue">ALWAYS</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_EMBEDDED_STATEMENT_ON_SAME_LINE/@EntryValue">NEVER</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AROUND_ARROW_OP/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/STICK_COMMENT/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/TYPE_DECLARATION_BRACES/@EntryValue">END_OF_LINE</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_BEFORE_BINARY_OPSIGN/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_CHAINED_BINARY_EXPRESSIONS/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_CHAINED_METHOD_CALLS/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/HtmlFormatter/INDENT_STYLE/@EntryValue">Tab</s:String>
<s:Boolean x:Key="/Default/CodeStyle/Naming/CSharpAutoNaming/IsNotificationDisabled/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

57
Startup.cs Normal file
View file

@ -0,0 +1,57 @@
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace RTMPDash {
public class Startup {
public Startup(IConfiguration configuration) => Configuration = configuration;
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.AddRazorPages();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.MaxValue;
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
#if (DEBUG)
services.AddControllers().AddRazorRuntimeCompilation();
#else
services.AddControllers();
#endif
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
else {
app.UseExceptionHandler("/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.UseSession();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
}
}

127
StreamUtils.cs Normal file
View file

@ -0,0 +1,127 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Serialization;
using RTMPDash.DataModels;
namespace RTMPDash {
public class StreamUtils {
private const string Hlsroot = "/mnt/ssd_data/hls/src";
public static bool IsLive(string user) => File.Exists(Path.Combine(Hlsroot, $"{user}.m3u8"));
public static List<string> ListLiveUsers() {
var db = new AppDb.DbConn();
return (from file in Directory.EnumerateFiles(Path.Combine(Hlsroot))
where file.EndsWith(".m3u8")
&& db.Users.Any(p => p.Username == Path.GetFileNameWithoutExtension(file))
select Path.GetFileNameWithoutExtension(file)).OrderBy(p => p)
.ToList();
}
public static StatsObject GetStatsObject() {
var serializer = new XmlSerializer(typeof(StatsObject));
var xml = new WebClient().DownloadString("http://localhost:8080");
using var reader = new StringReader(xml);
var obj = (StatsObject) serializer.Deserialize(reader);
return obj;
}
}
[XmlRoot(ElementName = "rtmp")]
public class StatsObject {
[XmlElement(ElementName = "nginx_version", IsNullable = true)]
public string NginxVersion { get; set; }
[XmlElement(ElementName = "nginx_rtmp_version", IsNullable = true)]
public string NginxRtmpVersion { get; set; }
[XmlElement(ElementName = "server", IsNullable = true)] public Server Server { get; set; }
[XmlElement(ElementName = "built", IsNullable = true)] public string Built { get; set; }
[XmlElement(ElementName = "pid", IsNullable = true)] public string Pid { get; set; }
[XmlElement(ElementName = "uptime", IsNullable = true)] public string Uptime { get; set; }
[XmlElement(ElementName = "naccepted", IsNullable = true)] public string AcceptedConnections { get; set; }
[XmlElement(ElementName = "bw_in", IsNullable = true)] public string BwIn { get; set; }
[XmlElement(ElementName = "bytes_in", IsNullable = true)] public string BytesIn { get; set; }
[XmlElement(ElementName = "bw_out", IsNullable = true)] public string BwOut { get; set; }
[XmlElement(ElementName = "bytes_out", IsNullable = true)] public string BytesOut { get; set; }
}
[XmlRoot(ElementName = "server", IsNullable = true)]
public class Server {
[XmlElement(ElementName = "application", IsNullable = true)] public List<Application> Applications { get; set; }
}
[XmlRoot(ElementName = "application", IsNullable = true)]
public class Application {