aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Startup.Common/EntryPoints/KeepServerAwake.cs
blob: 79debce8daf8f8f709d910afdd3a6cdbc03c70c3 (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
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Logging;
using System;
using System.Linq;
using MediaBrowser.Server.Implementations.Threading;

namespace MediaBrowser.Server.Startup.Common.EntryPoints
{
    public class KeepServerAwake : IServerEntryPoint
    {
        private readonly ISessionManager _sessionManager;
        private readonly ILogger _logger;
        private PeriodicTimer _timer;
        private readonly IServerApplicationHost _appHost;

        public KeepServerAwake(ISessionManager sessionManager, ILogger logger, IServerApplicationHost appHost)
        {
            _sessionManager = sessionManager;
            _logger = logger;
            _appHost = appHost;
        }

        public void Run()
        {
            _timer = new PeriodicTimer(obj =>
            {
                var now = DateTime.UtcNow;
                var nativeApp = ((ApplicationHost)_appHost).NativeApp;

                try
                {
                    if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15))
                    {
                        nativeApp.PreventSystemStandby();
                    }
                    else
                    {
                        nativeApp.AllowSystemStandby();
                    }
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error resetting system standby timer", ex);
                }

            }, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
        }

        public void Dispose()
        {
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
        }
    }
}