aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
blob: d8aef909bb091baceba9591f99fefa58ca5b4239 (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
using MediaBrowser.Common;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Server.Implementations.EntryPoints
{
    /// <summary>
    /// Class UsageEntryPoint
    /// </summary>
    public class UsageEntryPoint : IServerEntryPoint
    {
        private readonly IApplicationHost _applicationHost;
        private readonly IHttpClient _httpClient;
        private readonly ILogger _logger;
        private readonly ISessionManager _sessionManager;
        private readonly IUserManager _userManager;

        private readonly TimeSpan _frequency = TimeSpan.FromHours(24);

        private readonly ConcurrentDictionary<Guid, ClientInfo> _apps = new ConcurrentDictionary<Guid, ClientInfo>();

        public UsageEntryPoint(ILogger logger, IApplicationHost applicationHost, IHttpClient httpClient, ISessionManager sessionManager, IUserManager userManager)
        {
            _logger = logger;
            _applicationHost = applicationHost;
            _httpClient = httpClient;
            _sessionManager = sessionManager;
            _userManager = userManager;

            _sessionManager.SessionStarted += _sessionManager_SessionStarted;
        }

        void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
        {
            var session = e.SessionInfo;

            if (!string.IsNullOrEmpty(session.Client) &&
                !string.IsNullOrEmpty(session.DeviceName) &&
                !string.IsNullOrEmpty(session.DeviceId) &&
                !string.IsNullOrEmpty(session.ApplicationVersion))
            {
                var keys = new List<string>
                {
                    session.Client,
                    session.DeviceName,
                    session.DeviceId,
                    session.ApplicationVersion
                };

                var key = string.Join("_", keys.ToArray()).GetMD5();

                _apps.GetOrAdd(key, guid => GetNewClientInfo(session));
            }
        }

        private async void ReportNewSession(ClientInfo client)
        {
            try
            {
                await new UsageReporter(_applicationHost, _httpClient, _userManager, _logger)
                    .ReportAppUsage(client, CancellationToken.None)
                    .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error sending anonymous usage statistics.", ex);
            }
        }

        private ClientInfo GetNewClientInfo(SessionInfo session)
        {
            var info = new ClientInfo
            {
                AppName = session.Client,
                AppVersion = session.ApplicationVersion,
                DeviceName = session.DeviceName,
                DeviceId = session.DeviceId
            };

            // Report usage to remote server, except for web client, since we already have data on that
            if (!string.Equals(info.AppName, "Dashboard", StringComparison.OrdinalIgnoreCase))
            {
                ReportNewSession(info);
            }

            return info;
        }

        public async void Run()
        {
            await Task.Delay(5000).ConfigureAwait(false);
            OnTimerFired();
        }

        /// <summary>
        /// Called when [timer fired].
        /// </summary>
        private async void OnTimerFired()
        {
            try
            {
                await new UsageReporter(_applicationHost, _httpClient, _userManager, _logger)
                    .ReportServerUsage(CancellationToken.None)
                    .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error sending anonymous usage statistics.", ex);
            }
        }

        public void Dispose()
        {
            _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
        }
    }
}