Service and more UI

This commit is contained in:
tidusjar 2022-08-23 20:01:21 +01:00
commit 43a4903875
20 changed files with 394 additions and 2776 deletions

View file

@ -0,0 +1,146 @@
using MockQueryable.Moq;
using Moq.AutoMock;
using NUnit.Framework;
using Ombi.Core.Models;
using Ombi.Core.Services;
using Ombi.Store.Entities;
using Ombi.Store.Repository;
using Ombi.Test.Common;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UserType = Ombi.Store.Entities.UserType;
namespace Ombi.Core.Tests.Services
{
public class PlexServiceTests
{
private PlexService _subject;
private AutoMocker _mocker;
[SetUp]
public void Setup()
{
_mocker = new AutoMocker();
_subject = _mocker.CreateInstance<PlexService>();
}
[Test]
public async Task GetWatchListUsers_AllUsersSynced()
{
var userMock = MockHelper.MockUserManager(new List<OmbiUser>
{
new OmbiUser
{
MediaServerToken = "token",
Id = "1",
UserName = "user1",
UserType = UserType.PlexUser,
},
new OmbiUser
{
MediaServerToken = "token",
Id = "2",
UserName = "user2",
UserType = UserType.PlexUser,
},
new OmbiUser
{
MediaServerToken = "token",
Id = "2",
UserName = "user2",
UserType = UserType.LocalUser,
}
});
_mocker.Use(userMock.Object);
_subject = _mocker.CreateInstance<PlexService>();
_mocker.Setup<IRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll())
.Returns(new List<PlexWatchlistUserError>().AsQueryable().BuildMock().Object);
var result = await _subject.GetWatchlistUsers(CancellationToken.None);
Assert.Multiple(() =>
{
Assert.That(result.All(x => x.SyncStatus == WatchlistSyncStatus.Successful));
Assert.That(result.Count, Is.EqualTo(2));
});
}
[Test]
public async Task GetWatchListUsers_NotEnabled()
{
var userMock = MockHelper.MockUserManager(new List<OmbiUser>
{
new OmbiUser
{
MediaServerToken = "",
Id = "1",
UserName = "user1",
UserType = UserType.PlexUser,
},
new OmbiUser
{
MediaServerToken = null,
Id = "2",
UserName = "user2",
UserType = UserType.PlexUser,
},
});
_mocker.Use(userMock.Object);
_subject = _mocker.CreateInstance<PlexService>();
_mocker.Setup<IRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll())
.Returns(new List<PlexWatchlistUserError>().AsQueryable().BuildMock().Object);
var result = await _subject.GetWatchlistUsers(CancellationToken.None);
Assert.Multiple(() =>
{
Assert.That(result.All(x => x.SyncStatus == WatchlistSyncStatus.NotEnabled));
Assert.That(result.Count, Is.EqualTo(2));
});
}
[Test]
public async Task GetWatchListUsers_Failed()
{
var userMock = MockHelper.MockUserManager(new List<OmbiUser>
{
new OmbiUser
{
MediaServerToken = "test",
Id = "1",
UserName = "user1",
UserType = UserType.PlexUser,
},
});
_mocker.Use(userMock.Object);
_subject = _mocker.CreateInstance<PlexService>();
_mocker.Setup<IRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll())
.Returns(new List<PlexWatchlistUserError>
{
new PlexWatchlistUserError
{
UserId = "1",
MediaServerToken = "test",
}
}.AsQueryable().BuildMock().Object);
var result = await _subject.GetWatchlistUsers(CancellationToken.None);
Assert.Multiple(() =>
{
Assert.That(result.All(x => x.SyncStatus == WatchlistSyncStatus.Failed));
Assert.That(result.Count, Is.EqualTo(1));
});
}
}
}

View file

@ -0,0 +1,16 @@
namespace Ombi.Core.Models
{
public class PlexUserWatchlistModel
{
public string UserId { get; set; }
public WatchlistSyncStatus SyncStatus { get; set; }
public string UserName { get; set; }
}
public enum WatchlistSyncStatus
{
Successful,
Failed,
NotEnabled
}
}

View file

@ -0,0 +1,12 @@
using Ombi.Core.Models;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Ombi.Core.Services
{
public interface IPlexService
{
Task<List<PlexUserWatchlistModel>> GetWatchlistUsers(CancellationToken cancellationToken);
}
}

View file

@ -0,0 +1,55 @@
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Authentication;
using Ombi.Core.Models;
using Ombi.Store.Entities;
using Ombi.Store.Repository;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UserType = Ombi.Store.Entities.UserType;
namespace Ombi.Core.Services
{
public class PlexService : IPlexService
{
private readonly IRepository<PlexWatchlistUserError> _watchlistUserErrors;
private readonly OmbiUserManager _userManager;
public PlexService(IRepository<PlexWatchlistUserError> watchlistUserErrors, OmbiUserManager userManager)
{
_watchlistUserErrors = watchlistUserErrors;
_userManager = userManager;
}
public async Task<List<PlexUserWatchlistModel>> GetWatchlistUsers(CancellationToken cancellationToken)
{
var plexUsers = _userManager.Users.Where(x => x.UserType == UserType.PlexUser);
var userErrors = await _watchlistUserErrors.GetAll().ToListAsync(cancellationToken);
var model = new List<PlexUserWatchlistModel>();
foreach(var plexUser in plexUsers)
{
model.Add(new PlexUserWatchlistModel
{
UserId = plexUser.Id,
UserName = plexUser.UserName,
SyncStatus = GetWatchlistSyncStatus(plexUser, userErrors)
});
}
return model;
}
private static WatchlistSyncStatus GetWatchlistSyncStatus(OmbiUser user, List<PlexWatchlistUserError> userErrors)
{
if (string.IsNullOrWhiteSpace(user.MediaServerToken))
{
return WatchlistSyncStatus.NotEnabled;
}
return userErrors.Any(x => x.UserId == user.Id) ? WatchlistSyncStatus.Failed : WatchlistSyncStatus.Successful;
}
}
}

View file

@ -229,6 +229,7 @@ namespace Ombi.DependencyInjection
services.AddTransient<IChangeLogProcessor, ChangeLogProcessor>();
services.AddScoped<IFeatureService, FeatureService>();
services.AddTransient<IRecentlyRequestedService, RecentlyRequestedService>();
services.AddTransient<IPlexService, PlexService>();
}
public static void RegisterJobs(this IServiceCollection services)

View file

@ -97,7 +97,7 @@ namespace Ombi.Schedule.Tests
[Test]
public async Task FailedWatchListUser_NewToken_ShouldBeRemoved()
{
_mocker.Setup<IExternalRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll()).Returns(new List<PlexWatchlistUserError>
_mocker.Setup<IRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll()).Returns(new List<PlexWatchlistUserError>
{
new PlexWatchlistUserError
{
@ -121,7 +121,7 @@ namespace Ombi.Schedule.Tests
[Test]
public async Task FailedWatchListUser_OldToken_ShouldSkip()
{
_mocker.Setup<IExternalRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll()).Returns(new List<PlexWatchlistUserError>
_mocker.Setup<IRepository<PlexWatchlistUserError>, IQueryable<PlexWatchlistUserError>>(x => x.GetAll()).Returns(new List<PlexWatchlistUserError>
{
new PlexWatchlistUserError
{

View file

@ -7,8 +7,5 @@ namespace Ombi.Store.Entities
{
public string UserId { get; set; }
public string MediaServerToken { get; set; }
[ForeignKey(nameof(UserId))]
public OmbiUser User { get; set; }
}
}

View file

@ -1,46 +0,0 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Ombi.Store.Migrations.OmbiMySql
{
public partial class PlexWatchlistUserError : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PlexWatchlistUserError",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(type: "varchar(255)", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
MediaServerToken = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_PlexWatchlistUserError", x => x.Id);
table.ForeignKey(
name: "FK_PlexWatchlistUserError_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id");
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_PlexWatchlistUserError_UserId",
table: "PlexWatchlistUserError",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PlexWatchlistUserError");
}
}
}

View file

@ -350,25 +350,6 @@ namespace Ombi.Store.Migrations.OmbiMySql
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Ombi.Store.Entities.PlexWatchlistUserError", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("MediaServerToken")
.HasColumnType("longtext");
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PlexWatchlistUserError");
});
modelBuilder.Entity("Ombi.Store.Entities.RecentlyAddedLog", b =>
{
b.Property<int>("Id")
@ -1112,15 +1093,6 @@ namespace Ombi.Store.Migrations.OmbiMySql
b.Navigation("User");
});
modelBuilder.Entity("Ombi.Store.Entities.PlexWatchlistUserError", b =>
{
b.HasOne("Ombi.Store.Entities.OmbiUser", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("User");
});
modelBuilder.Entity("Ombi.Store.Entities.Requests.AlbumRequest", b =>
{
b.HasOne("Ombi.Store.Entities.OmbiUser", "RequestedUser")

View file

@ -1,42 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Ombi.Store.Migrations.OmbiSqlite
{
public partial class PlexWatchlistUserError : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PlexWatchlistUserError",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
UserId = table.Column<string>(type: "TEXT", nullable: true),
MediaServerToken = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PlexWatchlistUserError", x => x.Id);
table.ForeignKey(
name: "FK_PlexWatchlistUserError_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "IX_PlexWatchlistUserError_UserId",
table: "PlexWatchlistUserError",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PlexWatchlistUserError");
}
}
}

View file

@ -348,25 +348,6 @@ namespace Ombi.Store.Migrations.OmbiSqlite
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Ombi.Store.Entities.PlexWatchlistUserError", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("MediaServerToken")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PlexWatchlistUserError");
});
modelBuilder.Entity("Ombi.Store.Entities.RecentlyAddedLog", b =>
{
b.Property<int>("Id")
@ -1110,15 +1091,6 @@ namespace Ombi.Store.Migrations.OmbiSqlite
b.Navigation("User");
});
modelBuilder.Entity("Ombi.Store.Entities.PlexWatchlistUserError", b =>
{
b.HasOne("Ombi.Store.Entities.OmbiUser", "User")
.WithMany()
.HasForeignKey("UserId");
b.Navigation("User");
});
modelBuilder.Entity("Ombi.Store.Entities.Requests.AlbumRequest", b =>
{
b.HasOne("Ombi.Store.Entities.OmbiUser", "RequestedUser")

View file

@ -107,3 +107,16 @@ export interface IPlexServerResponse {
port: string;
scheme: string;
}
export interface IPlexWatchlistUsers {
userId: string;
syncStatus: WatchlistSyncStatus;
userName: string;
}
export enum WatchlistSyncStatus
{
Successful,
Failed,
NotEnabled
}

View file

@ -1,4 +1,4 @@
import { PlatformLocation, APP_BASE_HREF } from "@angular/common";
import { APP_BASE_HREF } from "@angular/common";
import { HttpClient } from "@angular/common/http";
import { Injectable, Inject } from "@angular/core";
@ -6,7 +6,7 @@ import { Observable } from "rxjs";
import { ServiceHelpers } from "../service.helpers";
import { IPlexAuthentication, IPlexLibResponse, IPlexLibSimpleResponse, IPlexOAuthViewModel, IPlexServer, IPlexServerAddViewModel, IPlexServerViewModel, IPlexUserAddResponse, IPlexUserViewModel, IUsersModel } from "../../interfaces";
import { IPlexAuthentication, IPlexLibResponse, IPlexLibSimpleResponse, IPlexOAuthViewModel, IPlexServer, IPlexServerAddViewModel, IPlexServerViewModel, IPlexUserAddResponse, IPlexUserViewModel, IPlexWatchlistUsers, IUsersModel } from "../../interfaces";
@Injectable()
export class PlexService extends ServiceHelpers {
@ -45,4 +45,8 @@ export class PlexService extends ServiceHelpers {
public oAuth(wizard: IPlexOAuthViewModel): Observable<any> {
return this.http.post<any>(`${this.url}oauth`, JSON.stringify(wizard), {headers: this.headers});
}
public getWatchlistUsers(): Observable<IPlexWatchlistUsers[]> {
return this.http.get<IPlexWatchlistUsers[]>(`${this.url}WatchlistUsers`, {headers: this.headers});
}
}

View file

@ -0,0 +1,32 @@
<div class="small-middle-container">
<fieldset style="fieldset">
<legend>Watchlist Errors</legend>
<p>If the Sync fails, this is because of an authentication issue with Plex (Token has expired). If this happens the user needs to re-login to Ombi.</p>
<p>Key:
<br>
<em class="fa-solid fa-check"></em>
<br>
<em class="fa-solid fa-times"></em>
<br>
<em class="fas fa-user-alt-slash"></em>
</p>
<table mat-table *ngIf="dataSource" [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container matColumnDef="userName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Username </th>
<td mat-cell *matCellDef="let element"> {{element.userName}} </td>
</ng-container>
<ng-container matColumnDef="syncStatus">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Watchlist Sync Result </th>
<td mat-cell *matCellDef="let element">
<em *ngIf="element.syncStatus === WatchlistSyncStatus.Successful" class="fa-solid fa-check"></em>
<em *ngIf="element.syncStatus === WatchlistSyncStatus.Failed" class="fa-solid fa-times"></em>
<em *ngIf="element.syncStatus === WatchlistSyncStatus.NotEnabled" class="fas fa-user-alt-slash"></em>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</fieldset>
</div>

View file

@ -0,0 +1,9 @@
@import "~styles/shared.scss";
.small-middle-container {
margin: auto;
width: 95%;
margin-top: 10px;
}
.fieldset {
width: 100%;
}

View file

@ -0,0 +1,68 @@
// also exported from '@storybook/angular' if you can deal with breaking changes in 6.1
import { APP_BASE_HREF, CommonModule } from '@angular/common';
import { Story, Meta, moduleMetadata } from '@storybook/angular';
import { Observable, of } from 'rxjs';
import { IPlexWatchlistUsers, WatchlistSyncStatus } from '../../../../interfaces';
import { PlexService } from '../../../../services';
import { SharedModule } from '../../../../shared/shared.module';
import { PlexWatchlistComponent } from './plex-watchlist.component';
const mockUsers: IPlexWatchlistUsers[] =
[
{
userName: "Success User",
userId: "a",
syncStatus: WatchlistSyncStatus.Successful
},
{
userName: "Failed User",
userId: "2",
syncStatus: WatchlistSyncStatus.Failed
},
{
userName: "Not Enabled",
userId: "2",
syncStatus: WatchlistSyncStatus.NotEnabled
},
];
function plexServiveMock(): Partial<PlexService> {
return {
getWatchlistUsers: () : Observable<IPlexWatchlistUsers[]> => of(mockUsers),
};
}
// More on default export: https://storybook.js.org/docs/angular/writing-stories/introduction#default-export
export default {
title: 'Plex Watchlist Component',
component: PlexWatchlistComponent,
decorators: [
moduleMetadata({
providers: [
{
provide: APP_BASE_HREF,
useValue: ""
},
{
provide: PlexService,
useValue: plexServiveMock()
}
],
imports: [
CommonModule,
SharedModule
]
})
]
} as Meta;
// More on component templates: https://storybook.js.org/docs/angular/writing-stories/introduction#using-args
const Template: Story<PlexWatchlistComponent> = (args: PlexWatchlistComponent) => ({
props: args,
});
export const Default = Template.bind({});
Default.args = {
};

View file

@ -0,0 +1,25 @@
import { Component, OnInit } from "@angular/core";
import { MatTableDataSource } from "@angular/material/table";
import { take } from "rxjs";
import { IPlexWatchlistUsers, WatchlistSyncStatus } from "../../../../interfaces";
import { PlexService } from "../../../../services";
@Component({
templateUrl: "./plex-watchlist.component.html",
styleUrls: ["./plex-watchlist.component.scss"]
})
export class PlexWatchlistComponent implements OnInit{
public dataSource: MatTableDataSource<IPlexWatchlistUsers> = new MatTableDataSource();
public displayedColumns: string[] = ['userName','syncStatus'];
public WatchlistSyncStatus = WatchlistSyncStatus;
constructor(private plexService: PlexService) { }
public ngOnInit() {
this.plexService.getWatchlistUsers().pipe(take(1)).subscribe((x: IPlexWatchlistUsers[]) => {
this.dataSource = new MatTableDataSource(x);
});
}
}

View file

@ -9,6 +9,8 @@ using Ombi.Api.Plex;
using Ombi.Api.Plex.Models;
using Ombi.Attributes;
using Ombi.Core.Authentication;
using Ombi.Core.Models;
using Ombi.Core.Services;
using Ombi.Core.Settings;
using Ombi.Core.Settings.Models.External;
using Ombi.Helpers;
@ -23,18 +25,20 @@ namespace Ombi.Controllers.V1.External
public class PlexController : Controller
{
public PlexController(IPlexApi plexApi, ISettingsService<PlexSettings> plexSettings,
ILogger<PlexController> logger, IPlexOAuthManager manager)
ILogger<PlexController> logger, IPlexOAuthManager manager, IPlexService plexService)
{
PlexApi = plexApi;
PlexSettings = plexSettings;
_log = logger;
_plexOAuthManager = manager;
_plexService = plexService;
}
private IPlexApi PlexApi { get; }
private ISettingsService<PlexSettings> PlexSettings { get; }
private readonly ILogger<PlexController> _log;
private readonly IPlexOAuthManager _plexOAuthManager;
private readonly IPlexService _plexService;
/// <summary>
/// Signs into the Plex API.
@ -300,5 +304,9 @@ namespace Ombi.Controllers.V1.External
return new JsonResult(new {url = url.ToString()});
}
[Admin]
[HttpGet("WatchlistUsers")]
public async Task<List<PlexUserWatchlistModel>> GetPlexWatchlistUsers() => await _plexService.GetWatchlistUsers(HttpContext.RequestAborted);
}
}