You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Ombi/Old/Ombi.Services/Notification/PlexNotificationEngine.cs

262 lines
12 KiB

8 years ago
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
8 years ago
// File: PlexNotificationEngine.cs
8 years ago
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NLog;
8 years ago
using Ombi.Api.Interfaces;
8 years ago
using Ombi.Core;
8 years ago
using Ombi.Core.Models;
8 years ago
using Ombi.Core.SettingModels;
8 years ago
using Ombi.Core.Users;
using Ombi.Helpers.Permissions;
using Ombi.Services.Interfaces;
using Ombi.Store;
using Ombi.Store.Models;
using Ombi.Store.Repository;
8 years ago
8 years ago
namespace Ombi.Services.Notification
8 years ago
{
8 years ago
public class PlexNotificationEngine : IPlexNotificationEngine
8 years ago
{
8 years ago
public PlexNotificationEngine(IPlexApi p, IRepository<UsersToNotify> repo, INotificationService service, IUserHelper userHelper, ISettingsService<PlexSettings> ps)
8 years ago
{
PlexApi = p;
UserNotifyRepo = repo;
Notification = service;
UserHelper = userHelper;
8 years ago
PlexSettings = ps;
8 years ago
}
private IPlexApi PlexApi { get; }
private IRepository<UsersToNotify> UserNotifyRepo { get; }
private static Logger Log = LogManager.GetCurrentClassLogger();
private INotificationService Notification { get; }
private IUserHelper UserHelper { get; }
8 years ago
private ISettingsService<PlexSettings> PlexSettings { get; }
8 years ago
8 years ago
public async Task NotifyUsers(IEnumerable<RequestedModel> modelChanged, NotificationType type)
8 years ago
{
try
{
8 years ago
var settings = await PlexSettings.GetSettingsAsync();
var plexUser = PlexApi.GetUsers(settings.PlexAuthToken);
var userAccount = PlexApi.GetAccount(settings.PlexAuthToken);
8 years ago
var adminUsername = userAccount.Username ?? string.Empty;
var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList();
8 years ago
Log.Debug("Notifying Users Count {0}", users.Count);
foreach (var model in modelChanged)
{
var selectedUsers = new List<string>();
foreach (var u in users)
{
var requestUser = model.RequestedUsers.FirstOrDefault(
x => x.Equals(u.Username, StringComparison.CurrentCultureIgnoreCase) || x.Equals(u.UserAlias, StringComparison.CurrentCultureIgnoreCase));
if (string.IsNullOrEmpty(requestUser))
{
continue;
}
// Make sure we do not already have the user
if (!selectedUsers.Contains(requestUser))
{
selectedUsers.Add(requestUser);
}
}
8 years ago
foreach (var user in selectedUsers)
{
Log.Info("Notifying user {0}", user);
if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase))
{
Log.Info("This user is the Plex server owner");
8 years ago
await PublishUserNotification(userAccount.Username, userAccount.Email, model.Title, model.PosterPath, type, model.Type);
8 years ago
return;
}
8 years ago
UserHelperModel localUser = null;
//users.FirstOrDefault( x =>
// x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase) ||
// x.UserAlias.Equals(user, StringComparison.CurrentCultureIgnoreCase));
foreach (var userHelperModel in users)
{
if (!string.IsNullOrEmpty(userHelperModel.Username))
{
if (userHelperModel.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase))
{
localUser = userHelperModel;
break;
}
}
if (!string.IsNullOrEmpty(userHelperModel.UserAlias))
{
if (userHelperModel.UserAlias.Equals(user, StringComparison.CurrentCultureIgnoreCase))
{
localUser = userHelperModel;
break;
}
}
}
// So if the request was from an alias, then we need to use the local user (since that contains the alias).
// If we do not have a local user, then we should be using the Plex user if that user exists.
// This will execute most of the time since Plex and Local users will most always be in the database.
if (localUser != null)
8 years ago
{
if (string.IsNullOrEmpty(localUser?.EmailAddress))
{
Log.Info("There is no email address for this Local user ({0}), cannot send notification", localUser.Username);
continue;
}
Log.Info("Sending notification to: {0} at: {1}, for : {2}", localUser, localUser.EmailAddress, model.Title);
await PublishUserNotification(localUser.Username, localUser.EmailAddress, model.Title, model.PosterPath, type, model.Type);
8 years ago
}
else
{
var email = plexUser.User.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase));
if (string.IsNullOrEmpty(email?.Email))
{
Log.Info("There is no email address for this Plex user ({0}), cannot send notification", email?.Username);
// We do not have a plex user that requested this!
continue;
}
8 years ago
Log.Info("Sending notification to: {0} at: {1}, for : {2}", email.Username, email.Email, model.Title);
await PublishUserNotification(email.Username, email.Email, model.Title, model.PosterPath, type, model.Type);
}
8 years ago
}
}
}
catch (Exception e)
{
Log.Error(e);
}
}
8 years ago
public async Task NotifyUsers(RequestedModel model, NotificationType type)
8 years ago
{
try
{
8 years ago
var settings = await PlexSettings.GetSettingsAsync();
8 years ago
var plexUser = PlexApi.GetUsers(settings.PlexAuthToken); // TODO emby
8 years ago
var userAccount = PlexApi.GetAccount(settings.PlexAuthToken);
8 years ago
var localUsers = UserHelper.GetUsers().ToList();
8 years ago
var adminUsername = userAccount.Username ?? string.Empty;
var users = UserHelper.GetUsersWithFeature(Features.RequestAddedNotification).ToList();
8 years ago
Log.Debug("Notifying Users Count {0}", users.Count);
// Get the usernames or alias depending if they have an alias
var userNamesWithFeature = users.Select(x => x.UsernameOrAlias).ToList();
Log.Debug("Users with the feature count {0}", userNamesWithFeature.Count);
Log.Debug("Usernames: ");
foreach (var u in userNamesWithFeature)
{
Log.Debug(u);
}
Log.Debug("Users in the requested model count: {0}", model.AllUsers.Count);
Log.Debug("usernames from model: ");
foreach (var modelAllUser in model.AllUsers)
{
Log.Debug(modelAllUser);
}
if (model.AllUsers == null || !model.AllUsers.Any())
{
Log.Debug("There are no users in the model.AllUsers, no users to notify");
return;
}
var usersToNotify = userNamesWithFeature.Intersect(model.AllUsers, StringComparer.CurrentCultureIgnoreCase).ToList();
if (!usersToNotify.Any())
{
Log.Debug("Could not find any users after the .Intersect()");
}
Log.Debug("Users being notified for this request count {0}", users.Count);
foreach (var user in usersToNotify)
8 years ago
{
Log.Info("Notifying user {0}", user);
if (user.Equals(adminUsername, StringComparison.CurrentCultureIgnoreCase))
{
Log.Info("This user is the Plex server owner");
8 years ago
await PublishUserNotification(userAccount.Username, userAccount.Email, model.Title, model.PosterPath, type, model.Type);
8 years ago
return;
}
var email = plexUser.User.FirstOrDefault(x => x.Username.Equals(user, StringComparison.CurrentCultureIgnoreCase));
8 years ago
if (email == null) // This is not a Plex User
8 years ago
{
8 years ago
// Local User?
var local = localUsers.FirstOrDefault(x => x.UsernameOrAlias.Equals(user));
if (local != null)
{
Log.Info("Sending notification to: {0} at: {1}, for title: {2}", local.UsernameOrAlias, local.EmailAddress, model.Title);
await PublishUserNotification(local.UsernameOrAlias, local.EmailAddress, model.Title, model.PosterPath, type, model.Type);
continue;
}
8 years ago
}
Log.Info("Sending notification to: {0} at: {1}, for title: {2}", email.Username, email.Email, model.Title);
8 years ago
await PublishUserNotification(email.Username, email.Email, model.Title, model.PosterPath, type, model.Type);
8 years ago
}
}
catch (Exception e)
{
Log.Error(e);
}
}
8 years ago
private async Task PublishUserNotification(string username, string email, string title, string img, NotificationType type, RequestType requestType)
8 years ago
{
var notificationModel = new NotificationModel
{
User = username,
UserEmail = email,
8 years ago
NotificationType = type,
Title = title,
8 years ago
ImgSrc = requestType == RequestType.Movie ? $"https://image.tmdb.org/t/p/w300/{img}" : img
8 years ago
};
// Send the notification to the user.
await Notification.Publish(notificationModel);
}
}
}