Skip to content

Commit

Permalink
more fixes and other stuff
Browse files Browse the repository at this point in the history
moved button styles to own file
different loglevel for prod and dev build
own DispatcherUtil
FluentScheduler instead of timers (not all yet)
moved UpdateTorrentProgress from mainviewmodel to torrentservice
  • Loading branch information
Tensei committed May 25, 2021
1 parent 51479b4 commit e998485
Show file tree
Hide file tree
Showing 14 changed files with 274 additions and 130 deletions.
33 changes: 1 addition & 32 deletions anidow/App.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<ResourceDictionary Source="pack://application:,,,/Styles/Expander.xaml" />
<ResourceDictionary Source="pack://application:,,,/Styles/TabControl.xaml" />
<ResourceDictionary Source="pack://application:,,,/Styles/ListViewItem.xaml" />
<ResourceDictionary Source="pack://application:,,,/Styles/Button.xaml" />
</s:ApplicationLoader.MergedDictionaries>

<!-- Override colors -->
Expand Down Expand Up @@ -133,38 +134,6 @@
</Setter>
</Style>

<Style
x:Key="DeleteButton"
BasedOn="{StaticResource {x:Type Button}}"
TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static adonisUi:Brushes.ForegroundBrush}}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{DynamicResource {x:Static adonisUi:Brushes.ErrorBrush}}" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</Style.Triggers>
</Style>

<Style
x:Key="ActionButton"
BasedOn="{StaticResource {x:Type Button}}"
TargetType="{x:Type Button}">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Padding" Value="8" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{DynamicResource {x:Static adonisUi:Brushes.AccentBrush}}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Background" Value="Transparent" />
</Trigger>
</Style.Triggers>
</Style>
</s:ApplicationLoader>
</Application.Resources>
</Application>
16 changes: 14 additions & 2 deletions anidow/Bootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Anidow.Services;
using Anidow.Torrent_Clients;
using Anidow.Validators;
using FluentScheduler;
using FluentValidation;
using Hardcodet.Wpf.TaskbarNotification;
using Jot;
Expand Down Expand Up @@ -129,11 +130,16 @@ private Tracker InitTracker()

private void InitLogger(ILogEventSink logViewModel)
{
var logLevel = LogEventLevel.Information;
#if DEBUG
logLevel = LogEventLevel.Verbose;
#endif

var logConfiguration = new LoggerConfiguration()
.MinimumLevel.Is(LogEventLevel.Verbose)
.MinimumLevel.Is(logLevel)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Sink(logViewModel, LogEventLevel.Verbose)
.WriteTo.Sink(logViewModel, logLevel)
.WriteTo.File(
"./logs/log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7);

Expand All @@ -143,6 +149,7 @@ private void InitLogger(ILogEventSink logViewModel)
protected override void OnExit(ExitEventArgs e)
{
_taskBarIcon?.Dispose();
JobManager.StopAndBlock();
}

protected override async void Configure()
Expand Down Expand Up @@ -179,6 +186,11 @@ protected override async void Configure()
XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);
}

// Initialize FluentScheduler
JobManager.Initialize();
JobManager.JobException += info => _logger.Error(info.Exception, "An error just happened with a scheduled job");



var selfContained = false;
#if SELF_CONTAINED && RELEASE
Expand Down
9 changes: 1 addition & 8 deletions anidow/Pages/FolderFilesViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Anidow.Database.Models;
using Anidow.Extensions;
using Anidow.Model;
using Anidow.Utils;
using Microsoft.VisualBasic;
using Serilog;
using Stylet;
using MessageBox = AdonisUI.Controls.MessageBox;
Expand Down Expand Up @@ -111,16 +108,12 @@ public async Task GetFilesFromFolder(bool clear = false)
}
#endif
}
private async Task Dispatch(Action action)
{
await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, action);
}

public async Task LoadMore()
{
foreach (var filesModel in _files.Skip(FileInfos.Count).Take(_maxFilesInView))
{
await Dispatch(() => FileInfos.Add(filesModel));
await DispatcherUtil.DispatchAsync(() => FileInfos.Add(filesModel));
}
CanLoadMore = FileInfos.Count < _files.Count;
DisplayName = $"Files ({FileInfos.Count}/{_files.Count}) - {_name}";
Expand Down
10 changes: 2 additions & 8 deletions anidow/Pages/HistoryViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Anidow.Database;
using Anidow.Database.Models;
using Anidow.Extensions;
Expand Down Expand Up @@ -125,17 +124,12 @@ public async Task LoadEpisodes(bool clear = false)

CanLoadEpisodes = true;
}

private async Task Dispatch(Action action)
{
await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, action);
}


public async Task LoadMore()
{
foreach (var episode in _episodes.Skip(Items.Count).Take(_maxFilesInView))
{
await Dispatch(() => Items.Add(episode));
await DispatcherUtil.DispatchAsync(() => Items.Add(episode));
}
CanLoadMore = Items.Count < _episodes.Count;
EpisodesLoaded = $"{Items.Count}/{_episodes.Count}";
Expand Down
8 changes: 4 additions & 4 deletions anidow/Pages/LogViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.ObjectModel;
using Anidow.Utils;
using Serilog.Core;
using Serilog.Events;
using Stylet;
Expand All @@ -9,14 +9,14 @@ public class LogViewModel : Screen, ILogEventSink
{
public LogViewModel()
{
Items = new ObservableCollection<LogEvent>();
Items = new BindableCollection<LogEvent>();
}

public ObservableCollection<LogEvent> Items { get; }
public IObservableCollection<LogEvent> Items { get; }

public void Emit(LogEvent logEvent)
{
Execute.OnUIThreadSync(() => Items.Insert(0, logEvent));
DispatcherUtil.DispatchSync(() => Items.Insert(0, logEvent));
}
}
}
41 changes: 19 additions & 22 deletions anidow/Pages/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
using Anidow.Enums;
using Anidow.Events;
using Anidow.Extensions;
using Anidow.Interfaces;
using Anidow.Model;
using Anidow.Services;
using Anidow.Torrent_Clients;
using Anidow.Utils;
using BencodeNET.Torrents;
using FluentScheduler;
using Hardcodet.Wpf.TaskbarNotification;
using Humanizer;
using Microsoft.EntityFrameworkCore;
Expand All @@ -36,7 +38,6 @@ public class MainViewModel : Conductor<Episode>.Collection.OneActive, IHandle<Do
private readonly TaskbarIcon _taskbarIcon;
private readonly TorrentService _torrentService;
private readonly IWindowManager _windowManager;
private Timer _getTorrentsStatusTimer;


public MainViewModel(IEventAggregator eventAggregator, ILogger logger,
Expand Down Expand Up @@ -299,9 +300,15 @@ public async Task DeleteWithFile()

protected override void OnInitialActivate()
{
_getTorrentsStatusTimer = new Timer { Interval = 5000 };
_getTorrentsStatusTimer.Elapsed += async (_, _) => { await UpdateTorrents(); };
_getTorrentsStatusTimer.Start();
JobManager.AddJob(
() =>
{
UpdateTorrents().Wait();
},
s => s.WithName("Home:UpdateTorrents").NonReentrant().ToRunEvery(1).Seconds()
);


NextCheckTimer = new Timer(100);
NextCheckTimer.Elapsed += NextCheckTimerOnElapsed;
Expand Down Expand Up @@ -380,33 +387,23 @@ private async Task LoadEpisodes()

private async Task UpdateTorrents()
{
_logger.Debug("started job: UpdateTorrents");
if (Items.Count <= 0)
{
_logger.Debug("finished job: UpdateTorrents");
return;
}

var torrents = await _torrentService.GetTorrents<QBitTorrentEntry[]>();
if (torrents is null)
try
{
return;
await _torrentService.UpdateTorrentProgress(Items);
}

foreach (var anime in Items)
catch (Exception e)
{
if (string.IsNullOrWhiteSpace(anime.TorrentId))
{
continue;
}

var torrent = torrents.SingleOrDefault(t =>
t.hash.Equals(anime.TorrentId, StringComparison.InvariantCultureIgnoreCase));
if (torrent is null)
{
continue;
}

anime.TorrentProgress = torrent.progress;
_logger.Error(e, "failed updating torrent progress");
}

_logger.Debug("finished job: UpdateTorrents");
}

public async Task GetAiringEpisodesForToday()
Expand Down
36 changes: 9 additions & 27 deletions anidow/Pages/ShellView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,35 +35,17 @@
</Grid.ColumnDefinitions>
<Button
Grid.Column="1"
Command="{s:Action TestCrash}"
FontFamily="Segoe UI"
FontSize="14"
Visibility="{Binding CanTestCrash, Converter={x:Static s:BoolToVisibilityConverter.Instance}}">
<Button.Style>
<Style BasedOn="{StaticResource {x:Static adonisUi:Styles.WindowButton}}" TargetType="Button">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Content" Value="Crash" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Command="{s:Action TestCrash,
ActionNotFound=Disable}"
Content="Crash"
Style="{DynamicResource WindowButtonHidden}"
Visibility="{Binding CanTestCrash, Converter={x:Static s:BoolToVisibilityConverter.Instance}}" />
<Button
Grid.Column="2"
Command="{s:Action ShowLogs}"
FontFamily="Segoe UI"
FontSize="14">
<Button.Style>
<Style BasedOn="{StaticResource {x:Static adonisUi:Styles.WindowButton}}" TargetType="Button">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Content" Value="Logs" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Command="{s:Action ShowLogs,
ActionNotFound=Disable}"
Content="Logs"
Style="{DynamicResource WindowButtonHidden}" />
<Button
Grid.Column="3"
Command="{s:Action OpenGithub,
Expand Down
6 changes: 2 additions & 4 deletions anidow/Pages/ShellViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using System.Timers;
Expand Down Expand Up @@ -54,7 +55,7 @@ public class ShellViewModel : Conductor<Screen>.Collection.OneActive
public bool CanForceCheck { get; set; } = true;
public string NextCheckIn { get; set; }
public Timer NextCheckTimer { get; set; }
public bool CanTestCrash { get; set; }
public bool CanTestCrash => Debugger.IsAttached;

protected override async void OnInitialActivate()
{
Expand All @@ -63,9 +64,6 @@ protected override async void OnInitialActivate()
NextCheckTimer = new Timer(1000);
NextCheckTimer.Elapsed += NextCheckTimerOnElapsed;
NextCheckTimer.Start();
#if DEBUG
CanTestCrash = true;
#endif
}

public void TestCrash()
Expand Down
11 changes: 2 additions & 9 deletions anidow/Pages/TrackedViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Threading;
using Anidow.Database;
using Anidow.Database.Models;
using Anidow.Enums;
Expand All @@ -17,7 +16,6 @@
using Microsoft.EntityFrameworkCore;
using Serilog;
using Stylet;
using Application = System.Windows.Application;
using UserControl = System.Windows.Controls.UserControl;

namespace Anidow.Pages
Expand Down Expand Up @@ -55,7 +53,7 @@ public string Search
{
SetAndNotify(ref _search, value);
Debouncer.DebounceAction("load_tracked",
async _ => { await Dispatch(async () => await Load()); });
async _ => { await DispatcherUtil.DispatchAsync(async () => await Load()); });
}
}

Expand Down Expand Up @@ -98,17 +96,12 @@ public async Task Load()
foreach (var a in anime)
{
a.Episodes = await db.Episodes.CountAsync(e => e.AnimeId == a.GroupId);
await Dispatch(() => Items.Add(a));
await DispatcherUtil.DispatchAsync(() => Items.Add(a));
}

CanLoad = true;
}

private async Task Dispatch(Action action)
{
await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, action);
}

private void ScrollToTop()
{
if (_scrollViewers == null)
Expand Down

0 comments on commit e998485

Please sign in to comment.