Example #1
0
        public StatusWithMessage PurgeStaticFiles([FromBody] PurgeStaticFilesRequestModel model)
        {
            List <string> allowedFileExtensions = new List <string>()
            {
                ".css", ".js", ".jpg", ".png", ".gif", ".aspx", ".html"
            };
            string generalSuccessMessage = "Successfully purged the cache for the selected static files.";
            string generalErrorMessage   = "Sorry, we could not purge the cache for the static files.";

            if (model.StaticFiles == null)
            {
                return(new StatusWithMessage(false, generalErrorMessage));
            }

            if (!model.StaticFiles.Any())
            {
                return(new StatusWithMessage(true, generalSuccessMessage));
            }

            List <StatusWithMessage> errors;
            IEnumerable <string>     allFilePaths = GetAllFilePaths(model.StaticFiles, out errors);

            //Save a list of each individual file if it errors so we can give detailed errors to the user.
            List <StatusWithMessage> results = new List <StatusWithMessage>();

            List <string> fullUrlsToPurge = new List <string>();

            //build the urls with the domain we are on now
            foreach (string filePath in allFilePaths)
            {
                string extension = Path.GetExtension(filePath);

                if (!allowedFileExtensions.Contains(extension))
                {
                    //results.Add(new StatusWithMessage(false, String.Format("You cannot purge the file {0} because its extension is not allowed.", filePath)));
                }
                else
                {
                    fullUrlsToPurge.AddRange(UrlHelper.MakeFullUrlWithDomain(filePath, model.Hosts, true));
                }
            }

            results.AddRange(CloudflareManager.Instance.PurgePages(fullUrlsToPurge));

            if (results.Any(x => !x.Success))
            {
                return(new StatusWithMessage(false, CloudflareManager.PrintResultsSummary(results)));
            }
            else
            {
                return(new StatusWithMessage(true, String.Format("{0} static files purged successfully.", results.Where(x => x.Success).Count())));
            }
        }
Example #2
0
        public StatusWithMessage PurgeAll()
        {
            //it doesn't matter what domain we pick bc it will purge everything.
            IEnumerable <string> domains = UmbracoFlareDomainManager.Instance.GetDomainsFromCloudflareZones();

            List <StatusWithMessage> results = new List <StatusWithMessage>();

            foreach (string domain in domains)
            {
                results.Add(CloudflareManager.Instance.PurgeEverything(domain));
            }

            return(new StatusWithMessage()
            {
                Success = !results.Any(x => !x.Success), Message = CloudflareManager.PrintResultsSummary(results)
            });
        }
Example #3
0
        public StatusWithMessage PurgeCacheForUrls([FromBody] PurgeCacheForUrlsRequestModel model)
        {
            /*Important to note that the urls can come in here in two different ways.
             * 1) They can come in here without domains on them. If that is the case then the domains property should have values.
             *      1a) They will need to have the urls built by appending each domain to each url. These urls technically might not exist
             *          but that is the responsibility of whoever called this method to ensure that. They will still go to cloudflare even know the
             *          urls physically do not exists, which is fine because it won't cause an error.
             * 2) They can come in here with domains, if that is the case then we are good to go, no work needed.
             *
             * */

            if (model.Urls == null || !model.Urls.Any())
            {
                return(new StatusWithMessage(false, "You must provide urls to clear the cache for."));
            }

            List <string> builtUrls = new List <string>();

            //Check to see if there are any domains. If there are, then we know that we need to build the urls using the domains
            if (model.Domains != null && model.Domains.Any())
            {
                builtUrls.AddRange(UrlHelper.MakeFullUrlWithDomain(model.Urls, model.Domains, true));
            }
            else
            {
                builtUrls = model.Urls.ToList();
            }

            builtUrls.AddRange(AccountForWildCards(builtUrls));

            List <StatusWithMessage> results = CloudflareManager.Instance.PurgePages(builtUrls);

            if (results.Any(x => !x.Success))
            {
                return(new StatusWithMessage(false, CloudflareManager.PrintResultsSummary(results)));
            }
            else
            {
                return(new StatusWithMessage(true, String.Format("{0} urls purged successfully.", results.Count(x => x.Success))));
            }
        }
        protected void PurgeCloudflareCacheForMedia(IMediaService sender, SaveEventArgs <IMedia> e)
        {
            //If we have the cache buster turned off then just return.
            if (!CloudflareConfiguration.Instance.PurgeCacheOn)
            {
                return;
            }

            List <Crop>   imageCropSizes = ImageCropperManager.Instance.GetAllCrops();
            List <string> urls           = new List <string>();

            UmbracoHelper uh = new UmbracoHelper(UmbracoContext.Current);

            //GetUmbracoDomains
            IEnumerable <string> domains = UmbracoFlareDomainManager.Instance.AllowedDomains;

            //delete the cloudflare cache for the saved entities.
            foreach (IMedia media in e.SavedEntities)
            {
                if (media.IsNewEntity())
                {
                    //If its new we don't want to purge the cache as this causes slow upload times.
                    continue;
                }

                try
                {
                    //Check to see if the page has cache purging on publish disabled.
                    if (media.GetValue <bool>("cloudflareDisabledOnPublish"))
                    {
                        //it was disabled so just continue;
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    //continue;
                }

                IPublishedContent publishedMedia = uh.TypedMedia(media.Id);

                if (publishedMedia == null)
                {
                    e.Messages.Add(new EventMessage("Cloudflare Caching", "We could not find the IPublishedContent version of the media: " + media.Id + " you are trying to save.", EventMessageType.Error));
                    continue;
                }
                foreach (Crop crop in imageCropSizes)
                {
                    urls.Add(publishedMedia.GetCropUrl(crop.alias));
                }
                urls.Add(publishedMedia.Url);
            }


            List <StatusWithMessage> results = CloudflareManager.Instance.PurgePages(UrlHelper.MakeFullUrlWithDomain(urls, domains, true));

            if (results.Any() && results.Where(x => !x.Success).Any())
            {
                e.Messages.Add(new EventMessage("Cloudflare Caching", "We could not purge the Cloudflare cache. \n \n" + CloudflareManager.PrintResultsSummary(results), EventMessageType.Warning));
            }
            else if (results.Any())
            {
                e.Messages.Add(new EventMessage("Cloudflare Caching", "Successfully purged the cloudflare cache.", EventMessageType.Success));
            }
        }
        protected void PurgeCloudflareCache(IPublishingStrategy strategy, PublishEventArgs <IContent> e)
        {
            //If we have the cache buster turned off then just return.
            if (!CloudflareConfiguration.Instance.PurgeCacheOn)
            {
                return;
            }

            List <string> urls = new List <string>();

            //Else we can continue to delete the cache for the saved entities.
            foreach (IContent content in e.PublishedEntities)
            {
                try
                {
                    //Check to see if the page has cache purging on publish disabled.
                    if (content.GetValue <bool>("cloudflareDisabledOnPublish"))
                    {
                        //it was disabled so just continue;
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    //continue;
                }

                urls.AddRange(UmbracoFlareDomainManager.Instance.GetUrlsForNode(content, false));
            }

            List <StatusWithMessage> results = CloudflareManager.Instance.PurgePages(urls);

            if (results.Any() && results.Where(x => !x.Success).Any())
            {
                e.Messages.Add(new EventMessage("Cloudflare Caching", "We could not purge the Cloudflare cache. \n \n" + CloudflareManager.PrintResultsSummary(results), EventMessageType.Warning));
            }
            else if (results.Any())
            {
                e.Messages.Add(new EventMessage("Cloudflare Caching", "Successfully purged the cloudflare cache.", EventMessageType.Success));
            }
        }
        private void PurgeCloudflareCacheForFiles <T>(IEnumerable <File> files, SaveEventArgs <T> e)
        {
            //If we have the cache buster turned off then just return.
            if (!CloudflareConfiguration.Instance.PurgeCacheOn)
            {
                return;
            }

            List <string> urls = new List <string>();
            UmbracoHelper uh   = new UmbracoHelper(UmbracoContext.Current);
            //GetUmbracoDomains
            IEnumerable <string> domains = UmbracoFlareDomainManager.Instance.AllowedDomains;

            foreach (var file in files)
            {
                if (file.IsNewEntity())
                {
                    //If its new we don't want to purge the cache as this causes slow upload times.
                    continue;
                }

                urls.Add(file.VirtualPath);
            }


            List <StatusWithMessage> results = CloudflareManager.Instance.PurgePages(UrlHelper.MakeFullUrlWithDomain(urls, domains, true));

            if (results.Any() && results.Where(x => !x.Success).Any())
            {
                e.Messages.Add(new EventMessage("Cloudflare Caching", "We could not purge the Cloudflare cache. \n \n" + CloudflareManager.PrintResultsSummary(results), EventMessageType.Warning));
            }
            else if (results.Any())
            {
                e.Messages.Add(new EventMessage("Cloudflare Caching", "Successfully purged the cloudflare cache.", EventMessageType.Success));
            }
        }
        public IHttpActionResult ConfirmWebsite(string websiteId)
        {
            ew.common.EwhLogger.Common.Debug("START CONFIRM WEBSITE: " + websiteId);
            if (ModelState.IsValid)
            {
                var ewhWebsite = _websiteManager.GetEwhWebsite(websiteId);
                if (ewhWebsite == null)
                {
                    return(NotFound());
                }
                var githubManager = new GitHubManager();
                Octokit.Repository gitRepository = null;
                //create github repository
                if (string.IsNullOrEmpty(ewhWebsite.Git))
                {
                    if (githubManager.CreateRepository(ewhWebsite.RepositoryName, ewhWebsite.DisplayName).Result)
                    {
                        gitRepository  = githubManager.RepositoryAdded;
                        ewhWebsite.Git = githubManager.RepositoryAdded.CloneUrl;
                        ewhWebsite.Save();
                    }
                    else
                    {
                        EwhLogger.Common.Debug(string.Format("Create Repository Failed: {0} - {1}", ewhWebsite.RepositoryName, ewhWebsite.DisplayName));
                        return(NoOK("Can not create github repository"));
                    }
                }
                else
                {
                    gitRepository = githubManager.GetRepository(repoName: ewhWebsite.RepositoryName).Result;
                }

                if (string.IsNullOrEmpty(ewhWebsite.Source))
                {
                    ewhWebsite.InitGogSource();
                }
                if (string.IsNullOrEmpty(ewhWebsite.Source))
                {
                    return(NoOK("Source_Empty"));
                }

                // add web-hook to demo & production server
                var ewhGogsSource     = new EwhSource();
                var ewhAccountAsOwner = _accountManager.GetEwhAccount(ewhWebsite.GetOwnerId());
                if (ewhAccountAsOwner != null)
                {
                    ewhGogsSource.CreateWebHook(new EwhSource.CreateWebHookDto(ewhAccountAsOwner.UserName, ewhWebsite.RepositoryName));

                    ewhGogsSource.CreateWebHook(new EwhSource.CreateWebHookDto(ewhAccountAsOwner.UserName, ewhWebsite.RepositoryName, ew.config.ProductionServer.WebHookUrl, ew.config.ProductionServer.SecretKey));
                }

                // create sub domain
                var websiteDomain     = string.Empty;
                var subDomainName     = string.Format("{0}-{1}.{2}", ewhAccountAsOwner.UserName, ewhWebsite.Name, ew.config.CloudflareInfo.EwhDomain).ToLower();
                var cloudflareManager = new CloudflareManager();
                if (cloudflareManager.CreateDNSRecord(ew.config.CloudflareInfo.EwhCloudflareZoneId, new cloudflare_wrapper.Models.UpdateDNSRecordDto()
                {
                    Type = "CNAME", Name = subDomainName, Content = "easywebhub.github.io"
                }))
                {
                    websiteDomain = cloudflareManager.DNSRecordAdded.name;
                }
                else
                {
                }

                if (gitRepository != null)
                {
                    var gitUrlIncludePass  = githubManager.GetGitUrlIncludePassword(ewhWebsite.Git);
                    var sourceRepoUrl      = ewhWebsite.Source;
                    var ewhGitHookListener = new EwhGitHookListener();
                    var demoGitHook        = new git_hook_listener.Models.CreateGitHookListenerConfigDto()
                    {
                        GitHookListenerBaseUrl = ew.config.DemoServer.BaseUrl,
                        repoUrl     = sourceRepoUrl,
                        branch      = "gh-pages",
                        cloneBranch = "gh-pages",
                        path        = string.Format("repositories/{0}", gitRepository.Name),
                        args        = new List <string>(),
                        then        = new List <git_hook_listener.Models.RepoCommand>()
                    };
                    demoGitHook.then.Add(new git_hook_listener.Models.RepoCommand()
                    {
                        command = "git", args = new List <string>()
                        {
                            "remote", "add", "github", gitUrlIncludePass
                        }, options = new git_hook_listener.Models.RepoCommandOption()
                        {
                            cwd = demoGitHook.path
                        }
                    });
                    demoGitHook.then.Add(new git_hook_listener.Models.RepoCommand()
                    {
                        command = "git", args = new List <string>()
                        {
                            "push", "--force", "github", "HEAD:gh-pages"
                        }, options = new git_hook_listener.Models.RepoCommandOption()
                        {
                            cwd = demoGitHook.path
                        }
                    });

                    if (ewhGitHookListener.CreateGitHookListernerConfig(demoGitHook))
                    {
                        ewhWebsite.AddStagging(new UpdateDeploymentEnvironmentToWebsite()
                        {
                            Url = websiteDomain, Git = sourceRepoUrl, HostingFee = HostingFees.Free.ToString(), Name = "EasyWeb Environment"
                        });
                    }

                    var productionGitHook = new git_hook_listener.Models.CreateGitHookListenerConfigDto()
                    {
                        GitHookListenerBaseUrl = ew.config.ProductionServer.BaseUrl,
                        repoUrl     = sourceRepoUrl,
                        branch      = "master",
                        cloneBranch = "master",
                        path        = string.Format("repositories/{0}", gitRepository.Name)
                    };
                    productionGitHook.then.Add(new git_hook_listener.Models.RepoCommand()
                    {
                        command = "git", args = new List <string>()
                        {
                            "remote", "add", "github", gitUrlIncludePass
                        }, options = new git_hook_listener.Models.RepoCommandOption()
                        {
                            cwd = productionGitHook.path
                        }
                    });
                    productionGitHook.then.Add(new git_hook_listener.Models.RepoCommand()
                    {
                        command = "git", args = new List <string>()
                        {
                            "push", "--force", "github", "gh-pages"
                        }, options = new git_hook_listener.Models.RepoCommandOption()
                        {
                            cwd = productionGitHook.path
                        }
                    });

                    if (ewhGitHookListener.CreateGitHookListernerConfig(productionGitHook))
                    {
                        ewhWebsite.AddProduction(new UpdateDeploymentEnvironmentToWebsite()
                        {
                            Git = sourceRepoUrl, HostingFee = HostingFees.Basic.ToString(), Name = "Production Enviroment"
                        });
                    }
                }
                return(Ok(new WebsiteDetailDto(ewhWebsite)));
            }
            return(BadRequest());
        }