summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrake.Worker/Routing/ApiRouter.cs
blob: e1ea632a8e5f71a71b84accadfea9e4fb827568d (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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApiRouter.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.Routing
{
    using System;
    using System.Net;
    using System.Text.Json;

    using HandBrake.Interop.Interop;
    using HandBrake.Interop.Interop.Json.State;
    using HandBrake.Interop.Json;
    using HandBrake.Interop.Utilities;
    using HandBrake.Worker.Logging;
    using HandBrake.Worker.Logging.Interfaces;
    using HandBrake.Worker.Routing.Commands;
    using HandBrake.Worker.Routing.Results;
    using HandBrake.Worker.Utilities;
    using HandBrake.Worker.Watcher;

    public class ApiRouter
    {
        private JsonState completedState;
        private HandBrakeInstance handbrakeInstance;
        private ILogHandler logHandler;
        private InstanceWatcher instanceWatcher;

        public event EventHandler TerminationEvent; 

        public string GetVersionInfo(HttpListenerRequest request)
        {
            string versionInfo = JsonSerializer.Serialize(VersionHelper.GetVersion(), JsonSettings.Options);

            return versionInfo;
        }

        public string StartEncode(HttpListenerRequest request)
        {
            this.completedState = null;
            string requestPostData = HttpUtilities.GetRequestPostData(request);

            if (!string.IsNullOrEmpty(requestPostData))
            {
                EncodeCommand command = JsonSerializer.Deserialize<EncodeCommand>(requestPostData, JsonSettings.Options);

                this.Initialise(command.InitialiseCommand);
                
                this.handbrakeInstance.StartEncode(command.EncodeJob);

                return JsonSerializer.Serialize(new CommandResult() { WasSuccessful = true }, JsonSettings.Options);
            }

            return JsonSerializer.Serialize(new CommandResult() { WasSuccessful = false, Error = "No POST data" }, JsonSettings.Options);
        }

        public string StopEncode(HttpListenerRequest request)
        {
            this.handbrakeInstance?.StopEncode();

            return (string)null;
        }

        public string PauseEncode(HttpListenerRequest request)
        {
            this.handbrakeInstance?.PauseEncode();

            return null;
        }

        public string ResumeEncode(HttpListenerRequest request)
        {
            this.handbrakeInstance?.ResumeEncode();

            return null;
        }

        public string PollEncodeProgress(HttpListenerRequest request)
        {
            if (this.completedState != null)
            {
                string json = JsonSerializer.Serialize(this.completedState, JsonSettings.Options);
                return json;
            }

            if (this.handbrakeInstance != null)
            {
                JsonState statusJson = this.handbrakeInstance.GetEncodeProgress();
                string json = JsonSerializer.Serialize(statusJson, JsonSettings.Options);

                return json;
            }

            return null;
        }

        /* Logging API */
        
        // GET
        public string GetAllLogMessages(HttpListenerRequest request)
        {
            return JsonSerializer.Serialize(this.logHandler.GetLogMessages(), JsonSettings.Options);
        }
        
        // POST
        public string GetLogMessagesFromIndex(HttpListenerRequest request)
        {
            string requestPostData = HttpUtilities.GetRequestPostData(request);

            if (int.TryParse(requestPostData, out int index))
            {
                return JsonSerializer.Serialize(this.logHandler.GetLogMessagesFromIndex(index), JsonSettings.Options);
            }

            return null;
        }

        public string ResetLogging(HttpListenerRequest request)
        {
            this.logHandler.Reset();

            return null;
        }

        public void OnTerminationEvent()
        {
            this.TerminationEvent?.Invoke(this, EventArgs.Empty);
        }

        private void HandbrakeInstance_EncodeCompleted(object sender, Interop.Interop.EventArgs.EncodeCompletedEventArgs e)
        {
            this.completedState = new JsonState() { WorkDone = new WorkDone() { Error = e.Error } };
            this.completedState.State = "WORKDONE";
            this.logHandler.ShutdownFileWriter();
            this.handbrakeInstance.Dispose();
            HandBrakeUtils.DisposeGlobal();
        }

        private void Initialise(InitCommand command)
        {
            if (this.handbrakeInstance == null)
            {
                this.handbrakeInstance = new HandBrakeInstance();
            }

            if (this.logHandler == null)
            {
                this.logHandler = new LogHandler(command.LogDirectory, command.LogFile, command.EnableDiskLogging);
            }

            if (!command.AllowDisconnectedWorker)
            {
                Console.WriteLine("Worker: Disconnected worker monitoring enabled!");
                this.instanceWatcher = new InstanceWatcher(this);
                this.instanceWatcher.Start(5000);
            }

            this.completedState = null;

            this.handbrakeInstance.Initialize(command.LogVerbosity, !command.EnableHardwareAcceleration);
            this.handbrakeInstance.EncodeCompleted += this.HandbrakeInstance_EncodeCompleted;

            if (command.DisableLibDvdNav)
            {
                HandBrakeUtils.SetDvdNav(true); // TODO check this is correct
            }
        }
    }
}