aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Controller/Providers/TV/RemoteSeasonProvider.cs
blob: 9d1a7c256601aeb93af2407748b2f09aeebb8b9c (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
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace MediaBrowser.Controller.Providers.TV
{
    /// <summary>
    /// Class RemoteSeasonProvider
    /// </summary>
    class RemoteSeasonProvider : BaseMetadataProvider
    {
        /// <summary>
        /// Gets the HTTP client.
        /// </summary>
        /// <value>The HTTP client.</value>
        protected IHttpClient HttpClient { get; private set; }

        private readonly IProviderManager _providerManager;
        
        public RemoteSeasonProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
            : base(logManager, configurationManager)
        {
            if (httpClient == null)
            {
                throw new ArgumentNullException("httpClient");
            }
            HttpClient = httpClient;
            _providerManager = providerManager;
        }

        /// <summary>
        /// Supportses the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public override bool Supports(BaseItem item)
        {
            return item is Season;
        }

        /// <summary>
        /// Gets the priority.
        /// </summary>
        /// <value>The priority.</value>
        public override MetadataProviderPriority Priority
        {
            get { return MetadataProviderPriority.Second; }
        }

        /// <summary>
        /// Gets a value indicating whether [requires internet].
        /// </summary>
        /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
        public override bool RequiresInternet
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Needses the refresh internal.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="providerInfo">The provider info.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
        {
            bool fetch = false;
            var downloadDate = providerInfo.LastRefreshed;

            if (ConfigurationManager.Configuration.MetadataRefreshDays == -1 && downloadDate != DateTime.MinValue)
                return false;

            if (!HasLocalMeta(item))
            {
                fetch = ConfigurationManager.Configuration.MetadataRefreshDays != -1 &&
                    DateTime.UtcNow.Subtract(downloadDate).TotalDays > ConfigurationManager.Configuration.MetadataRefreshDays;
            }

            return fetch;
        }

        /// <summary>
        /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{System.Boolean}.</returns>
        public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var season = (Season)item;

            if (!HasLocalMeta(item))
            {
                var seriesId = season.Series != null ? season.Series.GetProviderId(MetadataProviders.Tvdb) : null;

                if (seriesId != null)
                {
                    await FetchSeasonData(season, seriesId, cancellationToken).ConfigureAwait(false);
                    SetLastRefreshed(item, DateTime.UtcNow);
                    return true;
                }
                Logger.Info("Season provider unable to obtain series id for {0}", item.Path);
            }
            else
            {
                Logger.Info("Season provider not fetching because local meta exists: " + season.Name);
            }
            return false;
        }


        /// <summary>
        /// Fetches the season data.
        /// </summary>
        /// <param name="season">The season.</param>
        /// <param name="seriesId">The series id.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{System.Boolean}.</returns>
        private async Task<bool> FetchSeasonData(Season season, string seriesId, CancellationToken cancellationToken)
        {
            string name = season.Name;

            Logger.Debug("TvDbProvider: Fetching season data: " + name);
            var seasonNumber = TVUtils.GetSeasonNumberFromPath(season.Path) ?? -1;

            season.IndexNumber = seasonNumber;

            if (seasonNumber == 0)
            {
                season.Name = "Specials";
            }

            if (!string.IsNullOrEmpty(seriesId))
            {
                if ((season.PrimaryImagePath == null) || (!season.HasImage(ImageType.Banner)) || (season.BackdropImagePaths == null))
                {
                    var images = new XmlDocument();
                    var url = string.Format("http://www.thetvdb.com/api/" + TVUtils.TVDBApiKey + "/series/{0}/banners.xml", seriesId);

                    try
                    {
                        using (var imgs = await HttpClient.Get(url, RemoteSeriesProvider.Current.TvDbResourcePool, cancellationToken).ConfigureAwait(false))
                        {
                            images.Load(imgs);
                        }
                    }
                    catch (HttpException)
                    {
                    }

                    if (images.HasChildNodes)
                    {
                        if (ConfigurationManager.Configuration.RefreshItemImages || !season.HasLocalImage("folder"))
                        {
                            var n = images.SelectSingleNode("//Banner[BannerType='season'][BannerType2='season'][Season='" + seasonNumber + "']");
                            if (n != null)
                            {
                                n = n.SelectSingleNode("./BannerPath");

                                try
                                {
                                    if (n != null)
                                        season.PrimaryImagePath = await _providerManager.DownloadAndSaveImage(season, TVUtils.BannerUrl + n.InnerText, "folder" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, RemoteSeriesProvider.Current.TvDbResourcePool, cancellationToken).ConfigureAwait(false);
                                }
                                catch (HttpException)
                                {
                                }
                                catch (IOException)
                                {

                                }
                            }
                        }

                        if (ConfigurationManager.Configuration.DownloadSeasonImages.Banner && (ConfigurationManager.Configuration.RefreshItemImages || !season.HasLocalImage("banner")))
                        {
                            var n = images.SelectSingleNode("//Banner[BannerType='season'][BannerType2='seasonwide'][Season='" + seasonNumber + "']");
                            if (n != null)
                            {
                                n = n.SelectSingleNode("./BannerPath");
                                if (n != null)
                                {
                                    try
                                    {
                                        var bannerImagePath =
                                            await _providerManager.DownloadAndSaveImage(season,
                                                                                             TVUtils.BannerUrl + n.InnerText,
                                                                                             "banner" +
                                                                                             Path.GetExtension(n.InnerText),
                                                                                             ConfigurationManager.Configuration.SaveLocalMeta, RemoteSeriesProvider.Current.TvDbResourcePool, cancellationToken).
                                                               ConfigureAwait(false);

                                        season.SetImage(ImageType.Banner, bannerImagePath);
                                    }
                                    catch (HttpException)
                                    {
                                    }
                                    catch (IOException)
                                    {

                                    }
                                }
                            }
                        }

                        if (ConfigurationManager.Configuration.DownloadSeasonImages.Backdrops && (ConfigurationManager.Configuration.RefreshItemImages || !season.HasLocalImage("backdrop")))
                        {
                            var n = images.SelectSingleNode("//Banner[BannerType='fanart'][Season='" + seasonNumber + "']");
                            if (n != null)
                            {
                                n = n.SelectSingleNode("./BannerPath");
                                if (n != null)
                                {
                                    try
                                    {
                                        if (season.BackdropImagePaths == null) season.BackdropImagePaths = new List<string>();
                                        season.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(season, TVUtils.BannerUrl + n.InnerText, "backdrop" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, RemoteSeriesProvider.Current.TvDbResourcePool, cancellationToken).ConfigureAwait(false));
                                    }
                                    catch (HttpException)
                                    {
                                    }
                                    catch (IOException)
                                    {

                                    }
                                }
                            }
                            else if (!ConfigurationManager.Configuration.SaveLocalMeta) //if saving local - season will inherit from series
                            {
                                // not necessarily accurate but will give a different bit of art to each season
                                var lst = images.SelectNodes("//Banner[BannerType='fanart']");
                                if (lst != null && lst.Count > 0)
                                {
                                    var num = seasonNumber % lst.Count;
                                    n = lst[num];
                                    n = n.SelectSingleNode("./BannerPath");
                                    if (n != null)
                                    {
                                        if (season.BackdropImagePaths == null)
                                            season.BackdropImagePaths = new List<string>();

                                        try
                                        {
                                            season.BackdropImagePaths.Add(
                                                await _providerManager.DownloadAndSaveImage(season,
                                                                                                 TVUtils.BannerUrl +
                                                                                                 n.InnerText,
                                                                                                 "backdrop" +
                                                                                                 Path.GetExtension(
                                                                                                     n.InnerText),
                                                                                                 ConfigurationManager.Configuration.SaveLocalMeta, RemoteSeriesProvider.Current.TvDbResourcePool, cancellationToken)
                                                                  .ConfigureAwait(false));
                                        }
                                        catch (HttpException)
                                        {
                                        }
                                        catch (IOException)
                                        {

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }

            return false;
        }

        /// <summary>
        /// Determines whether [has local meta] [the specified item].
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
        private bool HasLocalMeta(BaseItem item)
        {
            //just folder.jpg/png
            return (item.ResolveArgs.ContainsMetaFileByName("folder.jpg") ||
                    item.ResolveArgs.ContainsMetaFileByName("folder.png"));
        }

    }
}