public AlbumViewModel(IAlbum iAlbum)
 {
     _Album = iAlbum;
     _ImagesVM = new CollectionWithDetailVM<IAlbumPicture>(_Album.Images);
     var tm = Register(Album.Tracks.LiveOrderBy(t => t.TrackNumber));
     _OrderedTracks = Register(tm.LiveThenBy(t => t.Path));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of a <see cref="Audio" /> object.
        /// </summary>
        /// <param name="audioFile">A <see cref="FileInfo"/> object containing the original audio file for this object. This is intended to be 
        /// specified when creating a new media object from a file. Specify null when instantiating an object for an existing database
        /// record.</param>
        /// <param name="parentAlbum">The album that contains this object. This is a required parameter.</param>
        /// <exception cref="GalleryServerPro.Events.CustomExceptions.InvalidMediaObjectException">Thrown when 
        /// <paramref name="audioFile"/> refers to a file that is not in the same directory as the parent album's directory.</exception>
        /// <exception cref="GalleryServerPro.Events.CustomExceptions.UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name="audioFile"/> is specified (not null) and its file extension does not correspond to an audio MIME
        /// type, as determined by the MIME type definition in the configuration file.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="parentAlbum" /> is null.</exception>
        /// <remarks>This constructor does not verify that <paramref name="audioFile"/> refers to a file type that is enabled in the 
        /// configuration file.</remarks>
        internal Audio(FileInfo audioFile, IAlbum parentAlbum)
            : this(int.MinValue, parentAlbum, string.Empty,
						int.MinValue, int.MinValue, int.MinValue, string.Empty, int.MinValue, int.MinValue,
						int.MinValue, string.Empty, int.MinValue, int.MinValue, int.MinValue, int.MinValue,
						String.Empty, DateTime.Now, String.Empty, DateTime.MinValue, parentAlbum != null ? parentAlbum.IsPrivate : false, false, audioFile, null)
        {
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of an <see cref="Image"/> object.
        /// </summary>
        /// <param name="imageFile">A <see cref="System.IO.FileInfo"/> object containing the original image for this object.</param>
        /// <param name="parentAlbum">The album that contains this object. This is a required parameter.</param>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.InvalidMediaObjectException">Thrown when 
        /// <paramref name="imageFile"/> refers to a file that is not in the same directory as the parent album's directory.</exception>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name="imageFile"/> is specified (not null) and its file extension does not correspond to an image MIME
        /// type, as determined by the MIME type definition in the configuration file.</exception>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedImageTypeException">Thrown when the 
        /// .NET Framework is unable to load an image file into the <see cref="System.Drawing.Bitmap"/> class. This is 
        /// probably because it is corrupted, not an image supported by the .NET Framework, or the server does not have 
        /// enough memory to process the image. The file cannot, therefore, be handled using the <see cref="Image"/> 
        /// class; use <see cref="GenericMediaObject"/> instead. This exception is thrown only when <paramref name="imageFile"/>
        /// is specified (non-null).</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="parentAlbum" /> is null.</exception>
        /// <remarks>This constructor does not verify that <paramref name="imageFile"/> refers to a file type that is enabled in the 
        /// configuration file.</remarks>
        internal Image(System.IO.FileInfo imageFile, IAlbum parentAlbum)
            : this(int.MinValue, parentAlbum, string.Empty, string.Empty, string.Empty,
				int.MinValue, int.MinValue, int.MinValue, string.Empty, int.MinValue, int.MinValue,
				int.MinValue, string.Empty, int.MinValue, int.MinValue, int.MinValue, int.MinValue,
				String.Empty, DateTime.MinValue, String.Empty, DateTime.MinValue, parentAlbum != null ? parentAlbum.IsPrivate : false, false, imageFile)
        {
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of a <see cref="Video" /> object.
        /// </summary>
        /// <param name="videoFile">A <see cref="FileInfo"/> object containing the original video file for this object. This is intended to be 
        /// specified when creating a new media object from a file. Specify null when instantiating an object for an existing database
        /// record.</param>
        /// <param name="parentAlbum">The album that contains this object. This is a required parameter.</param>
        /// <exception cref="GalleryServerPro.Events.CustomExceptions.InvalidMediaObjectException">Thrown when 
        /// <paramref name="videoFile"/> refers to a file that is not in the same directory as the parent album's directory.</exception>
        /// <exception cref="GalleryServerPro.Events.CustomExceptions.UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name="videoFile"/> is specified (not null) and its file extension does not correspond to an video MIME
        /// type, as determined by the MIME type definition in the configuration file.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="parentAlbum" /> is null.</exception>
        /// <remarks>This constructor does not verify that <paramref name="videoFile"/> refers to a file type that is enabled in the 
        /// configuration file.</remarks>
        internal Video(System.IO.FileInfo videoFile, IAlbum parentAlbum)
            : this(int.MinValue, parentAlbum, string.Empty,
						int.MinValue, int.MinValue, int.MinValue, string.Empty, int.MinValue, int.MinValue,
						int.MinValue, string.Empty, int.MinValue, int.MinValue, int.MinValue, int.MinValue,
						String.Empty, DateTime.Now, String.Empty, DateTime.MinValue, parentAlbum != null ? parentAlbum.IsPrivate : false, false, videoFile, null)
        {
        }
		public FieldProblem_leftend()
		{
            viewMock = MockRepository.Mock<IAddAlbumPresenter>();
            albumMock = MockRepository.Mock<IAlbum>();

            viewMock.ExpectEvent(x => x.Save += Arg<EventHandler<EventArgs>>.Is.NotNull);
		}
Exemplo n.º 6
0
        public FieldProblem_leftend()
        {
            viewMock = (IAddAlbumPresenter)MockRepository.GenerateMock(typeof(IAddAlbumPresenter), null, null);
            albumMock = MockRepository.GenerateStrictMock<IAlbum>();

            saveRaiser = viewMock.Expect(x => x.Save += null).IgnoreArguments().Constraints(Is.NotNull()).GetEventRaiser();
        }
Exemplo n.º 7
0
 public Album(IAlbum album)
 {
     Artist = new Artist(album.Artist);
     CoverId = album.CoverId;
     Name = album.Name;
     Type = album.Type;
     Year = album.Year;
 }
Exemplo n.º 8
0
        public AlbumViewer(IAlbum album)
        {
            InitializeComponent();
            _album = album;

            albumName.Text = _album.Name;
            musicList.Items.AddRange(_album.GetAllMusics().Select(p=>p.Name).ToArray());
        }
        //public static IAlbum ForAlbum(int iTrackNumber=0)
        //{
        //    CompleteObservableCollectionImpl<ITrack> coci = new CompleteObservableCollectionImpl<ITrack>();
        //    IAlbum res = Substitute.For<IAlbum>();
        //    res.IsAlive.Returns(true);
        //    res.Tracks.Returns(coci);

        //    for (int i = 0; i < iTrackNumber; i++)
        //    {
        //        IInternalTrack subres = ForTrack(res);
        //    }
        //    return res;
        //}

        internal static IInternalTrack ForTrack(IAlbum Father)
        {
            IInternalTrack res = Substitute.For<IInternalTrack>();
            Father.Tracks.Add(res);
            res.Album.Returns(Father);
            res.IsAlive.Returns(true);
            return res;
        }
Exemplo n.º 10
0
 public LoadSongsViewModel()
 {
     _artist = new Artist();
     _album = new Album();
     _discography = new Discography();
     _songs = new List<Song>();
     _artistContact = new ArtistContact();
 }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewPhotoForm"/> class.
 /// </summary>
 /// <param name="currentAlbum">The album whose photos the user is viewing.</param>
 /// <param name="photoToDisplay">the specific photo to view.</param>
 /// <remarks>
 /// Author(s): Miguel Gonzales and Andrea Tan
 /// </remarks>
 public ViewPhotoForm(IAlbum currentAlbum, IPhoto photoToDisplay)
 {
     this.InitializeComponent();
     this.album = currentAlbum;
     this.Text = this.album.AlbumId + " - Photo Buddy";
     this.allPhotosInAlbum = new List<IPhoto>(this.album.Photos);
     this.photoIndex = this.allPhotosInAlbum.IndexOf(photoToDisplay);
     this.DisplayPhoto(this.photoIndex);
 }
        /// <summary>
        /// Copy the specified object and place it in the specified destination album. This method creates a completely separate copy
        /// of the original, including copying the physical files associated with this object. The copy is persisted to the data
        /// store and then returned to the caller. When copying albums, all the album's children, grandchildren, etc are also copied.
        /// The audit fields of the copied objects are automatically updated before saving.
        /// </summary>
        /// <param name="galleryObjectToCopy">The gallery object to copy.</param>
        /// <param name="destinationAlbum">The album to which the current object should be copied.</param>
        /// <returns>
        /// Returns a new gallery object that is an exact copy of the original, except that it resides in the specified
        /// destination album, and of course has a new ID. Child objects are recursively copied.
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObjectToCopy" /> is null.</exception>
        public static IGalleryObject CopyGalleryObject(IGalleryObject galleryObjectToCopy, IAlbum destinationAlbum)
        {
            if (galleryObjectToCopy == null)
                throw new ArgumentNullException("galleryObjectToCopy");

            string currentUser = Utils.UserName;

            return galleryObjectToCopy.CopyTo(destinationAlbum, currentUser);
        }
Exemplo n.º 13
0
        public static Album ConvertToDto(IAlbum album)
        {
            using (album)
            {
                album.WaitUntilLoaded();

                return Mapper.Map<IAlbum, Album>(album);
            }
        }
Exemplo n.º 14
0
 public void SaveCommit(IAlbum album, out bool success)
 {
     using (IUnitOfWork u = UnitOfWork.Begin())
     {
         Save(album, out success);
         if (success)
             u.Commit();
     }
 }
Exemplo n.º 15
0
		/// <summary>
		/// Move the specified object to the specified destination album. This method moves the physical files associated with this
		/// object to the destination album's physical directory. The object's Save() method is invoked to persist the changes to the
		/// data store. When moving albums, all the album's children, grandchildren, etc are also moved. 
		/// The audit fields are automatically updated before saving.
		/// </summary>
		/// <param name="galleryObjectToMove">The gallery object to move.</param>
		/// <param name="destinationAlbum">The album to which the current object should be moved.</param>
		public static void MoveGalleryObject(IGalleryObject galleryObjectToMove, IAlbum destinationAlbum)
		{
			string currentUser = Util.UserName;
			DateTime currentTimestamp = DateTime.Now;

			galleryObjectToMove.LastModifiedByUserName = currentUser;
			galleryObjectToMove.DateLastModified = currentTimestamp;

			galleryObjectToMove.MoveTo(destinationAlbum);
		}
Exemplo n.º 16
0
 public AlbumInformation(IAlbum album, Dispatcher dispatcher)
 {
     _tracks = new ObservableCollection<Track>();
     _copyrights = new ObservableCollection<string>();
     _dispatcher = dispatcher;
     _album = album;
     _browse = _album.Browse();
     _isLoading = !_browse.IsComplete;
     _browse.Completed += AlbumBrowseCompleted;
 }
Exemplo n.º 17
0
        public void DeleteCommit(IAlbum album)
        {
            Checks.Argument.IsNotNull(album, "album");

            using (IUnitOfWork u = UnitOfWork.Begin())
            {
                _repo.Remove(album);
                u.Commit();
            }
        }
Exemplo n.º 18
0
        public Album(IAlbum album, Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            InternalAlbum = album;

            _artist = new Lazy<Artist>(() => new Artist(InternalAlbum.Artist, dispatcher));
            _albumType = new Lazy<TorshifyAlbumType>(GetAlbumType);
            _name = new Lazy<string>(() => InternalAlbum.Name);
            _year = new Lazy<int>(() => InternalAlbum.Year);
        }
Exemplo n.º 19
0
        public FieldProblem_leftend()
        {
            mocks = new MockRepository();
            viewMock =
                (IAddAlbumPresenter) mocks.DynamicMock(typeof (IAddAlbumPresenter));
            albumMock = mocks.StrictMock<IAlbum>();

            viewMock.Save += null;
            LastCall.IgnoreArguments().Constraints(Is.NotNull());
            saveRaiser = LastCall.GetEventRaiser();
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UploadViewForm"/> class.
        /// </summary>
        /// <param name="photo">The photo to display.</param>
        /// <remarks>
        ///   <para>Author: Jim Counts and Eric Wei</para>
        ///   <para>Created: 2011-10-25</para>
        ///   <para>Modified: 2011-10-25</para>
        ///   <para>
        /// Creates an instance of the UploadViewForm that is configured to rename a photo.
        ///   </para>
        /// </remarks>
        public UploadViewForm(IPhoto photo)
        {
            this.InitializeComponent();

            Album = photo.Album;

            this.Text = Format.Culture("{0} {1} - Photo Buddy", "Rename", photo.DisplayName);
            this.UploadViewBox.Image = photo.Image;
            this.displayNameTextBox.Text = photo.DisplayName;
            this.messageLabel.Text = "This is the photo you have selected to rename.";
        }
Exemplo n.º 21
0
		/// <summary>
		/// Update the directory on disk with the current name and location of the album. A new directory is
		/// created for new albums, and the directory is moved to the location specified by FullPhysicalPath if
		/// that property is different than FullPhysicalPathOnDisk.
		/// </summary>
		/// <param name="album">The album to persist to disk.</param>
		private static void PersistToFileSystemStore(IAlbum album)
		{
			if (album.IsNew)
			{
				System.IO.Directory.CreateDirectory(album.FullPhysicalPath);

				// Create directory for thumbnail cache, if needed.
				string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, AppSetting.Instance.ThumbnailPath);
				if (thumbnailPath != album.FullPhysicalPath)
				{
					System.IO.Directory.CreateDirectory(thumbnailPath);
				}

				// Create directory for optimized image cache, if needed.
				string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, AppSetting.Instance.OptimizedPath);
				if (optimizedPath != album.FullPhysicalPath)
				{
					System.IO.Directory.CreateDirectory(optimizedPath);
				}
			}
			else if (album.FullPhysicalPathOnDisk != album.FullPhysicalPath)
			{
				// We need to move the directory to its new location or change its name. Verify that the containing directory doesn't already
				// have a directory with the new name. If it does, alter it slightly to make it unique.
				System.IO.DirectoryInfo di = System.IO.Directory.GetParent(album.FullPhysicalPath);

				string newDirName = HelperFunctions.ValidateDirectoryName(di.FullName, album.DirectoryName);
				if (album.DirectoryName != newDirName)
				{
					album.DirectoryName = newDirName;
				}

				// Now we are guaranteed to have a "safe" directory name, so proceed with the move/rename.
				System.IO.Directory.Move(album.FullPhysicalPathOnDisk, album.FullPhysicalPath);

				// Rename directory for thumbnail cache, if needed.
				string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, AppSetting.Instance.ThumbnailPath);
				if (thumbnailPath != album.FullPhysicalPath)
				{
					string currentThumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPathOnDisk, AppSetting.Instance.ThumbnailPath);

					RenameDirectory(currentThumbnailPath, thumbnailPath);
				}

				// Rename directory for optimized image cache, if needed.
				string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, AppSetting.Instance.OptimizedPath);
				if (optimizedPath != album.FullPhysicalPath)
				{
					string currentOptimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPathOnDisk, AppSetting.Instance.OptimizedPath);

					RenameDirectory(currentOptimizedPath, optimizedPath);
				}
			}
		}
Exemplo n.º 22
0
        public static Task<IAlbumBrowse> BrowseAsync(
            this ISession session,
            IAlbum album,
            object userState = null)
        {
            var tcs = new TaskCompletionSource<IAlbumBrowse>();

            var browse = session.Browse(album, userState);
            browse.Completed += (sender, args) => tcs.SetResult(browse);
            return tcs.Task;
        }
Exemplo n.º 23
0
		private static void DeleteFromFileSystem(IAlbum album)
		{
			string albumPath = album.FullPhysicalPath;
			if (album.IsRootAlbum)
			{
				DeleteRootAlbumDirectory(albumPath);
			}
			else
			{
				DeleteAlbumDirectory(albumPath);
			}
		}
        /// <summary>
        /// Move the specified object to the specified destination album. This method moves the physical files associated with this
        /// object to the destination album's physical directory. The object's Save() method is invoked to persist the changes to the
        /// data store. When moving albums, all the album's children, grandchildren, etc are also moved. 
        /// The audit fields are automatically updated before saving.
        /// </summary>
        /// <param name="galleryObjectToMove">The gallery object to move.</param>
        /// <param name="destinationAlbum">The album to which the current object should be moved.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObjectToMove" /> is null.</exception>
        public static void MoveGalleryObject(IGalleryObject galleryObjectToMove, IAlbum destinationAlbum)
        {
            if (galleryObjectToMove == null)
                throw new ArgumentNullException("galleryObjectToMove");

            string currentUser = Utils.UserName;
            DateTime currentTimestamp = DateTime.Now;

            galleryObjectToMove.LastModifiedByUserName = currentUser;
            galleryObjectToMove.DateLastModified = currentTimestamp;

            galleryObjectToMove.MoveTo(destinationAlbum);
        }
        private void InsertSongToAlbum(ISong song, IAlbum album)
        {
            if (this.media.FirstOrDefault(a => a is IAlbum && a == album) == null)
            {
                throw new ArgumentException("The album does not exist in the database.");
            }
            if (this.media.FirstOrDefault(s => s is ISong && s == song) == null)
            {
                throw new ArgumentException("The song does not exist in the database.");
            }

            album.AddSong(song);
            this.Printer.PrintLine(string.Format("The song {0} has been added to the album {1}.", song.Title, album.Title));
        }
Exemplo n.º 26
0
        private bool NeedUpdateCovers(IAlbum al)
        {
            string tr = al.Tracks[0].Path;

            using (TagLib.File TLF = TagLib.File.Create(tr))
            {
                if (TLF == null)
                {
                    Console.WriteLine("ERROR - Problem for status {0}", al);
                    return false;
                }


                return ((TLF.Tag.Pictures == null) || (TLF.Tag.Pictures.Length == 0));
            }
        }
Exemplo n.º 27
0
        public void Save(IAlbum album, out bool success)
        {
            Checks.Argument.IsNotNull(album, "album");

            success = false;

            if (null == _repo.FindByAlbumId(album.AlbumId))
            {
                try
                {
                    _repo.Add(album);
                    success = true;
                }
                catch (Exception ex)
                {
                    success = false;
                }
            }
        }
Exemplo n.º 28
0
		public void DisplayThumbnails(IAlbum album)
		{
			string msg = string.Empty;

			//Get the data associated with the album and display
			IGalleryObjectCollection albumObjects;
			if (this.PageBase.IsAnonymousUser)
			{
				albumObjects = album.GetChildGalleryObjects(true, true);
			}
			else
			{
				albumObjects = album.GetChildGalleryObjects(true);
			}

			if (albumObjects.Count > 0)
			{
				// At least one album or media object in album.
				msg = String.Format(CultureInfo.CurrentCulture, "<p class='addtopmargin2'>{0}</p>", Resources.GalleryServerPro.UC_ThumbnailView_Intro_Text_With_Objects);
				phMsg.Controls.Add(new LiteralControl(msg));
			}
			else if (this.PageBase.UserCanAddMediaObject)
			{
				// No objects, user has permission to add media objects.
				string innerMsg = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.UC_ThumbnailView_Intro_Text_No_Objects_User_Has_Add_MediaObject_Permission, album.Id);
				msg = String.Format(CultureInfo.CurrentCulture, "<p class='addtopmargin2 msgfriendly'>{0}</p>", innerMsg);
				phMsg.Controls.Add(new LiteralControl(msg));
			}
			else
			{
				// No objects, user doesn't have permission to add media objects.
				msg = String.Format(CultureInfo.CurrentCulture, "<p class='addtopmargin2 msgfriendly'>{0}</p>", Resources.GalleryServerPro.UC_ThumbnailView_Intro_Text_No_Objects);
				phMsg.Controls.Add(new LiteralControl(msg));
			}

			this.PageBase.SetThumbnailCssStyle(albumObjects);

			rptr.DataSource = albumObjects;
			rptr.DataBind();
		}
Exemplo n.º 29
0
        /// <summary>
        /// Create a minimally populated <see cref="Audio" /> instance from the specified parameters.
        /// </summary>
        /// <param name="audioFile">A <see cref="System.IO.FileInfo" /> object representing a supported audio type. The file must already
        /// exist in the album's directory. If the file has a matching record in the data store, a reference to the existing 
        /// object is returned; otherwise, a new instance is returned. Otherwise, a new instance is returned. For new instances, 
        ///		call <see cref="IGalleryObject.Save" /> to persist the object to the data store.</param>
        /// <param name="parentAlbum">The album in which the audio exists (for media objects that already exist
        /// in the data store), or should be added to (for new media objects which need to be inserted into the 
        /// data store).</param>
        /// <returns>Returns an <see cref="Audio" /> instance corresponding to the specified parameters.</returns>
        /// <exception cref="InvalidMediaObjectException">Thrown when 
        /// <paramref name = "audioFile" /> refers to a file that is not in the same directory as the parent album's directory.</exception>
        /// <exception cref="UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name = "audioFile" /> has a file extension that Gallery Server Pro is configured to reject, or it is
        /// associated with a non-audio MIME type.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name = "audioFile" /> or <paramref name = "parentAlbum" /> is null.</exception>
        public static IGalleryObject CreateAudioInstance(FileInfo audioFile, IAlbum parentAlbum)
        {
            if (audioFile == null)
                throw new ArgumentNullException("audioFile");

            if (parentAlbum == null)
                throw new ArgumentNullException("parentAlbum");

            // Validation check: Make sure the configuration settings allow for this particular type of file to be added.
            if (!HelperFunctions.IsFileAuthorizedForAddingToGallery(audioFile.Name, parentAlbum.GalleryId))
                throw new UnsupportedMediaObjectTypeException(audioFile.FullName);

            // If the file belongs to an existing media object, return a reference to it.
            foreach (IGalleryObject childMediaObject in parentAlbum.GetChildGalleryObjects(GalleryObjectType.Audio))
            {
                if (childMediaObject.Original.FileNamePhysicalPath == audioFile.FullName)
                    return childMediaObject;
            }

            // Create a new audio object, which will cause a new record to be inserted in the data store when Save() is called.
            return new Audio(audioFile, parentAlbum);
        }
Exemplo n.º 30
0
        public override IClip GetClip(ISecurityContext securityContext, IMediaFactory mediaFactory, IMetadataRepository mediaItemRepository, IArtist artist, IAlbum album)
        {
            var clip = mediaItemRepository.GetByTarget<IClip>(Location).FirstOrDefault();
            if (clip != null)
            {
                return clip;
            }

            var name = GetClipName();
            var summary = string.Empty;
            var number = GetClipNumber();
            var date = GetDate();
            var duration = file != null && file.Properties != null ? file.Properties.Duration : TimeSpan.FromMinutes(5);
            var height = file != null && file.Properties != null ? (uint)file.Properties.VideoHeight : 480;
            var width = file != null && file.Properties != null ? (uint)file.Properties.VideoWidth : 640;

            var builder = new MediaItemBuilder<IClip>(securityContext, mediaFactory)
                .Identity(name, summary, date, date, number)
                .Size(duration, height, width)
                .Target(Location, Type.Name);

            return builder.ToMediaItem();
        }
Exemplo n.º 31
0
        public static string GetMostCommonYearFromTracks(IAlbum album)
        {
            var yearsQuery = album.Tracks().Select(f => f.Year);

            return(GetCommonString(yearsQuery));
        }
Exemplo n.º 32
0
        public virtual IClip GetClip(ISecurityContext securityContext, IMediaFactory mediaFactory, IMetadataRepository mediaItemRepository, IArtist artist, IAlbum album)
        {
            var clip = mediaItemRepository.GetByTarget <IClip>(Location).FirstOrDefault();

            if (clip != null)
            {
                return(clip);
            }

            var  name     = GetClipName();
            var  summary  = string.Empty;
            var  number   = GetClipNumber();
            var  date     = GetDate();
            var  duration = TimeSpan.FromMinutes(10); //file != null && file.Properties != null ? file.Properties.Duration : TimeSpan.FromMinutes(5);
            uint height   = 480;                      //file != null && file.Properties != null ? (uint)file.Properties.VideoHeight : 480;
            uint width    = 640;                      //file != null && file.Properties != null ? (uint)file.Properties.VideoWidth : 640;

            var builder = new MediaItemBuilder <IClip>(securityContext, mediaFactory)
                          .Identity(name, summary, date, date, number)
                          .Size(duration, height, width)
                          .Creator(artist.Location, artist.Name)
                          .Catalog(album.Location, album.Name)
                          .Target(Location, Type.Name);

            return(builder.ToMediaItem());
        }
Exemplo n.º 33
0
        /// <summary>
        /// Initializes a new instance of an <see cref="Video" /> object.
        /// </summary>
        /// <param name="id">The ID that uniquely identifies this object. Specify int.MinValue for a new object.</param>
        /// <param name="parentId">The ID of the album that contains this object.</param>
        /// <param name="parentAlbum">The album that contains this object.</param>
        /// <param name="title">The title of this image.</param>
        /// <param name="hashKey">The hash key that uniquely identifies the original image file.</param>
        /// <param name="thumbnailFilename">The filename of the thumbnail image.</param>
        /// <param name="thumbnailWidth">The width (px) of the thumbnail image.</param>
        /// <param name="thumbnailHeight">The height (px) of the thumbnail image.</param>
        /// <param name="thumbnailSizeKb">The size (KB) of the thumbnail image.</param>
        /// <param name="originalFilename">The filename of the original image.</param>
        /// <param name="originalWidth">The width (px) of the original image.</param>
        /// <param name="originalHeight">The height (px) of the original image.</param>
        /// <param name="originalSizeKb">The size (KB) of the original image.</param>
        /// <param name="sequence">An integer that represents the order in which this image should appear when displayed.</param>
        /// <param name="createdByUsername">The user name of the account that originally added this object to the data store.</param>
        /// <param name="dateAdded">The date this image was added to the data store.</param>
        /// <param name="lastModifiedByUsername">The user name of the account that last modified this object.</param>
        /// <param name="dateLastModified">The date this object was last modified.</param>
        /// <param name="isPrivate">Indicates whether this object should be hidden from un-authenticated (anonymous) users.</param>
        /// <param name="isInflated">A bool indicating whether this object is fully inflated.</param>
        /// <param name="videoFile">A <see cref="FileInfo"/> object containing the original video file for this object. This is intended to be
        /// specified when creating a new media object from a file. Specify null when instantiating an object for an existing database
        /// record.</param>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.InvalidMediaObjectException">Thrown when
        /// <paramref name="videoFile"/> is specified (not null) and the file it refers to is not in the same directory
        /// as the parent album's directory.</exception>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name="videoFile"/> is specified (not null) and its file extension does not correspond to an video MIME
        /// type, as determined by the MIME type definition in the configuration file.</exception>
        /// <remarks>This constructor does not verify that <paramref name="videoFile"/> refers to a file type that is enabled in the
        /// configuration file.</remarks>
        internal Video(int id, int parentId, IAlbum parentAlbum, string title, string hashKey, string thumbnailFilename, int thumbnailWidth, int thumbnailHeight, int thumbnailSizeKb, string originalFilename, int originalWidth, int originalHeight, int originalSizeKb, int sequence, string createdByUsername, DateTime dateAdded, string lastModifiedByUsername, DateTime dateLastModified, bool isPrivate, bool isInflated, FileInfo videoFile)
        {
            System.Diagnostics.Debug.Assert(((originalFilename.Length > 0) || (videoFile != null)), "Invalid Video constructor arguments: The original filename or a FileInfo reference to the original file must be passed to the Video constructor.");

            this.Id                     = id;
            this.Title                  = title;
            this.Sequence               = sequence;
            this.Hashkey                = hashKey;
            this.CreatedByUserName      = createdByUsername;
            this.DateAdded              = dateAdded;
            this.LastModifiedByUserName = lastModifiedByUsername;
            this.DateLastModified       = dateLastModified;
            this.IsPrivate              = isPrivate;

            // Set parent to album instance if present, otherwise create default Album instance if the album ID
            // is specified. If neither are specified, do not set parent (client will, however, need to set the
            // parent before saving).
            if (parentAlbum != null)
            {
                this.Parent = parentAlbum;
            }
            else if (parentId != int.MinValue)
            {
                this.Parent = Factory.CreateAlbumInstance(parentId);
            }

            string parentPhysicalPath = this.Parent.FullPhysicalPathOnDisk;

            // Thumbnail image
            this.Thumbnail            = DisplayObject.CreateInstance(this, thumbnailFilename, thumbnailWidth, thumbnailHeight, DisplayObjectType.Thumbnail, new GenericThumbnailCreator(this));
            this.Thumbnail.FileSizeKB = thumbnailSizeKb;
            if (thumbnailFilename.Length > 0)
            {
                // The thumbnail is stored in either the album's physical path or an alternate location (if thumbnailPath config setting is specified) .
                string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(parentPhysicalPath, AppSetting.Instance.ThumbnailPath);
                this.Thumbnail.FileNamePhysicalPath = System.IO.Path.Combine(thumbnailPath, thumbnailFilename);
            }

            // Videos do not have an optimized version.
            this.Optimized = new NullObjects.NullDisplayObject();

            // Original video file
            this.Original = DisplayObject.CreateInstance(this, originalFilename, originalWidth, originalHeight, DisplayObjectType.Original, new NullObjects.NullDisplayObjectCreator());
            this.Original.ExternalHtmlSource = String.Empty;
            this.Original.ExternalType       = MimeTypeCategory.NotSet;

            if (videoFile != null)
            {
                this.Hashkey           = HelperFunctions.GetHashKeyUnique(videoFile);
                this.Original.FileInfo = videoFile;                 // Will throw InvalidMediaObjectException if the file's directory is not the same as the album's directory.

                if (this.Original.MimeType.TypeCategory != MimeTypeCategory.Video)
                {
                    throw new GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException(this.Original.FileInfo);
                }

                if (String.IsNullOrEmpty(title))
                {
                    this.Title = videoFile.Name;
                }
                this.Original.Width  = GalleryServerPro.Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.DefaultVideoPlayerWidth;
                this.Original.Height = GalleryServerPro.Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.DefaultVideoPlayerHeight;

                int fileSize = (int)(videoFile.Length / 1024);
                this.Original.FileSizeKB = (fileSize < 1 ? 1 : fileSize);                 // Very small files should be 1, not 0.
            }
            else
            {
                this.Original.FileNamePhysicalPath = System.IO.Path.Combine(parentPhysicalPath, originalFilename);
                this.Original.FileSizeKB           = originalSizeKb;
            }

            this.SaveBehavior   = Factory.GetMediaObjectSaveBehavior(this);
            this.DeleteBehavior = Factory.GetMediaObjectDeleteBehavior(this);

            this.IsInflated = isInflated;

            // Setting the previous properties has caused HasChanges = true, but we don't want this while
            // we're instantiating a new object. Reset to false.
            this.HasChanges = false;

            // Set up our event handlers.
            //this.Saving += new EventHandler(Image_Saving); // Don't need
            this.Saved += Image_Saved;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Find, or create if necessary, the album corresponding to the specified directory and set it as the
        /// child of the parentAlbum parameter.
        /// </summary>
        /// <param name="directory">The directory for which to obtain a matching album object.</param>
        /// <param name="parentAlbum">The album that contains the album at the specified directory.</param>
        /// <returns>Returns an album object corresponding to the specified directory and having the specified
        /// parent album.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="directory" /> or <paramref name="parentAlbum" /> is null.</exception>
        /// <exception cref="ArgumentException">Thrown when </exception>
        /// <exception cref="ArgumentException">Thrown when the full directory path of the parent of <paramref name="directory" /> does not match the
        /// directory path of <paramref name="parentAlbum" />.</exception>
        private IAlbum SynchronizeDirectory(DirectoryInfo directory, IAlbum parentAlbum)
        {
            #region Parameter validation

            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }

            if (parentAlbum == null)
            {
                throw new ArgumentNullException("parentAlbum");
            }

            if (!directory.Parent.FullName.Equals(parentAlbum.FullPhysicalPathOnDisk.TrimEnd(new char[] { Path.DirectorySeparatorChar }), StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException(String.Format("Error in SynchronizeDirectory(). directory.Parent.FullName='{0}'; parentAlbum.FullPhysicalPathOnDisk='{1}'", directory.Parent.FullName, parentAlbum.FullPhysicalPathOnDisk.TrimEnd(new char[] { Path.DirectorySeparatorChar })));
            }

            #endregion

            var childAlbum = (IAlbum)parentAlbum.GetChildGalleryObjects(GalleryObjectType.Album)
                             .FirstOrDefault(a => a.FullPhysicalPathOnDisk == directory.FullName);

            if (childAlbum != null)
            {
                // Found the album. Update properties.
                childAlbum.IsPrivate = (parentAlbum.IsPrivate ? true : childAlbum.IsPrivate);                 // Only set to private if parent is private
                childAlbum.RegenerateThumbnailOnSave = RebuildThumbnail;
            }
            else
            {
                // No album exists for this directory. Create a new one.
                childAlbum        = Factory.CreateEmptyAlbumInstance(parentAlbum.GalleryId);
                childAlbum.Parent = parentAlbum;

                string directoryName = directory.Name;
                childAlbum.Title = directoryName;
                //childAlbum.ThumbnailMediaObjectId = 0; // not needed
                childAlbum.DirectoryName          = directoryName;
                childAlbum.FullPhysicalPathOnDisk = Path.Combine(parentAlbum.FullPhysicalPathOnDisk, directoryName);
                childAlbum.IsPrivate = parentAlbum.IsPrivate;
            }

            childAlbum.IsSynchronized = true;

            if (childAlbum.IsNew || childAlbum.HasChanges)
            {
                HelperFunctions.UpdateAuditFields(childAlbum, UserName);
                childAlbum.Save();
            }

            // Commit the transaction to the database for every 100 media objects that are processed.
            if ((_synchStatus.CurrentFileIndex - _lastTransactionCommitFileIndex) >= 100)
            {
                HelperFunctions.CommitTransaction();
                HelperFunctions.BeginTransaction();
                _lastTransactionCommitFileIndex = _synchStatus.CurrentFileIndex;
            }

            return(childAlbum);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Initializes a new instance of an <see cref="Audio"/> object.
        /// </summary>
        /// <param name="id">The ID that uniquely identifies this object. Specify int.MinValue for a new object.</param>
        /// <param name="parentAlbum">The album that contains this object. This is a required parameter.</param>
        /// <param name="thumbnailFilename">The filename of the thumbnail image.</param>
        /// <param name="thumbnailWidth">The width (px) of the thumbnail image.</param>
        /// <param name="thumbnailHeight">The height (px) of the thumbnail image.</param>
        /// <param name="thumbnailSizeKb">The size (KB) of the thumbnail image.</param>
        /// <param name="optimizedFilename">The filename of the optimized image.</param>
        /// <param name="optimizedWidth">The width (px) of the optimized image.</param>
        /// <param name="optimizedHeight">The height (px) of the optimized image.</param>
        /// <param name="optimizedSizeKb">The size (KB) of the optimized image.</param>
        /// <param name="originalFilename">The filename of the original image.</param>
        /// <param name="originalWidth">The width (px) of the original image.</param>
        /// <param name="originalHeight">The height (px) of the original image.</param>
        /// <param name="originalSizeKb">The size (KB) of the original image.</param>
        /// <param name="sequence">An integer that represents the order in which this image should appear when displayed.</param>
        /// <param name="createdByUsername">The user name of the account that originally added this object to the data store.</param>
        /// <param name="dateAdded">The date this image was added to the data store.</param>
        /// <param name="lastModifiedByUsername">The user name of the account that last modified this object.</param>
        /// <param name="dateLastModified">The date this object was last modified.</param>
        /// <param name="isPrivate">Indicates whether this object should be hidden from un-authenticated (anonymous) users.</param>
        /// <param name="isInflated">A bool indicating whether this object is fully inflated.</param>
        /// <param name="audioFile">A <see cref="FileInfo"/> object containing the original audio file for this object. This is intended to be
        ///   specified when creating a new media object from a file. Specify null when instantiating an object for an existing database
        ///   record.</param>
        /// <param name="metadata">A collection of <see cref="Data.MetadataDto" /> instances containing metadata for the
        ///   object. Specify null if not available.</param>
        /// <exception cref="InvalidMediaObjectException">Thrown when
        /// <paramref name="audioFile"/> is specified (not null) and the file it refers to is not in the same directory
        /// as the parent album's directory.</exception>
        /// <exception cref="UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name="audioFile"/> is specified (not null) and its file extension does not correspond to an audio MIME
        /// type, as determined by the MIME type definition in the configuration file.</exception>
        /// <remarks>This constructor does not verify that <paramref name="audioFile"/> refers to a file type that is enabled in the
        /// configuration file.</remarks>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="parentAlbum" /> is null.</exception>
        internal Audio(int id, IAlbum parentAlbum, string thumbnailFilename, int thumbnailWidth, int thumbnailHeight, int thumbnailSizeKb, string optimizedFilename, int optimizedWidth, int optimizedHeight, int optimizedSizeKb, string originalFilename, int originalWidth, int originalHeight, int originalSizeKb, int sequence, string createdByUsername, DateTime dateAdded, string lastModifiedByUsername, DateTime dateLastModified, bool isPrivate, bool isInflated, FileInfo audioFile, IEnumerable <MetadataDto> metadata)
        {
            if (parentAlbum == null)
            {
                throw new ArgumentNullException("parentAlbum");
            }

            System.Diagnostics.Debug.Assert(((originalFilename.Length > 0) || (audioFile != null)), "Invalid Audio constructor arguments: The original filename or a FileInfo reference to the original file must be passed to the Audio constructor.");

            this.Id        = id;
            this.Parent    = parentAlbum;
            this.GalleryId = this.Parent.GalleryId;
            //this.Title = title;
            this.Sequence               = sequence;
            this.CreatedByUserName      = createdByUsername;
            this.DateAdded              = dateAdded;
            this.LastModifiedByUserName = lastModifiedByUsername;
            this.DateLastModified       = dateLastModified;
            this.IsPrivate              = isPrivate;
            this.IsWritable             = parentAlbum.IsWritable;

            this.SaveBehavior       = Factory.GetMediaObjectSaveBehavior(this);
            this.DeleteBehavior     = Factory.GetMediaObjectDeleteBehavior(this);
            this.MetadataReadWriter = Factory.GetMetadataReadWriter(this);

            string parentPhysicalPath = this.Parent.FullPhysicalPathOnDisk;

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(GalleryId);

            // Thumbnail image
            this.Thumbnail            = DisplayObject.CreateInstance(this, thumbnailFilename, thumbnailWidth, thumbnailHeight, DisplayObjectType.Thumbnail, new GenericThumbnailCreator(this));
            this.Thumbnail.FileSizeKB = thumbnailSizeKb;
            if (thumbnailFilename.Length > 0)
            {
                // The thumbnail is stored in either the album's physical path or an alternate location (if thumbnailPath config setting is specified) .
                string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(parentPhysicalPath, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);
                this.Thumbnail.FileNamePhysicalPath = Path.Combine(thumbnailPath, thumbnailFilename);
            }

            // Optimized audio
            this.Optimized            = DisplayObject.CreateInstance(this, optimizedFilename, optimizedWidth, optimizedHeight, DisplayObjectType.Optimized, new AudioOptimizedCreator(this));
            this.Optimized.FileSizeKB = optimizedSizeKb;
            if (optimizedFilename.Length > 0)
            {
                // Calcululate the full file path to the optimized audio. If the optimized filename is equal to the original filename, then no
                // optimized version exists, and we'll just point to the original. If the names are different, then there is a separate optimized
                // image file, and it is stored in either the album's physical path or an alternate location (if optimizedPath config setting is specified).
                string optimizedPath = parentPhysicalPath;

                if (optimizedFilename != originalFilename)
                {
                    optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(parentPhysicalPath, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);
                }

                this.Optimized.FileNamePhysicalPath = System.IO.Path.Combine(optimizedPath, optimizedFilename);
            }

            // Original audio file
            this.Original = DisplayObject.CreateInstance(this, originalFilename, originalWidth, originalHeight, DisplayObjectType.Original, new NullObjects.NullDisplayObjectCreator());
            this.Original.ExternalHtmlSource = String.Empty;
            this.Original.ExternalType       = MimeTypeCategory.NotSet;

            if (audioFile != null)
            {
                this.Optimized.FileInfo = audioFile;                // Will throw InvalidMediaObjectException if the file's directory is not the same as the album's directory.
                this.Original.FileInfo  = audioFile;                // Will throw InvalidMediaObjectException if the file's directory is not the same as the album's directory.

                if (this.Original.MimeType.TypeCategory != MimeTypeCategory.Audio)
                {
                    throw new Events.CustomExceptions.UnsupportedMediaObjectTypeException(this.Original.FileInfo);
                }

                this.Optimized.Width  = gallerySetting.DefaultAudioPlayerWidth;
                this.Optimized.Height = gallerySetting.DefaultAudioPlayerHeight;

                this.Original.Width  = gallerySetting.DefaultAudioPlayerWidth;
                this.Original.Height = gallerySetting.DefaultAudioPlayerHeight;

                int fileSize = (int)(audioFile.Length / 1024);
                this.Optimized.FileSizeKB = (fileSize < 1 ? 1 : fileSize);                // Very small files should be 1, not 0.
                this.Original.FileSizeKB  = (fileSize < 1 ? 1 : fileSize);                // Very small files should be 1, not 0.

                if (IsNew)
                {
                    ExtractMetadata();
                }
            }
            else
            {
                this.Original.FileNamePhysicalPath = Path.Combine(parentPhysicalPath, originalFilename);
                this.Original.FileSizeKB           = originalSizeKb;
            }

            if (metadata != null)
            {
                AddMeta(GalleryObjectMetadataItemCollection.FromMetaDtos(this, metadata));
            }

            this.IsInflated = isInflated;

            // Setting the previous properties has caused HasChanges = true, but we don't want this while
            // we're instantiating a new object. Reset to false.
            this.HasChanges = false;

            // Set up our event handlers.
            //this.Saving += new EventHandler(Image_Saving); // Don't need
            this.Saved += MediaObject_Saved;
        }
Exemplo n.º 36
0
 public ChannelController(UserManager <LoginUser> userManager, IChannel service, IAlbum albumService)
 {
     _userManager  = userManager;
     _service      = service;
     _albumService = albumService;
 }
Exemplo n.º 37
0
 /// <overloads>
 /// Permanently delete this album from the data store and optionally the hard drive.
 /// </overloads>
 /// <summary>
 /// Permanently delete this album from the data store and the hard drive. Validation is performed prior to deletion to ensure
 /// album can be safely deleted. The validation is contained in the method <see cref="ValidateBeforeAlbumDelete"/>
 /// and may be invoked separately if desired. No security checks are performed; the caller must ensure the user
 /// has permission to delete an album prior to invoking this method.
 /// </summary>
 /// <param name="album">The album to delete. If null, the function returns without taking any action.</param>
 /// <param name="deleteFromFileSystem">if set to <c>true</c> the files and directories associated with the album
 /// are deleted from the hard disk. Set this to <c>false</c> to delete only the database records.</param>
 /// <exception cref="ErrorHandler.CustomExceptions.CannotDeleteAlbumException">Thrown when the album does not meet the
 /// requirements for safe deletion. At this time this exception is thrown only when the album is or contains the user album
 /// parent album and user albums are enabled.</exception>
 public static void DeleteAlbum(IAlbum album)
 {
     DeleteAlbum(album, true);
 }
Exemplo n.º 38
0
        /// <summary>
        /// Update the album with the specified properties in the albumEntity parameter. The title is validated before
        /// saving, and may be altered to conform to business rules, such as removing HTML tags. After the object is persisted
        /// to the data store, the albumEntity parameter is updated with the latest properties from the album object and returned.
        /// If the user is not authorized to edit the album, no action is taken.
        /// </summary>
        /// <param name="albumEntity">An AlbumWebEntity instance containing data to be persisted to the data store.</param>
        /// <returns>Returns an AlbumWebEntity instance containing the data as persisted to the data store. Some properties,
        /// such as the Title property, may be slightly altered to conform to validation rules.</returns>
        public static AlbumWebEntity UpdateAlbumInfo(AlbumWebEntity albumEntity)
        {
            if (albumEntity.Owner == Resources.GalleryServerPro.UC_Album_Header_Edit_Album_No_Owner_Text)
            {
                albumEntity.Owner = String.Empty;
            }

            IAlbum album = Factory.LoadAlbumInstance(albumEntity.Id, false, true);

            // Update remaining properties if user has edit album permission.
            if (Util.IsUserAuthorized(SecurityActions.EditAlbum, album.Id, album.GalleryId, album.IsPrivate))
            {
                if (album.Title != albumEntity.Title)
                {
                    IGallerySettings gallerySetting = Factory.LoadGallerySetting(album.GalleryId);

                    album.Title = Util.CleanHtmlTags(albumEntity.Title, album.GalleryId);
                    if ((!album.IsRootAlbum) && (gallerySetting.SynchAlbumTitleAndDirectoryName))
                    {
                        // Root albums do not have a directory name that reflects the album's title, so only update this property for non-root albums.
                        album.DirectoryName = HelperFunctions.ValidateDirectoryName(album.Parent.FullPhysicalPath, album.Title, gallerySetting.DefaultAlbumDirectoryNameLength);
                    }
                }
                album.Summary   = Util.CleanHtmlTags(albumEntity.Summary, album.GalleryId);
                album.DateStart = albumEntity.DateStart.Date;
                album.DateEnd   = albumEntity.DateEnd.Date;
                if (albumEntity.IsPrivate != album.IsPrivate)
                {
                    if (!albumEntity.IsPrivate && album.Parent.IsPrivate)
                    {
                        throw new NotSupportedException("Cannot make album public: It is invalid to make an album public when it's parent album is private.");
                    }
                    album.IsPrivate = albumEntity.IsPrivate;
                    SynchIsPrivatePropertyOnChildGalleryObjects(album);
                }

                // If the owner has changed, update it, but only if the user is administrator.
                if (albumEntity.Owner != album.OwnerUserName)
                {
                    if (Util.IsUserAuthorized(SecurityActions.AdministerSite | SecurityActions.AdministerGallery, RoleController.GetGalleryServerRolesForUser(), album.Id, album.GalleryId, album.IsPrivate))
                    {
                        if (!String.IsNullOrEmpty(album.OwnerUserName))
                        {
                            // Another user was previously assigned as owner. Delete role since this person will no longer be the owner.
                            RoleController.DeleteGalleryServerProRole(album.OwnerRoleName);
                        }

                        if (UserController.GetUsersCurrentUserCanView(album.GalleryId).Contains(albumEntity.Owner))
                        {
                            // Util.SaveGalleryObject will make sure there is a role created for this user.
                            album.OwnerUserName = albumEntity.Owner;
                        }
                    }
                }

                GalleryObjectController.SaveGalleryObject(album);
                HelperFunctions.PurgeCache();

                // Refresh the entity object with the data from the album object, in case something changed. For example,
                // some javascript or HTML may have been removed from the Title or Summary fields.
                albumEntity.Title     = album.Title;
                albumEntity.Summary   = album.Summary;
                albumEntity.DateStart = album.DateStart;
                albumEntity.DateEnd   = album.DateEnd;
                albumEntity.IsPrivate = album.IsPrivate;
                albumEntity.Owner     = album.OwnerUserName;
            }

            return(albumEntity);
        }
Exemplo n.º 39
0
        public static string GetMostCommonArtistNameFromTracks(IAlbum album)
        {
            var artistQuery = album.Tracks().Select(f => f.Artist);

            return(GetCommonString(artistQuery));
        }
Exemplo n.º 40
0
 public static IAlbum GetInstanceAlbumImpl()
 {
     return(_album ?? (_album = new AlbumImpl()));
 }
Exemplo n.º 41
0
        /// <summary>
        /// Synchronizes the media object files in the <paramref name="directory" /> associated with the <paramref name="album" />.
        /// Does not act recursively.
        /// </summary>
        /// <param name="directory">The directory.</param>
        /// <param name="album">The album.</param>
        /// <exception cref="UnauthorizedAccessException">Thrown when the IIS app pool identity cannot access the files in the directory.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> or <paramref name="directory" /> is null.</exception>
        /// <exception cref="ArgumentException">Thrown when the full directory path of <paramref name="directory" /> does not match the directory path of
        /// <paramref name="album" />.</exception>
        private void SynchronizeMediaObjectFiles(DirectoryInfo directory, IAlbum album)
        {
            #region Parameter validation

            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }

            if (album == null)
            {
                throw new ArgumentNullException("album");
            }

            if (!directory.FullName.Equals(album.FullPhysicalPath, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Error in SynchronizeMediaObjectFiles(): The full directory path of the parameter 'directory' does not match the directory path of the parameter 'album'. directory.FullName='{0}'; album.FullPhysicalPath='{1}'", directory.FullName, album.FullPhysicalPath));
            }

            #endregion

            //Update the media object table in the database with the file attributes of all
            //files in the directory passed to this function. Skip any hidden files.
            FileInfo[] files;
            try
            {
                files = directory.GetFiles();
            }
            catch (UnauthorizedAccessException)
            {
                _synchStatus.SkippedMediaObjects.Add(new KeyValuePair <string, string>(directory.Name, Resources.SynchronizationStatus_Restricted_Directory_Msg));
                throw;
            }

            // First sort by the filename.
            Array.Sort(files, (a, b) => String.Compare(a.Name, b.Name, StringComparison.InvariantCultureIgnoreCase));             // Don't use Ordinal or OrdinalIgnoreCase, as it sorts unexpectedly (e.g. 100.pdf comes before _100.pdf)

            foreach (FileInfo file in files)
            {
                if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    _synchStatus.SkippedMediaObjects.Add(new KeyValuePair <string, string>(file.FullName.Remove(0, _fullMediaObjectPathLength + 1), Resources.SynchronizationStatus_Hidden_File_Msg));
                    continue;
                }

                #region Process thumbnail or optimized image

                if (file.Name.StartsWith(_thumbnailPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    // We have a thumbnail image. If we are storing thumbnails in a different directory, delete the file, but only if the path
                    // is writeable. The user may have just specified a new thumbnail path, and we need to delete all the previous thumbnails
                    // from their original location.
                    if (_thumbnailRootPath != GallerySettings.FullMediaObjectPath && !GallerySettings.MediaObjectPathIsReadOnly)
                    {
                        File.Delete(file.FullName);
                    }
                    continue;
                }

                if (file.Name.StartsWith(_optimizedPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    // We have an optimized image. If we are storing optimized images in a different directory, delete the file, but only if the path
                    // is writeable. The user may have just specified a new optimized path, and we need to delete all the previous optimized images
                    // from their original location.
                    if (_optimizedRootPath != GallerySettings.FullMediaObjectPath && !GallerySettings.MediaObjectPathIsReadOnly)
                    {
                        File.Delete(file.FullName);
                    }
                    continue;
                }

                #endregion

                // See if this file is an existing media object.
                var mediaObject = album
                                  .GetChildGalleryObjects(GalleryObjectType.MediaObject)
                                  .FirstOrDefault(mo => mo.Original.FileNamePhysicalPath.Equals(file.FullName, StringComparison.OrdinalIgnoreCase));

                if (mediaObject != null)
                {
                    // Found an existing media object matching the file on disk. Update properties, but only if its file extension
                    // is enabled. (If this is a media object that had been added to Gallery Server but its file type was
                    // subsequently disabled, we do not want to synchronize it - we want its info in the data store to be deleted.)
                    if (HelperFunctions.IsFileAuthorizedForAddingToGallery(file.Name, album.GalleryId))
                    {
                        UpdateExistingMediaObject(mediaObject);
                    }
                }
                else
                {
                    // No media object exists for this file. Create a new one.
                    CreateNewMediaObject(album, file);
                }

                int newFileIndex = _synchStatus.CurrentFileIndex + 1;
                if (newFileIndex < _synchStatus.TotalFileCount)
                {
                    var persistToDatabase = (_synchStatus.CurrentFileIndex % 100) == 0;                     // Save to DB every 100 files

                    UpdateStatus(newFileIndex, file.DirectoryName, file.Name, persistToDatabase: persistToDatabase);
                }

                lock (_synchStatus)
                {
                    if (_synchStatus.ShouldTerminate)
                    {
                        // Immediately set this property back to false so that we don't trigger this code again, then throw a special exception
                        // that will be caught and used to cancel the synch.
                        _synchStatus.Update(SynchronizationState.Aborted, null, String.Empty, null, String.Empty, false, true);
                        throw new SynchronizationTerminationRequestedException();
                    }
                }
            }

            // Synchronize any external media objects previously added. No recursive action.
            SynchronizeExternalMediaObjects(album);

            DeleteOrphanedMediaObjectRecords(album);

            DeleteOrphanedThumbnailAndOptimizedImages(album);
        }
Exemplo n.º 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AlbumDeleteBehavior"/> class.
 /// </summary>
 /// <param name="albumObject">The album object.</param>
 public AlbumDeleteBehavior(IAlbum albumObject)
 {
     this._albumObject = albumObject;
 }
Exemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of a <see cref="Video" /> object.
 /// </summary>
 /// <param name="videoFile">A <see cref="FileInfo"/> object containing the original video file for this object. This is intended to be
 /// specified when creating a new media object from a file. Specify null when instantiating an object for an existing database
 /// record.</param>
 /// <param name="parentAlbum">The album that contains this object. May be null.</param>
 /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.InvalidMediaObjectException">Thrown when
 /// <paramref name="videoFile"/> refers to a file that is not in the same directory as the parent album's directory.</exception>
 /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException">Thrown when
 /// <paramref name="videoFile"/> is specified (not null) and its file extension does not correspond to an video MIME
 /// type, as determined by the MIME type definition in the configuration file.</exception>
 /// <remarks>This constructor does not verify that <paramref name="videoFile"/> refers to a file type that is enabled in the
 /// configuration file.</remarks>
 internal Video(System.IO.FileInfo videoFile, IAlbum parentAlbum)
     : this(int.MinValue, parentAlbum != null ? parentAlbum.Id : int.MinValue, parentAlbum, string.Empty, string.Empty, string.Empty,
            int.MinValue, int.MinValue, int.MinValue, string.Empty, int.MinValue, int.MinValue, int.MinValue, int.MinValue,
            String.Empty, DateTime.MinValue, String.Empty, DateTime.MinValue, parentAlbum != null ? parentAlbum.IsPrivate : false, false, videoFile)
 {
 }
 public void DeletePhoto(IAlbum album)
 {
     my_album.Remove(album);
 }
Exemplo n.º 45
0
 public void Maintenance(IAlbum album, int optionIndex)
 {
     Console.WriteLine(@"{0} process for {1} ({2})....", album.Media.MaintenanceOptions[optionIndex], album.Name, album.Media.GetMediaType());
 }
Exemplo n.º 46
0
 public Album(IAlbum album)
 {
     _album      = album;
     _pictures   = new ReadOnlyCollection <IPicture>(album.Pictures.ToArray());
     _lastUpdate = _pictures.Max(p => p.Timestamp);
 }
Exemplo n.º 47
0
 public AlbumDescription(IAlbum album)
 {
     Id       = album.Id;
     Name     = album.Name;
     CoverArt = album.CoverArt;
 }
Exemplo n.º 48
0
 public IList <ITrack> GetFromAlbum(IAlbum album)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 49
0
 public AlbumManager(IAlbum implementation)
 {
     dal = implementation;
 }
Exemplo n.º 50
0
        public static string GetMostCommonAlbumTitleFromTracks(IAlbum album)
        {
            var albumQuery = album.Tracks().Select(f => f.Album);

            return(GetCommonString(albumQuery));
        }
Exemplo n.º 51
0
 /// <summary>
 /// Persist the specified album to the data store. Return the ID of the album.
 /// </summary>
 /// <param name="album">An instance of <see cref="IAlbum"/> to persist to the data store.</param>
 /// <returns>
 /// Return the ID of the album. If this is a new album and a new ID has been
 /// assigned, then this value has also been assigned to the ID property of the object.
 /// </returns>
 public override int Album_Save(IAlbum album)
 {
     return(Album.Save(album));
 }
Exemplo n.º 52
0
 /// <summary>
 /// Permanently delete the specified album from the data store, including any
 /// child albums and media objects (cascading delete). This action cannot be undone.
 /// </summary>
 /// <param name="album">The <see cref="IAlbum"/> to delete from the data store.</param>
 public override void Album_Delete(IAlbum album)
 {
     Album.Delete(album);
 }
Exemplo n.º 53
0
        public override ITrack GetTrack(ISecurityContext securityContext, IMediaFactory mediaFactory, IMetadataRepository mediaItemRepository, IAudioStreamFactory audioStreamFactory, IArtist artist, IAlbum album)
        {
            var track = mediaItemRepository.GetByTarget <ITrack>(Location).FirstOrDefault();

            //if (track != null)
            //return track;

            if (id3v2Tag == null)
            {
                if (track != null)
                {
                    return(track);
                }

                var builder = new MediaItemBuilder <ITrack>(securityContext, mediaFactory)
                              .Identity("Unknown", string.Empty)
                              .Creator(artist.Location, artist.Name)
                              .Catalog(album.Location, album.Name)
                              .Target(Location, Type.Name);

                return(builder.ToMediaItem());
            }

            var name    = id3v2Tag.Title != null ? id3v2Tag.Title : "Unknown Track";
            var summary = id3v2Tag.Lyrics ?? string.Empty;

            var recordDate = DateTime.MinValue;

            if (id3v2Tag != null && id3v2Tag.RecordingDate > DateTime.MinValue)
            {
                recordDate = id3v2Tag.RecordingDate;
            }
            else if (id3v1Tag != null && id3v1Tag.Year >= DateTime.MinValue.Year && id3v1Tag.Year <= DateTime.MaxValue.Year)
            {
                recordDate = new DateTime((int)id3v1Tag.Year, 1, 1);
            }

            var releaseDate = DateTime.MinValue;

            if (id3v2Tag != null && id3v2Tag.ReleaseDate > DateTime.MinValue)
            {
                releaseDate = id3v2Tag.ReleaseDate;
            }
            else if (id3v1Tag != null && id3v1Tag.Year >= DateTime.MinValue.Year && id3v1Tag.Year <= DateTime.MaxValue.Year)
            {
                releaseDate = new DateTime((int)id3v1Tag.Year, 1, 1);
            }

            var number   = id3v2Tag.Track;
            var duration = id3v2Tag.Duration;

            if (duration == TimeSpan.Zero)
            {
                using (var audioStream = audioStreamFactory.CreateAudioStream(Location))
                {
                    if (audioStream != null)
                    {
                        duration = audioStream.Duration;
                    }
                }
            }

            var thumbnail     = Guid.Empty.ToUrn();
            var thumbnailData = id3v2Tag.Pictures != null && id3v2Tag.Pictures.Length > 0 ? id3v2Tag.Pictures[0].Data.ToArray() : new byte[0];

            var trackId = track != null ? track.Location : Guid.NewGuid().ToUrn();

            var fullBuilder = new MediaItemBuilder <ITrack>(securityContext, mediaFactory)
                              .Identity(name, summary, recordDate, releaseDate, number, trackId)
                              .Size(duration)
                              .Creator(artist.Location, artist.Name)
                              .Catalog(album.Location, album.Name)
                              .Target(Location, Type.Name)
                              .Thumbnail(thumbnail, thumbnailData);

            return(fullBuilder.ToMediaItem());
        }
Exemplo n.º 54
0
        public void Delete(IAlbum album)
        {
            Checks.Argument.IsNotNull(album, "album");

            _repo.Remove(album);
        }
Exemplo n.º 55
0
 public async Task <IEnumerable <ITrack> > GetTracksByAlbum(IAlbum album)
 {
     return(await Repository.GetTracksByAlbum(album));
 }
Exemplo n.º 56
0
        private string BuildMenuString()
        {
            if (!this.GalleryPage.ShowAlbumBreadCrumb)
            {
                return(String.Empty);
            }

            string menuString  = string.Empty;
            string appPath     = Utils.GetCurrentPageUrl();
            bool   renderLinks = GalleryPage.GalleryControl.AllowUrlOverride;

            IAlbum album = GalleryPage.GetAlbum();
            IGalleryServerRoleCollection roles = this.GalleryPage.GetGalleryServerRolesForUser();
            string dividerText      = Resources.GalleryServerPro.UC_Album_Menu_Album_Divider_Text;
            bool   foundTopAlbum    = false;
            bool   foundBottomAlbum = false;

            while (!foundTopAlbum)
            {
                // Iterate through each album and it's parents, working the way toward the top. For each album, build up a breadcrumb menu item.
                // Eventually we will reach one of three situations: (1) a virtual album that contains the child albums, (2) an album the current
                // user does not have permission to view, or (3) the actual top-level album.
                if (album.IsVirtualAlbum)
                {
                    menuString    = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, appPath, Resources.GalleryServerPro.Site_Virtual_Album_Title));
                    foundTopAlbum = true;
                }
                else if (!Utils.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, album.Id, album.GalleryId, album.IsPrivate))
                {
                    // User is not authorized to view this album. If the user has permission to view more than one top-level album, then we want
                    // to display an "All albums" link. To determine this, load the root album. If a virtual album is returned, then we know the
                    // user has access to more than one top-level album. If it is an actual album (with a real ID and persisted in the data store),
                    // that means that album is the only top-level album the user can view, and thus we do not need to create a link that is one
                    // "higher" than that album.
                    IAlbum rootAlbum = Factory.LoadRootAlbum(this.GalleryPage.GalleryId, SecurityActions.ViewAlbumOrMediaObject | SecurityActions.ViewOriginalImage, GalleryPage.GetGalleryServerRolesForUser(), Utils.IsAuthenticated);
                    if (rootAlbum.IsVirtualAlbum)
                    {
                        menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, appPath, Resources.GalleryServerPro.Site_Virtual_Album_Title));
                    }
                    foundTopAlbum = true;
                }
                else
                {
                    // Regular album somewhere in the hierarchy. Create a breadcrumb link.
                    string hyperlinkIdString = String.Empty;
                    if (!foundBottomAlbum)
                    {
                        hyperlinkIdString = " id=\"currentAlbumLink\"";                         // ID is referenced when inline editing an album's title
                        foundBottomAlbum  = true;
                    }

                    if (renderLinks)
                    {
                        menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a{1} href=\"{2}\">{3}</a>", dividerText, hyperlinkIdString, Utils.AddQueryStringParameter(appPath, String.Concat("aid=", album.Id)), Utils.RemoveHtmlTags(album.Title)));
                    }
                    else
                    {
                        menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} {1}", dividerText, Utils.RemoveHtmlTags(album.Title)));
                    }
                }

                if (album.Parent is GalleryServerPro.Business.NullObjects.NullGalleryObject)
                {
                    foundTopAlbum = true;
                }
                else
                {
                    album = (IAlbum)album.Parent;
                }
            }

            if (menuString.Length > (dividerText.Length + 2))
            {
                menuString = menuString.Substring(dividerText.Length + 2);                 // Remove the first divider character
            }

            return(menuString);
        }
        static void Main(string[] args)
        {
            int albumId       = 0;
            int menuSelection = 0;

            string name;

            Album root, album;
            Photo photo;

            root = new Album("Root", 0);
            do
            {
                Console.WriteLine("~~ Menu ~~");
                Console.WriteLine("1 - To create new album");
                Console.WriteLine("2 - To create new photo");
                Console.WriteLine("3 - To rename items");
                Console.WriteLine("4 - To delete item");
                Console.WriteLine("9 - To show all");
                Console.WriteLine("0 - To exit");

                menuSelection = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(menuSelection);


                switch (menuSelection)
                {
                case 1:
                    Console.Clear();

                    Console.WriteLine("Please enter an album name (0 - Go back to Menu)");
                    name = Convert.ToString(Console.ReadLine());

                    if (name == "0")
                    {
                        break;
                    }
                    Console.WriteLine("Album '" + name + "' created!");
                    album = new Album(name, GetId());
                    root.AddPhoto(album);

                    break;

                case 2:
                    Console.Clear();
                    Console.WriteLine("Please enter a photo name (0 - Go back to Menu)");
                    name = Convert.ToString(Console.ReadLine());

                    if (name == "0")
                    {
                        break;
                    }
                    Console.WriteLine("Photo '" + name + "' created!");
                    photo = new Photo(name, GetId());
                    root.AddPhoto(photo);
                    break;

                case 3:
                    Console.Clear();
                    root.Show(0);
                    Console.WriteLine("Enter item Id");
                    int id = Convert.ToInt32(Console.ReadLine());

                    Console.WriteLine("Enter new name");
                    root.GetPhoto(id).Rename(Console.ReadLine());


                    break;

                case 4:
                    Console.Clear();
                    root.Show(0);
                    Console.WriteLine("Enter item Id to delete");
                    int deleteId = Convert.ToInt32(Console.ReadLine());

                    root.DeletePhoto(root.GetPhoto(deleteId));


                    break;


                case 5:
                    Console.Clear();
                    root.Show(0);
                    Console.WriteLine("Enter two item id ([add_me] [to_this_ALBUM]");
                    int addId  = Convert.ToInt32(Console.ReadLine());
                    int thisId = Convert.ToInt32(Console.ReadLine());

                    Album  addToAlbum = null;
                    IAlbum item       = null;


                    addToAlbum = (Album)root.GetPhoto(thisId);
                    item       = root.GetPhoto(addId);

                    addToAlbum.AddPhoto(item);
                    root.DeletePhoto(item);
                    root.Show(0);
                    break;

                case 9:
                    Console.Clear();
                    root.Show(0);
                    break;
                }
            } while (menuSelection != 0);

            int GetId()
            {
                albumId++;
                return(albumId);
            }

            Console.WriteLine("Exit from switch-case");
            Console.ReadKey();
        }
Exemplo n.º 58
0
        /// <summary>
        /// Delete any thumbnail and optimized images that do not have matching media objects.
        /// This can occur when a user manually transfers (e.g. uses Windows Explorer)
        /// original images to a new directory and leaves the thumbnail and optimized
        /// images in the original directory or when a user deletes the original media file in
        /// Explorer. This function *only* deletes files that begin the the thumbnail and optimized
        /// prefix (e.g. zThumb_, zOpt_).
        /// </summary>
        /// <param name="album">The album whose directory is to be processed for orphaned image files.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception>
        private void DeleteOrphanedThumbnailAndOptimizedImages(IAlbum album)
        {
            if (album == null)
            {
                throw new ArgumentNullException("album");
            }

            // STEP 1: Get list of directories that may contain thumbnail or optimized images for the current album
            string originalPath  = album.FullPhysicalPathOnDisk;
            string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPathOnDisk, GallerySettings.FullThumbnailPath, GallerySettings.FullMediaObjectPath);
            string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPathOnDisk, GallerySettings.FullOptimizedPath, GallerySettings.FullMediaObjectPath);

            List <string> albumPaths = new List <string>(3);

            // The original path may contain thumbnails or optimized images when the thumbnail/optimized path is the same as the original path
            if ((GallerySettings.FullThumbnailPath.Equals(GallerySettings.FullMediaObjectPath, StringComparison.OrdinalIgnoreCase)) ||
                (GallerySettings.FullOptimizedPath.Equals(GallerySettings.FullMediaObjectPath, StringComparison.OrdinalIgnoreCase)))
            {
                albumPaths.Add(originalPath);
            }

            if (!albumPaths.Contains(thumbnailPath))
            {
                albumPaths.Add(thumbnailPath);
            }

            if (!albumPaths.Contains(optimizedPath))
            {
                albumPaths.Add(optimizedPath);
            }


            string thumbnailPrefix = GallerySettings.ThumbnailFileNamePrefix;
            string optimizedPrefix = GallerySettings.OptimizedFileNamePrefix;

            IGalleryObjectCollection mediaObjects = album.GetChildGalleryObjects(GalleryObjectType.MediaObject);

            // STEP 2: Loop through each path and make sure all thumbnail and optimized files in each directory have
            // matching media objects. Delete any files that do not.
            foreach (string albumPath in albumPaths)
            {
                if (!Directory.Exists(albumPath))
                {
                    return;
                }

                DirectoryInfo directory = new DirectoryInfo(albumPath);

                // Loop through each file in the directory.
                FileInfo[] files;
                try
                {
                    files = directory.GetFiles();
                }
                catch (UnauthorizedAccessException)
                {
                    return;
                }

                var queueItems = GetCurrentAndCompleteMediaQueueItems();

                foreach (FileInfo file in files)
                {
                    if ((file.Name.StartsWith(thumbnailPrefix, StringComparison.OrdinalIgnoreCase)) || (file.Name.StartsWith(optimizedPrefix, StringComparison.OrdinalIgnoreCase)))
                    {
                        // This file is a thumbnail or optimized file.

                        // TEST 1: Check to see if any media object in this album refers to it.
                        var foundMediaObject = false;
                        foreach (IGalleryObject mediaObject in mediaObjects)
                        {
                            if ((mediaObject.Optimized.FileName.Equals(file.Name, StringComparison.OrdinalIgnoreCase)) ||
                                (mediaObject.Thumbnail.FileName.Equals(file.Name, StringComparison.OrdinalIgnoreCase)))
                            {
                                foundMediaObject = true;
                                break;
                            }
                        }

                        if (!foundMediaObject)
                        {
                            // TEST 2: Maybe the encoder engine is currently creating the file or just finished it.

                            // First check to see if we started processing a new media item since we started this loop.
                            // If so, add it to our list of queue items.
                            var currentQueueItem = MediaConversionQueue.Instance.GetCurrentMediaQueueItem();
                            if (currentQueueItem != null && !queueItems.Any(mq => mq.MediaQueueId == currentQueueItem.MediaQueueId))
                            {
                                queueItems = queueItems.Concat(new[] { currentQueueItem });
                            }

                            // See if this file is mentioned in any of the media queue items
                            foundMediaObject = queueItems.Any(mq => mq.StatusDetail.Contains(file.Name));
                        }

                        if (!foundMediaObject)
                        {
                            // No media object in this album refers to this thumbnail or optimized image. Smoke it!
                            try
                            {
                                file.Delete();
                            }
                            catch (IOException ex)
                            {
                                // An exception occurred, probably because the account ASP.NET is running under does not
                                // have permission to delete the file. Let's record the error, but otherwise ignore it.
                                EventController.RecordError(ex, AppSetting.Instance, _galleryId, Factory.LoadGallerySettings());
                            }
                            catch (SecurityException ex)
                            {
                                // An exception occurred, probably because the account ASP.NET is running under does not
                                // have permission to delete the file. Let's record the error, but otherwise ignore it.
                                EventController.RecordError(ex, AppSetting.Instance, _galleryId, Factory.LoadGallerySettings());
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                // An exception occurred, probably because the account ASP.NET is running under does not
                                // have permission to delete the file. Let's record the error, but otherwise ignore it.
                                EventController.RecordError(ex, AppSetting.Instance, _galleryId, Factory.LoadGallerySettings());
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 59
0
        /// <summary>
        /// In certain cases, the web-based installer creates a text file in the App Data directory that is meant as a signal to this
        /// code that additional setup steps are required. If this file is found, carry out the additional actions. This file is
        /// created in the SetFlagForMembershipConfiguration() method of pages\install.ascx.cs.
        /// </summary>
        internal static void ProcessInstallerFile()
        {
            string filePath = Path.Combine(AppSetting.Instance.PhysicalApplicationPath, Path.Combine(GlobalConstants.AppDataDirectory, GlobalConstants.InstallerFileName));

            if (!File.Exists(filePath))
            {
                return;
            }

            string adminUserName;
            string adminPwd;
            string adminEmail;

            using (StreamReader sw = File.OpenText(filePath))
            {
                adminUserName = sw.ReadLine();
                adminPwd      = sw.ReadLine();
                adminEmail    = sw.ReadLine();
            }

            HelperFunctions.BeginTransaction();

            #region Create the Sys Admin role.

            // Create the Sys Admin role. If it already exists, make sure it has AllowAdministerSite permission.
            string sysAdminRoleName = Resources.GalleryServerPro.Installer_Sys_Admin_Role_Name;
            if (!RoleController.RoleExists(sysAdminRoleName))
            {
                RoleController.CreateRole(sysAdminRoleName);
            }

            IGalleryServerRole role = Factory.LoadGalleryServerRole(sysAdminRoleName);
            if (role == null)
            {
                role = Factory.CreateGalleryServerRoleInstance(sysAdminRoleName, true, true, true, true, true, true, true, true, true, true, false);
                role.RootAlbumIds.Add(Factory.LoadRootAlbumInstance().Id);
                role.Save();
            }
            else
            {
                // Role already exists. Make sure it has Sys Admin permission.
                if (!role.AllowAdministerSite)
                {
                    role.AllowAdministerSite = true;
                    role.Save();
                }
            }

            #endregion

            #region Create the Sys Admin user account.

            // Create the Sys Admin user account. Will throw an exception if the name is already in use.
            try
            {
                CreateUser(adminUserName, adminPwd, adminEmail);
            }
            catch (MembershipCreateUserException ex)
            {
                if (ex.StatusCode == MembershipCreateStatus.DuplicateUserName)
                {
                    // The user already exists. Update the password and email address to our values.
                    UserEntity user = GetUser(adminUserName, true);
                    ChangePassword(user.UserName, GetPassword(user.UserName), adminPwd);
                    user.Email = adminEmail;
                    UpdateUser(user);
                }
            }

            // Add the Sys Admin user to the Sys Admin role.
            if (!RoleController.IsUserInRole(adminUserName, sysAdminRoleName))
            {
                RoleController.AddUserToRole(adminUserName, sysAdminRoleName);
            }

            #endregion

            #region Create sample album and image

            if (!Config.GetCore().MediaObjectPathIsReadOnly)
            {
                DateTime currentTimestamp = DateTime.Now;
                IAlbum   sampleAlbum      = null;
                foreach (IAlbum album in Factory.LoadRootAlbumInstance().GetChildGalleryObjects(GalleryObjectType.Album))
                {
                    if (album.DirectoryName == "Samples")
                    {
                        sampleAlbum = album;
                        break;
                    }
                }
                if (sampleAlbum == null)
                {
                    // Create sample album.
                    sampleAlbum                        = Factory.CreateAlbumInstance();
                    sampleAlbum.Parent                 = Factory.LoadRootAlbumInstance();
                    sampleAlbum.Title                  = "Samples";
                    sampleAlbum.DirectoryName          = "Samples";
                    sampleAlbum.Summary                = "Welcome to Gallery Server Pro!";
                    sampleAlbum.CreatedByUserName      = adminUserName;
                    sampleAlbum.DateAdded              = currentTimestamp;
                    sampleAlbum.LastModifiedByUserName = adminUserName;
                    sampleAlbum.DateLastModified       = currentTimestamp;
                    sampleAlbum.Save();
                }

                // Look for sample image in sample album.
                IGalleryObject sampleImage = null;
                foreach (IGalleryObject image in sampleAlbum.GetChildGalleryObjects(GalleryObjectType.Image))
                {
                    if (image.Original.FileName == Constants.SAMPLE_IMAGE_FILENAME)
                    {
                        sampleImage = image;
                        break;
                    }
                }

                if (sampleImage == null)
                {
                    // Sample image not found. Pull image from assembly, save to disk, and create a media object from it.
                    string sampleDirPath       = Path.Combine(AppSetting.Instance.MediaObjectPhysicalPath, sampleAlbum.DirectoryName);
                    string sampleImageFilename = HelperFunctions.ValidateFileName(sampleDirPath, Constants.SAMPLE_IMAGE_FILENAME);
                    string sampleImageFilepath = Path.Combine(sampleDirPath, sampleImageFilename);

                    System.Reflection.Assembly asm = Assembly.GetExecutingAssembly();
                    using (Stream stream = asm.GetManifestResourceStream(String.Concat("GalleryServerPro.Web.gs.images.", Constants.SAMPLE_IMAGE_FILENAME)))
                    {
                        if (stream != null)
                        {
                            BinaryWriter bw     = new BinaryWriter(File.Create(sampleImageFilepath));
                            byte[]       buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            bw.Write(buffer);
                            bw.Flush();
                            bw.Close();
                        }
                    }

                    if (File.Exists(sampleImageFilepath))
                    {
                        IGalleryObject image = Factory.CreateImageInstance(new FileInfo(sampleImageFilepath), sampleAlbum);
                        image.Title                  = "Margaret, Skyler and Roger Martin (December 2008)";
                        image.CreatedByUserName      = adminUserName;
                        image.DateAdded              = currentTimestamp;
                        image.LastModifiedByUserName = adminUserName;
                        image.DateLastModified       = currentTimestamp;
                        image.Save();
                    }
                }
            }

            #endregion

            HelperFunctions.CommitTransaction();
            HelperFunctions.PurgeCache();

            File.Delete(filePath);
        }
 public void AddPhoto(IAlbum album)
 {
     my_album.Add(album);
 }