-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWebServer.cs
112 lines (91 loc) · 3.2 KB
/
WebServer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Host.HttpListener;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Microsoft.Owin.StaticFiles.ContentTypes;
using Owin;
namespace MusicBeePlugin
{
public class WebServer : IDisposable
{
public IDisposable MediaWebServer { get; set; } = null;
bool disposed;
private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0);
public int? MEDIA_PORT { get; set; }
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (MediaWebServer != null)
{
MediaWebServer.Dispose();
}
Debug.WriteLine("closing webserver");
}
}
//dispose unmanaged resources
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public WebServer(int? port_number, string @imageDirectory = null)
{
try
{
MEDIA_PORT = port_number ?? throw new Exception("Port Number Undefined");
var mediaURL = "http://*:" + MEDIA_PORT;
string path = @System.IO.Path.GetTempPath() + @"\\MusicBeeChromecast";
System.IO.Directory.CreateDirectory(path);
var mediaFileSystem = new PhysicalFileSystem(path);
var mediaServerOptions = new FileServerOptions
{
EnableDirectoryBrowsing = true,
FileSystem = mediaFileSystem
};
mediaServerOptions.StaticFileOptions.ContentTypeProvider = new CustomContentTypeProvider();
MediaWebServer = WebApp.Start(mediaURL, builder => builder.UseFileServer(mediaServerOptions));
//Debug.WriteLine(mediaURL);
Debug.WriteLine("Listening at " + mediaURL);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
//Change this after
throw new Exception("Webserver exception");
}
}
public class CustomContentTypeProvider : FileExtensionContentTypeProvider
{
public CustomContentTypeProvider()
{
Mappings.Add(".flac", "audio/flac");
//The webserver can understand to treat the .tmp image files music bee produces as image files,
//however the chromecast needs a proper image format sent to it.
Mappings.Add(".tmp", "image/png");
}
}
public void Stop()
{
if (MediaWebServer != null)
{
Dispose();
}
else
{
throw new NullReferenceException("Webserver is null");
}
}
}
}