// **************************************
        // NextStep
        // **************************************
        public WorkflowStep<CatalogUploadState> NextStep(CatalogUploadState state)
        {
            if (state.WorkflowStepsStatus == null) {
                return null;
            }
            var incompleteSteps = state.WorkflowStepsStatus.Where(s => s.Value == WorkflowStepStatus.Incomplete);

            return incompleteSteps.Count() > 0 ?
                CatalogUploadWorkflow.WorkflowSteps.SingleOrDefault(s => s.StepIndex == incompleteSteps.First().Key)
                : null;
        }
 // **************************************
 // RunNextStep
 // **************************************
 public CatalogUploadState RunNextStep(CatalogUploadState state)
 {
     var step = NextStep(state);
     if (step != null) {
         step.Process(state);
         if (state.WorkflowStepsStatus.ContainsKey(step.StepIndex)) {
             state.WorkflowStepsStatus[step.StepIndex] = WorkflowStepStatus.Complete;
         } else {
             state.WorkflowStepsStatus.Add(step.StepIndex, WorkflowStepStatus.Complete);
         }
     }
     return state;
 }
        public virtual ActionResult Upload(CatalogUploadState state)
        {
            var stepStatus = Session["CatalogUploadState.WorkflowStepsStatus"] as IDictionary<int, WorkflowStepStatus>;
            var uploadFiles = Session["CatalogUploadState.UploadFiles"] as IList<UploadFile>;

            if (state == null) {
                state = new CatalogUploadState();
            } else {
                state.WorkflowStepsStatus = stepStatus;
                state.UploadFiles = uploadFiles;
            //				state.TempFiles = state.TempFiles ?? sessionFiles;
            }
            var wf = _catUploadService.CatalogUploadWorkflow;
            try {
                state = _catUploadService.RunNextStep(state);

                var nextStep = _catUploadService.NextStep(state);

                if (nextStep != null) {
                    state.CurrentStepIndex = nextStep.StepIndex;
                    Session["CatalogUploadState.WorkflowStepsStatus"] = state.WorkflowStepsStatus;
                    // Add any new files from this step
                    //uploadFiles = state.UploadFiles != null ?
                    //    (uploadFiles != null ?
                    //        uploadFiles.Union(state.UploadFiles).ToList()
                    //        : state.UploadFiles)
                    //    : uploadFiles;
                    Session["CatalogUploadState.UploadFiles"] = state.UploadFiles != null ? state.UploadFiles.Distinct().ToList() : state.UploadFiles;
                    var vm = GetCatalogViewModel(nextStep, state);
                    vm.StepActionName = nextStep.StepButton;

                    return View(vm);
                } else {
                    UserEventLogService.LogUserEvent(UserActions.UploadCatalog);
                    SessionService.Session().RefreshUser(this.UserName());

                    return RedirectToAction(Actions.Complete());
                }
            }
            catch (Exception ex){
                Log.Error(ex);
                this.FeedbackError(ex.Message ?? "There was an error uploading your song files. Please try again.");
                return RedirectToAction(Actions.Upload());
            }
        }
        // **************************************
        // URL: /Catalog/Upload
        // **************************************
        public virtual ActionResult Upload(int? id)
        {
            // Cleanup upload folder
            FileSystem.SafeDeleteFolder(User.User().UploadFolder(create: false));

            var state = new CatalogUploadState(_catUploadService.CatalogUploadWorkflow.WorkflowSteps.Count);
            if (id.GetValueOrDefault() > 0) {
                state.CatalogId = id.GetValueOrDefault();
            }
            var nextStep = _catUploadService.NextStep(state);
            state.CurrentStepIndex = nextStep.StepIndex;
            Session["CatalogUploadState.WorkflowStepsStatus"] = state.WorkflowStepsStatus;
            Session["CatalogUploadState.UploadFiles"] = state.UploadFiles;

            var vm = GetCatalogViewModel(nextStep, state);

            return View(vm);
        }
        // **************************************
        // Steps
        // **************************************
        // **************************************
        // SelectCatalog
        // **************************************
        private CatalogUploadState SelectCatalog(CatalogUploadState state)
        {
            // lookup catalog id
            if (state.CatalogId > 0) {
                if (!Account.User().IsAtLeastInCatalogRole(Roles.Admin, state.CatalogId)) {
                    throw new AccessViolationException("You do not have admin rights to this catalog.", innerException: null);
                }

                using(var ctx = new SongSearchContext()){
                    var catalog = ctx.Catalogs.SingleOrDefault(c => c.CatalogId == state.CatalogId);
                    if (catalog == null) {
                        throw new ArgumentOutOfRangeException("Catalog does not exist.", innerException: null);
                    }
                    state.CatalogName = catalog.CatalogName;
                    return state;
                }

            }

            if (!String.IsNullOrWhiteSpace(state.CatalogName)) {
                state.CatalogName = state.CatalogName.ToUpper();
                return state;
            } else {
                throw new ArgumentNullException("Catalog name cannot be blank. Please enter a catalog name or select an existing catalog.", innerException: null);
            }
        }
        // **************************************
        // SaveCatalog
        // **************************************
        private CatalogUploadState SaveCatalog(CatalogUploadState state)
        {
            System.Diagnostics.Debug.Write("Step5");

            var user = Account.User();
            // Save/create Catalog
            if (user.IsAtLeastInRole(Roles.Admin) && !user.MyBalances().NumberOfSongs.IsAtTheLimit) {

                using (var ctx = new SongSearchContext()) {

                    var catalog = ctx.Catalogs.SingleOrDefault(c => c.CatalogName.ToUpper() == state.CatalogName) ??
                        new Catalog() {
                            CatalogName = state.CatalogName,
                            CreatedByUserId = user.UserId,
                            CreatedOn = DateTime.Now
                        };

                    if (catalog.CatalogId == 0) {

                        ctx.Catalogs.AddObject(catalog);
                        //DataSession.CommitChanges();

                        //Make current user an admin
                        var userCatalog = new UserCatalogRole() {
                            UserId = user.UserId,
                            CatalogId = catalog.CatalogId,
                            RoleId = (int)Roles.Admin
                        };
                        ctx.UserCatalogRoles.AddObject(userCatalog);

                        //Make parent user an admin
                        if (user.ParentUserId.HasValue) {
                            var parentUserCatalog =
                                //DataSession.Single<UserCatalogRole>(
                                //    x => x.UserId == user.ParentUserId.Value &&
                                //        x.CatalogId == catalog.CatalogId &&
                                //        x.RoleId == (int)Roles.Admin
                                //        ) ??
                                new UserCatalogRole() {
                                    UserId = user.ParentUserId.Value,
                                    CatalogId = catalog.CatalogId,
                                    RoleId = (int)Roles.Admin
                                };
                            ctx.UserCatalogRoles.AddObject(parentUserCatalog);
                        }

                        //Make plan user an admin
                        if (!user.IsPlanOwner && user.PlanUserId != user.ParentUserId.GetValueOrDefault()) {
                            var planUserCatalog =
                                //DataSession.Single<UserCatalogRole>(
                                //    x => x.UserId == user.PlanUserId &&
                                //        x.CatalogId == catalog.CatalogId &&
                                //        x.RoleId == (int)Roles.Admin
                                //        ) ??
                                new UserCatalogRole() {
                                    UserId = user.PlanUserId,
                                    CatalogId = catalog.CatalogId,
                                    RoleId = (int)Roles.Admin
                                };
                            ctx.UserCatalogRoles.AddObject(planUserCatalog);
                        }

                        // defer?
                        ctx.SaveChanges();
                    }

                    state.CatalogId = catalog.CatalogId;
                    state.CatalogName = catalog.CatalogName.ToUpper();

                    // Save Content
                    var content = App.IsLicensedVersion ?
                        state.Content.Take(user.MyBalances().NumberOfSongs.IsGoodFor(state.Content.Count())).ToList() :
                        state.Content;

                    foreach (var itm in content) {

                        itm.CatalogId = state.CatalogId;
                        itm.CreatedByUserId = user.UserId;
                        itm.CreatedOn = DateTime.Now;
                        itm.LastUpdatedByUserId = user.UserId;
                        itm.LastUpdatedOn = DateTime.Now;
                        //itm.IsMediaOnRemoteServer = false;

                        itm.Title = itm.Title.AsEmptyIfNull();//.CamelCase();//.ToUpper();
                        itm.Artist = itm.Artist.AsEmptyIfNull();//.CamelCase();//.ToUpper();
                        itm.RecordLabel = itm.RecordLabel.AsEmptyIfNull();//.CamelCase();//.ToUpper();
                        itm.ReleaseYear = itm.ReleaseYear.GetValueOrDefault().AsNullIfZero();
                        itm.Notes = itm.Notes;

                        var full = itm.UploadFiles.SingleOrDefault(f => f.FileMediaVersion == MediaVersion.Full);
                        foreach (var version in ModelEnums.MediaVersions()) {

                            var upl = itm.UploadFiles.SingleOrDefault(f => f.FileMediaVersion == version);
                            if (upl != null) {

                                var file = new FileInfo(upl.FilePath);
                                var id3 = ID3Writer.NormalizeTag(upl.FilePath, itm);

                                var media = new ContentMedia() {

                                    MediaVersion = (int)version,
                                    MediaType = "mp3",
                                    MediaSize = file.Length,
                                    MediaLength = id3.MediaLength,
                                    MediaDate = file.GetMediaDate(),
                                    MediaBitRate = id3.GetBitRate(file.Length)
                                };

                                media.IsRemote = false;

                                itm.ContentMedia.Add(media);
                            }

                        }
                        ctx.Contents.AddObject(itm);
                        ctx.AddToSongsBalance(user);
                        ctx.SaveChanges();

                        if (itm.ContentId > 0) {
                            foreach (var file in itm.UploadFiles) {
                                MediaService.SaveContentMedia(file.FilePath, itm.Media(file.FileMediaVersion));
                            }
                        }

                    }

                }
            }

            SessionService.Session().InitializeSession(true);
            CacheService.InitializeApp(true);

            return state;
        }
 private CatalogUploadState ReviewComplete(CatalogUploadState state)
 {
     return state;
 }
        // **************************************
        // EditMetadata
        // **************************************
        private CatalogUploadState EditMetadata(CatalogUploadState state)
        {
            // Check Metadata, e.g. make stuff uppercase etc
            foreach (var itm in state.Content) {
                itm.Title = itm.Title.AsEmptyIfNull();//.ToUpper();
                itm.Artist = itm.Artist.AsEmptyIfNull();//.ToUpper();
                itm.RecordLabel = itm.RecordLabel.AsEmptyIfNull();//.ToUpper();
                itm.ReleaseYear = itm.ReleaseYear.GetValueOrDefault().AsNullIfZero();
                itm.Notes = itm.Notes;
            }

            return state;
        }
        // **************************************
        // AddSongPreviews
        // **************************************
        private CatalogUploadState AddSongPreviews(CatalogUploadState state)
        {
            if (state.TempFiles != null && state.TempFiles.Count() > 0) {

                var uploadFiles = MoveToMediaVersionFolder(state.TempFiles.Distinct().ToList(), state.MediaVersion);

                //Attach previews
                uploadFiles = state.UploadFiles != null ?
                    (uploadFiles != null ?
                        uploadFiles.Union(state.UploadFiles).ToList()
                        : state.UploadFiles)
                    : uploadFiles;

                state.UploadFiles = uploadFiles.Distinct().ToList();
            }

            IList<Content> contentList = new List<Content>();
            IDictionary<UploadFile, ID3Data> taggedContent = new Dictionary<UploadFile, ID3Data>();

            //var contentFiles = state.UploadFiles.Select(f => f.FileName).Distinct().ToList();

            foreach (var file in state.UploadFiles) {

                taggedContent.Add(file, ID3Reader.GetID3Metadata(file.FilePath));
            }

            // try filename
            // try title + artist
            var taggedFullSongs = taggedContent.Where(c => c.Key.FileMediaVersion == MediaVersion.Full);
            var taggedPreviews = taggedContent.Where(c => c.Key.FileMediaVersion == MediaVersion.Preview);
            foreach (var itm in taggedFullSongs) {

                var preview = new KeyValuePair<UploadFile, ID3Data>();

                if (itm.Value.Title != null && itm.Value.Artist != null) {
                    //Get a matching preview file based on ID3 data or filename
                    preview = taggedPreviews.Where(c => c.Value.Title != null && c.Value.Artist != null)
                                        .FirstOrDefault(c =>
                                        c.Value.Title.Equals(itm.Value.Title, StringComparison.InvariantCultureIgnoreCase) &&
                                        c.Value.Artist.Equals(itm.Value.Artist, StringComparison.InvariantCultureIgnoreCase)
                                        );
                }
                if (preview.Key == null && itm.Key.FileName != null) {
                    preview = taggedPreviews.Where(c => c.Key.FileName != null)
                            .FirstOrDefault(c =>
                            c.Key.FileName.Equals(itm.Key.FileName, StringComparison.InvariantCultureIgnoreCase)
                            );
                }

                var id3 = itm.Value;
                //var file = new FileInfo(itm.Key.FilePath);
                var fileNameData = Path.GetFileNameWithoutExtension(itm.Key.FileName).Split('-');

                var title = id3.Title.AsNullIfWhiteSpace() ?? fileNameData.First();
                var artist = id3.Artist.AsNullIfWhiteSpace() ?? (fileNameData.Length > 1 ? fileNameData[1] : "");
                var album = id3.Album.AsNullIfWhiteSpace() ?? "";
                string year = id3.Year.AsNullIfWhiteSpace() ?? (fileNameData.Length > 2 ? fileNameData[2] : "");
                int releaseYear;
                int.TryParse(year, out releaseYear);

                //var kb = (int)(file.Length * 8 / 1024);
                //var secs = (id3.LengthMilliseconds / 1000);

                var content = new Content() {
                    Title = title,
                    Artist = artist,
                    ReleaseYear = releaseYear.AsNullIfZero(),
                    Notes = !String.IsNullOrWhiteSpace(album) ? String.Concat("Album: ", album) : null,
                    HasMediaFullVersion = true,
                    HasMediaPreviewVersion = preview.Key != null,
                    //FileType = "mp3",
                    //FileSize = (int)file.Length,
                    //BitRate = secs > 0 ? (kb / secs) : 0,
                    UploadFiles = new List<UploadFile>()
                };

                content.UploadFiles.Add(itm.Key);
                if (preview.Key != null) { content.UploadFiles.Add(preview.Key); }

                contentList.Add(content);
            }

            state.Content = contentList;

            return state;
        }
示例#10
0
        // **************************************
        // AddSongFiles
        // **************************************
        private CatalogUploadState AddSongFiles(CatalogUploadState state)
        {
            if (state.TempFiles == null){
                throw new ArgumentNullException("There was an error uploading your song files", innerException: null);
            }

            var filesList = state.TempFiles.Distinct().ToList();
            var uploadFiles = MoveToMediaVersionFolder(filesList, state.MediaVersion);

            uploadFiles = state.UploadFiles != null ?
                (uploadFiles != null ?
                    uploadFiles.Union(state.UploadFiles).ToList()
                    : state.UploadFiles)
                : uploadFiles;
            state.UploadFiles = uploadFiles;
            return state;
        }
        private CatalogUploadViewModel GetCatalogViewModel(WorkflowStep<CatalogUploadState> nextStep, CatalogUploadState state)
        {
            var vm = new CatalogUploadViewModel();
            vm.PageTitle = nextStep.StepName;
            vm.NavigationLocation = new string[] { "Admin" };
            vm.CatalogUploadState = state;
            vm.StepView = nextStep.StepView;
            vm.StepActionName = nextStep.StepButton;// "Next Step";
            vm.MyCatalogs = Account.User(false).MyAdminCatalogs().OrderBy(c => c.CatalogName).ToList();
            vm.MyPricingPlan = Account.User().PricingPlan;
            vm.MyUserBalances = Account.User().MyBalances();
            //			vm.DefaultSongBalance = vm.PricingPlans.Where(p => p.IsEnabled == true).Min(p => p.NumberOfSongs);
            vm.MinUploadFiles = 1;

            return vm;
        }