summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrake.Worker/HttpServer.cs
blob: 095b51b436471da203ac441dd6c6cc8f5f077d17 (plain)
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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HttpServer.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   This is a service worker for the HandBrake app. It allows us to run encodes / scans in a seperate process easily.
//   All API's expose the ApplicationServices models as JSON.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrake.Worker
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Net;
    using System.Text;
    using System.Threading;

    public class HttpServer
    {
        private readonly HttpListener httpListener = new HttpListener();
        private readonly Dictionary<string, Func<HttpListenerRequest, string>> apiHandlers;

        public HttpServer(Dictionary<string, Func<HttpListenerRequest, string>> apiCalls, int port)
        {
            if (!HttpListener.IsSupported)
            {
                throw new NotSupportedException("HttpListener not supported on this computer.");
            }

            // Store the Handlers
            this.apiHandlers = new Dictionary<string, Func<HttpListenerRequest, string>>(apiCalls);

            Console.WriteLine(Environment.NewLine + "Available APIs: ");
            foreach (KeyValuePair<string, Func<HttpListenerRequest, string>> api in apiCalls)
            {
                string url = string.Format("http://localhost:{0}/{1}/", port, api.Key);
                this.httpListener.Prefixes.Add(url);
                Console.WriteLine(url);
            }

            Console.WriteLine(Environment.NewLine);
              
            this.httpListener.Start();
        }

        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                try
                {
                    while (this.httpListener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem(
                            (c) =>
                                {
                                    var context = c as HttpListenerContext;
                                    if (context == null)
                                    {
                                        return;
                                    }

                                    try
                                    {
                                        string path = context.Request.RawUrl.TrimStart('/').TrimEnd('/');

                                        if (this.apiHandlers.TryGetValue(path, out var actionToPerform))
                                        {
                                            string rstr = actionToPerform(context.Request);
                                            byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                            context.Response.ContentLength64 = buf.Length;
                                            context.Response.OutputStream.Write(buf, 0, buf.Length);
                                        }
                                        else
                                        {
                                            string rstr = "Error, There is a missing API handler.";
                                            byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                            context.Response.ContentLength64 = buf.Length;
                                            context.Response.OutputStream.Write(buf, 0, buf.Length);
                                        }
                                    }
                                    catch (Exception exc)
                                    {
                                        Debug.WriteLine(exc);
                                    }
                                    finally
                                    {
                                        context?.Response.OutputStream.Close();
                                    }
                                },
                            this.httpListener.GetContext());
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            });
        }

        public void Stop()
        {
            this.httpListener.Stop();
            this.httpListener.Close();
        }
    }
}