Beispiel #1
0
 public virtual int GetNumberOfDownloads(int productId)
 {
     return(_productDownloadsLogService.GetAsQueryable()
            .DeferredCount(p => p.ProductId == productId)
            .FromCache(DateTimeOffset.Now.AddHours(24)));
 }
Beispiel #2
0
        public virtual async Task <ActionResult> DownloadProduct(int productId, bool?demoFiles)
        {
            var product = await _productService.FindByIdAsync(productId);

            var user = await UserManager.FindByIdAsync(HttpContext.User.Identity.GetUserId());

            var requestDemoFiles = demoFiles ?? false;

            if (product == null || (!product.Published && !HttpContext.User.IsInRole("Admin")))
            {
                return(View("PageNotFound")); // product id is invalid or not published
            }
            var model = new DownloadModel
            {
                PageTitle      = product.GetLocalized(p => p.Title),
                ProductPageUrl = Url.Action("Index", "Product", new { slug = product.Slug }),
                IsDemo         = requestDemoFiles
            };

            var userHasAccessToFiles = _productService.UserCanDownloadProduct(product, user, requestDemoFiles);
            var canDownload          =
                userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserCanDownloadProduct);

            if (!canDownload &&
                (!string.IsNullOrWhiteSpace(product.FilesPath) ||
                 product.CheckoutAttributes.Any(p =>
                                                p.Options.Any(x => !string.IsNullOrWhiteSpace(x.FilesPath)))))
            {
                model.UserHasAccessToFiles   = userHasAccessToFiles;
                model.DiscountsForUserGroups = GenerateUserGroupDiscountsDescription(product, user);
            }
            //---------------------------

            //User must upgrade subscription
            if (userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlan) ||
                userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserMustSubscribeToAPlanOrHigher))
            {
                model.UserGroupName = product.DownloadLimitedToUserGroup.GetLocalized(p => p.GroupName);
            }

            //User download limit has been reached
            if (userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserDownloadLimitReached) ||
                userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserGroupDownloadLimitReached))
            {
                TimePeriodType?periodType = null;
                //User number of download limitation
                if (userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserDownloadLimitReached))
                {
                    if (user.MaxDownloadCount > 0 && user.MaxDownloadPeriodType != null)
                    {
                        model.DownloadLimit = user.MaxDownloadCount.Value;
                        periodType          = user.MaxDownloadPeriodType.Value;
                    }
                }

                //User group number of download limitation
                if (userHasAccessToFiles.HasFlagFast(ProductService.UserCanDownloadProductResult.UserGroupDownloadLimitReached))
                {
                    if (user.UserGroup?.MaxDownloadCount > 0 && user.UserGroup?.MaxDownloadPeriodType != null)
                    {
                        model.DownloadLimit = user.UserGroup.MaxDownloadCount.Value;
                        periodType          = user.UserGroup.MaxDownloadPeriodType.Value;
                    }
                }

                var date = DateTime.Now.AddTimePeriodToDateTime(periodType, -1);
                var userLatestDownloadDate = _downloadsLogService.GetAsQueryable().Where(p =>
                                                                                         p.UserId == user.Id &&
                                                                                         p.DownloadDate >= date && p.ProductId != product.Id &&
                                                                                         !p.IsDemoVersion)
                                             .OrderByDescending(p => p.DownloadDate).FirstOrDefault()
                                             ?.DownloadDate
                                             ??
                                             DateTime.Now;

                model.DownloadLimitResetDate = userLatestDownloadDate.AddTimePeriodToDateTime(periodType, 1) ?? DateTime.MaxValue;

                switch (periodType)
                {
                case TimePeriodType.Hour:
                    model.DownloadLimitPer = _localizationService.GetResource("Hour");
                    break;

                case TimePeriodType.Day:
                    model.DownloadLimitPer = _localizationService.GetResource("Day");
                    break;

                case TimePeriodType.Month:
                    model.DownloadLimitPer = _localizationService.GetResource("Month");
                    break;

                case TimePeriodType.Year:
                    model.DownloadLimitPer = _localizationService.GetResource("Year");
                    break;

                default:
                    model.DownloadLimitPer = "";
                    break;
                }
            }
            //---------------------------

            var productTitle = product.GetLocalized(p => p.Title);
            var filesPath    = requestDemoFiles ? product.DemoFilesPath : product.FilesPath;

            if (!string.IsNullOrWhiteSpace(filesPath))
            {
                if (product.FileServerId != null)
                {
                    //Load files from server
                    var entriesList = await Task.Run(() =>
                    {
                        var fileServer = _fileServersService.GetWebService(product.FileServer);
                        return(fileServer.EnumerateDirectoryEntries(filesPath,
                                                                    CurrentSettings.DownloadableFilesExtensions, true, true,
                                                                    TimeSpan.FromHours(CurrentSettings.DownloadUrlsAgeByHour),
                                                                    CurrentSettings.NumberOfDownloadUrlsFireLimit));
                    }).ConfigureAwait(false);

                    model.FileGroups.Add(new FileGroup()
                    {
                        Title        = productTitle,
                        FileListTree = entriesList.Length > 0
                            ? GenerateFileTreeHtml(entriesList.ToList(), canDownload, productId, requestDemoFiles)
                            : ""
                    });
                }
                else
                {
                    //File(s) is in outside of server
                    var downloadLink = canDownload
                        ? Url.Action("DownloadLog", new { productId = productId, downloadLink = filesPath, version = requestDemoFiles ? ("DEMO" + productId).EncryptString() : ("FULL" + productId).EncryptString() })
                        : $"#' onclick='WarningAlert(\"{_localizationService.GetResource("Note")}\", \"{_localizationService.GetResource("YouDoNotHaveAccessRightsToThisFile")}\")";
                    model.FileGroups.Add(new FileGroup()
                    {
                        Title        = productTitle,
                        FileListTree = $"<ul><li data-jstree='{{\"icon\":\"/Content/img/FileExtIcons/download.png\"}}'><a target='_blank' href='{downloadLink}'><img src='/Content/img/FileExtIcons/link.png'/> <span class='{(productTitle.IsRtlLanguage() ? "rtl-dir" : "ltr-dir")}'>{productTitle}</span></a></li></ul>"
                    });
                }
            }
            else
            {
                model.FileGroups.Add(new FileGroup()
                {
                    Title        = productTitle,
                    FileListTree = ""
                });
            }

            if (!requestDemoFiles)
            {
                //Get product attributes files
                var userPurchasedAttributes = await _productService.GetUserDownloadableAttributesAsync(product, user);

                var productCheckoutAttributes =
                    await _productCheckoutAttributesService.FindProductAttributesAsync(productId);

                foreach (var attribute in productCheckoutAttributes.Where(p => p.Options.Any(x => !string.IsNullOrWhiteSpace(x.FilesPath))).OrderBy(p => p.DisplayOrder))
                {
                    var attributeName    = attribute.GetLocalized(p => p.Name);
                    var fileListTreeHtml = "";

                    foreach (var attributeOption in attribute.Options.Where(p => !string.IsNullOrWhiteSpace(p.FilesPath)).OrderBy(p => p.DisplayOrder))
                    {
                        var optionName       = attributeOption.GetLocalized(p => p.Name);
                        var showDownloadLink = userPurchasedAttributes.Any(p => p.Id == attributeOption.Id);
                        {
                            fileListTreeHtml +=
                                $"<li data-jstree='{{\"icon\":\"/Content/img/FileExtIcons/dir.png\"}}'>{optionName}<ul>";
                            if (!string.IsNullOrWhiteSpace(attributeOption.FilesPath))
                            {
                                if (attributeOption.FileServerId != null)
                                {
                                    //Load files from server
                                    var entriesList = await Task.Run(() =>
                                    {
                                        var fileServer = _fileServersService.GetWebService(attributeOption.FileServer);
                                        return(fileServer.EnumerateDirectoryEntries(attributeOption.FilesPath,
                                                                                    CurrentSettings.DownloadableFilesExtensions, true, true,
                                                                                    TimeSpan.FromHours(CurrentSettings.DownloadUrlsAgeByHour),
                                                                                    CurrentSettings.NumberOfDownloadUrlsFireLimit));
                                    }).ConfigureAwait(false);

                                    fileListTreeHtml += entriesList.Length > 0
                                        ? GenerateFileTreeHtml(entriesList.ToList(), showDownloadLink, productId, requestDemoFiles).TrimStart("<ul>").TrimEnd("</ul>")
                                        : "";
                                }
                                else
                                {
                                    //File(s) is in outside of server
                                    var downloadLink = showDownloadLink ?
                                                       Url.Action("DownloadLog", new { productId = productId, downloadLink = attributeOption.FilesPath, version = requestDemoFiles ? ("DEMO" + productId).EncryptString() : ("FULL" + productId).EncryptString() })
                                        : $"#' onclick='WarningAlert(\"{_localizationService.GetResource("Note")}\", \"{_localizationService.GetResource("YouDoNotHaveAccessRightsToThisFile")}\")";
                                    fileListTreeHtml +=
                                        $"<li data-jstree='{{\"icon\":\"/Content/img/FileExtIcons/download.png\"}}'><a target='_blank' href='{downloadLink}'><img src='/Content/img/FileExtIcons/link.png'/> <span class='{(optionName.IsRtlLanguage() ? "rtl-dir" : "ltr-dir")}'>{optionName}</span></a></li>";
                                }
                            }

                            fileListTreeHtml += "</li></ul>";
                        }
                    }

                    model.FileGroups.Add(new FileGroup()
                    {
                        Title        = attributeName,
                        FileListTree = string.IsNullOrWhiteSpace(fileListTreeHtml) ? "" : $"<ul>{fileListTreeHtml}</ul>"
                    });
                }
            }

            return(View(model));
        }