public static void SaveAssetFile(Asset asset, BinaryFile file, bool notify, bool checkHash, bool doNotProcessForPreview) { // Quit if empty asset if (asset == null || asset.IsNull || asset.IsNew) { return; } // Quit if no file was uploaded if (file == null || file.IsEmpty) { return; } if (checkHash) { // Check the hash. Don't allow a processed asset to be re-uploaded AssetFinder finder = new AssetFinder { FileHash = file.FileHash, IsProcessed = true }; Asset assetFromHash = Asset.FindOne(finder); if (!assetFromHash.IsNull) { throw new InvalidAssetFileException(string.Format("{0} is already uploaded and has the Asset ID: {1}", file.FileName, assetFromHash.AssetId)); } } m_Logger.DebugFormat("SaveAssetFile - AssetId: {0}", asset.AssetId); // Ensure asset has path if (asset.AssetFilePath.IsNull) { asset.AssetFilePathId = AssetFilePathManager.GetDefault().AssetFilePathId.GetValueOrDefault(); } // Delete old files foreach (string path in Directory.GetFiles(asset.AssetFilePath.Path, asset.FileReference + ".*", SearchOption.AllDirectories)) { File.Delete(path); } // Delete any cached files string cacheFolder = Path.Combine(Settings.CachedAssetFilesFolder, asset.AssetId.ToString()); if (Directory.Exists(cacheFolder)) { Directory.Delete(cacheFolder, true); m_Logger.DebugFormat("Deleted cache folder: {0}", cacheFolder); } // Update the asset file path asset.AssetFilePathId = AssetFilePathManager.GetDefault().AssetFilePathId.GetValueOrDefault(); // Update asset file information asset.Filename = file.FileName; asset.FileSize = file.FileSize; asset.FileHash = file.FileHash; // The file extension comes from the view but set this for now // in case we need it elsewhere in the code before the Asset entity // is refreshed from the database. asset.FileExtension = file.FileExtension; // If not processing for Preview the asset.IsProcessed flag should be set // depending on the file extension. if (!doNotProcessForPreview) { asset.IsProcessed = (!APSGateway.Instance.CanProcess(file.FileExtension)); } // Save asset to database Asset.Update(asset); Asset.SaveAssetMetadata(asset); // Construct location to save asset file string assetFolder = GetFolder(asset.AssetFilePath, AssetFileType.AssetFile); string assetFilePath = Path.Combine(assetFolder, asset.FileReference + "." + file.FileExtension); // Save the file. Don't bother doing a mimetype check here, as the // files will be forced to open the download box by using 'application/octet-stream' // as the content type, so the server doesn't need to set this value. file.SaveAs(assetFilePath); m_Logger.DebugFormat("Saved file: {0}", assetFilePath); // Send this to the gateway for processing unless the do not process flag is set. // When the preview and thumbnail are ready, the APS will callback to the web app to save them. if (!doNotProcessForPreview && !asset.IsProcessed) { APSGateway.Instance.ProcessFile(asset, notify, FileOutputs.All); } // Regenerate bitmaps. This submits the assets to the APS and returns. // When the files are ready, the APS will callback to the web app to save them. AssetBitmapGroupManager.Generate(asset); // Check if file indexing is enabled, and if so, read the file contents into a byte // array and then store this in the database so that we can search it using full-text // indexing. As we're using an indexed view, this is done using a subquery. // See AssetFinder.cs for full details of how this is implemented. if (AssetFinder.FileIndexingEnabled && m_IndexableExtensions.Contains(file.FileExtension)) { ByteArray byteArray = ByteArray.New(file.InputStream); Asset.AddUpdateFileContents(asset.AssetId.GetValueOrDefault(), file.FileName, AssetFileType.AssetFile, byteArray, false); } // Now create the zip file if required if (ZipAssetFiles) { AssetFileZipper.CreateZip(asset); } }
/// <summary> /// Saves the asset into the database, and the file to disk. /// </summary> private Asset SaveUploadedAsset(BinaryFile file, string sourceFolder) { // Basic asset values Asset asset = Asset.New(); asset.Filename = file.FileName; asset.UploadDate = DateTime.Now; asset.UploadedByUserId = UploadedBy.UserId.GetValueOrDefault(); asset.BrandId = UploadedBy.PrimaryBrandId; asset.ContactEmail = UploadedBy.Email; asset.UsageRestrictions = UploadedBy.PrimaryBrand.DefaultUsageRestrictionsCopy; asset.CopyrightOwner = UploadedBy.CompanyName; asset.CreateDate = DateTime.Now; asset.LastUpdate = DateTime.Now; // Get the asset type ID based on file extension if the type was not specified asset.AssetTypeId = (AssetTypeId == Int32.MinValue) ? AssetTypeManager.GetAssetTypeId(file.FileExtension) : AssetTypeId; // Set the asset publish status depending on whether the uploading user is required to use workflow asset.AssetPublishStatus = (UploadedBy.UseWorkflow) ? AssetPublishStatus.NotApproved : AssetPublishStatus.Approved; // Set the asset file path (required for referential integrity in the database) asset.AssetFilePathId = AssetFilePathManager.GetDefault().AssetFilePathId.GetValueOrDefault(); // Default download restrictions asset.WatermarkPreview = false; asset.InternalUsers_DownloadApprovalRequired = false; asset.InternalUsers_HideFromUsers = false; asset.ExternalUsers_DownloadApprovalRequired = false; asset.ExternalUsers_HideFromUsers = false; // Default production year to current year asset.ProductionYear = DateTime.Now.Year; // Publish year cannot be null, so default to current year // and set expiry date to 2 years ahead asset.PublishDate = DateTime.Now; asset.ExpiryDate = DateTime.Now.AddYears(2); // Get the base Category which willl be the default brand category if Specify during cataloguing // or the target category if a target category has been passed. Category baseCategory; int categoryId; if (TargetCategoryId == int.MinValue) { baseCategory = CategoryCache.Instance.GetRootCategory(asset.BrandId); } else { baseCategory = CategoryCache.Instance.GetById(TargetCategoryId); } if (sourceFolder != String.Empty && CreateCategorySubFolders) { categoryId = CategoryManager.CreateCategoryTreeFromPath(baseCategory.CategoryId, asset.BrandId, sourceFolder, asset.UploadedByUser); } else { categoryId = baseCategory.CategoryId.GetValueOrDefault(); } // Set processed flag depending on the DoNotProcessForPreview. If this is true // the IsProcessed flag should also be set to true. asset.IsProcessed = DoNotProcessForPreview; // Assign default categories asset.CategoryList.Clear(); asset.CategoryList.Add(CategoryCache.Instance.GetById(categoryId)); asset.PrimaryCategoryId = asset.CategoryList[0].CategoryId.GetValueOrDefault(); OnProgress("Saving asset..."); if (BeforeSave != null) { BeforeSave(this, new AssetEventArgs(asset)); } Asset.Update(asset); Asset.SaveAssetMetadata(asset); OnProgress("Saved with reference: " + asset.AssetId); if (AfterSave != null) { AfterSave(this, new AssetEventArgs(asset)); } if (BeforeFileSave != null) { BeforeFileSave(this, new AssetEventArgs(asset)); } if (!file.IsEmpty) { // Hash should only be checked for non super-admins bool checkHash = (UploadedBy.UserRole != UserRole.SuperAdministrator); // Save the file OnProgress("Saving asset file to disk: " + file.FileName); AssetFileManager.SaveAssetFile(asset, file, SendEmailOnCompletion, checkHash, DoNotProcessForPreview); OnProgress("Saved file '" + file.FileName + "' to disk"); // Fire post-save events if (AfterFileSave != null) { AfterFileSave(this, new AssetEventArgs(asset)); } } m_Logger.DebugFormat("Saved {0} to database, asset ID: {1}", file.FileName, asset.AssetId); return(asset); }