/// <summary> /// Deletes a poster source map record from the database for a VOD Asset /// </summary> /// <param name="ConnectionString">SQL Connection String</param> /// <param name="VAsset">Vod Asset to have it's poster source map deleted</param> /// <returns></returns> public async Task DeleteVodAssetAsync(VODAsset VAsset, CancellationToken CancelToken) { StringBuilder sbCmd = new StringBuilder(); sbCmd.AppendFormat("SELECT TOP 1 * FROM {0} WHERE {0}.strAssetId = '{1}'", _posterSourceMapTbl, VAsset.AssetId); bool isExists = false; CancelToken.ThrowIfCancellationRequested(); while (this.committing || this.resetting) { await Task.Delay(100, CancelToken); } this.inserting++; try { using (var command = this.connection.CreateCommand()) { await this.OpenAsync(CancelToken); command.CommandText = sbCmd.ToString(); using (var reader = await command.ExecuteReaderAsync(CancelToken)) { isExists = reader.HasRows; } if (!isExists) { return; } sbCmd.Clear(); sbCmd.AppendFormat("DELETE FROM {0} WHERE {0}.strAssetId = '{1}'", _posterSourceMapTbl, VAsset.AssetId); command.Transaction = this.transaction; command.CommandText = sbCmd.ToString(); if (!CancelToken.IsCancellationRequested) { await command.ExecuteNonQueryAsync(CancelToken); } } } finally { this.inserting--; } }
/// <summary> /// Get VOD assets from the database asyncronously for a VHO /// </summary> /// <param name="ConnectionString">SQL connection string</param> /// <param name="maxAssets">Max number of assests to get</param> /// <param name="vhoName">Name of the vho being processed</param> /// <param name="srcDir">Poster source directory</param> /// <param name="destDir">Poster destination directory</param> /// <returns>All VOD Assets for a particular VHO</returns> internal IEnumerable <VODAsset> GetVODAssets(string ConnectionString, int?maxAssets, string vhoName, string srcDir, string destDir, CancellationToken cancelToken) { Trace.TraceInformation("INFO({0}): Getting VOD Asset Info from Database", vhoName); string sproc = "sp_FUI_GetAllVODFolderAssetInfo"; int index = 1; foreach (var dr in DBFactory.SQL_ExecuteReader(ConnectionString, sproc, System.Data.CommandType.StoredProcedure, null)) { cancelToken.ThrowIfCancellationRequested(); //only add assets up to max value if set if (maxAssets.HasValue && index == maxAssets.Value) { break; } var vAsset = new VODAsset(); vAsset.AssetId = int.Parse(dr.GetString(0)); vAsset.Title = dr.GetString(1); vAsset.PID = dr.GetString(2); vAsset.PAID = dr.GetString(3); vAsset.PosterSource = dr.IsDBNull(4) ? string.Empty : dr.GetString(4); //If only processing new or assets with no posters, don't return assets assets with posters if (this._onlyNew && !string.IsNullOrEmpty(vAsset.PosterSource)) { continue; } vAsset.PosterDest = GetDestImagePath(vAsset.AssetId, destDir); index++; yield return(vAsset); } ; }
/// <summary> /// Gets all VOD assets from all vho's in the config /// </summary> /// <param name="config">Configuration parameters</param> /// <returns></returns> internal IEnumerable <VODAsset> GetAllVodAssets(NGVodPosterConfig config) { foreach (var vho in config.Vhos) { string conStr = vho.Value.IMGDs.CreateConnectionString(vho.Value.IMGDb); string sproc = "sp_FUI_GetAllVODFolderAssetInfo"; foreach (var dr in DBFactory.SQL_ExecuteReader(conStr, sproc, System.Data.CommandType.StoredProcedure)) { var vAsset = new VODAsset(); vAsset.AssetId = int.Parse(dr.GetString(0)); vAsset.Title = dr.GetString(1); vAsset.PID = dr.GetString(2); vAsset.PAID = dr.GetString(3); vAsset.PosterSource = dr.IsDBNull(4) ? string.Empty : dr.GetString(4); vAsset.PosterDest = GetDestImagePath(vAsset.AssetId, vho.Value.PosterDir); yield return(vAsset); } } }
/// <summary> /// Resizes and saves the image as the asset ID jpg /// </summary> /// <param name="VAsset">VOD Asset</param> /// <param name="Height">Final height of the image</param> /// <param name="Width">Final width of the image</param> /// <param name="token">Cancellation token</param> private int ProcessImage(VODAsset VAsset, int Height, int Width, string vhoName, CancellationToken token) { token.ThrowIfCancellationRequested(); //Temporary folder path used to backup any existing images before any manipulation string tmpPath = Path.Combine(Directory.GetCurrentDirectory(), "Temp"); string tmpFile = string.Empty; //Create root temp folder if it doesn't exist if (!Directory.Exists(tmpPath)) { Directory.CreateDirectory(tmpPath); } //Make a temp path child folder by VHO name to prevent asset id conflicts tmpPath = Path.Combine(tmpPath, vhoName); if (!Directory.Exists(tmpPath)) { Directory.CreateDirectory(tmpPath); } try { //Poster destination file name cannot be null if (string.IsNullOrEmpty(VAsset.PosterDest)) { throw new ArgumentNullException("Destination folder cannot be null. " + VAsset.ToString()); } //Verify file extension is .jpg if (!VAsset.PosterDest.EndsWith(".jpg")) { throw new ArgumentException("(ProcessImages) Invalid destination file name.", VAsset.PosterDest); } //Throw error if source file not found, used to populate missing poster log if (!File.Exists(VAsset.PosterSource)) { throw new FileNotFoundException(string.Format("(ProcessImages) Source poster file not found. AssetID: {0}", VAsset.AssetId), VAsset.PosterSource); } //if destination file already exists, check if it needs updated using timestamp if (File.Exists(VAsset.PosterDest)) { tmpFile = Path.Combine(tmpPath, Path.GetFileName(VAsset.PosterDest)); //If a temp file exists in the temp directory for this asset, remove it if (File.Exists(tmpFile)) { File.Delete(tmpFile); } //Move the file to the temp directory, and set it as a temp file File.Move(VAsset.PosterDest, tmpFile); File.SetAttributes(tmpFile, FileAttributes.Temporary); } //Resize source image file if it is above 50MB try { FileInfo srcFInfo = new FileInfo(VAsset.PosterSource); if (((srcFInfo.Length / 1024F) / 1024F) > 50) { string tmpName = Path.Combine(Path.GetFullPath(srcFInfo.FullName), Path.GetFileNameWithoutExtension(srcFInfo.FullName) + "_tmp.jpg"); using (var origBM = new Bitmap(srcFInfo.FullName)) using (var srcBM = new Bitmap(origBM, Width, Height)) { srcBM.Save(tmpName, ImageFormat.Jpeg); } File.Copy(tmpName, srcFInfo.FullName, true); File.Delete(tmpName); } } catch (Exception ex) { Trace.TraceError("Failed to resize source image file above 50mb. {0}", ex.Message); } //Resize poster, save, and increment progress success if no errors using (var sourceBM = new Bitmap(VAsset.PosterSource)) using (var destBM = new Bitmap(sourceBM, Width, Height)) //using (var destBM = Toolset.ResizeBitmap(sourceBM, Width, Height, null, null, true)) { token.ThrowIfCancellationRequested(); destBM.Save(VAsset.PosterDest, ImageFormat.Jpeg); } //Verify file was saved and it exists if (!File.Exists(VAsset.PosterDest)) { throw new Exception("(ProcessImages) File failed to save in destination folder."); } return(0); } catch { //Restore backup file from temp directory if (!string.IsNullOrEmpty(tmpFile) && File.Exists(tmpFile)) { File.Copy(tmpFile, VAsset.PosterDest, true); } throw; } finally { //Delete backup file from temp directory if (!string.IsNullOrEmpty(tmpFile) && File.Exists(tmpFile)) { File.Delete(tmpFile); } } }
/// <summary> /// Inserts or Updates a single asset poster source into the database async /// </summary> /// <param name="Asset">Vod Asset to insert or update the poster source value</param> /// <param name="ConnectionString">SQL Connection String</param> /// <returns></returns> public async Task InsertAssetAsync(VODAsset Asset, CancellationToken CancelToken) { if (string.IsNullOrEmpty(Asset.PosterSource)) { throw new ArgumentNullException("Asset poster source cannot be null"); } while (this.committing || this.resetting) { await Task.Delay(100, CancelToken); } if (!this.isOpen) { await this.OpenAsync(CancelToken); } StringBuilder strCmd = new StringBuilder(); strCmd.AppendFormat("SELECT TOP 1 * FROM {0} a WHERE a.strAssetId = {1}", _posterSourceMapTbl, Asset.AssetId); bool isAlreadyExists = false; CancelToken.ThrowIfCancellationRequested(); this.inserting++; try { using (var command = this.connection.CreateCommand()) { command.Transaction = this.transaction; command.CommandText = strCmd.ToString(); command.CommandType = CommandType.Text; using (SqlDataReader reader = await command.ExecuteReaderAsync()) { isAlreadyExists = reader.HasRows; } strCmd.Clear(); if (isAlreadyExists) { strCmd.AppendFormat("UPDATE {0} SET {0}.strPosterFile = '{1}' WHERE {0}.strAssetId = '{2}'", _posterSourceMapTbl, Path.GetFileName(Asset.PosterSource), Asset.AssetId); } else { strCmd.AppendFormat("INSERT INTO {0} VALUES ('{1}', '{2}')", _posterSourceMapTbl, Asset.AssetId, Path.GetFileName(Asset.PosterSource)); } command.CommandText = strCmd.ToString(); await command.ExecuteNonQueryAsync(CancelToken); } } finally { this.inserting--; } this.inserts++; if (this.inserts % 100 == 0) { this.CommitTransaction(true); } }