aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/EntryPoints/Notifications/RemoteNotifications.cs
blob: 932e94b2af0ae58c0d893bcbc3d80de9fcfb3204 (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
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
    public class RemoteNotifications : IServerEntryPoint
    {
        private const string Url = "http://www.mb3admin.com/admin/service/MB3ServerNotifications.json";

        private Timer _timer;
        private readonly IHttpClient _httpClient;
        private readonly IApplicationPaths _appPaths;
        private readonly ILogger _logger;
        private readonly IJsonSerializer _json;
        private readonly IUserManager _userManager;
        private readonly IFileSystem _fileSystem;

        private readonly TimeSpan _frequency = TimeSpan.FromHours(6);
        private readonly TimeSpan _maxAge = TimeSpan.FromDays(31);

        private readonly INotificationManager _notificationManager;

        public RemoteNotifications(IApplicationPaths appPaths, ILogger logger, IHttpClient httpClient, IJsonSerializer json, IUserManager userManager, IFileSystem fileSystem, INotificationManager notificationManager)
        {
            _appPaths = appPaths;
            _logger = logger;
            _httpClient = httpClient;
            _json = json;
            _userManager = userManager;
            _fileSystem = fileSystem;
            _notificationManager = notificationManager;
        }

        /// <summary>
        /// Runs this instance.
        /// </summary>
        public void Run()
        {
            _timer = new Timer(OnTimerFired, null, TimeSpan.FromMilliseconds(500), _frequency);
        }

        /// <summary>
        /// Called when [timer fired].
        /// </summary>
        /// <param name="state">The state.</param>
        private async void OnTimerFired(object state)
        {
            var dataPath = Path.Combine(_appPaths.DataPath, "remotenotifications.json");

			var lastRunTime = _fileSystem.FileExists(dataPath) ? _fileSystem.GetLastWriteTimeUtc(dataPath) : DateTime.MinValue;

            try
            {
                await DownloadNotifications(dataPath, lastRunTime).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error downloading remote notifications", ex);
            }
        }

        /// <summary>
        /// Downloads the notifications.
        /// </summary>
        /// <param name="dataPath">The data path.</param>
        /// <param name="lastRunTime">The last run time.</param>
        /// <returns>Task.</returns>
        private async Task DownloadNotifications(string dataPath, DateTime lastRunTime)
        {
            using (var stream = await _httpClient.Get(new HttpRequestOptions
            {
                Url = Url

            }).ConfigureAwait(false))
            {
                var notifications = _json.DeserializeFromStream<RemoteNotification[]>(stream);

				_fileSystem.WriteAllText(dataPath, string.Empty);

                await CreateNotifications(notifications, lastRunTime).ConfigureAwait(false);
            }
        }

        /// <summary>
        /// Creates the notifications.
        /// </summary>
        /// <param name="notifications">The notifications.</param>
        /// <param name="lastRunTime">The last run time.</param>
        /// <returns>Task.</returns>
        private async Task CreateNotifications(IEnumerable<RemoteNotification> notifications, DateTime lastRunTime)
        {
            // Only show notifications that are active, new since last download, and not older than max age
            var notificationList = notifications
                .Where(i => string.Equals(i.active, "1") && i.date.ToUniversalTime() > lastRunTime && (DateTime.UtcNow - i.date.ToUniversalTime()) <= _maxAge)
                .ToList();

            var userIds = _userManager.Users.Select(i => i.Id.ToString("N")).ToList();

            foreach (var notification in notificationList)
            {
                await _notificationManager.SendNotification(new NotificationRequest
                {
                    Date = notification.date,
                    Name = notification.name,
                    Description = notification.description,
                    Url = notification.url,
                    UserIds = userIds

                }, CancellationToken.None).ConfigureAwait(false);
            }
        }

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

        private class RemoteNotification
        {
            public string id { get; set; }
            public DateTime date { get; set; }
            public string name { get; set; }
            public string description { get; set; }
            public string category { get; set; }
            public string url { get; set; }
            public object imageUrl { get; set; }
            public string active { get; set; }
        }
    }
}