Skip to content

Commit

Permalink
[Android] [Shared] [UWP] Old log files are now automatically deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
Wolfteam committed Jul 16, 2020
1 parent 95e9daf commit d8935a5
Show file tree
Hide file tree
Showing 15 changed files with 103 additions and 23 deletions.
7 changes: 3 additions & 4 deletions MiraiNotes.Android/App.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using Android.App;
using AutoMapper;
using AutoMapper;
using FluentValidation;
using MiraiNotes.Abstractions.Data;
using MiraiNotes.Abstractions.GoogleApi;
using MiraiNotes.Abstractions.Services;
using MiraiNotes.Android.Background;
using MiraiNotes.Android.Common;
using MiraiNotes.Android.Common.Utils;
using MiraiNotes.Android.Common.Validators;
using MiraiNotes.Android.Interfaces;
using MiraiNotes.Android.Services;
Expand Down Expand Up @@ -112,8 +112,7 @@ private ILogger SetupLogging()
{
const string fileOutputTemplate =
"{Timestamp:dd-MM-yyyy HH:mm:ss.fff} [{Level}] {Message:lj}{NewLine}{Exception}";
var externalFolder = Application.Context.GetExternalFilesDir(null).AbsolutePath;
var basePath = Path.Combine(externalFolder, "Logs");
var basePath = AndroidUtils.GetLogsPath();

var loggerConfig = new LoggerConfiguration().MinimumLevel
.Verbose();
Expand Down
6 changes: 6 additions & 0 deletions MiraiNotes.Android/Common/Utils/AndroidUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,5 +178,11 @@ public static bool IsViewVisibleOnScreen(Context context, View view)

return actualPosition.Intersect(screen);
}

public static string GetLogsPath()
{
var externalFolder = Application.Context.GetExternalFilesDir(null).AbsolutePath;
return System.IO.Path.Combine(externalFolder, "Logs");
}
}
}
11 changes: 8 additions & 3 deletions MiraiNotes.Android/Common/Utils/MiscellaneousUtils.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using Android.App;
using Android.Content;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using AndroidGraphics = Android.Graphics;

namespace MiraiNotes.Android.Common.Utils
Expand All @@ -16,9 +16,14 @@ public class MiscellaneousUtils

public static string GetAppVersion()
{
return Application.Context.PackageManager
string appVersion = Application.Context.PackageManager
.GetPackageInfo(Application.Context.PackageName, 0)
.VersionName;
#if DEBUG
return $"{appVersion} - DEBUG";
#else
return appVersion;
#endif
}

public static async Task DownloadProfileImage(string url, string googleUserId)
Expand Down
2 changes: 1 addition & 1 deletion MiraiNotes.Android/Properties/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="12" android:versionName="1.1.7" package="com.miraisoft.notes" android:installLocation="internalOnly">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="13" android:versionName="1.1.8" package="com.miraisoft.notes" android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,8 @@ public async Task UpdateTaskList(TaskListItemViewModel taskList)
private void Validate()
{
Errors.Clear();
var validationResult = _validator.Validate(this);
var validationContext = new ValidationContext<AddEditTaskListDialogViewModel>(this);
var validationResult = _validator.Validate(validationContext);
Errors.AddRange(validationResult.ToDictionary());
RaisePropertyChanged(() => IsSaveButtonEnabled);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ private async Task SaveSubTask()
private void Validate()
{
Errors.Clear();
var validationResult = _validator.Validate(this);
var validationContext = new ValidationContext<AddSubTaskDialogViewModel>(this);
var validationResult = _validator.Validate(validationContext);
Errors.AddRange(validationResult.ToDictionary());
RaisePropertyChanged(() => IsSaveButtonEnabled);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ private async Task SavePassword()
private void Validate()
{
Errors.Clear();
var validationResult = _validator.Validate(this);
var validationContext = new ValidationContext<PasswordDialogViewModel>(this);
var validationResult = _validator.Validate(validationContext);
Errors.AddRange(validationResult.ToDictionary());
RaisePropertyChanged(() => IsSaveButtonEnabled);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@ private void SendUpdatedDateMsg()
private void Validate()
{
Errors.Clear();
var validationResult = _validator.Validate(this);
var validationContext = new ValidationContext<TaskDateDialogViewModel>(this);
var validationResult = _validator.Validate(validationContext);
Errors.AddRange(validationResult.ToDictionary());
RaisePropertyChanged(() => IsSaveButtonEnabled);
}
Expand Down
19 changes: 19 additions & 0 deletions MiraiNotes.Android/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
using MiraiNotes.Abstractions.Data;
using MiraiNotes.Abstractions.Services;
using MiraiNotes.Android.Common.Messages;
using MiraiNotes.Android.Common.Utils;
using MiraiNotes.Android.Interfaces;
using MiraiNotes.Android.Models;
using MiraiNotes.Android.Models.Parameters;
using MiraiNotes.Android.ViewModels.Dialogs;
using MiraiNotes.Android.ViewModels.Settings;
using MiraiNotes.Core.Enums;
using MiraiNotes.Shared.Utils;
using MvvmCross.Commands;
using MvvmCross.Navigation;
using MvvmCross.Plugin.Messenger;
using MvvmCross.ViewModels;
using Serilog;
using System;
using System.Threading.Tasks;

namespace MiraiNotes.Android.ViewModels
Expand Down Expand Up @@ -101,6 +104,22 @@ public MainViewModel(
_backgroundTaskManager = backgroundTaskManager;
}

public override Task Initialize()
{
try
{
Logger.Information($"{nameof(Prepare)}: Trying to delete old logs...");
var logsPath = AndroidUtils.GetLogsPath();
FileUtils.DeleteFilesInDirectory(logsPath, DateTime.Now.AddDays(-3));
}
catch (Exception e)
{
Logger.Error(e, $"{nameof(Prepare)}: Unknonw error while trying to delete old logs");
TelemetryService.TrackError(e);
}
return base.Initialize();
}

public override void SetCommands()
{
base.SetCommands();
Expand Down
3 changes: 2 additions & 1 deletion MiraiNotes.Android/ViewModels/NewTaskViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,8 @@ private void OnTaskDeleted(string taskId, bool hasParentTask)
private void Validate()
{
Errors.Clear();
var validationResult = _validator.Validate(Task);
var validationContext = new ValidationContext<TaskItemViewModel>(Task);
var validationResult = _validator.Validate(validationContext);
Errors.AddRange(validationResult.ToDictionary());
}

Expand Down
21 changes: 21 additions & 0 deletions MiraiNotes.Shared/Utils/FileUtils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.IO;
using System.Linq;

namespace MiraiNotes.Shared.Utils
{
public static class FileUtils
{
public static void DeleteFilesInDirectory(string dir, DateTime lastAccessTime)
{
var files = new DirectoryInfo(dir)
.GetFiles()
.Where(f => f.LastAccessTime < lastAccessTime)
.ToList();
foreach (var file in files)
{
file.Delete();
}
}
}
}
2 changes: 1 addition & 1 deletion MiraiNotes.UWP/Package.appxmanifest
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" IgnorableNamespaces="uap mp">
<Identity Name="52493MiraiSoft.MiraiNotes" Publisher="CN=58BF90DC-3D34-433E-A12B-4C504DF78641" Version="1.1.7.0" />
<Identity Name="52493MiraiSoft.MiraiNotes" Publisher="CN=58BF90DC-3D34-433E-A12B-4C504DF78641" Version="1.1.8.0" />
<mp:PhoneIdentity PhoneProductId="e2c92573-2529-41a6-86cf-eff6af39b78a" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
<Properties>
<DisplayName>Mirai Notes</DisplayName>
Expand Down
14 changes: 11 additions & 3 deletions MiraiNotes.UWP/Utils/MiscellaneousUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

namespace MiraiNotes.UWP.Utils
{
public class MiscellaneousUtils
public static class MiscellaneousUtils
{
const string USER_IMAGE_FILE_NAME = "user_image.png";

Expand All @@ -28,7 +28,12 @@ public static string GetAppVersion()
var package = Package.Current;
var packageId = package.Id;
var version = packageId.Version;
return $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}";
string appVersion = $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}";
#if DEBUG
return $"{appVersion} - DEBUG";
#else
return appVersion;
#endif
}

/// <summary>
Expand Down Expand Up @@ -166,7 +171,7 @@ public static async Task DownloadProfileImage(string url, string googleUserId)
}
}

public static T FindControl<T>(UIElement parent, string ControlName) where
public static T FindControl<T>(UIElement parent, string ControlName) where
T : FrameworkElement
{
if (parent == null)
Expand All @@ -189,5 +194,8 @@ public static T FindControl<T>(UIElement parent, string ControlName) where
}
return result;
}

public static string GetLogsPath()
=> Path.Combine(GetApplicationPath(), "Logs");
}
}
27 changes: 22 additions & 5 deletions MiraiNotes.UWP/ViewModels/NavPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,23 @@
using MiraiNotes.UWP.Interfaces;
using MiraiNotes.UWP.Models;
using MiraiNotes.UWP.Utils;
using Serilog;

namespace MiraiNotes.UWP.ViewModels
{
public class NavPageViewModel : BaseViewModel
{
#region Members

private readonly ICustomDialogService _dialogService;
private readonly IMessenger _messenger;
private readonly INavigationService _navigationService;
private readonly IUserCredentialService _userCredentialService;
private readonly IMapper _mapper;
private readonly IMiraiNotesDataService _dataService;
private readonly IDispatcherHelper _dispatcher;
private readonly IAppSettingsService _appSettings;
private readonly IBackgroundTaskManagerService _backgroundTaskManager;
private readonly ITelemetryService _telemetryService;
private readonly ILogger _logger;

private object _selectedItem;

Expand Down Expand Up @@ -167,19 +168,21 @@ public NavPageViewModel(
IUserCredentialService userCredentialService,
IMapper mapper,
IMiraiNotesDataService dataService,
IDispatcherHelper dispatcher,
IAppSettingsService appSettings,
IBackgroundTaskManagerService backgroundTaskManager)
IBackgroundTaskManagerService backgroundTaskManager,
ILogger logger,
ITelemetryService telemetryService)
{
_dialogService = dialogService;
_messenger = messenger;
_navigationService = navigationService;
_userCredentialService = userCredentialService;
_mapper = mapper;
_dataService = dataService;
_dispatcher = dispatcher;
_appSettings = appSettings;
_backgroundTaskManager = backgroundTaskManager;
_telemetryService = telemetryService;
_logger = logger.ForContext<NavPageViewModel>();

RegisterMessages();
SetCommands();
Expand Down Expand Up @@ -220,6 +223,7 @@ private void SetCommands()
{
PageLoadedCommand = new RelayCommand(async () =>
{
DeleteOldLogs();
await LoadProfileInfo();
await InitViewAsync();
});
Expand Down Expand Up @@ -589,6 +593,19 @@ private void SortTaskLists(TaskListSortType sortType)
_isSelectionInProgress = false;
}

private void DeleteOldLogs()
{
try
{
_logger.Information($"{nameof(DeleteOldLogs)}: Deleting old log files...");
FileUtils.DeleteFilesInDirectory(MiscellaneousUtils.GetLogsPath(), DateTime.Now.AddDays(-3));
}
catch (Exception e)
{
_logger.Error(e, $"{nameof(DeleteOldLogs)}: Unknown error while deleting old files..");
_telemetryService.TrackError(e);
}
}
#endregion
}
}
2 changes: 1 addition & 1 deletion MiraiNotes.UWP/ViewModels/ViewModelLocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ private INavigationService SetupNavigation()
private ILogger SetupLogging()
{
const string fileOutputTemplate = "{Timestamp:dd-MM-yyyy HH:mm:ss.fff} [{Level}] {Message:lj}{NewLine}{Exception}";
string basePath = Path.Combine(MiscellaneousUtils.GetApplicationPath(), "Logs");
string basePath = MiscellaneousUtils.GetLogsPath();
var logs = new Dictionary<string, string>
{
{typeof(NavPageViewModel).Namespace, "vm_.log" },
Expand Down

0 comments on commit d8935a5

Please sign in to comment.