aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Kernel/BaseKernel.cs
blob: a6081a68816d4c1f94dcc2c1e16a23bb9e481403 (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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Logging;
using MediaBrowser.Common.Mef;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Net.Handlers;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Serialization;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Progress;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace MediaBrowser.Common.Kernel
{
    /// <summary>
    /// Represents a shared base kernel for both the Ui and server apps
    /// </summary>
    public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
        where TConfigurationType : BaseApplicationConfiguration, new()
        where TApplicationPathsType : BaseApplicationPaths, new()
    {
        #region ReloadBeginning Event
        /// <summary>
        /// Fires whenever the kernel begins reloading
        /// </summary>
        public event EventHandler<GenericEventArgs<IProgress<TaskProgress>>> ReloadBeginning;
        private void OnReloadBeginning(IProgress<TaskProgress> progress)
        {
            if (ReloadBeginning != null)
            {
                ReloadBeginning(this, new GenericEventArgs<IProgress<TaskProgress>> { Argument = progress });
            }
        }
        #endregion

        #region ReloadCompleted Event
        /// <summary>
        /// Fires whenever the kernel completes reloading
        /// </summary>
        public event EventHandler<GenericEventArgs<IProgress<TaskProgress>>> ReloadCompleted;
        private void OnReloadCompleted(IProgress<TaskProgress> progress)
        {
            if (ReloadCompleted != null)
            {
                ReloadCompleted(this, new GenericEventArgs<IProgress<TaskProgress>> { Argument = progress });
            }
        }
        #endregion

        /// <summary>
        /// Gets the current configuration
        /// </summary>
        public TConfigurationType Configuration { get; private set; }

        public TApplicationPathsType ApplicationPaths { get; private set; }

        /// <summary>
        /// Gets the list of currently loaded plugins
        /// </summary>
        [ImportMany(typeof(BasePlugin))]
        public IEnumerable<BasePlugin> Plugins { get; private set; }

        /// <summary>
        /// Gets the list of currently registered http handlers
        /// </summary>
        [ImportMany(typeof(BaseHandler))]
        private IEnumerable<BaseHandler> HttpHandlers { get; set; }

        /// <summary>
        /// Gets the list of currently registered Loggers
        /// </summary>
        [ImportMany(typeof(BaseLogger))]
        public IEnumerable<BaseLogger> Loggers { get; set; }

        /// <summary>
        /// Both the Ui and server will have a built-in HttpServer.
        /// People will inevitably want remote control apps so it's needed in the Ui too.
        /// </summary>
        public HttpServer HttpServer { get; private set; }

        /// <summary>
        /// This subscribes to HttpListener requests and finds the appropate BaseHandler to process it
        /// </summary>
        private IDisposable HttpListener { get; set; }

        /// <summary>
        /// Gets the MEF CompositionContainer
        /// </summary>
        private CompositionContainer CompositionContainer { get; set; }

        protected virtual string HttpServerUrlPrefix
        {
            get
            {
                return "http://+:" + Configuration.HttpServerPortNumber + "/mediabrowser/";
            }
        }

        /// <summary>
        /// Gets the kernel context. Subclasses will have to override.
        /// </summary>
        public abstract KernelContext KernelContext { get; }

        /// <summary>
        /// Initializes the Kernel
        /// </summary>
        public async Task Init(IProgress<TaskProgress> progress)
        {
            Logger.Kernel = this;

            // Performs initializations that only occur once
            InitializeInternal(progress);

            // Performs initializations that can be reloaded at anytime
            await Reload(progress).ConfigureAwait(false);
        }

        /// <summary>
        /// Performs initializations that only occur once
        /// </summary>
        protected virtual void InitializeInternal(IProgress<TaskProgress> progress)
        {
            ApplicationPaths = new TApplicationPathsType();

            ReportProgress(progress, "Loading Configuration");
            ReloadConfiguration();

            ReportProgress(progress, "Loading Http Server");
            ReloadHttpServer();
        }

        /// <summary>
        /// Performs initializations that can be reloaded at anytime
        /// </summary>
        public async Task Reload(IProgress<TaskProgress> progress)
        {
            OnReloadBeginning(progress);

            await ReloadInternal(progress).ConfigureAwait(false);

            OnReloadCompleted(progress);

            ReportProgress(progress, "Kernel.Reload Complete");
        }

        /// <summary>
        /// Performs initializations that can be reloaded at anytime
        /// </summary>
        protected virtual async Task ReloadInternal(IProgress<TaskProgress> progress)
        {
            await Task.Run(() =>
            {
                ReportProgress(progress, "Loading Plugins");
                ReloadComposableParts();

            }).ConfigureAwait(false);
        }

        /// <summary>
        /// Uses MEF to locate plugins
        /// Subclasses can use this to locate types within plugins
        /// </summary>
        private void ReloadComposableParts()
        {
            DisposeComposableParts();

            CompositionContainer = GetCompositionContainer(includeCurrentAssembly: true);

            CompositionContainer.ComposeParts(this);

            OnComposablePartsLoaded();

            CompositionContainer.Catalog.Dispose();
        }

        /// <summary>
        /// Constructs an MEF CompositionContainer based on the current running assembly and all plugin assemblies
        /// </summary>
        public CompositionContainer GetCompositionContainer(bool includeCurrentAssembly = false)
        {
            // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
            // This will prevent the .dll file from getting locked, and allow us to replace it when needed
            IEnumerable<Assembly> pluginAssemblies = Directory.GetFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly).Select(f => Assembly.Load(File.ReadAllBytes((f))));

            var catalogs = new List<ComposablePartCatalog>();

            catalogs.AddRange(pluginAssemblies.Select(a => new AssemblyCatalog(a)));

            // Include composable parts in the Common assembly 
            catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            if (includeCurrentAssembly)
            {
                // Include composable parts in the subclass assembly
                catalogs.Add(new AssemblyCatalog(GetType().Assembly));
            }

            return MefUtils.GetSafeCompositionContainer(catalogs);
        }

        /// <summary>
        /// Fires after MEF finishes finding composable parts within plugin assemblies
        /// </summary>
        protected virtual void OnComposablePartsLoaded()
        {
            foreach (var logger in Loggers)
            {
                logger.Initialize(this);
            }

            // Start-up each plugin
            foreach (var plugin in Plugins)
            {
                plugin.Initialize(this);
            }
        }

        /// <summary>
        /// Reloads application configuration from the config file
        /// </summary>
        private void ReloadConfiguration()
        {
            //Configuration information for anything other than server-specific configuration will have to come via the API... -ebr

            // Deserialize config
            // Use try/catch to avoid the extra file system lookup using File.Exists
            try
            {
                Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
            }
            catch (FileNotFoundException)
            {
                Configuration = new TConfigurationType();
                XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
            }
        }

        /// <summary>
        /// Restarts the Http Server, or starts it if not currently running
        /// </summary>
        private void ReloadHttpServer()
        {
            DisposeHttpServer();

            HttpServer = new HttpServer(HttpServerUrlPrefix);

            HttpListener = HttpServer.Subscribe(ctx =>
            {
                BaseHandler handler = HttpHandlers.FirstOrDefault(h => h.HandlesRequest(ctx.Request));

                // Find the appropiate http handler
                if (handler != null)
                {
                    // Need to create a new instance because handlers are currently stateful
                    handler = Activator.CreateInstance(handler.GetType()) as BaseHandler;

                    // No need to await this, despite the compiler warning
                    handler.ProcessRequest(ctx);
                }
            });
        }

        /// <summary>
        /// Disposes all resources currently in use.
        /// </summary>
        public virtual void Dispose()
        {
            Logger.LogInfo("Beginning Kernel.Dispose");

            DisposeHttpServer();

            DisposeComposableParts();
        }

        /// <summary>
        /// Disposes all objects gathered through MEF composable parts
        /// </summary>
        protected virtual void DisposeComposableParts()
        {
            if (CompositionContainer != null)
            {
                CompositionContainer.Dispose();
            }
        }

        /// <summary>
        /// Disposes the current HttpServer
        /// </summary>
        private void DisposeHttpServer()
        {
            if (HttpServer != null)
            {
                Logger.LogInfo("Disposing Http Server");

                HttpServer.Dispose();
            }

            if (HttpListener != null)
            {
                HttpListener.Dispose();
            }
        }

        /// <summary>
        /// Gets the current application version
        /// </summary>
        public Version ApplicationVersion
        {
            get
            {
                return GetType().Assembly.GetName().Version;
            }
        }

        protected void ReportProgress(IProgress<TaskProgress> progress, string message)
        {
            progress.Report(new TaskProgress { Description = message });

            Logger.LogInfo(message);
        }

        BaseApplicationPaths IKernel.ApplicationPaths
        {
            get { return ApplicationPaths; }
        }
    }

    public interface IKernel
    {
        BaseApplicationPaths ApplicationPaths { get; }
        KernelContext KernelContext { get; }

        Task Init(IProgress<TaskProgress> progress);
        Task Reload(IProgress<TaskProgress> progress);
        IEnumerable<BaseLogger> Loggers { get; }
        void Dispose();
    }
}