2019-01-24 08:43:03 +00:00
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
2018-04-13 09:19:50 +00:00
using System ;
using System.Collections.Generic ;
using System.IO ;
using System.Linq ;
2019-05-28 09:59:21 +00:00
using System.Threading ;
2018-08-31 09:28:53 +00:00
using System.Threading.Tasks ;
2018-07-18 03:58:28 +00:00
using JetBrains.Annotations ;
2018-04-13 09:19:50 +00:00
using Microsoft.EntityFrameworkCore ;
2019-02-28 04:09:38 +00:00
using osu.Framework ;
2018-11-28 10:16:05 +00:00
using osu.Framework.Extensions ;
2018-06-05 02:28:51 +00:00
using osu.Framework.IO.File ;
2018-04-13 09:19:50 +00:00
using osu.Framework.Logging ;
using osu.Framework.Platform ;
2019-05-28 09:59:21 +00:00
using osu.Framework.Threading ;
2018-04-13 09:19:50 +00:00
using osu.Game.IO ;
using osu.Game.IO.Archives ;
using osu.Game.IPC ;
using osu.Game.Overlays.Notifications ;
using osu.Game.Utils ;
using SharpCompress.Common ;
using FileInfo = osu . Game . IO . FileInfo ;
namespace osu.Game.Database
{
/// <summary>
/// Encapsulates a model store class to give it import functionality.
/// Adds cross-functionality with <see cref="FileStore"/> to give access to the central file store for the provided model.
/// </summary>
/// <typeparam name="TModel">The model type.</typeparam>
/// <typeparam name="TFileModel">The associated file join type.</typeparam>
2019-06-12 12:06:43 +00:00
public abstract class ArchiveModelManager < TModel , TFileModel > : ArchiveModelManager , ICanAcceptFiles , IModelManager < TModel >
2018-04-13 09:19:50 +00:00
where TModel : class , IHasFiles < TFileModel > , IHasPrimaryKey , ISoftDelete
where TFileModel : INamedFileInfo , new ( )
{
/// <summary>
/// Set an endpoint for notifications to be posted to.
/// </summary>
public Action < Notification > PostNotification { protected get ; set ; }
/// <summary>
/// Fired when a new <see cref="TModel"/> becomes available in the database.
/// This is not guaranteed to run on the update thread.
/// </summary>
2019-06-26 02:40:33 +00:00
public event Action < TModel > ItemAdded ;
2018-04-13 09:19:50 +00:00
/// <summary>
/// Fired when a <see cref="TModel"/> is removed from the database.
/// This is not guaranteed to run on the update thread.
/// </summary>
public event Action < TModel > ItemRemoved ;
public virtual string [ ] HandledExtensions = > new [ ] { ".zip" } ;
2019-02-28 04:09:38 +00:00
public virtual bool SupportsImportFromStable = > RuntimeInfo . IsDesktop ;
2018-04-13 09:19:50 +00:00
protected readonly FileStore Files ;
protected readonly IDatabaseContextFactory ContextFactory ;
protected readonly MutableDatabaseBackedStore < TModel > ModelStore ;
// ReSharper disable once NotAccessedField.Local (we should keep a reference to this so it is not finalised)
private ArchiveImportIPCChannel ipc ;
2019-03-01 01:25:21 +00:00
protected ArchiveModelManager ( Storage storage , IDatabaseContextFactory contextFactory , MutableDatabaseBackedStoreWithFileIncludes < TModel , TFileModel > modelStore , IIpcHost importHost = null )
2018-04-13 09:19:50 +00:00
{
ContextFactory = contextFactory ;
ModelStore = modelStore ;
2019-06-26 02:40:33 +00:00
ModelStore . ItemAdded + = item = > handleEvent ( ( ) = > ItemAdded ? . Invoke ( item ) ) ;
2018-05-28 10:56:27 +00:00
ModelStore . ItemRemoved + = s = > handleEvent ( ( ) = > ItemRemoved ? . Invoke ( s ) ) ;
2018-04-13 09:19:50 +00:00
Files = new FileStore ( contextFactory , storage ) ;
if ( importHost ! = null )
ipc = new ArchiveImportIPCChannel ( importHost , this ) ;
ModelStore . Cleanup ( ) ;
}
/// <summary>
/// Import one or more <see cref="TModel"/> items from filesystem <paramref name="paths"/>.
/// This will post notifications tracking progress.
/// </summary>
/// <param name="paths">One or more archive locations on disk.</param>
2019-06-12 08:08:50 +00:00
public Task Import ( params string [ ] paths )
2018-04-13 09:19:50 +00:00
{
2019-02-25 09:24:06 +00:00
var notification = new ProgressNotification { State = ProgressNotificationState . Active } ;
2018-04-13 09:19:50 +00:00
PostNotification ? . Invoke ( notification ) ;
2019-05-28 09:59:21 +00:00
2019-06-12 08:08:50 +00:00
return Import ( notification , paths ) ;
2019-02-25 09:24:06 +00:00
}
2019-05-28 09:59:21 +00:00
protected async Task Import ( ProgressNotification notification , params string [ ] paths )
2019-02-25 09:24:06 +00:00
{
notification . Progress = 0 ;
notification . Text = "Import is initialising..." ;
2018-04-13 09:19:50 +00:00
int current = 0 ;
2019-04-01 03:16:05 +00:00
2019-06-10 04:19:58 +00:00
var imported = new List < TModel > ( ) ;
2019-06-10 08:12:25 +00:00
await Task . WhenAll ( paths . Select ( async path = >
2018-04-13 09:19:50 +00:00
{
2019-06-10 07:14:42 +00:00
notification . CancellationToken . ThrowIfCancellationRequested ( ) ;
2018-04-13 09:19:50 +00:00
try
{
2019-06-10 08:12:25 +00:00
var model = await Import ( path , notification . CancellationToken ) ;
2018-12-18 19:49:53 +00:00
2019-06-10 08:12:25 +00:00
lock ( imported )
2019-06-10 07:14:42 +00:00
{
2019-07-05 05:47:55 +00:00
if ( model ! = null )
imported . Add ( model ) ;
2019-06-12 08:10:55 +00:00
current + + ;
2018-04-13 09:19:50 +00:00
2019-06-12 11:41:02 +00:00
notification . Text = $"Imported {current} of {paths.Length} {HumanisedModelName}s" ;
2019-06-10 07:14:42 +00:00
notification . Progress = ( float ) current / paths . Length ;
}
2019-06-10 04:19:58 +00:00
}
2019-06-10 08:12:25 +00:00
catch ( TaskCanceledException )
{
throw ;
2018-04-13 09:19:50 +00:00
}
catch ( Exception e )
{
2019-06-10 10:34:32 +00:00
Logger . Error ( e , $@"Could not import ({Path.GetFileName(path)})" , LoggingTarget . Database ) ;
2018-04-13 09:19:50 +00:00
}
2019-06-10 08:12:25 +00:00
} ) ) ;
2018-04-13 09:19:50 +00:00
2018-09-07 09:14:23 +00:00
if ( imported . Count = = 0 )
{
notification . Text = "Import failed!" ;
notification . State = ProgressNotificationState . Cancelled ;
}
else
{
2019-02-25 09:24:06 +00:00
notification . CompletionText = imported . Count = = 1
? $"Imported {imported.First()}!"
2019-07-05 05:47:55 +00:00
: $"Imported {imported.Count} {HumanisedModelName}s!" ;
2019-02-25 09:24:06 +00:00
if ( imported . Count > 0 & & PresentImport ! = null )
2018-09-07 09:18:03 +00:00
{
2019-02-25 09:24:06 +00:00
notification . CompletionText + = " Click to view." ;
notification . CompletionClickAction = ( ) = >
{
PresentImport ? . Invoke ( imported ) ;
return true ;
} ;
}
2018-09-07 09:14:23 +00:00
notification . State = ProgressNotificationState . Completed ;
}
2018-04-13 09:19:50 +00:00
}
2019-01-29 09:34:10 +00:00
/// <summary>
/// Import one <see cref="TModel"/> from the filesystem and delete the file on success.
/// </summary>
2019-01-29 14:04:48 +00:00
/// <param name="path">The archive location on disk.</param>
2019-05-28 09:59:21 +00:00
/// <param name="cancellationToken">An optional cancellation token.</param>
2019-01-29 09:34:10 +00:00
/// <returns>The imported model, if successful.</returns>
2019-05-28 09:59:21 +00:00
public async Task < TModel > Import ( string path , CancellationToken cancellationToken = default )
2019-01-29 09:34:10 +00:00
{
2019-06-10 04:37:20 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
2019-01-29 09:34:10 +00:00
TModel import ;
using ( ArchiveReader reader = getReaderFrom ( path ) )
2019-05-28 09:59:21 +00:00
import = await Import ( reader , cancellationToken ) ;
2019-01-29 09:34:10 +00:00
// We may or may not want to delete the file depending on where it is stored.
// e.g. reconstructing/repairing database with items from default storage.
// Also, not always a single file, i.e. for LegacyFilesystemReader
// TODO: Add a check to prevent files from storage to be deleted.
try
{
if ( import ! = null & & File . Exists ( path ) )
File . Delete ( path ) ;
}
catch ( Exception e )
{
2019-06-10 10:34:32 +00:00
LogForModel ( import , $@"Could not delete original file after import ({Path.GetFileName(path)})" , e ) ;
2019-01-29 09:34:10 +00:00
}
return import ;
}
2019-02-25 09:24:06 +00:00
/// <summary>
/// Fired when the user requests to view the resulting import.
/// </summary>
public Action < IEnumerable < TModel > > PresentImport ;
2018-09-07 07:30:11 +00:00
2018-04-13 09:19:50 +00:00
/// <summary>
/// Import an item from an <see cref="ArchiveReader"/>.
/// </summary>
/// <param name="archive">The archive to be imported.</param>
2019-05-28 09:59:21 +00:00
/// <param name="cancellationToken">An optional cancellation token.</param>
2019-06-12 08:08:50 +00:00
public Task < TModel > Import ( ArchiveReader archive , CancellationToken cancellationToken = default )
2018-04-13 09:19:50 +00:00
{
2019-06-10 04:37:20 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
2019-06-10 10:34:32 +00:00
TModel model = null ;
2019-06-10 08:12:37 +00:00
2018-07-18 03:58:28 +00:00
try
{
2019-06-10 08:12:37 +00:00
model = CreateModel ( archive ) ;
2018-11-28 10:16:05 +00:00
if ( model = = null ) return null ;
2018-11-30 06:09:15 +00:00
model . Hash = computeHash ( archive ) ;
2018-07-18 03:58:28 +00:00
}
2019-06-10 04:37:20 +00:00
catch ( TaskCanceledException )
{
throw ;
2018-07-18 03:58:28 +00:00
}
catch ( Exception e )
{
2019-06-10 10:34:32 +00:00
LogForModel ( model , $"Model creation of {archive.Name} failed." , e ) ;
2018-07-18 03:58:28 +00:00
return null ;
}
2019-06-10 08:12:37 +00:00
2019-06-12 08:08:50 +00:00
return Import ( model , archive , cancellationToken ) ;
2018-07-18 03:58:28 +00:00
}
2018-11-28 10:16:05 +00:00
/// <summary>
/// Any file extensions which should be included in hash creation.
/// Generally should include all file types which determine the file's uniqueness.
/// Large files should be avoided if possible.
/// </summary>
protected abstract string [ ] HashableFileTypes { get ; }
2019-06-10 10:34:32 +00:00
protected static void LogForModel ( TModel model , string message , Exception e = null )
{
string prefix = $"[{(model?.Hash ?? " ? ? ? ? ? ").Substring(0, 5)}]" ;
if ( e ! = null )
Logger . Error ( e , $"{prefix} {message}" , LoggingTarget . Database ) ;
else
Logger . Log ( $"{prefix} {message}" , LoggingTarget . Database ) ;
}
2018-11-28 10:16:05 +00:00
/// <summary>
2018-11-30 06:09:15 +00:00
/// Create a SHA-2 hash from the provided archive based on file content of all files matching <see cref="HashableFileTypes"/>.
2018-11-28 10:16:05 +00:00
/// </summary>
2018-11-30 06:09:15 +00:00
private string computeHash ( ArchiveReader reader )
2018-11-28 10:16:05 +00:00
{
// for now, concatenate all .osu files in the set to create a unique hash.
MemoryStream hashable = new MemoryStream ( ) ;
2018-11-30 06:09:15 +00:00
foreach ( string file in reader . Filenames . Where ( f = > HashableFileTypes . Any ( f . EndsWith ) ) )
2018-11-28 10:16:05 +00:00
using ( Stream s = reader . GetStream ( file ) )
s . CopyTo ( hashable ) ;
return hashable . ComputeSHA2Hash ( ) ;
}
2018-07-18 03:58:28 +00:00
/// <summary>
/// Import an item from a <see cref="TModel"/>.
/// </summary>
/// <param name="item">The model to be imported.</param>
/// <param name="archive">An optional archive to use for model population.</param>
2019-05-28 09:59:21 +00:00
/// <param name="cancellationToken">An optional cancellation token.</param>
public async Task < TModel > Import ( TModel item , ArchiveReader archive = null , CancellationToken cancellationToken = default ) = > await Task . Factory . StartNew ( async ( ) = >
2018-07-18 03:58:28 +00:00
{
2019-06-10 04:37:20 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
2018-05-28 12:45:05 +00:00
delayEvents ( ) ;
2018-05-28 10:56:27 +00:00
2019-06-10 07:14:42 +00:00
void rollback ( )
{
if ( ! Delete ( item ) )
{
// We may have not yet added the model to the underlying table, but should still clean up files.
2019-06-10 10:34:32 +00:00
LogForModel ( item , "Dereferencing files for incomplete import." ) ;
2019-06-10 07:14:42 +00:00
Files . Dereference ( item . Files . Select ( f = > f . FileInfo ) . ToArray ( ) ) ;
}
}
2018-05-28 10:56:27 +00:00
try
2018-04-13 09:19:50 +00:00
{
2019-06-10 10:34:32 +00:00
LogForModel ( item , "Beginning import..." ) ;
2018-08-17 04:50:27 +00:00
2019-06-10 05:13:36 +00:00
item . Files = archive ! = null ? createFileInfos ( archive , Files ) : new List < TFileModel > ( ) ;
2019-05-28 09:59:21 +00:00
2019-06-10 07:14:42 +00:00
await Populate ( item , archive , cancellationToken ) ;
2018-08-17 04:50:27 +00:00
2018-05-28 10:56:27 +00:00
using ( var write = ContextFactory . GetForWrite ( ) ) // used to share a context for full import. keep in mind this will block all writes.
{
2018-05-29 04:48:14 +00:00
try
{
if ( ! write . IsTransactionLeader ) throw new InvalidOperationException ( $"Ensure there is no parent transaction so errors can correctly be handled by {this}" ) ;
2018-04-13 09:19:50 +00:00
2018-05-29 04:48:14 +00:00
var existing = CheckForExisting ( item ) ;
2018-04-13 09:19:50 +00:00
2018-05-29 07:14:09 +00:00
if ( existing ! = null )
{
2019-03-11 08:03:01 +00:00
if ( CanUndelete ( existing , item ) )
{
Undelete ( existing ) ;
2019-06-12 11:41:02 +00:00
LogForModel ( item , $"Found existing {HumanisedModelName} for {item} (ID {existing.ID}) – skipping import." ) ;
2019-06-10 08:12:37 +00:00
// existing item will be used; rollback new import and exit early.
2019-06-10 07:14:42 +00:00
rollback ( ) ;
2019-06-10 08:12:37 +00:00
flushEvents ( true ) ;
2019-03-11 08:03:01 +00:00
return existing ;
}
2019-06-10 10:34:32 +00:00
Delete ( existing ) ;
ModelStore . PurgeDeletable ( s = > s . ID = = existing . ID ) ;
2018-05-29 07:14:09 +00:00
}
2018-04-13 09:19:50 +00:00
2019-03-11 08:03:01 +00:00
PreImport ( item ) ;
2018-04-13 09:19:50 +00:00
2018-05-29 04:48:14 +00:00
// import to store
2019-02-25 09:24:06 +00:00
ModelStore . Add ( item ) ;
2018-05-29 04:48:14 +00:00
}
catch ( Exception e )
{
write . Errors . Add ( e ) ;
throw ;
}
2018-05-28 10:56:27 +00:00
}
2018-05-29 07:14:09 +00:00
2019-06-10 10:34:32 +00:00
LogForModel ( item , "Import successfully completed!" ) ;
2018-04-13 09:19:50 +00:00
}
2018-05-29 09:37:45 +00:00
catch ( Exception e )
2018-05-28 10:56:27 +00:00
{
2019-06-10 07:14:42 +00:00
if ( ! ( e is TaskCanceledException ) )
2019-06-10 10:34:32 +00:00
LogForModel ( item , "Database import or population failed and has been rolled back." , e ) ;
2019-06-10 07:14:42 +00:00
rollback ( ) ;
2019-06-10 08:12:37 +00:00
flushEvents ( false ) ;
throw ;
2018-05-29 10:43:52 +00:00
}
2018-05-28 10:56:27 +00:00
2019-06-10 08:12:37 +00:00
flushEvents ( true ) ;
2018-05-28 10:56:27 +00:00
return item ;
2019-06-10 04:37:20 +00:00
} , cancellationToken , TaskCreationOptions . HideScheduler , IMPORT_SCHEDULER ) . Unwrap ( ) ;
2018-04-13 09:19:50 +00:00
/// <summary>
/// Perform an update of the specified item.
/// TODO: Support file changes.
/// </summary>
/// <param name="item">The item to update.</param>
public void Update ( TModel item ) = > ModelStore . Update ( item ) ;
/// <summary>
/// Delete an item from the manager.
/// Is a no-op for already deleted items.
/// </summary>
/// <param name="item">The item to delete.</param>
2018-09-21 03:21:27 +00:00
/// <returns>false if no operation was performed</returns>
public bool Delete ( TModel item )
2018-04-13 09:19:50 +00:00
{
2018-05-30 04:43:43 +00:00
using ( ContextFactory . GetForWrite ( ) )
2018-04-13 09:19:50 +00:00
{
// re-fetch the model on the import context.
2018-09-21 00:01:04 +00:00
var foundModel = queryModel ( ) . Include ( s = > s . Files ) . ThenInclude ( f = > f . FileInfo ) . FirstOrDefault ( s = > s . ID = = item . ID ) ;
2018-04-13 09:19:50 +00:00
2018-09-21 03:21:27 +00:00
if ( foundModel = = null | | foundModel . DeletePending ) return false ;
2018-04-13 09:19:50 +00:00
if ( ModelStore . Delete ( foundModel ) )
Files . Dereference ( foundModel . Files . Select ( f = > f . FileInfo ) . ToArray ( ) ) ;
2018-09-21 03:21:27 +00:00
return true ;
2018-04-13 09:19:50 +00:00
}
}
/// <summary>
/// Delete multiple items.
/// This will post notifications tracking progress.
/// </summary>
2019-05-09 06:15:02 +00:00
public void Delete ( List < TModel > items , bool silent = false )
2018-04-13 09:19:50 +00:00
{
if ( items . Count = = 0 ) return ;
var notification = new ProgressNotification
{
Progress = 0 ,
2019-06-12 11:41:02 +00:00
Text = $"Preparing to delete all {HumanisedModelName}s..." ,
CompletionText = $"Deleted all {HumanisedModelName}s!" ,
2018-04-13 09:19:50 +00:00
State = ProgressNotificationState . Active ,
} ;
2019-05-09 06:15:02 +00:00
if ( ! silent )
PostNotification ? . Invoke ( notification ) ;
2018-04-13 09:19:50 +00:00
int i = 0 ;
using ( ContextFactory . GetForWrite ( ) )
{
foreach ( var b in items )
{
if ( notification . State = = ProgressNotificationState . Cancelled )
// user requested abort
return ;
2019-06-12 11:41:02 +00:00
notification . Text = $"Deleting {HumanisedModelName}s ({++i} of {items.Count})" ;
2018-04-13 09:19:50 +00:00
Delete ( b ) ;
notification . Progress = ( float ) i / items . Count ;
}
}
notification . State = ProgressNotificationState . Completed ;
}
/// <summary>
/// Restore multiple items that were previously deleted.
/// This will post notifications tracking progress.
/// </summary>
2019-05-09 06:15:02 +00:00
public void Undelete ( List < TModel > items , bool silent = false )
2018-04-13 09:19:50 +00:00
{
if ( ! items . Any ( ) ) return ;
var notification = new ProgressNotification
{
CompletionText = "Restored all deleted items!" ,
Progress = 0 ,
State = ProgressNotificationState . Active ,
} ;
2019-05-09 06:15:02 +00:00
if ( ! silent )
PostNotification ? . Invoke ( notification ) ;
2018-04-13 09:19:50 +00:00
int i = 0 ;
using ( ContextFactory . GetForWrite ( ) )
{
foreach ( var item in items )
{
if ( notification . State = = ProgressNotificationState . Cancelled )
// user requested abort
return ;
notification . Text = $"Restoring ({++i} of {items.Count})" ;
Undelete ( item ) ;
notification . Progress = ( float ) i / items . Count ;
}
}
notification . State = ProgressNotificationState . Completed ;
}
/// <summary>
/// Restore an item that was previously deleted. Is a no-op if the item is not in a deleted state, or has its protected flag set.
/// </summary>
/// <param name="item">The item to restore</param>
public void Undelete ( TModel item )
{
using ( var usage = ContextFactory . GetForWrite ( ) )
{
usage . Context . ChangeTracker . AutoDetectChangesEnabled = false ;
if ( ! ModelStore . Undelete ( item ) ) return ;
Files . Reference ( item . Files . Select ( f = > f . FileInfo ) . ToArray ( ) ) ;
usage . Context . ChangeTracker . AutoDetectChangesEnabled = true ;
}
}
/// <summary>
/// Create all required <see cref="FileInfo"/>s for the provided archive, adding them to the global file store.
/// </summary>
private List < TFileModel > createFileInfos ( ArchiveReader reader , FileStore files )
{
var fileInfos = new List < TFileModel > ( ) ;
// import files to manager
foreach ( string file in reader . Filenames )
using ( Stream s = reader . GetStream ( file ) )
fileInfos . Add ( new TFileModel
{
2018-10-07 17:15:42 +00:00
Filename = FileSafety . PathStandardise ( file ) ,
2018-04-13 09:19:50 +00:00
FileInfo = files . Add ( s )
} ) ;
return fileInfos ;
}
2018-08-31 09:28:53 +00:00
#region osu - stable import
/// <summary>
/// Set a storage with access to an osu-stable install for import purposes.
/// </summary>
public Func < Storage > GetStableStorage { private get ; set ; }
/// <summary>
/// Denotes whether an osu-stable installation is present to perform automated imports from.
/// </summary>
public bool StableInstallationAvailable = > GetStableStorage ? . Invoke ( ) ! = null ;
/// <summary>
/// The relative path from osu-stable's data directory to import items from.
/// </summary>
protected virtual string ImportFromStablePath = > null ;
/// <summary>
/// This is a temporary method and will likely be replaced by a full-fledged (and more correctly placed) migration process in the future.
/// </summary>
public Task ImportFromStableAsync ( )
{
var stable = GetStableStorage ? . Invoke ( ) ;
if ( stable = = null )
{
Logger . Log ( "No osu!stable installation available!" , LoggingTarget . Information , LogLevel . Error ) ;
return Task . CompletedTask ;
}
2018-09-18 01:05:28 +00:00
if ( ! stable . ExistsDirectory ( ImportFromStablePath ) )
2018-09-15 13:53:59 +00:00
{
2018-09-18 01:05:28 +00:00
// This handles situations like when the user does not have a Skins folder
2018-09-21 02:50:36 +00:00
Logger . Log ( $"No {ImportFromStablePath} folder available in osu!stable installation" , LoggingTarget . Information , LogLevel . Error ) ;
2018-09-18 01:05:28 +00:00
return Task . CompletedTask ;
}
2019-06-12 08:08:50 +00:00
return Task . Run ( async ( ) = > await Import ( stable . GetDirectories ( ImportFromStablePath ) . Select ( f = > stable . GetFullPath ( f ) ) . ToArray ( ) ) ) ;
2018-08-31 09:28:53 +00:00
}
#endregion
2018-04-13 09:19:50 +00:00
/// <summary>
/// Create a barebones model from the provided archive.
/// Actual expensive population should be done in <see cref="Populate"/>; this should just prepare for duplicate checking.
/// </summary>
/// <param name="archive">The archive to create the model for.</param>
2018-08-25 05:51:42 +00:00
/// <returns>A model populated with minimal information. Returning a null will abort importing silently.</returns>
2018-04-13 09:19:50 +00:00
protected abstract TModel CreateModel ( ArchiveReader archive ) ;
/// <summary>
/// Populate the provided model completely from the given archive.
/// After this method, the model should be in a state ready to commit to a store.
/// </summary>
/// <param name="model">The model to populate.</param>
2018-07-18 03:58:28 +00:00
/// <param name="archive">The archive to use as a reference for population. May be null.</param>
2019-05-28 09:59:21 +00:00
/// <param name="cancellationToken">An optional cancellation token.</param>
2019-06-10 07:13:51 +00:00
protected virtual Task Populate ( TModel model , [ CanBeNull ] ArchiveReader archive , CancellationToken cancellationToken = default ) = > Task . CompletedTask ;
2018-04-13 09:19:50 +00:00
2019-03-11 08:03:01 +00:00
/// <summary>
/// Perform any final actions before the import to database executes.
/// </summary>
/// <param name="model">The model prepared for import.</param>
protected virtual void PreImport ( TModel model )
{
}
2018-11-28 10:01:22 +00:00
/// <summary>
/// Check whether an existing model already exists for a new import item.
/// </summary>
2019-04-25 08:36:17 +00:00
/// <param name="model">The new model proposed for import.</param>
2018-11-28 10:01:22 +00:00
/// <returns>An existing model which matches the criteria to skip importing, else null.</returns>
2019-03-11 08:03:01 +00:00
protected TModel CheckForExisting ( TModel model ) = > model . Hash = = null ? null : ModelStore . ConsumableItems . FirstOrDefault ( b = > b . Hash = = model . Hash ) ;
/// <summary>
/// After an existing <see cref="TModel"/> is found during an import process, the default behaviour is to restore the existing
/// item and skip the import. This method allows changing that behaviour.
/// </summary>
/// <param name="existing">The existing model.</param>
/// <param name="import">The newly imported model.</param>
/// <returns>Whether the existing model should be restored and used. Returning false will delete the existing a force a re-import.</returns>
protected virtual bool CanUndelete ( TModel existing , TModel import ) = > true ;
2018-04-13 09:19:50 +00:00
private DbSet < TModel > queryModel ( ) = > ContextFactory . Get ( ) . Set < TModel > ( ) ;
2019-06-12 11:41:02 +00:00
protected virtual string HumanisedModelName = > $"{typeof(TModel).Name.Replace(" Info ", " ").ToLower()}" ;
2019-06-10 09:41:56 +00:00
2018-04-13 09:19:50 +00:00
/// <summary>
/// Creates an <see cref="ArchiveReader"/> from a valid storage path.
/// </summary>
/// <param name="path">A file or folder path resolving the archive content.</param>
/// <returns>A reader giving access to the archive's content.</returns>
private ArchiveReader getReaderFrom ( string path )
{
if ( ZipUtils . IsZipArchive ( path ) )
2018-08-15 06:49:55 +00:00
return new ZipArchiveReader ( File . Open ( path , FileMode . Open , FileAccess . Read , FileShare . Read ) , Path . GetFileName ( path ) ) ;
2018-04-13 09:19:50 +00:00
if ( Directory . Exists ( path ) )
2018-11-28 06:13:27 +00:00
return new LegacyDirectoryArchiveReader ( path ) ;
2018-11-28 07:13:16 +00:00
if ( File . Exists ( path ) )
return new LegacyFileArchiveReader ( path ) ;
2019-02-28 04:31:40 +00:00
2018-04-13 09:19:50 +00:00
throw new InvalidFormatException ( $"{path} is not a valid archive" ) ;
}
2019-06-18 16:32:37 +00:00
#region Event handling / delaying
private readonly List < Action > queuedEvents = new List < Action > ( ) ;
/// <summary>
/// Allows delaying of outwards events until an operation is confirmed (at a database level).
/// </summary>
private bool delayingEvents ;
/// <summary>
/// Begin delaying outwards events.
/// </summary>
private void delayEvents ( ) = > delayingEvents = true ;
/// <summary>
/// Flush delayed events and disable delaying.
/// </summary>
/// <param name="perform">Whether the flushed events should be performed.</param>
private void flushEvents ( bool perform )
{
Action [ ] events ;
lock ( queuedEvents )
{
events = queuedEvents . ToArray ( ) ;
queuedEvents . Clear ( ) ;
}
if ( perform )
{
foreach ( var a in events )
a . Invoke ( ) ;
}
delayingEvents = false ;
}
private void handleEvent ( Action a )
{
if ( delayingEvents )
lock ( queuedEvents )
queuedEvents . Add ( a ) ;
else
a . Invoke ( ) ;
}
#endregion
2018-04-13 09:19:50 +00:00
}
2019-06-10 04:19:58 +00:00
public abstract class ArchiveModelManager
{
2019-06-10 09:38:03 +00:00
private const int import_queue_request_concurrency = 1 ;
/// <summary>
/// A singleton scheduler shared by all <see cref="ArchiveModelManager{TModel,TFileModel}"/>.
/// </summary>
/// <remarks>
/// This scheduler generally performs IO and CPU intensive work so concurrency is limited harshly.
/// It is mainly being used as a queue mechanism for large imports.
/// </remarks>
2019-06-11 15:35:13 +00:00
protected static readonly ThreadedTaskScheduler IMPORT_SCHEDULER = new ThreadedTaskScheduler ( import_queue_request_concurrency , nameof ( ArchiveModelManager ) ) ;
2019-06-10 04:19:58 +00:00
}
2018-04-13 09:19:50 +00:00
}