-
Notifications
You must be signed in to change notification settings - Fork 1
/
MusicDownloadWrapper.cs
71 lines (59 loc) · 1.85 KB
/
MusicDownloadWrapper.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
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using Banshee.Web;
namespace Banshee.GoogleMusic
{
public class MusicDownloadWrapper : BaseHttpServer
{
private static readonly Regex TRACK_REGEX = new Regex("^/track/(.+)$", RegexOptions.Compiled);
private Google.Music.Api api;
public MusicDownloadWrapper (Google.Music.Api api) : base(new IPEndPoint(IPAddress.Loopback, 0), "music-download-wrapper")
{
this.api = api;
}
private void WriteRedirect (Socket client, string location)
{
if (!client.Connected)
return;
var data = new StringBuilder()
.Append("HTTP/1.1 302 Redirect\n")
.AppendFormat("Location: {0}\n", location)
.Append("Connection: close\n\n")
.ToString();
using (var writer = new BinaryWriter(new NetworkStream(client))) {
writer.Write(Encoding.UTF8.GetBytes(data));
}
client.Close();
}
private void WriteResponse (Socket client, HttpStatusCode code)
{
WriteResponse(client, code, "");
}
protected override void HandleValidRequest (Socket client, string[] split_request, string[] request_headers)
{
if (split_request == null || split_request.Length != 3 || split_request[0] != "GET") {
WriteResponse(client, HttpStatusCode.BadRequest);
return;
}
var requestUrl = split_request[1];
if (TRACK_REGEX.IsMatch(requestUrl)) {
var match = TRACK_REGEX.Match(requestUrl);
var url = api.PlayTrack(match.Groups[1].Value);
if (!string.IsNullOrEmpty(url))
WriteRedirect(client, url);
else
WriteResponse(client, HttpStatusCode.InternalServerError);
} else {
WriteResponse(client, HttpStatusCode.NotFound);
}
}
public string formTrackUrl(string trackId)
{
return string.Format("http://localhost:{0}/track/{1}", Port, trackId);
}
}
}