public void GetMediaHtmlTest()
        {
            var testUser    = GetTestUser();
            var testCompany = GetTestCompany(testUser);

            // Create a record
            string testImage  = MediaServices.GetSiteFolder() + @"\\Content\\EvolutionLogo.png";
            string sourceFile = MediaServices.GetTempFolder() + testImage.FileName();

            LogTestFile(sourceFile);
            var error = MediaService.MediaService.CopyOrMoveFile(testImage, sourceFile, Enumerations.FileCopyType.Copy);

            Assert.IsTrue(!error.IsError, error.Message);

            var model = new MediaModel();

            error = createMedia(testCompany, testUser, sourceFile, model);
            Assert.IsTrue(!error.IsError, error.Message);

            string html = MediaServices.GetMediaHtml(model, MediaSize.Medium, (int)MediaSize.MediumW, (int)MediaSize.MediumH);

            Assert.IsTrue(!string.IsNullOrEmpty(html), "Error: An empty string was returned");

            // TBD: Need to add further checks to make sure the html is valid
        }
        private Error createMedia(CompanyModel testCompany, UserModel testUser, string sourceFile,
                                  MediaModel media)
        {
            media.CompanyId = testCompany.Id;

            var mediaType = db.FindMediaType(sourceFile);

            if (mediaType == null)
            {
                mediaType = db.FindMediaType((int)Enumerations.MediaType.UNKNOWN);
            }
            media.MediaTypeId = mediaType.Id;
            media.MediaFile   = "/Content/MediaThumbs/" + mediaType.ThumbMedium;

            var error = MediaServices.InsertOrUpdateMedia(media,
                                                          testCompany,
                                                          testUser,
                                                          Enumerations.MediaFolder.User,
                                                          sourceFile,
                                                          "",
                                                          testUser.Id,
                                                          -1,
                                                          FileCopyType.Move);

            return(error);
        }
        public void DeleteMediaTest()
        {
            var testUser    = GetTestUser();
            var testCompany = GetTestCompany(testUser);

            // Create a record
            string sourceFile = MediaService.MediaService.GetTempFile(".txt");

            LogTestFile(sourceFile);
            File.WriteAllText(sourceFile, LorumIpsum());

            var model = new MediaModel();
            var error = createMedia(testCompany, testUser, sourceFile, model);

            Assert.IsTrue(!error.IsError, $"Error: {error.Message}");

            // Check that the media exists
            var mediaFile = MediaServices.GetMediaFileName(model, false);

            Assert.IsTrue(File.Exists(mediaFile), $"Error: File '{mediaFile}' could not be found");

            // Now delete the media
            error = MediaServices.DeleteMedia(model);

            // Check that the media has been deleted
            var check = db.FindMedias()
                        .Where(m => m.Id == model.Id)
                        .FirstOrDefault();

            Assert.IsTrue(check == null, "Error: Media record was found when it should have been deleted");
            Assert.IsTrue(!File.Exists(mediaFile), $"Error: File '{mediaFile}' exists when it should have been deleted");
        }
        internal static string GetMainGltfFile(this MediaModel model)
        {
            var gltfFiles = model.Files.Gltf;
            var fileName  = gltfFiles.Keys.First(k => k.EndsWith(".gltf"));

            return(gltfFiles[fileName]);
        }
Exemple #5
0
        private void SetFeaturedCategories(MediaModel model)
        {
            var cat1 = _documentService.GetDocumentByUrl <Category>(FeaturedCategoriesInfo.Category1Url);
            var cat2 = _documentService.GetDocumentByUrl <Category>(FeaturedCategoriesInfo.Category2Url);
            var cat3 = _documentService.GetDocumentByUrl <Category>(FeaturedCategoriesInfo.Category3Url);
            var cat4 = _documentService.GetDocumentByUrl <Category>(FeaturedCategoriesInfo.Category4Url);

            if (cat1 != null)
            {
                cat1.FeatureImage = model.FeaturedCategory1.FileUrl;
                _documentService.SaveDocument(cat1);
            }
            if (cat2 != null)
            {
                cat2.FeatureImage = model.FeaturedCategory2.FileUrl;
                _documentService.SaveDocument(cat2);
            }
            if (cat3 != null)
            {
                cat3.FeatureImage = model.FeaturedCategory3.FileUrl;
                _documentService.SaveDocument(cat3);
            }
            if (cat4 != null)
            {
                cat4.FeatureImage = model.FeaturedCategory4.FileUrl;
                _documentService.SaveDocument(cat4);
            }
        }
    public static int Update(MediaModel param)
    {
        int        ret    = 0;
        MediaModel cmedia = new MediaModel();
        MediaTax   mt     = new MediaTax();

        try
        {
            if (cmedia.model_Update(param))
            {
                mt.model_DeleteMediaTaxAllbyMID(param.MID);

                if (param.MediaTax.Length > 0)
                {
                    foreach (MediaTax i in param.MediaTax)
                    {
                        ret += mt.model_InsertTax(i);
                    }
                }
            }
            ret = 1;
        }
        catch (Exception ex) { string ss = ex.Message + ex.StackTrace; }

        return(ret);
    }
        public void FindMediaModelTest()
        {
            var testUser    = GetTestUser();
            var testCompany = GetTestCompany(testUser);

            // Create a media item
            var media = new MediaModel();
            var error = createMedia(testCompany, testUser, "", media);

            Assert.IsTrue(error.IsError, "Error: Success was returned when a blank sourceFile should have caused an error");

            // Now supply a valid source file
            string sourceFile = MediaService.MediaService.GetTempFile(".txt");

            File.WriteAllText(sourceFile, LorumIpsum());

            error = createMedia(testCompany, testUser, sourceFile, media);
            Assert.IsTrue(!error.IsError, error.Message);

            // Now find it
            var checkMedia = MediaServices.FindMediaModel(media.Id);

            Assert.IsTrue(checkMedia != null, "Error: A NULL value was returned when a non-NULL value was expected");

            var excludes = new List <string>();

            excludes.Add("MediaHtml");              // MediaHtml is not known up-front
            AreEqual(media, checkMedia, excludes);
        }
            private void LoadPhoto(MediaModel mediaModel, CardView photoCard)
            {
                if (mediaModel != null)
                {
                    var photo = (ImageView)photoCard.GetChildAt(0);
                    var url   = mediaModel.Thumbnails.Mini;
                    Picasso.With(_context).Load(url).NoFade()
                    .Resize(_context.Resources.DisplayMetrics.WidthPixels, 0).Priority(Picasso.Priority.High)
                    .Into(photo, null, () =>
                    {
                        Picasso.With(_context).Load(url).NoFade().Priority(Picasso.Priority.High).Into(photo);
                    });

                    if (_type == PostPagerType.PostScreen)
                    {
                        photoCard.Radius = (int)BitmapUtils.DpToPixel(7, _context.Resources);
                    }

                    var size = new Size {
                        Height = mediaModel.Size.Height / Style.Density, Width = mediaModel.Size.Width / Style.Density
                    };
                    var height = (int)(OptimalPhotoSize.Get(size, Style.ScreenWidthInDp, 130, Style.MaxPostHeight) * Style.Density);
                    photoCard.LayoutParameters.Height = height;
                    ((View)photoCard.Parent).LayoutParameters.Height = height;
                    photo.LayoutParameters.Height = height;
                }
            }
        public async Task <ItemGlyph> GetThumbImageFromVideo(MediaModel argMediaModel)
        {
            ItemGlyph returnItemGlyph = argMediaModel.ModelItemGlyph;

            IMediaModel newMediaModel = UtilCreateNewMediaObject(argMediaModel, "~imagevideo", ".jpg");

            IMediaModel videoImage;

            // Check if new image file already exists
            IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkKey(newMediaModel.HLinkKey);

            if ((!fileExists.Valid) && argMediaModel.IsMediaStorageFileValid)
            {
                // check if we can get an image for the video
                videoImage = await _iocPlatformSpecific.GenerateThumbImageFromVideo(DataStore.Instance.AD.CurrentDataFolder.Value, argMediaModel, newMediaModel);

                returnItemGlyph = UtilSaveNewMediaObject(returnItemGlyph, videoImage, IconFont.FileArchive);
            }
            else
            {
                ErrorInfo t = UtilGetPostGlyphErrorInfo("File not found when trying to create image from video file", argMediaModel);

                _commonNotifications.NotifyError(t);
            }

            return(returnItemGlyph);
        }
    public static int Update(MediaModel param)
    {
        int        ret    = 0;
        MediaModel cmedia = new MediaModel();
        MediaTax   mt     = new MediaTax();

        try
        {
            if (cmedia.model_Update(param))
            {
                mt.model_DeleteMediaTaxAllbyMID(param.MID);

                if (param.MediaTax.Length > 0)
                {
                    foreach (MediaTax i in param.MediaTax)
                    {
                        ret += mt.model_InsertTax(i);
                    }
                }
            }
            ret = 1;
        }
        catch { }

        return(ret);
    }
Exemple #11
0
        public void GetMessageMedias_ByMessageId()
        {
            var mediaModel1 = new MediaModel
            {
                Id   = Guid.NewGuid(),
                Data = "random data"
            };

            var mediaModel2 = new MediaModel
            {
                Id     = Guid.NewGuid(),
                Data   = "random data2",
                Parent = null
            };

            var messageModel = new MessageModel
            {
                Id     = Guid.NewGuid(),
                Text   = "FirstName",
                User   = fixture.userModel,
                Group  = fixture.groupModel,
                Parent = null
            };


            var returnedMediaModel1 = fixture.Repository.AddMedia(mediaModel1.Id, mediaModel1);
            var returnedMediaModel2 = fixture.Repository.AddMedia(mediaModel2.Id, mediaModel2);

            Assert.NotNull(returnedMediaModel1);
            Assert.NotNull(returnedMediaModel2);

            var returnedMessageModelCreated = fixture.Repository.Create(messageModel);

            Assert.NotNull(returnedMessageModelCreated);
        }
        public async Task <ItemGlyph> GetThumbImageFromPDF(MediaModel argMediaModel)
        {
            ItemGlyph returnItemGlyph = argMediaModel.ModelItemGlyph;

            IMediaModel newMediaModel = UtilCreateNewMediaObject(argMediaModel, "~imagepdf", ".jpg");

            // TODO Having an issue where Gramps XML content type is not always correct
            if (argMediaModel.MediaStorageFile.FInfo.Extension != ".pdf")
            {
                _commonNotifications.DataLogEntryAdd($"??? {argMediaModel.Id} Inconsistant File Extension ({argMediaModel.MediaStorageFile.FInfo.Extension}) and MIME type ({argMediaModel.FileMimeType}/{argMediaModel.FileMimeSubType})");
                return(argMediaModel.ModelItemGlyph);
            }

            IMediaModel pdfimage;

            // Check if new pdf image file already exists
            IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkKey(newMediaModel.HLinkKey);

            if ((!fileExists.Valid) && (argMediaModel.IsMediaStorageFileValid))
            {
                // check if we can get an image for the first page of the PDF
                pdfimage = await _iocPlatformSpecific.GenerateThumbImageFromPDF(DataStore.Instance.AD.CurrentDataFolder.Value, argMediaModel, newMediaModel);

                returnItemGlyph = UtilSaveNewMediaObject(returnItemGlyph, pdfimage, IconFont.FilePdf);
            }
            else
            {
                ErrorInfo t = UtilGetPostGlyphErrorInfo("File not found when trying to create image from PDF file", argMediaModel);

                _commonNotifications.NotifyError(t);
            }

            return(returnItemGlyph);
        }
Exemple #13
0
        public void Test_Create_MediaModel(MediaModel media)
        {
            var validationContext = new ValidationContext(media);
            var actual            = Validator.TryValidateObject(media, validationContext, null, true);

            Assert.True(actual);
        }
Exemple #14
0
        public void GetGroupMediaById_Count()
        {
            var mediaModel1 = new MediaModel
            {
                Id   = Guid.NewGuid(),
                Data = "random data"
            };

            var mediaModel2 = new MediaModel
            {
                Id     = Guid.NewGuid(),
                Data   = "random data2",
                Parent = null
            };


            var returnedMediaModel1 = fixture.Repository.AddMedia(mediaModel1.Id, mediaModel1);
            var returnedMediaModel2 = fixture.Repository.AddMedia(mediaModel2.Id, mediaModel2);

            IEnumerable <MediaModel> mediaModels = fixture.Repository.GetGroupMedia(fixture.groupModel.Id);
            int expected = 2;

            Assert.Equal(expected, mediaModels.Count());


            // clean
            fixture.Repository.DeleteMedia(returnedMediaModel1.Id);
            fixture.Repository.DeleteMedia(returnedMediaModel2.Id);
        }
Exemple #15
0
        public void Test_Validate_MediaModel_ValidGroups()
        {
            MediaModel mediaProfile = new MediaModel()
            {
                MediaId = 12345, Group = "profile", GroupIdentifier = "*****@*****.**", Uri = "https://notblobstorage/%22", AltText = "hat"
            };
            MediaModel mediaCampground = new MediaModel()
            {
                MediaId = 12345, Group = "campground", GroupIdentifier = "*****@*****.**", Uri = "https://notblobstorage/%22", AltText = "hat"
            };
            MediaModel mediaCampsite = new MediaModel()
            {
                MediaId = 12345, Group = "campsite", GroupIdentifier = "*****@*****.**", Uri = "https://notblobstorage/%22", AltText = "hat"
            };

            var validationContext = new ValidationContext(mediaProfile);
            var actual            = Validator.TryValidateObject(mediaProfile, validationContext, null, true);

            Assert.True(actual);

            validationContext = new ValidationContext(mediaCampground);
            actual            = Validator.TryValidateObject(mediaCampground, validationContext, null, true);

            Assert.True(actual);

            validationContext = new ValidationContext(mediaCampsite);
            actual            = Validator.TryValidateObject(mediaCampsite, validationContext, null, true);

            Assert.True(actual);
        }
        public async static Task <bool> FixSingleMediaFile(MediaModel argMediaModel)
        {
            try
            {
                if ((argMediaModel.HomeImageHLink.LinkToImage == true) && argMediaModel.IsOriginalFilePathValid)
                {
                    //_CL.LogVariable("tt.OriginalFilePath", argMediaModel.OriginalFilePath); //
                    //_CL.LogVariable("localMediaFolder.path", DataStore.AD.CurrentDataFolder.FullName); //
                    //_CL.LogVariable("path", DataStore.AD.CurrentDataFolder.FullName + "\\" + argMediaModel.OriginalFilePath);

                    DataStore.DS.MediaData[argMediaModel.HLinkKey].MediaStorageFile = await StoreFolder.FolderGetFileAsync(DataStore.AD.CurrentDataFolder, argMediaModel.OriginalFilePath).ConfigureAwait(false);
                }
            }
            catch (FileNotFoundException ex)
            {
                DataStore.CN.NotifyError("File (" + argMediaModel.OriginalFilePath + ") not found while   loading media. Has the GRAMPS database been verified ? " + ex.ToString());

                DataStore.CN.NotifyException("Trying to  add media file pointer", ex);
            }
            catch (Exception ex)
            {
                CommonLocalSettings.DataSerialised = false;
                DataStore.CN.NotifyException("Trying to add media file pointer", ex);

                await DataStore.CN.MajorStatusDelete().ConfigureAwait(false);

                throw;
            }

            return(false);
        }
        public async Task <OperationResult <UploadResultModel> > UploadMediaAsync(MediaModel model, string path, TokenModel tokenModel, CancellationToken token)
        {
            var stream = new FileStream(path, FileMode.Open);
            var file   = new StreamContent(stream);

            file.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeTypeHelper.GetMimeType(Path.GetExtension(path)));
            var multiContent = new MultipartFormDataContent
            {
                { file, "file", Path.GetFileName(path) },
                { new StringContent(model.Thumbnails.ToString()), "thumbnails" },
                { new StringContent(model.Aws.ToString()), "aws" },
                { new StringContent(model.Ipfs.ToString()), "ipfs" }
            };


            var client = new HttpClient();

            if (tokenModel != null)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, tokenModel.Token);
            }

            var response = await client.PostAsync(Url, multiContent, token)
                           .ConfigureAwait(false);

            var result = await CreateResultAsync <UploadResultModel>(response, token)
                         .ConfigureAwait(false);

            if (result.IsSuccess && result.Result == null)
            {
                result.Exception = new ArgumentNullException(nameof(result.Result));
            }

            return(result);
        }
        public void UpdateData(Post post, Context context, int cellSize)
        {
            _post    = post;
            _context = context;

            _mediaModel = post.Media[0];

            if (_mediaModel != null)
            {
                Picasso.With(_context).Load(_mediaModel.GetImageProxy(cellSize))
                .Placeholder(Resource.Color.rgb244_244_246)
                .NoFade()
                .Priority(Picasso.Priority.High)
                .Into(_photo, null, OnError);
            }

            _gallery.Visibility = post.Media.Length > 1 ? ViewStates.Visible : ViewStates.Gone;

            if (_post.ShowMask && (_post.IsNsfw || _post.IsLowRated) && _post.Author != AppSettings.User.Login)
            {
                _nsfwMaskMessage.Text = AppSettings.LocalizationManager.GetText(_post.IsLowRated ? LocalizationKeys.LowRated : LocalizationKeys.Nsfw);
                _nsfwMask.Visibility  = ViewStates.Visible;
            }
            else
            {
                _nsfwMask.Visibility = ViewStates.Gone;
            }
        }
Exemple #19
0
        private void Enrich(MediaModel media, UrlHelper url)
        {
            var selfUrl = url.Link("DefaultApi", new { controller = "media", id = media.Id });

            media.AddLink(new SelfLink(selfUrl));
            media.AddLink(new EditLink(selfUrl));
        }
        private void SetFeaturedCategories(MediaModel model)
        {
            var cat1 = _getCategoryByUrl.GetByUrl(FeaturedCategoriesInfo.Category1Url);
            var cat2 = _getCategoryByUrl.GetByUrl(FeaturedCategoriesInfo.Category2Url);
            var cat3 = _getCategoryByUrl.GetByUrl(FeaturedCategoriesInfo.Category3Url);
            var cat4 = _getCategoryByUrl.GetByUrl(FeaturedCategoriesInfo.Category4Url);

            if (cat1 != null)
            {
                cat1.FeatureImage = model.FeaturedCategory1.FileUrl;
                _webpageAdminService.Add(cat1);
            }
            if (cat2 != null)
            {
                cat2.FeatureImage = model.FeaturedCategory2.FileUrl;
                _webpageAdminService.Add(cat2);
            }
            if (cat3 != null)
            {
                cat3.FeatureImage = model.FeaturedCategory3.FileUrl;
                _webpageAdminService.Add(cat3);
            }
            if (cat4 != null)
            {
                cat4.FeatureImage = model.FeaturedCategory4.FileUrl;
                _webpageAdminService.Add(cat4);
            }
        }
Exemple #21
0
        /// <summary>
        /// Helper method to sort and set the firt image link.
        /// </summary>
        /// <param name="collectionArg">
        /// The collection argument.
        /// </param>
        public void SortAndSetFirst()
        {
            // Set the first image link. Assumes main image is manually set to the first image in
            // Gramps if we need it to be, e.g. Citations.
            IMediaModel tempMediaModel = new MediaModel();

            FirstHLinkHomeImage.HomeImageType = CommonEnums.HomeImageType.Unknown;

            if (Count > 0)
            {
                // Step through each mediamodel hlink in the collection
                for (int i = 0; i < Count; i++)
                {
                    tempMediaModel = DataStore.DS.MediaData.GetModelFromHLink(this[i]);

                    if (tempMediaModel.IsMediaFile)
                    {
                        FirstHLinkHomeImage.ConvertFromMediaModel(this[i].DeRef);

                        break;
                    }
                }

                // Sort the collection
                List <HLinkMediaModel> t = this.OrderBy(hLinkMediaModel => hLinkMediaModel.DeRef.GDescription).ToList();

                Items.Clear();

                foreach (HLinkMediaModel item in t)
                {
                    Items.Add(item);
                }
            }
        }
        private void SetupCheckoutLayoutWidgets(MediaModel mediaModel, LayoutModel layoutModel)
        {
            //checkout images
            var checkoutLogo = new LinkedImage
            {
                Image = _fileService.GetFileLocation(mediaModel.Logo, new Size {
                    Width = 200, Height = 200
                }),
                Link            = "/",
                LayoutArea      = layoutModel.CheckoutLayout.LayoutAreas.First(x => x.AreaName == "Checkout Header Left"),
                Cache           = true,
                CacheExpiryType = CacheExpiryType.Sliding,
                CacheLength     = 60
            };

            _widgetService.AddWidget(checkoutLogo);

            var checkoutSecureBadge = new LinkedImage
            {
                Image           = mediaModel.SecureCheckout.FileUrl,
                LayoutArea      = layoutModel.CheckoutLayout.LayoutAreas.First(x => x.AreaName == "Checkout Header Middle"),
                Cache           = true,
                CacheExpiryType = CacheExpiryType.Sliding,
                CacheLength     = 60
            };

            _widgetService.AddWidget(checkoutSecureBadge);
        }
Exemple #23
0
        public static Series GenerateSeries()
        {
            var series = new Series {
                SeriesName = NewSeriesModel.NewSeriesName
            };

            series.Seasons = new SortedList <int, Season>();

            foreach (var seasonText in NewSeriesModel.SeriesList)
            {
                var season = new Season {
                    SeasonNumber = seasonText.GetNumber()
                };

                var seasonFiles = GetSeasonFiles(seasonText.GetNumber());

                foreach (var file in seasonFiles)
                {
                    var filePath = new MediaModel();

                    filePath.PathAndFilename = file.FilePath;

                    season.Episodes.Add(new Episode {
                        FilePath = filePath, EpisodeNumber = file.EpisodeNumber, EpisodeName = Path.GetFileName(file.FilePath)
                    });
                }

                series.Seasons.Add(seasonText.GetNumber(), season);
            }

            return(series);
        }
        private async Task <bool> SaveToIpfsAsync(MediaModel model, CancellationToken token)
        {
            FileStream fs = null;

            try
            {
                var options = new AddFileOptions();
                if (!model.Ipfs)
                {
                    options.OnlyHash = true;
                }

                fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

                var result = await Ipfs.FileSystem.AddAsync(fs, model.FileName, options, token);

                model.IpfsHash = result.Id;
                return(true);
            }
            catch (Exception e)
            {
                Logger.LogError(e, e.Message);
            }
            finally
            {
                fs?.Close();
            }
            return(false);
        }
Exemple #25
0
        public IActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                return(AccessDeniedView());
            }
            var model = new MediaModel();

            model.Id           = 0;
            model.CategoryList = new System.Collections.Generic.List <SelectListItem>
            {
                new SelectListItem()
                {
                    Value    = "0",
                    Text     = "بدون انتخاب",
                    Selected = true,
                }
            };
            model.CategoryList.AddRange(_MediaCategoryService.GetAllsMediaCategory().Select(x => new SelectListItem()
            {
                Text     = _MediaCategoryService.CategoryNavigation(x.Id),
                Value    = x.Id.ToString(),
                Selected = false
            }).ToList());
            return(View("~/Plugins/Company.Media/Views/Media/Create.cshtml", model));
        }
Exemple #26
0
        public void AddMediaToProductComplianceTest()
        {
            var testUser    = GetTestUser();
            var testCompany = GetTestCompany(testUser);
            var product     = createProduct(testCompany, testUser);

            ProductService.InsertOrUpdateProduct(product, testUser, "");

            var pcList = ProductService.FindProductComplianceListModel(product.Id);

            if (pcList.Items.Count > 0)
            {
                foreach (var pc in pcList.Items)
                {
                    ProductService.DeleteProductCompliance(pc.Id);
                }
            }

            // Check number of pc in list before test
            pcList = ProductService.FindProductComplianceListModel(product.Id);
            int expected = 0;
            int actual   = pcList.Items.Count();

            Assert.IsTrue(actual == expected, $"Error: {actual} items were found when {expected} were expected");

            // Create X number of records
            int randomNoOfRecords = RandomInt(5, 20);

            for (var i = 0; i < randomNoOfRecords; i++)
            {
                // Create Product Compliance
                var prodCom = createProductCompliance(testCompany, product);
                var error   = ProductService.InsertOrUpdateProductCompliance(prodCom, "");
                Assert.IsTrue(!error.IsError, error.Message);
                // Create Media
                var media      = new MediaModel();
                var targetFile = GetTempFile(".jpg");
                error = MediaServices.InsertOrUpdateMedia(media, testCompany, testUser, Evolution.Enumerations.MediaFolder.ProductCompliance,
                                                          targetFile, "", prodCom.ProductId, prodCom.Id, FileCopyType.Move);
                Assert.IsTrue(!error.IsError, error.Message);

                ProductService.AddMediaToProductCompliance(prodCom, media);
            }

            pcList   = ProductService.FindProductComplianceListModel(product.Id);
            expected = randomNoOfRecords;
            actual   = pcList.Items.Count();
            Assert.IsTrue(actual == expected, $"Error: {actual} items were found when {expected} were expected");

            // Delete them
            foreach (var pc in pcList.Items)
            {
                ProductService.DeleteProductCompliance(pc.Id);
            }
            // Check number of pc in list before test
            pcList   = ProductService.FindProductComplianceListModel(product.Id);
            expected = 0;
            actual   = pcList.Items.Count();
            Assert.IsTrue(actual == expected, $"Error: {actual} items were found when {expected} were expected");
        }
Exemple #27
0
        private void btnDeleteMedia_Click(object sender, EventArgs e)
        {
            if (_selectedMedia != null)
            {
                DialogResult result = MessageBox.Show("Do you want to delete " + _selectedMedia.MediaTitle, "Delete Media", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    //Delete user in DB
                    int affectedRows = _mediaLogic.DeleteMediaByID(_selectedMedia.MediaID);
                    if (affectedRows > 0)
                    {
                        lbStripStatus.Text = "\"" + _selectedMedia.MediaTitle + "\"" + " has been deleted";
                    }
                    else
                    {
                        //couldn't find any users of this userID
                    }

                    //Clear out selectedUser
                    _selectedMedia = null;

                    txtSeletedID.Text       = "";
                    txtSeletedTitle.Text    = "";
                    txtSeletedDirector.Text = "";
                    txtSeletedGenre.Text    = "";
                    txtSeletedLanguage.Text = "";
                    txtSeletedPublish.Text  = "";
                    txtSeletedBudget.Text   = "";

                    //refresh list
                    RefreshMediaList();
                }
            }
        }
        private async Task <MediaModel> LoadMediaModel()
        {
            MediaModel model = null;

            try
            {
                model = (await SvrfApiSingleton.Instance.Media.GetByIdAsync(_svrfModel.SvrfModelId)).Media;
                if (model.Type != MediaType.Model3D)
                {
                    SetErrorMessage(InvalidMediaTypeMessage);
                }
            }
            catch (ArgumentException)
            {
                SetErrorMessage(NoApiKeyMessage);
            }
            catch (ApiKeyNotFoundException)
            {
                SetErrorMessage(NoApiKeyMessage);
            }
            catch
            {
                SetErrorMessage(ModelIdNotFoundMessage);
            }

            return(model);
        }
        public IPagedResponse <MediaModel> Get([FromUri] PagingFilter filter)
        {
            if (filter == null)
            {
                filter = new PagingFilter(1, 25);
            }

            var userId = this.getUserId();

            IPagedResponse <IMedia> results = Business.Media.Media.GetMedia(userId, filter.Page, filter.Size);

            ICollection <MediaModel> models = new List <MediaModel>();

            if (results.Data != null)
            {
                foreach (IMedia a in results.Data)
                {
                    var model = MediaModel.Load(a);
                    models.Add(model);
                }
            }

            return(new PagedResponse <MediaModel>()
            {
                TotalCount = results.TotalCount,
                Data = models
            });
        }
        public MediaModel GetMediaByAssetId(int assetId)
        {
            IMedia     result = Business.Media.Media.GetMediaByAssetId(assetId);
            MediaModel media  = MediaModel.Load(result);

            return(media);
        }
        void InitializePlaybackList()
        {
            // Initialize the playlist data/view model.
            // In a production app your data would be sourced from a data store or service.

            // Add content
            var media1 = new MediaModel();
            media1.Title = "Fitness";
            media1.MediaUri = new Uri("ms-appx:///Assets/Media/multivideo-with-captions.mkv");
            media1.ArtUri = new Uri("ms-appx:///Assets/Media/multivideo.jpg");
            playlistView.Media.Add(media1);

            var media2 = new MediaModel();
            media2.Title = "Elephant's Dream";
            media2.MediaUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-H264_SD-AAC_eng-AAC_spa-AAC_eng_commentary-SRT_eng-SRT_por-SRT_swe.mkv");
            media2.ArtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream.jpg");
            playlistView.Media.Add(media2);

            var media3 = new MediaModel();
            media3.Title = "Sintel";
            media3.MediaUri = new Uri("ms-appx:///Assets/Media/sintel_trailer-480p.mp4");
            media3.ArtUri = new Uri("ms-appx:///Assets/Media/sintel.jpg");
            playlistView.Media.Add(media3);

            // Pre-cache all album art to facilitate smooth gapless transitions.
            // A production app would have a more sophisticated object cache.
            foreach (var media in playlistView.Media)
            {
                var bitmap = new BitmapImage();
                bitmap.UriSource = media.ArtUri;
                artCache[media.ArtUri.ToString()] = bitmap;
            }

            // Initialize the playback list for this content
            foreach(var media in playlistView.Media)
            {
                var mediaSource = MediaSource.CreateFromUri(media.MediaUri);
                mediaSource.CustomProperties["uri"] = media.MediaUri;

                var playbackItem = new MediaPlaybackItem(mediaSource);

                playbackList.Items.Add(playbackItem);
            }

            // Subscribe for changes
            playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;

            // Loop
            playbackList.AutoRepeatEnabled = true;
        }
        private ICollection<MediaModel> GenerateMedias(int count)
        {
            var medias = new List<MediaModel>();

            for (int i = 0; i < count; i++)
            {
                var media = new MediaModel()
                {
                    Name = "Media #" + i,
                    PriceSubscriptionPerMonth = 100 + i,
                    Type = (MediaType)Enum.Parse(typeof(MediaType), (i % 3).ToString())
                };

                medias.Add(media);
            }

            return medias;
        }
Exemple #33
0
        /// <summary>
        /// Scans all the individual episodes from a tv show in plex library
        /// </summary>
        /// <param name="id"></param>
        /// <param name="showTitle"></param>
        /// <param name="showSortTitle"></param>
        /// <param name="showRemoteSourceId"></param>
        /// <returns></returns>
        public IEnumerable<ContentModel> ScanEpisodes(int id, string showTitle, string showSortTitle, string showRemoteSourceId, string libraryName)
        {
            var results = new List<ContentModel>();

            var xml = XDocument.Load(string.Format("http://{0}/library/metadata/{1}/allLeaves", _plexServerAddress, id));

            foreach (var node in xml.Descendants("Video"))
            {
                var content = new ContentModel()
                {
                    VideoType = VideoType.TvShowEpisode,
                    Title = ReadAttribute(node, "title"),
                    Season = Convert.ToInt32(ReadNumberAttribute(node, "parentIndex")),
                    Episode = Convert.ToInt32(ReadNumberAttribute(node, "index")),
                    ParentId = id,
                    ParentRemoteSourceId = showRemoteSourceId,
                    ParentTitle = showTitle,
                    ParentSortTitle = showSortTitle,
                    LibraryName = libraryName
                };

                var media = new List<MediaModel>();

                // add a record for each file
                foreach (var mediaNode in node.Descendants("Media"))
                {
                    var mediaModel = new MediaModel()
                    {
                        VideoId = Convert.ToInt32(ReadNumberAttribute(node, "ratingKey")),
                        MediaId = Convert.ToInt32(ReadNumberAttribute(mediaNode, "id")),
                        AspectRatio = (decimal)ReadNumberAttribute(mediaNode, "aspectRatio"),
                        Resolution = ReadAttribute(mediaNode, "videoResolution"),
                        DateAdded = ReadDateAttribute(node, "addedAt")
                    };

                    var part = mediaNode.Descendants("Part").FirstOrDefault();
                    if (part != null)
                    {
                        mediaModel.Size = ReadNumberAttribute(part, "size");
                        mediaModel.FilePath = ReadAttribute(part, "file");
                    }

                    media.Add(mediaModel);
                }

                content.MediaModels = media.ToArray();
                content.ModelHash = CalculateComparisonHash(content);

                results.Add(content);
            }

            return results;
        }