Skip to content

Commit

Permalink
feat: Добавлены тосты с сообщениями синхронизации
Browse files Browse the repository at this point in the history
  • Loading branch information
Kibnet committed Mar 13, 2024
1 parent bd4d7c3 commit f88768f
Show file tree
Hide file tree
Showing 15 changed files with 158 additions and 55 deletions.
36 changes: 20 additions & 16 deletions src/Unlimotion.Desktop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public static void Main(string[] args)
var gitSection = configuration.GetSection("Git");

gitSection.GetSection(nameof(GitSettings.BackupEnabled)).Set(false);
gitSection.GetSection(nameof(GitSettings.ShowStatusToasts)).Set(gitSettings.ShowStatusToasts);

gitSection.GetSection(nameof(GitSettings.UserName)).Set(gitSettings.UserName);
gitSection.GetSection(nameof(GitSettings.Password)).Set(gitSettings.Password);
Expand All @@ -102,23 +103,27 @@ public static void Main(string[] args)
gitSection.GetSection(nameof(GitSettings.CommitterEmail)).Set(gitSettings.CommitterEmail);
}

var pullJob = JobBuilder.Create<GitPullJob>()
.WithIdentity("GitPullJob", "GitPullJob")
.Build();
var pushJob = JobBuilder.Create<GitPushJob>()
.WithIdentity("GitPushJob", "GitPushJob")
.Build();

var pullTrigger = GenerateTriggerBySecondsInterval("PullTrigger", "GitPullJob",
gitSettings.PullIntervalSeconds);
var pushTrigger = GenerateTriggerBySecondsInterval("PushTrigger", "GitPushJob",
gitSettings.PushIntervalSeconds);
var taskRepository = Locator.Current.GetService<ITaskRepository>();
taskRepository.Initiated += (sender, eventArgs) =>
{
var pullJob = JobBuilder.Create<GitPullJob>()
.WithIdentity("GitPullJob", "Git")
.Build();
var pushJob = JobBuilder.Create<GitPushJob>()
.WithIdentity("GitPushJob", "Git")
.Build();

var pullTrigger = GenerateTriggerBySecondsInterval("PullTrigger", "GitPullJob",
gitSettings.PullIntervalSeconds);
var pushTrigger = GenerateTriggerBySecondsInterval("PushTrigger", "GitPushJob",
gitSettings.PushIntervalSeconds);

scheduler.ScheduleJob(pullJob, pullTrigger);
scheduler.ScheduleJob(pushJob, pushTrigger);
scheduler.ScheduleJob(pullJob, pullTrigger);
scheduler.ScheduleJob(pushJob, pushTrigger);

if (gitSettings.BackupEnabled)
scheduler.Start();
if (gitSettings.BackupEnabled)
scheduler.Start();
};

BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
Expand All @@ -141,7 +146,6 @@ private static ITrigger GenerateTriggerBySecondsInterval(string name, string gro
{
return TriggerBuilder.Create()
.WithIdentity(name, group)
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(seconds)
.RepeatForever())
Expand Down
3 changes: 3 additions & 0 deletions src/Unlimotion.ViewModel/FileDbWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ public void AddIgnoredTask(string taskId)
private void OnError(object sender, ErrorEventArgs e)
{
Debug.WriteLine("Error in FileWatcher");
var notify = Locator.Current.GetService<INotificationManagerWrapper>();
notify?.ErrorToast(e.GetException().Message);

}

private FileSystemEventHandler CreateThrottledEventHandler(
Expand Down
4 changes: 4 additions & 0 deletions src/Unlimotion.ViewModel/INotificationManagerWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@ namespace Unlimotion.ViewModel;
public interface INotificationManagerWrapper
{
void Ask(string header, string message, Action yesAction, Action noAction = null);

void ErrorToast(string message);

void SuccessToast(string message);
}
1 change: 1 addition & 0 deletions src/Unlimotion.ViewModel/ITaskRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public interface ITaskRepository
{
SourceCache<TaskItemViewModel, string> Tasks { get; }
void Init();
event EventHandler<EventArgs> Initiated;
Task Remove(string itemId, bool deleteFile);
Task Save(TaskItem item);
Task<TaskItem> Load(string itemId);
Expand Down
1 change: 1 addition & 0 deletions src/Unlimotion.ViewModel/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@ public TaskWrapperViewModel FindTaskWrapperViewModel(TaskItemViewModel taskItemV
public DateFilter LastCreatedDateFilter { get; set; } = new();

public static ReadOnlyObservableCollection<string> DateFilterDefinitions { get; set; } = DateFilterDefinition.GetDefinitions();
public object ToastNotificationManager { get; set; }
}

[AddINotifyPropertyChangedInterface]
Expand Down
6 changes: 6 additions & 0 deletions src/Unlimotion.ViewModel/SettingsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ public bool GitBackupEnabled
get => _gitSettings.GetSection(nameof(GitSettings.BackupEnabled)).Get<bool>();
set => _gitSettings.GetSection(nameof(GitSettings.BackupEnabled)).Set(value);
}

public bool GitShowStatusToasts
{
get => _gitSettings.GetSection(nameof(GitSettings.ShowStatusToasts)).Get<bool>();
set => _gitSettings.GetSection(nameof(GitSettings.ShowStatusToasts)).Set(value);
}

public string GitUserName
{
Expand Down
9 changes: 9 additions & 0 deletions src/Unlimotion.ViewModel/TaskRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public class TaskRepository : ITaskRepository
{
private readonly ITaskStorage taskStorage;
private readonly IDatabaseWatcher? dbWatcher;
public event EventHandler<EventArgs> Initiated;

private Dictionary<string, HashSet<string>> blockedById { get; set; }
private IObservable<Func<TaskItemViewModel, bool>> rootFilter;
public SourceCache<TaskItemViewModel, string> Tasks { get; private set; }
Expand Down Expand Up @@ -99,6 +101,8 @@ private void Init(IEnumerable<TaskItem> items)
taskStorage.Updating += TaskStorageOnUpdating;
dbWatcher.OnUpdated += DbWatcherOnUpdated;
}

OnInited();
}

private void TaskStorageOnUpdating(object sender, TaskStorageUpdateEventArgs e)
Expand Down Expand Up @@ -184,5 +188,10 @@ public TaskItemViewModel Clone(TaskItem clone, params TaskItemViewModel[] destin
this.Tasks.AddOrUpdate(task);
return task;
}

protected virtual void OnInited()
{
Initiated?.Invoke(this, EventArgs.Empty);
}
}
}
1 change: 1 addition & 0 deletions src/Unlimotion.ViewModel/TaskStorageSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public class TaskStorageSettings
public class GitSettings
{
public bool BackupEnabled { get; set; } = false;
public bool ShowStatusToasts { get; set; } = true;

public string UserName { get; set; } = "YourEmail";
public string Password { get; set; } = "YourToken";
Expand Down
3 changes: 2 additions & 1 deletion src/Unlimotion/App.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,6 @@
</Setter>
</Style>
<dialogHostAvalonia:DialogHostStyles />
</Application.Styles>
<StyleInclude Source="avares://Notification.Avalonia/Themes/Generic.xaml" />
</Application.Styles>
</Application>
16 changes: 14 additions & 2 deletions src/Unlimotion/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Notification;
#if LIVE
using Live.Avalonia;
#endif
using ReactiveUI;
using Splat;
using Unlimotion.ViewModel;
using Unlimotion.Views;

Expand Down Expand Up @@ -47,7 +49,7 @@ public override void OnFrameworkInitializationCompleted()
{
desktop.MainWindow = new MainWindow
{
DataContext = new MainWindowViewModel(),
DataContext = GetMainWindowViewModel(),
};
}

Expand All @@ -59,7 +61,17 @@ public override void OnFrameworkInitializationCompleted()
{
singleViewPlatform.MainView = new MainControl
{
DataContext = new MainWindowViewModel(),
DataContext = GetMainWindowViewModel(),
};
}

MainWindowViewModel GetMainWindowViewModel()
{
var notificationMessageManager = new NotificationMessageManager();
Locator.CurrentMutable.RegisterConstant<INotificationMessageManager>(notificationMessageManager);
return new MainWindowViewModel
{
ToastNotificationManager = notificationMessageManager
};
}

Expand Down
32 changes: 32 additions & 0 deletions src/Unlimotion/NotificationManagerWrapper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using DialogHostAvalonia;
using System;
using System.Windows.Input;
using Avalonia.Notification;
using Avalonia.Threading;
using ReactiveUI;
using Splat;

namespace Unlimotion;

Expand All @@ -20,6 +23,35 @@ public void Ask(string header, string message, Action yesAction, Action noAction
var id = DialogHost.Show(askViewModel);
askViewModel.CloseAction = () => DialogHost.GetDialogSession("Ask")?.Close(false);
}


public void ErrorToast(string message)
{
var notify = Locator.Current.GetService<INotificationMessageManager>();
Dispatcher.UIThread.InvokeAsync(() =>
{
notify?.CreateMessage()
.Background("#DC483D")
.HasMessage(message)
.Dismiss().WithDelay(TimeSpan.FromSeconds(7))
.WithCloseButton()
.Queue();
});
}

public void SuccessToast(string message)
{
var notify = Locator.Current.GetService<INotificationMessageManager>();
Dispatcher.UIThread.InvokeAsync(() =>
{
notify?.CreateMessage()
.Background("#008800")
.HasMessage(message)
.Dismiss().WithDelay(TimeSpan.FromSeconds(7))
.WithCloseButton()
.Queue();
});
}
}

public class AskViewModel
Expand Down
40 changes: 30 additions & 10 deletions src/Unlimotion/Services/BackupViaGitService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ public List<string> Refs()
}
}
}
catch (Exception ex) { }
catch (Exception ex)
{
ShowUiError(ex.Message);
}

return result;
}
Expand All @@ -52,7 +55,10 @@ public List<string> Remotes()
result.Add(remote.Name);
}
}
catch (Exception ex) { }
catch (Exception ex)
{
ShowUiError(ex.Message);
}

return result;
}
Expand All @@ -67,6 +73,7 @@ public void Push(string msg)

using var repo = new Repository(GetRepositoryPath(settings.repositoryPath));

ShowUiMessage("Start Git Push");
if (repo.RetrieveStatus().IsDirty)
{
Commands.Checkout(repo, settings.git.PushRefSpec);
Expand All @@ -76,6 +83,8 @@ public void Push(string msg)
var committer = new Signature(settings.git.CommitterName, settings.git.CommitterEmail, DateTime.Now);

repo.Commit(msg, committer, committer);

ShowUiMessage("Commit Created");
}

var options = new PushOptions
Expand All @@ -96,12 +105,13 @@ public void Push(string msg)
try
{
repo.Network.Push(repo.Network.Remotes[settings.git.RemoteName], settings.git.PushRefSpec, options);
ShowUiMessage("Push Successful");
}
catch (Exception e)
{
var errorMessage = $"Can't push the remote repository, because {e.Message}";
Debug.WriteLine(errorMessage);
new Thread(() => ShowUiError(errorMessage)).Start();
ShowUiError(errorMessage);
}
}
}
Expand All @@ -118,6 +128,7 @@ public void Pull()

var refSpecs = repo.Network.Remotes[settings.git.RemoteName].FetchRefSpecs.Select(x => x.Specification);

ShowUiMessage("Start Git Pull");
Commands.Fetch(repo, settings.git.RemoteName, refSpecs, new FetchOptions
{
CredentialsProvider = (_, _, _) =>
Expand All @@ -144,27 +155,29 @@ public void Pull()
try
{
repo.Merge(remoteBranch, signature, new MergeOptions());
ShowUiMessage("Merge Successful");
}
catch (Exception e)
{
var errorMessage = $"Can't merge remote branch to local branch, because {e.Message}";
Debug.WriteLine(errorMessage);
new Thread(() => ShowUiError(errorMessage)).Start();
ShowUiError(errorMessage);
}

if (stash != null)
{
var stashIndex = repo.Stashes.ToList().IndexOf(stash);
var applyStatus = repo.Stashes.Apply(stashIndex);

ShowUiMessage("Stash Applied");
if (applyStatus == StashApplyStatus.Applied)
repo.Stashes.Remove(stashIndex);
}

if (repo.Index.Conflicts.Any())
{
const string errorMessage = "Fix conflicts and then commit the result";
new Thread(() => ShowUiError(errorMessage)).Start();
ShowUiError(errorMessage);
}
}
}
Expand All @@ -190,11 +203,18 @@ private static (GitSettings git, string? repositoryPath) GetSettings()

private static void ShowUiError(string message)
{
Dispatcher.UIThread.InvokeAsync(() =>
Debug.WriteLine($"Git error: {message} at {DateTime.Now}");
var notify = Locator.Current.GetService<INotificationManagerWrapper>();
notify?.ErrorToast(message);
}

private static void ShowUiMessage(string message)
{
var settings = GetSettings();
if (settings.git.ShowStatusToasts)
{
var notificationManager = Locator.Current.GetService<INotificationManagerWrapper>();
notificationManager?.Ask("Git Error", message,
() => Debug.WriteLine($"User read the git error {message} at {DateTime.Now}"));
});
var notify = Locator.Current.GetService<INotificationManagerWrapper>();
notify?.SuccessToast(message);
}
}
}
3 changes: 2 additions & 1 deletion src/Unlimotion/Unlimotion.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="$(AvaloniaVersion)" />
<PackageReference Include="AvaloniaGraphControl" Version="0.6.1" />
<PackageReference Include="LibGit2Sharp" Version="0.29.0" />
<PackageReference Include="Quartz" Version="3.7.0" />
<PackageReference Include="Mileeena.Notification.Avalonia" Version="2.1.2" />
<PackageReference Include="Quartz" Version="3.8.1" />
<PackageReference Include="ServiceStack.Client" Version="6.4.0" />
<PackageReference Include="SignalR.EasyUse.Client" Version="0.2.1" />
</ItemGroup>
Expand Down
Loading

0 comments on commit f88768f

Please sign in to comment.