コード例 #1
0
ファイル: SongService.cs プロジェクト: alexpopescu021/PAW
        public Song CreateNewSong(string artist, string genre, string title, decimal price, string path)
        {
            var song = Song.Create(artist, genre, title, price, path);

            song = songRepository.Add(song);
            persistanceContext.SaveChanges();

            return(song);
        }
コード例 #2
0
        private Song CreateNewSong()
        {
            var song = new Song();

            _songRepository.Add(song);
            return(song);
        }
コード例 #3
0
        private Song ImportSong(string songFileName, FileInfo coverImageFile, DateTimeOffset importDate, ISongRepository songRepository, IImageService imageService)
        {
            using (var songTagFile = TagLib.File.Create(songFileName))
            {
                var tagValidationResults = ValidateTags(songTagFile);
                if (tagValidationResults.Any())
                {
                    _logger.LogWarning("File {0} is invalid. {1}", songFileName, string.Join(", ", tagValidationResults));
                    return(null);
                }

                var songFileInfo         = new System.IO.FileInfo(songFileName);
                var relativeSongFileName = Path.Combine(songFileInfo.Directory.Name, songFileInfo.Name);

                var song = songRepository.GetByFileNameOrDefault(relativeSongFileName);
                if (song == null)
                {
                    song = songRepository.Create();
                    songRepository.Add(song);
                }

                song.Map(
                    title: songTagFile.Tag.Title,
                    album: songTagFile.Tag.Album,
                    artist: songTagFile.Tag.FirstPerformer,
                    coverImageFile: coverImageFile,
                    duration: songTagFile.Properties.Duration,
                    fileName: relativeSongFileName,
                    imageService: imageService);

                song.LastImportDate = importDate;

                return(song);
            }
        }
コード例 #4
0
        public async Task <SignalRMessage> ExecuteAsync(AddSongCommand command, SignalRMessage previousResult)
        {
            var user = await _userRepository.GetById(command.AddedByUser);

            var song = new Song()
            {
                AddedByUser     = command.AddedByUser,
                AddedAt         = DateTimeOffset.UtcNow,
                Author          = command.Author,
                Description     = command.Description,
                Duration        = command.Duration,
                Finished        = false,
                Id              = Guid.NewGuid(),
                NoAuthor        = command.NoAuthor,
                NoDescription   = command.NoDescription,
                Thumbnail       = command.Thumbnail,
                Title           = command.Title,
                Url             = command.Url,
                ViewCount       = command.ViewCount,
                AddedByUserName = user.UserName
            };

            await _songRepository.Add(song);

            return(new SignalRMessage
            {
                Arguments = new object[] { song },
                GroupName = null,
                Target = "addSongCommandNotification",
            });
        }
コード例 #5
0
        private static void CreateAndAddVotingCandidate(int number, int numberOfVotes, IVotingCandidateRepository votingCandidateRepository, IVoteRepository voteRepository, ISongRepository songRepository)
        {
            var song = songRepository.Create();

            song.Title             = "SongRepositoryTests" + number;
            song.DurationInSeconds = 120;
            song.FileName          = "SongRepositoryTests.mp3";

            songRepository.Add(song);

            var votingCandidate = votingCandidateRepository.Create();

            votingCandidate.SongId       = song.Id;
            votingCandidate.Song         = song;
            votingCandidate.DisplayOrder = number;

            votingCandidateRepository.Add(votingCandidate);

            foreach (var index in Enumerable.Range(0, numberOfVotes))
            {
                var vote = voteRepository.Create();
                vote.VotingCandidateId = votingCandidate.Id;
                vote.VotingCandidate   = votingCandidate;
                vote.UserIdentifier    = Guid.NewGuid();

                voteRepository.Add(vote);
            }
        }
コード例 #6
0
        public async Task <ServiceResult> Add(SongResultModel model)
        {
            var serviceResult = new ServiceResult();

            var linksResult = model.Links == null || model.Links.Count == 0 ? new DatabaseManyResult <LinkModel>()
            {
                Success = true, Entities = null
            } : await _linkRepository.GetMany(model.Links, 0, 50);

            if (!linksResult.Success)
            {
                serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                serviceResult.Error.Description = linksResult.Message;
                return(serviceResult);
            }
            var artistsResult = model.Artists == null || model.Artists.Count == 0 ? new DatabaseManyResult <ArtistModel>()
            {
                Success = true, Entities = null
            } : await _artistRepository.GetMany(model.Artists, 0, 50);

            if (!artistsResult.Success)
            {
                serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                serviceResult.Error.Description = artistsResult.Message;
                return(serviceResult);
            }
            var genresResult = model.Genres == null || model.Genres.Count == 0 ? new DatabaseManyResult <GenreModel>()
            {
                Success = true, Entities = null
            } : await _genreRepository.GetMany(model.Genres, 0, 50);

            if (!genresResult.Success)
            {
                serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                serviceResult.Error.Description = genresResult.Message;
                return(serviceResult);
            }

            var modelObject = new SongModel()
            {
                Id      = model.Id,
                Name    = model.Name,
                ArtId   = model.ArtId,
                Links   = linksResult.Entities,
                Artists = artistsResult.Entities,
                Genres  = genresResult.Entities
            };

            var result = await _songRepository.Add(modelObject);

            serviceResult.Success = result.Success;
            if (!result.Success)
            {
                serviceResult.Error.Code        = ErrorStatusCode.BudRequest;
                serviceResult.Error.Description = result.Message;
            }

            return(serviceResult);
        }
コード例 #7
0
        public void AddSong(Song song)
        {
            var album   = _albumRepository.Get(song.Album.AlbumId);
            var artists = _artistRepository.Get(song.Artists).ToList();

            song.Album   = album;
            song.Artists = artists;

            _songRepository.Add(song);
        }
コード例 #8
0
        private static Song CreateAndAddSong(int number, ISongRepository songRepository)
        {
            var song = songRepository.Create();

            song.Title             = "SongRepositoryTests" + number;
            song.DurationInSeconds = 120;
            song.FileName          = "SongRepositoryTests.mp3";

            songRepository.Add(song);

            return(song);
        }
コード例 #9
0
        public IActionResult AddSong([FromBody] SongCreateDto songCreateDto)
        {
            Song toAdd = Mapper.Map <Song>(songCreateDto);

            _songRepository.Add(toAdd);

            bool result = _songRepository.Save();

            if (!result)
            {
                return(new StatusCodeResult(500));
            }

            return(CreatedAtRoute("GetSingleSong", new { id = toAdd.ID }, Mapper.Map <SongDto>(toAdd)));
        }
コード例 #10
0
        public IActionResult CreateSong(string songName)
        {
            if (songName == "")
            {
                return(BadRequest());
            }

            var presentationId = "";
            var songResponse   = new SongResponse();

            try
            {
                presentationId = _googleSlides.Create(songName);

                var song = new Song()
                {
                    Name = songName, PresentationId = presentationId
                };

                if (!_songRepository.Add(song))
                {
                    _googleSlides.Remove(presentationId);
                    songResponse.AlertMessage = MagicString.ProblemOucuredDuringSavingSongToDatabase;
                    return(BadRequest(songResponse));
                }

                var createdSong = Mapper.Map <SongDto>(song);

                var historyEntity = new History()
                {
                    CreateDate  = DateTime.Now,
                    CreatedBy   = GetUserInformation().FullName,
                    Information = $"Dodano nową piosnkę z Id: {createdSong.Id} o tytule {createdSong.Name}"
                };


                return(Ok(createdSong));
            }
            catch (Exception ex)
            {
                _googleSlides.Remove(presentationId);
                songResponse.AlertMessage = ex.Message;
                return(BadRequest(songResponse));
            }
        }
コード例 #11
0
        //consider changing the out parameter to a validation type object
        public void Save(ISong song, out bool success)
        {
            Checks.Argument.IsNotNull(song, "song");

            success = false;

            if (null == _repo.FindBySongId(song.SongId))
            {
                try
                {
                    _repo.Add(song);
                    success = true;
                }
                catch (Exception ex)
                {
                    success = false;
                }
            }
        }
コード例 #12
0
        public IActionResult UploadMusic(SongCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = ProcessUploadedFile(model);

                Song newSong = new Song
                {
                    Artist    = model.Artist,
                    SongName  = model.SongName,
                    License   = model.License,
                    PhotoPath = uniqueFileName
                };

                _songRepository.Add(newSong);
                return(RedirectToAction("Details", new { id = newSong.Id }));
            }

            return(View());
        }
コード例 #13
0
        public void Add(AddUpdateSongModel addSongModel)
        {
            if (string.IsNullOrEmpty(addSongModel.Name))
            {
                throw new ValidationException(Messages.SongNameRequired);
            }

            if (string.IsNullOrEmpty(addSongModel.Url))
            {
                throw new ValidationException(Messages.SongUrlRequired);
            }

            if (string.IsNullOrEmpty(addSongModel.SongCategoryId))
            {
                throw new ValidationException(Messages.SongCategoryIdRequired);
            }

            if (string.IsNullOrEmpty(addSongModel.ArtistId))
            {
                throw new ValidationException(Messages.SongArtistIdRequired);
            }

            var songCategory = _songCategoryRepository.GetById(addSongModel.SongCategoryId);

            if (songCategory == null)
            {
                throw new NotFoundException(Messages.InvalidSongCategoryId);
            }

            var artist = _artistRepository.GetById(addSongModel.ArtistId);

            if (artist == null)
            {
                throw new NotFoundException(Messages.InvalidArtistId);
            }

            var song = SongMapper.ToSong(addSongModel);

            song.Id = SecurityUtils.GenerateEntityId();
            _songRepository.Add(song);
        }
コード例 #14
0
 public void Handle(SongAdded evt)
 {
     _songRepository.Add(evt.UserId, evt.PlaylistId, evt.SongId, evt.Title, evt.Artist);
 }
コード例 #15
0
        public int CreateAlbum(AlbumCreationViewModel album)
        {
            int albumId;

            var label       = _organizationLabelRepository.GetById(album.PublisherLabelId);
            var isrcSeries  = _organizationIsrcSeriesRepository.GetById(album.Publisher.IsrcSeriesId);
            var currentDate = DateTime.Now;

            var productPackage = new media_product_package
            {
                albumtitle           = album.BasicInfo.AlbumTitle,
                albumid              = 0,
                physicallocation     = "",
                labelid              = album.PublisherLabelId,
                cataloguenumber      = "",
                releasetypecode      = "0",
                countryofproduction  = label.countrycode,
                countryofpublication = label.countrycode,
                releasedate          = currentDate,
                packagestatusid      = 4,
                numberoftracks       = album.BasicInfo.NumberOfTracks,
                formattypeid         = 2,
                comment              = album.ReviewComment,
                updatedby            = "User",
                updatedon            = currentDate,
                createdby            = "User",
                createdon            = currentDate,
                mainartistid         = album.BasicInfo.MainArtistId
            };

            _albumRepository.Add(productPackage);

            _unitOfWork.Commit();

            albumId = productPackage.id;

            foreach (var song in album.Songs)
            {
                // If newly created song has already been created with the same isrc.
                if (song.Id == -1 && _mediaRecordingRepository.Get(m => m.isrc == song.Isrc) != null)
                {
                    throw new DuplicateNameException("Isrc provided does already exist.");
                }

                int recordingId;

                if (song.Id == -1)
                {
                    //   1.3. Create media_recording (s)
                    var recording = new media_recording
                    {
                        isrc                 = song.Isrc,
                        recordingtitle       = song.Name,
                        workingtitle         = song.Name,
                        recordingcountrycode = label.countrycode,
                        statusid             = 4,
                        updatedby            = "User",
                        updatedon            = currentDate,
                        createdby            = "User",
                        createdon            = currentDate,
                        recordingdate        = song.RecordingDate,
                        duration             = song.Length,
                        mainartist           = album.BasicInfo.MainArtistId,
                        markedfordeletion    = false
                    };

                    _mediaRecordingRepository.Add(recording);
                    _unitOfWork.Commit();

                    recordingId = recording.id;
                }
                else
                {
                    recordingId = song.Id;
                }

                //   1.4. Create media_product (s)
                _songRepository.Add(new media_product
                {
                    isrc                = song.Isrc,
                    recordingid         = recordingId,
                    title               = song.Name,
                    tracknumber         = song.Number,
                    sidenumber          = 1,
                    labelid             = album.PublisherLabelId,
                    cataloguenumber     = "",
                    mediaproducttypeid  = 1,
                    packageid           = albumId,
                    releasedate         = currentDate,
                    countryofproduction = label.countrycode,
                    statusid            = 4,
                    updatedby           = "User",
                    updatedon           = currentDate,
                    createdby           = "User",
                    createdon           = currentDate,
                    is_deleted          = false
                });

                //   1.5. Add to recording_party
                song.Performers.ForEach(performer => _recordingPartyRepository.Add(new recording_party
                {
                    recordingid    = recordingId,
                    partyrealid    = performer.Id,
                    rolecode       = performer.Role.RoleCode,
                    instrumentcode = performer.Instrument.IdCode,
                    updatedby      = "User",
                    updatedon      = currentDate,
                    createdby      = "User",
                    createdon      = currentDate,
                    status         = 2
                }));
            }

            isrcSeries.updatedon            = currentDate;
            isrcSeries.updatedby            = "User";
            isrcSeries.isrc_lastusednumber += 100;
            isrcSeries.isrc_lastusedyear    = DateTime.Now.Year;

            _organizationIsrcSeriesRepository.Update(isrcSeries);

            //   1.6. Commit changes
            _unitOfWork.Commit();

            return(albumId);
        }
コード例 #16
0
        public int PublishProjectById(int projectId, ProjectReviewViewModel reviewModel)
        {
            var projectToUpdate = _projectMasterRepository.GetById(projectId);
            int albumId         = 0;

            if (projectToUpdate != null)
            {
                //   1.1. Update project status
                projectToUpdate.statuscode      = "PUBLISHED";
                projectToUpdate.updatedby       = "User";
                projectToUpdate.updatedon       = DateTime.Now;
                projectToUpdate.reviewedby      = "User";
                projectToUpdate.reviewedok      = true;
                projectToUpdate.reviewedon      = DateTime.Now;
                projectToUpdate.reviewedcomment = reviewModel.ReviewComment;

                _projectMasterRepository.Update(projectToUpdate);

                var label       = _organizationLabelRepository.GetById(reviewModel.LabelId);
                var isrcSeries  = _organizationIsrcSeriesRepository.GetById(reviewModel.IsrcSeriesId);
                var currentDate = DateTime.Now;

                //   1.2. Create media_product_package
                var productPackage = new media_product_package
                {
                    albumtitle           = projectToUpdate.projectname,
                    albumid              = 0,
                    physicallocation     = "",
                    labelid              = reviewModel.LabelId,
                    cataloguenumber      = "",
                    releasetypecode      = "0",
                    countryofproduction  = label.countrycode,
                    countryofpublication = label.countrycode,
                    releasedate          = currentDate,
                    packagestatusid      = 4,
                    numberoftracks       = _projectTrackRepository.GetMany(pt => pt.projectid == projectId).Count(),
                    formattypeid         = 2,
                    comment              = reviewModel.ReviewComment,
                    updatedby            = "User",
                    updatedon            = currentDate,
                    createdby            = "User",
                    createdon            = currentDate,
                    mainartistid         = projectToUpdate.mainartistid
                };
                _albumRepository.Add(productPackage);

                _unitOfWork.Commit();

                albumId = productPackage.id;

                var projectTracks  = _projectTrackRepository.GetMany(pt => pt.projectid == projectId).ToList();
                var lastUsedNumber = isrcSeries.isrc_lastusednumber;

                foreach (var track in projectTracks)
                {
                    string isrc;

                    if (string.IsNullOrEmpty(track.isrc))
                    {
                        isrc = IsrcHelper.GenerateIsrcNumber(isrcSeries.isrc_countrypart,
                                                             isrcSeries.isrc_organizationpart,
                                                             isrcSeries.isrc_lastusedyear, ++lastUsedNumber);
                    }
                    else
                    {
                        isrc = track.isrc;
                    }

                    // Update track isrc as well.
                    track.isrc = isrc;
                    _projectTrackRepository.Update(track);

                    int recordingId;

                    if (track.recordingid != null && track.recordingid != -1)
                    {
                        recordingId = track.recordingid.Value;
                    }
                    else
                    {
                        //   1.3. Create media_recording (s)
                        var recording = new media_recording
                        {
                            isrc                 = isrc,
                            recordingtitle       = track.trackname,
                            workingtitle         = track.trackname,
                            recordingcountrycode = label.countrycode,
                            statusid             = 4,
                            updatedby            = "User",
                            updatedon            = currentDate,
                            createdby            = "User",
                            createdon            = currentDate,
                            recordingdate        = track.createdon,
                            duration             = track.duration,
                            mainartist           = projectToUpdate.mainartistid,
                            markedfordeletion    = false,
                            projecttrackid       = track.id
                        };

                        _mediaRecordingRepository.Add(recording);

                        _unitOfWork.Commit();

                        recordingId = recording.id;
                    }

                    //   1.4. Create media_product (s)
                    _songRepository.Add(new media_product
                    {
                        isrc                = isrc,
                        recordingid         = recordingId,
                        title               = track.trackname,
                        tracknumber         = track.trackorder,
                        sidenumber          = 1,
                        labelid             = reviewModel.LabelId,
                        cataloguenumber     = "",
                        mediaproducttypeid  = 1,
                        packageid           = albumId,
                        releasedate         = currentDate,
                        countryofproduction = label.countrycode,
                        statusid            = 4,
                        updatedby           = "User",
                        updatedon           = currentDate,
                        createdby           = "User",
                        createdon           = currentDate,
                        is_deleted          = false
                    });

                    var projectTrackArtists = _projectTrackArtistRepository.GetMany(p => p.projecttrackid == track.id).ToList();

                    //   1.5. Add to recording_party
                    projectTrackArtists.ForEach(pta => _recordingPartyRepository.Add(new recording_party
                    {
                        recordingid       = recordingId,
                        partyrealid       = pta.partyrealid,
                        rolecode          = pta.rolecode,
                        instrumentcode    = pta.instrumentcode,
                        artistpseudonymid = pta.artistpseudonymid,
                        updatedby         = "User",
                        updatedon         = currentDate,
                        createdby         = "User",
                        createdon         = currentDate,
                        status            = 2
                    }));
                }

                isrcSeries.updatedon            = currentDate;
                isrcSeries.updatedby            = "User";
                isrcSeries.isrc_lastusednumber += 100;
                isrcSeries.isrc_lastusedyear    = DateTime.Now.Year;

                _organizationIsrcSeriesRepository.Update(isrcSeries);

                //   1.6. Commit changes
                _unitOfWork.Commit();
            }

            return(albumId);
        }
コード例 #17
0
        public ActionResult Create(SongModel songModel)
        {
            _songRepository.Add(songModel);

            return(RedirectToAction(nameof(Index)));
        }
コード例 #18
0
ファイル: SongService.cs プロジェクト: RicardovanDijke/Musify
        public async Task <bool> AddSong(IFormFile file)
        {
            await using (Stream stream = file.OpenReadStream())
            {
                using var binaryReader = new BinaryReader(stream);
                var fileContent = binaryReader.ReadBytes((int)file.Length);
                var str         = Encoding.Default.GetString(fileContent);
                //await this.UploadFile(file.ContentDisposition);
                var filePath = @"songstorage/testmp3.mp3";

                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                TagLibFile.IFileAbstraction iFile = new TagLibFile.LocalFileAbstraction(filePath);

                var mp3 = TagLibFile.Create(iFile);

                var artistName  = mp3.Tag.Performers[0];
                var albumName   = mp3.Tag.Album;
                var albumNumber = mp3.Tag.Track;

                //todo add album art

                //create new artist / album if it doesnt exist yet
                var artist = _artistManager.FindByName(artistName) ?? new Artist()
                {
                    Name = artistName
                };

                var album = _albumManager.FindByName(albumName) ?? new Album()
                {
                    Artist = artist,
                    Name   = albumName
                };


                //TODO fix duration
                var song = new Song(mp3.Tag.Title, artist, album, mp3.Properties.Duration.Seconds, (int)albumNumber);

                _songManager.Add(song);

                // var extension = Path.GetExtension(file.FileName);
                //   var folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MusifyStorage", artistName, albumName);
                //  var fileName = albumNumber + " - " + mp3.Tag.Title;
                // var fullPath = Path.Combine(folderPath, fileName + extension);

                var fileInfo = new FileInfo(song.FilePath);
                if (!Directory.Exists(fileInfo.DirectoryName))
                {
                    Directory.CreateDirectory(fileInfo.DirectoryName);
                }

                using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }

                Console.WriteLine(fileInfo.FullName);
            }

            return(true);
        }
コード例 #19
0
 public ActionResult Add(Song song)
 {
     songRepo.Add(song);
     return(RedirectToAction("../Album/Details/" + song.AlbumID));
 }
コード例 #20
0
 public async Task Add(Song song)
 {
     await _songRepository.Add(song);
 }