Ejemplo n.º 1
0
        /// <summary>
        /// Creates an unpublished copy of the homepage and returns it
        /// </summary>
        /// <param name="homepage">The homepage to be copied</param>
        /// <returns>Copy of homepage</returns>
        public static Homepage GetCopy(Homepage homepage)
        {
            // List of images
            IList <BinaryFile> imageList = new List <BinaryFile>();

            // Get the ID of the homepage being copied
            int homepageId = homepage.HomepageId.GetValueOrDefault();

            // Set the homepage ID to null so we create a new record on save
            homepage.HomepageId = null;

            // The copied homepage is not published
            homepage.IsPublished = false;

            // Save the homepage
            Homepage.Update(homepage);

            // Get all of the images
            for (int i = 1; i <= 4; i++)
            {
                BinaryFile file = BinaryFile.Empty;

                string imagePath = HomepageImageManager.GetHomepageImagePath(homepageId, i);

                if (!StringUtils.IsBlank(imagePath) && File.Exists(imagePath))
                {
                    file = new BinaryFile(imagePath, BinaryFile.SaveMode.Copy);
                }

                imageList.Add(file);
            }

            // Save the homepage images
            SaveHomepageImages(homepage, imageList);

            // Return the copy
            return(homepage);
        }
        public static void SaveAssetBitmapFile(Asset asset, string assetBitmapReference, BinaryFile file)
        {
            if (asset.IsNew || asset.IsNull)
            {
                return;
            }

            if (file.IsEmpty)
            {
                return;
            }

            if (StringUtils.IsBlank(assetBitmapReference))
            {
                return;
            }

            var abg = new AssetBitmapInfo(asset, assetBitmapReference);

            if (abg.FileExists)
            {
                File.Delete(abg.FilePath);
            }

            if (!Directory.Exists(abg.FolderPath))
            {
                Directory.CreateDirectory(abg.FolderPath);
                m_Logger.DebugFormat("Created folder: {0}", abg.FolderPath);
            }

            string path = Path.Combine(abg.FolderPath, abg.Reference + "_" + abg.Asset.AssetId + "." + file.FileExtension);

            file.SaveAs(path);
        }
Ejemplo n.º 3
0
        private static void Validate(Brand entity, BinaryFile file, BinaryFile watermarkImage)
        {
            ErrorList errors = new ErrorList();

            if (StringUtils.IsBlank(entity.Name))
            {
                errors.Add("Name is required");
            }

            if (StringUtils.IsBlank(entity.ShortName))
            {
                errors.Add("Short Name is required");
            }

            if (StringUtils.IsBlank(entity.ApplicationName))
            {
                errors.Add("Application Name is required");
            }

            if (StringUtils.IsBlank(entity.OrganisationName))
            {
                errors.Add("Organisation Name is required");
            }

            if (StringUtils.IsBlank(entity.WebsiteUrl))
            {
                errors.Add("Website URL is required");
            }
            else if (!entity.WebsiteUrl.ToLower().StartsWith("http://"))
            {
                errors.Add("Website URL must start with http://");
            }

            if (StringUtils.IsBlank(entity.EmailFrom))
            {
                errors.Add("Email From is required");
            }
            else if (!StringUtils.IsEmail(entity.EmailFrom))
            {
                errors.Add("Email From must be a valid email address");
            }

            if (StringUtils.IsBlank(entity.LoginPageUpperCopy))
            {
                errors.Add("Login page upper copy is required");
            }

            if (StringUtils.IsBlank(entity.LoginPageLowerCopy))
            {
                errors.Add("Login page lower copy is required");
            }

            if (StringUtils.IsBlank(entity.DefaultUsageRestrictionsCopy))
            {
                errors.Add("Default Usage Restrictions notice is required");
            }

            if (StringUtils.IsBlank(entity.MyAccountCopy))
            {
                errors.Add("My Account copy is required");
            }

            if (StringUtils.IsBlank(entity.AdminCopy))
            {
                errors.Add("Admin copy is required");
            }

            if (StringUtils.IsBlank(entity.TermsConditionsCopy))
            {
                errors.Add("Terms and Conditions copy is required");
            }

            if (StringUtils.IsBlank(entity.PrivacyPolicyCopy))
            {
                errors.Add("Privacy Policy copy is required");
            }

            if (entity.IsMasterBrand)
            {
                BrandFinder finder = new BrandFinder {
                    IsMasterBrand = true
                };
                List <Brand> masterBrandList = Brand.FindMany(finder);

                if (masterBrandList.Count > 1)
                {
                    errors.Add("Only one master brand is allowed");
                }

                if (masterBrandList.Count == 1 && entity.IsNew)
                {
                    errors.Add("Only one master brand is allowed.  Current master brand is: " + masterBrandList[0].Name);
                }

                if (masterBrandList.Count == 1 && !entity.IsNew && !masterBrandList[0].BrandId.Equals(entity.BrandId))
                {
                    errors.Add("Only one master brand is allowed.  Current master brand is: " + masterBrandList[0].Name);
                }
            }

            if (!file.IsEmpty && file.FileExtension != "zip")
            {
                errors.Add("UI file pack must be a zip file");
            }

            if (!watermarkImage.IsEmpty && !GeneralUtils.ValueIsInList(watermarkImage.FileExtension, "gif", "jpg", "png"))
            {
                errors.Add("Watermark must be a GIF, JPG or PNG image");
            }

            if (errors.Count > 0)
            {
                throw new InvalidBrandException(errors, entity);
            }
        }
Ejemplo n.º 4
0
        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);
            }
        }
Ejemplo n.º 5
0
 public static void SaveAssetFile(Asset asset, BinaryFile file, bool notify, bool checkHash)
 {
     SaveAssetFile(asset, file, notify, checkHash, false);
 }
Ejemplo n.º 6
0
 public static void SaveAssetFile(Asset asset, BinaryFile file, bool sendEmailOnCompletion)
 {
     SaveAssetFile(asset, file, sendEmailOnCompletion, true);
 }
Ejemplo n.º 7
0
        private static ErrorList ValidateAsset(Asset asset, BinaryFile file)
        {
            ErrorList errors = new ErrorList();

            bool hasFullProductionDate = asset.ProductionYear.HasValue && asset.ProductionMonth.HasValue && asset.ProductionDay.HasValue;

            if (hasFullProductionDate)
            {
                string   productionDate = String.Format("{0}/{1}/{2}", asset.ProductionYear.Value, asset.ProductionMonth.Value, asset.ProductionDay.Value);
                DateTime dt;
                if (!DateTime.TryParse(productionDate, out dt))
                {
                    errors.Add(string.Format("{0} is not a valid date", productionDate));
                }
            }

            if (file != null && !file.IsEmpty)
            {
                // We also use a client-side javascript check to ensure that only valid files are uploaded, but this check
                // is just to make absolutely sure that the file is correct (ie. in case the client has javascript disabled)
                if (!asset.AssetType.FileExtensionList.Contains(file.FileExtension.ToLower()))
                {
                    errors.Add(string.Format("{0} is not a valid {1} file", file.FileName, asset.AssetType.Name.ToLower()));
                }
            }

            if (asset.BrandId == 0)
            {
                errors.Add(asset.Brand.GetMetadataSetting(BrandMetadataSettings.BRAND).FieldName + " is required");
            }

            var publicationDateField = asset.Brand.GetMetadataSetting(BrandMetadataSettings.PUBLICATION_DATE);
            var expiryDateField      = asset.Brand.GetMetadataSetting(BrandMetadataSettings.EXPIRY_DATE);

            if (publicationDateField.IsRequired && asset.PublishDate == DateTime.MinValue)
            {
                errors.Add(publicationDateField.FieldName + " is required");
            }

            if (expiryDateField.IsRequired && asset.ExpiryDate == DateTime.MinValue)
            {
                errors.Add(expiryDateField.FieldName + " is required");
            }

            if (publicationDateField.IsRequired &&
                expiryDateField.IsRequired &&
                asset.ExpiryDate < asset.PublishDate)
            {
                errors.Add(string.Format("{0} must be after {1}", publicationDateField.FieldName, expiryDateField.FieldName));
            }

            // We don't care about validation until asset is published or submitted to a workflow
            if (asset.AssetPublishStatus == AssetPublishStatus.Published || asset.AssetPublishStatus == AssetPublishStatus.PendingApproval)
            {
                // Assets submitted to a workflow must have a workflow specified
                if (asset.AssetPublishStatus == AssetPublishStatus.PendingApproval && asset.WorkflowId.GetValueOrDefault() == 0)
                {
                    errors.Add("Workflow is required");
                }

                if (asset.CategoryList.Count == 0)
                {
                    errors.Add("At least one category must be selected");
                }

                if (asset.PrimaryCategoryId <= 0)
                {
                    errors.Add(string.Format("{0} is required", asset.Brand.GetMetadataSetting(BrandMetadataSettings.PRIMARY_CATEGORY).FieldName));
                }

                //validate custom metadata - do it only if the asset is to be published though!
                // Get all of the metadata custom settings for this brand
                var customMetas = BrandMetadataSettingManager.GetCustomMetadataSettings(asset.BrandId);
                foreach (var setting in customMetas)
                {
                    if (!setting.IsRequired)
                    {
                        continue;
                    }

                    var notOk = false;

                    if (setting.UiControlType == (int)BrandMetadataUiControlType.Select)
                    {
                        var selectableSetting = setting.SelectableSetting;
                        var zeroSelected      = asset.GetMetadataForGroup(setting.GroupNumber).Count == 0;
                        var selType           = (SelectableMetadataType)selectableSetting.SelectableType;

                        if (selectableSetting.AllowMultiple &&
                            (selType == SelectableMetadataType.ComboBox || selType == SelectableMetadataType.Checkboxes) &&
                            zeroSelected)
                        {
                            notOk = true;
                        }

                        if (selType == SelectableMetadataType.RadioButtons && zeroSelected)
                        {
                            notOk = true;
                        }

                        if (selType == SelectableMetadataType.PresetTextArea)
                        {
                            notOk = string.IsNullOrEmpty(asset.GetStringValForGroup(setting.GroupNumber));
                        }
                    }
                    else
                    {
                        notOk = string.IsNullOrEmpty(asset.GetStringValForGroup(setting.GroupNumber));
                    }

                    if (notOk)
                    {
                        errors.Add(string.Format("{0} is required", setting.FieldName));
                    }
                }

                // Validate fields
                ValidateTextField(asset, errors, BrandMetadataSettings.TITLE, asset.Title);
                ValidateTextField(asset, errors, BrandMetadataSettings.PROJECT_CODE, asset.ProjectCode);
                ValidateTextField(asset, errors, BrandMetadataSettings.DESCRIPTION, asset.Description);
                ValidateTextField(asset, errors, BrandMetadataSettings.ORIGINATOR, asset.Originator);
                ValidateTextField(asset, errors, BrandMetadataSettings.ADDITIONAL_KEYWORDS, asset.Keywords);
                ValidateTextField(asset, errors, BrandMetadataSettings.COPYRIGHT_OWNER, asset.CopyrightOwner);
                ValidateTextField(asset, errors, BrandMetadataSettings.USAGE_RESTRICTIONS, asset.UsageRestrictions);

                // Ensure contact email has been specified if required
                if (asset.Brand.GetMetadataSetting(BrandMetadataSettings.CONTACT_EMAIL).IsRequired)
                {
                    if (StringUtils.IsBlank(asset.ContactEmail))
                    {
                        errors.Add(asset.Brand.GetMetadataSetting(BrandMetadataSettings.CONTACT_EMAIL).FieldName + " is required");
                    }
                    else if (!StringUtils.IsEmail(asset.ContactEmail))
                    {
                        errors.Add(asset.Brand.GetMetadataSetting(BrandMetadataSettings.CONTACT_EMAIL).FieldName + " is invalid");
                    }
                }

                // Ensure production date has been entered if required
                if (asset.Brand.GetMetadataSetting(BrandMetadataSettings.DATE_PRODUCED).IsRequired&& asset.ProductionYear == 0)
                {
                    errors.Add(asset.Brand.GetMetadataSetting(BrandMetadataSettings.DATE_PRODUCED).FieldName + " is required");
                }

                if (asset.Brand.GetMetadataSetting(BrandMetadataSettings.PUBLICATION_DATE).IsRequired)
                {
                    if (asset.PublishDate == DateTime.MinValue)
                    {
                        errors.Add("Publication date is required");
                    }
                }

                if (asset.Brand.GetMetadataSetting(BrandMetadataSettings.EXPIRY_DATE).IsRequired)
                {
                    if (asset.ExpiryDate == DateTime.MinValue)
                    {
                        errors.Add("Expiry date is required");
                    }
                    else if (asset.ExpiryDate.Date < asset.PublishDate.Date)
                    {
                        errors.Add("Expiry date must be after publication date");
                    }
                }
            }

            return(errors);
        }
Ejemplo n.º 8
0
 public DuplicateHashException(string message, BinaryFile binaryFile, Asset asset) : base(message)
 {
     BinaryFile = binaryFile;
     Asset      = asset;
 }
Ejemplo n.º 9
0
        public void Upload()
        {
            ValidateRequiredValues();

            m_Logger.DebugFormat("Uploading file: {0}", BinaryFile.FileName);

            if (BinaryFile.FileExtension == "zip" && !PreserveZipFile)
            {
                m_Logger.Debug("File is zip file");

                // If we're using a zip file, we need to go through the files inside
                // the zip and check them.  Files that are not valid are not unzipped,
                // we just skip over them as there's no point in unzipping files we don't need.

                using (ZipFile zipFile = new ZipFile(BinaryFile.InputStream))
                {
                    int fileCount = 0;

                    foreach (ZipEntry zipEntry in zipFile)
                    {
                        // Ignore non-files completely
                        if (!zipEntry.IsFile)
                        {
                            m_Logger.DebugFormat(" - {0} skipped, not a file", zipEntry.Name);
                            continue;
                        }

                        string filename = (Path.GetFileName(zipEntry.Name) ?? string.Empty).ToLower();

                        // Ignore blank filenames completely
                        if (StringUtils.IsBlank(filename))
                        {
                            m_Logger.Debug(" - skipped empty filename");
                            continue;
                        }

                        m_Logger.DebugFormat(" - {0} being processed", zipEntry.Name);

                        fileCount++;

                        // Initialise the uploaded asset result
                        UploadedAssetResult uar = new UploadedAssetResult {
                            Filename = filename, ZipFileIndex = zipEntry.ZipFileIndex
                        };

                        Asset asset;

                        if (IsDuplicateFile(zipFile, zipEntry, out asset))
                        {
                            uar.FileStatus = FileStatus.DuplicateHash;
                            uar.Asset      = asset;

                            if (UploadedBy.UserRole == UserRole.SuperAdministrator)
                            {
                                uar.SaveFile = true;
                                m_Logger.Debug("  -- File is duplicate hash, but uploader is superadmin so save anyway");
                            }
                            else
                            {
                                uar.SaveFile = false;
                                m_Logger.Debug("  -- File is ignored, duplicate hash");
                            }
                        }
                        else if (IgnorePath(zipEntry.Name))
                        {
                            uar.SaveFile   = false;
                            uar.FileStatus = FileStatus.IgnoredPath;
                            m_Logger.Debug("  -- Path is ignored");
                        }
                        else if (IgnoreFile(filename))
                        {
                            uar.SaveFile   = false;
                            uar.FileStatus = FileStatus.IgnoredFile;
                            m_Logger.Debug("  -- File is ignored");
                        }
                        else
                        {
                            uar.SaveFile   = true;
                            uar.FileStatus = FileStatus.Processed;
                            m_Logger.Debug("  -- File is valid");
                        }

                        UploadedAssetResultList.Add(uar);
                    }

                    // Ensure that the zip file has at least one file
                    // No point in continuing otherwise.
                    if (fileCount == 0)
                    {
                        m_Logger.Debug("- Zip file does not contain any assets and cannot be processed");
                        throw new AssetUploadException("Zip file does not contain any assets");
                    }

                    foreach (ZipEntry zipEntry in zipFile)
                    {
                        // Ignore non-files completely
                        if (!zipEntry.IsFile)
                        {
                            continue;
                        }

                        // Get the filename
                        string filename = (Path.GetFileName(zipEntry.Name) ?? string.Empty);

                        // Ignore blank filenames completely
                        if (StringUtils.IsBlank(filename))
                        {
                            continue;
                        }

                        // Parsed filename
                        string parsedFilename = (Path.GetFileName(zipEntry.Name) ?? string.Empty).ToLower();

                        // Only process the file if SaveFile is true (ie. it meets the save requirements)
                        bool process = (UploadedAssetResultList.FindAll(o => o.Filename.ToLower() == parsedFilename && o.SaveFile).Count > 0);

                        if (process)
                        {
                            OnProgress("Unzipping file: " + parsedFilename);

                            // Construct the filepath where the file will be unzipped to
                            string filePath = GetUniqueFilepath(Path.Combine(TempFolder, filename));

                            // Unzip the file
                            using (Stream inputStream = zipFile.GetInputStream(zipEntry))
                            {
                                using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                                {
                                    CopyStream(inputStream, fileStream);
                                    fileStream.Close();
                                }
                            }

                            if (CreateCategorySubFolders)
                            {
                                // Store the temporary filename along with the original path
                                m_TempFiles.Add(filePath, new OriginalLocation {
                                    OriginalPath = Path.GetDirectoryName(zipEntry.Name), ZipFileIndex = zipEntry.ZipFileIndex
                                });
                            }
                            else
                            {
                                m_TempFiles.Add(filePath, new OriginalLocation {
                                    OriginalPath = String.Empty, ZipFileIndex = zipEntry.ZipFileIndex
                                });
                            }

                            OnProgress("Unzipped file: " + parsedFilename);
                        }
                    }
                }
            }
            else
            {
                m_Logger.DebugFormat("Processing single file upload: {0}", BinaryFile.FileName);

                // Single file uploads.  These are managed a bit differently from zip uploads.
                // They are validated and if anything fails, we throw an AssetUpload exception.

                // Ensure that the file isn't one that should be ignored
                if (IgnoreFile(BinaryFile.FileName))
                {
                    m_Logger.DebugFormat("File {0} is not a valid asset file", BinaryFile.FileName);
                    throw new AssetUploadException(string.Format("The file '{0}' is not a valid asset file", BinaryFile.FileName));
                }

                // Search for assets with the same file hash
                AssetFinder finder = new AssetFinder {
                    FileHash = BinaryFile.FileHash, IsProcessed = true
                };
                finder.SortExpressions.Add(new DescendingSort("AssetId"));
                Asset duplicateAsset = Asset.FindOne(finder);

                // If a duplicate asset was found and the uploading user is not a superadmin, halt the upload and don't save the file to disk
                // Include the duplicate asset ID in the error message for information purposes.
                // We allow duplicate uploads from super-admins as we assume they know wha they are doing.
                if (!duplicateAsset.IsNull)
                {
                    // Log this duplicate
                    m_Logger.DebugFormat("The file {0} has already been uploaded to the system and has the Asset ID: {1}", BinaryFile.FileName, duplicateAsset.AssetId);

                    // Halt the upload if the user doing the upload is not a super-admin
                    if (UploadedBy.UserRole != UserRole.SuperAdministrator)
                    {
                        string message = string.Format("This file has already been uploaded to the system and has the ID: {0}", duplicateAsset.AssetId);
                        throw new DuplicateHashException(message, BinaryFile, duplicateAsset);
                    }
                }

                // Get the filename where this file should be saved to on disk
                string filename = Path.Combine(TempFolder, BinaryFile.FileName);

                // Save the file
                OnProgress("Saving asset file to disk");
                BinaryFile.SaveAs(filename);
                m_TempFiles.Add(filename, new OriginalLocation {
                    OriginalPath = SourcePath, ZipFileIndex = -1
                });
                OnProgress("Saved asset file to disk");

                // Set the filestatus based on whether the asset is a duplicate
                FileStatus fileStatus = (!duplicateAsset.IsNull) ? FileStatus.DuplicateHash : FileStatus.Processed;

                // Add it to the resut list
                UploadedAssetResult uar = new UploadedAssetResult {
                    Filename = BinaryFile.FileName, FileStatus = fileStatus, SaveFile = true, ZipFileIndex = -1
                };
                UploadedAssetResultList.Add(uar);
            }

            // Get all of the uploaded files and upload these to the system
            // foreach (string path in Directory.GetFiles(TempFolder))
            foreach (KeyValuePair <string, OriginalLocation> kvp in m_TempFiles)
            {
                // Save the asset file to the system
                OnProgress("Saving asset");
                OriginalLocation origLocation = (OriginalLocation)kvp.Value;
                // Asset asset = SaveUploadedAsset(new BinaryFile(path, BinaryFile.SaveMode.Move));
                Asset asset = SaveUploadedAsset(new BinaryFile(kvp.Key, BinaryFile.SaveMode.Move), origLocation.OriginalPath);
                OnProgress("Saved asset with ID: " + asset.AssetId);

                // Update audit logs
                LogUploadedAsset(asset, string.Format("Uploaded from: {0}", BinaryFile.FileName));

                // Update the uploaded asset result list item with the asset record that was created
                UploadedAssetResult uar;
                if (origLocation.ZipFileIndex != -1)
                {
                    // Original was from a zip file so use the zip file index
                    uar = UploadedAssetResultList.Find(o => o.ZipFileIndex == origLocation.ZipFileIndex && o.SaveFile);
                }
                else
                {
                    // Coming from a folder heirarchy so use filename.
                    uar = UploadedAssetResultList.Find(o => o.Filename.ToLower() == asset.Filename.ToLower() && o.SaveFile);
                }

                uar.Asset = asset;
            }

            try
            {
                OnProgress("Deleting temp folder");
                Directory.Delete(TempFolder, true);
                OnProgress("Deleted temp folder");

                m_Logger.DebugFormat("- Deleted directory: {0}", TempFolder);
            }
            catch (Exception e)
            {
                m_Logger.Warn("Error deleting: " + TempFolder, e);
            }
        }
Ejemplo n.º 10
0
        /// <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);
        }