public object GetPage(int pageId)
        {
            try {
                // Look for the page with the specified ID
                IDashboardPage page = DashboardContext.Current.GetPageById(pageId);
                if (page == null || page.Content == null)
                {
                    throw new DashboardException("Den pågældende side ser ikke til at være publiceret");
                }

                // Throw an exception if the site wasn't found
                if (page.Site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Det efterspurgte site blev ikke fundet.");
                }

                return(new {
                    page,
                    site = page.Site,
                    blocks = page.GetBlocks()
                });
            } catch (DashboardException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            } catch (Exception ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(
                                                  HttpStatusCode.InternalServerError,
                                                  "Unknown server error. Check the log for further information."
                                                  )));
            }
        }
Example #2
0
        public object AddRedirect([FromBody] JObject m)
        {
            var model = m.ToObject <AddRedirectOptions>();

            try {
                // Some input validation
                if (string.IsNullOrWhiteSpace(model.OriginalUrl))
                {
                    throw new RedirectsException(Localize("redirects/errorNoUrl") + "----");
                }
                if (string.IsNullOrWhiteSpace(model.Destination?.Url))
                {
                    throw new RedirectsException(Localize("redirects/errorNoDestination") + "\r\n\r\n" + m);
                }

                // Add the redirect
                RedirectItem redirect = _redirects.AddRedirect(model);

                // Return the redirect
                return(redirect);
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
        public object GetSiteData(int siteId, string period, bool cache = true)
        {
            DashboardHelpers.EnsureCurrentUserCulture();

            try {
                // Get the site
                IDashboardSite site = DashboardContext.Current.GetSiteById(siteId);
                if (site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Site ikke fundet", "Et site det angivne ID blev ikke fundet");
                }

                // Get analytics information
                IAnalyticsSite analytics = site as IAnalyticsSite;
                if (analytics == null || !analytics.HasAnalytics)
                {
                    throw new DashboardException(HttpStatusCode.InternalServerError, "Analytics", "Det valgte side understøtter eller er ikke konfigureret til visning af statistik fra Google Analytics");
                }

                // Build the query
                DataQuery query = DataQuery.GetFromPeriod(analytics, period, cache);
                query.Type = DataQueryType.Site;

                // Generate the response object
                DataResponse res = query.GetResponse();

                // Return a nice JSON response
                return(JsonMetaResponse.GetSuccess(res));
            } catch (DashboardException ex) {
                return(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Title + ": " + ex.Message));
            } catch (Exception ex) {
                return(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Oopsie (" + ex.GetType() + "): " + ex.Message, ex.StackTrace.Split('\n')));
            }
        }
Example #4
0
        public object GetAccounts(string userId)
        {
            AnalyticsConfig cfg = AnalyticsConfig.Current;

            AnalyticsConfigUser user = cfg.GetUserById(userId);

            if (user == null)
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.NotFound, "User not found.")));
            }

            GoogleService google = GoogleService.CreateFromRefreshToken(
                user.Client.ClientId,
                user.Client.ClientSecret,
                user.RefreshToken
                );

            var response1 = google.Analytics.Management.GetAccounts(new AnalyticsGetAccountsOptions(1000));
            var response2 = google.Analytics.Management.GetWebProperties(new AnalyticsGetWebPropertiesOptions(1000));
            var response3 = google.Analytics.Management.GetProfiles(new AnalyticsGetProfilesOptions(1000));

            var accounts      = response1.Body.Items;
            var webProperties = response2.Body.Items;
            var profiles      = response3.Body.Items;

            var body = new Models.Api.Selector.UserModel(user, accounts, webProperties, profiles);

            return(body);
        }
        public object GetSite(int siteId, bool blocks = true)
        {
            try {
                // Look for the site with the specified ID
                IDashboardSite site = DashboardContext.Current.GetSiteById(siteId);

                // Throw an exception if the site wasn't found
                if (site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Det efterspurgte site blev ikke fundet.");
                }

                // Convert to JSON
                JObject obj = JObject.FromObject(site);

                if (blocks)
                {
                    obj.Add("blocks", JToken.FromObject(site.GetBlocks()));
                }

                return(obj);
            } catch (DashboardException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            } catch (Exception ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(
                                                  HttpStatusCode.InternalServerError,
                                                  "Unknown server error. Check the log for further information."
                                                  )));
            }
        }
Example #6
0
        public object GetRedirectsForContent(int contentId)
        {
            try {
                // Get a reference to the content item
                IContent content = Current.Services.ContentService.GetById(contentId);

                // Trigger an exception if the content item couldn't be found
                if (content == null)
                {
                    throw new RedirectsException(HttpStatusCode.NotFound, Localize("redirects/errorContentNoRedirects"));
                }

                // Generate the response
                return(JsonMetaResponse.GetSuccess(new {
                    content = new {
                        id = content.Id,
                        name = content.Name
                    },
                    redirects = _redirects.GetRedirectsByContentId(contentId)
                }));
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
Example #7
0
        public object GetRedirectsForMedia(int contentId)
        {
            try {
                // Get a reference to the media item
                IMedia media = ApplicationContext.Services.MediaService.GetById(contentId);

                // Trigger an exception if the media item couldn't be found
                if (media == null)
                {
                    throw new RedirectsException(HttpStatusCode.NotFound, Localize("redirects/errorMediaNoRedirects"));
                }

                // Generate the response
                return(JsonMetaResponse.GetSuccess(new {
                    media = new {
                        id = media.Id,
                        name = media.Name
                    },
                    redirects = Repository.GetRedirectsByMediaId(contentId)
                }));
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
Example #8
0
 public object GetRedirects(int page = 1, int limit = 20, string type = null, string text = null, int?rootNodeId = null)
 {
     try {
         return(Repository.GetRedirects(page, limit, type, text, rootNodeId));
     } catch (RedirectsException ex) {
         return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
     }
 }
        public object AddRedirect(int rootNodeId, string url, string linkMode, int linkId, string linkUrl, string linkName = null)
        {
            try {
                RedirectLinkItem redirect = RedirectLinkItem.Parse(new JObject {
                    { "id", linkId },
                    { "name", linkName + "" },
                    { "url", linkUrl },
                    { "mode", linkMode }
                });

                return(Repository.AddRedirect(rootNodeId, url, redirect));
            } catch (RedirectsException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
Example #10
0
        public object DeleteClient(string id)
        {
            var config = AnalyticsConfig.Current;

            var client = config.GetClientById(id);

            if (client == null)
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.NotFound, "OAuth client not found.")));
            }

            config.DeleteClient(client, Security.CurrentUser);

            return(true);
        }
Example #11
0
        public object DeleteUser(string id)
        {
            var config = AnalyticsConfig.Current;

            AnalyticsConfigUser user = config.GetUserById(id);

            if (user == null)
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.NotFound, "User not found.")));
            }

            config.DeleteUser(user, Security.CurrentUser);

            return(true);
        }
Example #12
0
        protected virtual HttpResponseMessage ReturnRedirect(SpaApiRequest request, string destinationUrl, HttpStatusCode statusCode = HttpStatusCode.MovedPermanently)
        {
            // Initialize the "data" object for the response
            var body = new {
                url = destinationUrl
            };

            // Append scheme/protocol and host name if not already present
            if (destinationUrl.StartsWith("/"))
            {
                destinationUrl = $"{request.Protocol}://{request.HostName}{destinationUrl}";
            }

            // Generate the response
            return(CreateSpaResponse(JsonMetaResponse.GetError(statusCode, "Page has moved", body)));
        }
        public object EditRedirect(int rootNodeId, string redirectId, string url, string linkMode, int linkId, string linkUrl, string linkName = null)
        {
            try {
                // Get the redirect from the database
                RedirectItem redirect = Repository.GetRedirectById(redirectId);
                if (redirect == null)
                {
                    throw new RedirectNotFoundException();
                }

                if (String.IsNullOrWhiteSpace(url))
                {
                    throw new RedirectsException("You must specify a URL for the redirect.");
                }
                if (String.IsNullOrWhiteSpace(linkUrl))
                {
                    throw new RedirectsException("You must specify a destination link for the redirect.");
                }
                if (String.IsNullOrWhiteSpace(linkMode))
                {
                    throw new RedirectsException("You must specify a destination link for the redirect.");
                }

                // Initialize a new link picker item
                RedirectLinkItem link = RedirectLinkItem.Parse(new JObject {
                    { "id", linkId },
                    { "name", linkName + "" },
                    { "url", linkUrl },
                    { "mode", linkMode }
                });

                string[] urlParts = url.Split('?');
                url = urlParts[0].TrimEnd('/');
                string query = urlParts.Length == 2 ? urlParts[1] : "";

                redirect.RootNodeId  = rootNodeId;
                redirect.Url         = url;
                redirect.QueryString = query;
                redirect.Link        = link;

                Repository.SaveRedirect(redirect);

                return(redirect);
            } catch (RedirectsException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
        public object DeleteRedirect(string redirectId)
        {
            try {
                // Get the redirect from the database
                RedirectItem redirect = Repository.GetRedirectById(redirectId);
                if (redirect == null)
                {
                    throw new RedirectNotFoundException();
                }

                Repository.DeleteRedirect(redirect);

                return(redirect);
            } catch (RedirectsException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
Example #15
0
        public object SaveClient([FromBody] ClientModel model)
        {
            var config = AnalyticsConfig.Current;

            var client = config.GetClientById(model.Id);

            if (client == null)
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.NotFound, "OAuth client not found.")));
            }

            client.Name         = model.Name;
            client.ClientId     = model.ClientId;
            client.ClientSecret = model.ClientSecret;

            return(new ClientModel(config.SaveClient(client, Security.CurrentUser)));
        }
        /// <summary>
        /// Returns a JSON response for a SPA redirect.
        /// </summary>
        /// <param name="request">The current request.</param>
        /// <param name="destinationUrl">The destination URL of the redirect.</param>
        /// <param name="statusCode">The status code of the response - eg. <see cref="HttpStatusCode.MovedPermanently"/>.</param>
        /// <returns>An instance of <see cref="HttpResponseMessage"/>.</returns>
        protected virtual HttpResponseMessage ReturnRedirect(SpaRequest request, string destinationUrl, HttpStatusCode statusCode)
        {
            // Initialize the "data" object for the response
            var data = new {
                url       = destinationUrl,
                permanent = statusCode == HttpStatusCode.MovedPermanently
            };

            // Initialize the response body (including the correct status code)
            JsonMetaResponse body = JsonMetaResponse.GetError(statusCode, "Page has moved", data);

            // Overwrite the status code to make the frontenders happy
            statusCode = OverwriteStatusCodes ? HttpStatusCode.OK : SpaConstants.Teapot;

            // Generate the response
            return(CreateSpaResponse(statusCode, body));
        }
        public object GetData(string url, string langKey = "da")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            try
            {
                var urlName = HandleUrlDecoding(url);

                //find siden ud fra url eller returner null
                var content = !string.IsNullOrEmpty(urlName)
                    ? UmbracoContext.Current.ContentCache.GetByXPath(string.Format(@"//*[@isDoc and @urlName=""{0}""]", urlName)).FirstOrDefault()
                    : null;

                if (content != null)
                {
                    if (content.DocumentTypeAlias.ToLower() == "frontpage")
                    {
                        return
                            (Request.CreateResponse(JsonMetaResponse.GetSuccessFromObject(content,
                                                                                          FrontpageModel.GetFromContent)));
                    }
                    else if (content.DocumentTypeAlias.ToLower() == "subpage")
                    {
                        return
                            (Request.CreateResponse(JsonMetaResponse.GetSuccessFromObject(content,
                                                                                          SubpageModel.GetFromContent)));
                    }


                    //smid en 500
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Der skete en fejl på serveren." + content.DocumentTypeAlias)));
                }
                else
                {
                    //smid en 404
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.NotFound, "Siden fandtes ikke.")));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Info(typeof(ContentApiController), String.Format("Der skete en fejl: {0}", ex.Message));

                //smid en 500
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Der skete en fejl på serveren.")));
            }
        }
        public object EditRedirect(Guid redirectId, [FromBody] EditRedirectOptions model)
        {
            try {
                // Get a reference to the redirect
                RedirectItem redirect = _redirects.GetRedirectByKey(redirectId);
                if (redirect == null)
                {
                    throw new RedirectNotFoundException();
                }

                // Some input validation
                if (string.IsNullOrWhiteSpace(model.OriginalUrl))
                {
                    throw new RedirectsException(Localize("redirects/errorNoUrl"));
                }
                if (string.IsNullOrWhiteSpace(model.Destination?.Url))
                {
                    throw new RedirectsException(Localize("redirects/errorNoDestination"));
                }

                // Split the URL and query string
                string[] urlParts = model.OriginalUrl.Split('?');
                string   url      = urlParts[0].TrimEnd('/');
                string   query    = urlParts.Length == 2 ? urlParts[1] : string.Empty;

                redirect.RootId             = model.RootNodeId;
                redirect.RootKey            = model.RootNodeKey;
                redirect.Url                = url;
                redirect.QueryString        = query;
                redirect.LinkId             = model.Destination.Id;
                redirect.LinkKey            = model.Destination.Key;
                redirect.LinkUrl            = model.Destination.Url;
                redirect.LinkMode           = model.Destination.Type;
                redirect.IsPermanent        = model.IsPermanent;
                redirect.ForwardQueryString = model.ForwardQueryString;

                // Save/update the redirect
                _redirects.SaveRedirect(redirect);

                // Return the redirect
                return(redirect);
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
        public object GetPageData(int siteId, int pageId, string period, bool cache = true)
        {
            DashboardHelpers.EnsureCurrentUserCulture();

            try {
                // Look for the site with the specified ID
                IDashboardSite site = DashboardContext.Current.GetSiteById(siteId);
                if (site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Site ikke fundet", "Et site det angivne ID blev ikke fundet");
                }

                // Attempt to cast the site to an Analytics site
                IAnalyticsSite analytics = site as IAnalyticsSite;
                if (analytics == null || !analytics.HasAnalytics)
                {
                    throw new DashboardException(HttpStatusCode.InternalServerError, "Analytics", "Det valgte side understøtter eller er ikke konfigureret til visning af statistik fra Google Analytics");
                }

                // Get the published content of the page
                IPublishedContent content = UmbracoContext.ContentCache.GetById(pageId);

                // Build the query
                DataQuery query = DataQuery.GetFromPeriod(analytics, period, cache);
                query.Type   = DataQueryType.Page;
                query.PageId = content.Id;

                // Set the URL for the query. The protocol and domain is stripped so we only have the path
                query.PageUrl = Regex.Replace(content.Url, "^http(s|)://[a-z0-9-.]+/", "/");

                // Google Analytics sees the same URL with and without a trailing slash as two different pages, so we should tell the query to check both
                string pageUrlTrimmed = query.PageUrl.TrimEnd('/');
                string pageUrlSlashed = pageUrlTrimmed + '/';
                query.PageUrls = String.IsNullOrEmpty(pageUrlTrimmed) ? new[] { pageUrlSlashed } : new[] { pageUrlTrimmed, pageUrlSlashed };

                // Generate the response object
                DataResponse res = query.GetResponse();

                // Return a nice JSON response
                return(JsonMetaResponse.GetSuccess(res));
            } catch (DashboardException ex) {
                return(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Title + ": " + ex.Message));
            } catch (Exception ex) {
                return(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Oopsie (" + ex.GetType() + "): " + ex.Message, ex.StackTrace.Split('\n')));
            }
        }
Example #20
0
        public object AddRedirect(int rootNodeId, string url, string linkMode, int linkId, string linkUrl, string linkName = null, bool permanent = true, bool regex = false, bool forward = false)
        {
            try {
                // Some input validation
                if (String.IsNullOrWhiteSpace(url))
                {
                    throw new RedirectsException(Localize("redirects/errorNoUrl"));
                }
                if (String.IsNullOrWhiteSpace(linkUrl))
                {
                    throw new RedirectsException(Localize("redirects/errorNoDestination"));
                }
                if (String.IsNullOrWhiteSpace(linkMode))
                {
                    throw new RedirectsException(Localize("redirects/errorNoDestination"));
                }

                // Parse the link mode
                RedirectLinkMode mode;
                switch (linkMode)
                {
                case "content": mode = RedirectLinkMode.Content; break;

                case "media": mode = RedirectLinkMode.Media; break;

                case "url": mode = RedirectLinkMode.Url; break;

                default: throw new RedirectsException(Localize("redirects/errorUnknownLinkMode"));
                }

                // Initialize a new link item
                RedirectLinkItem destination = new RedirectLinkItem(linkId, linkName, linkUrl, mode);

                // Add the redirect
                RedirectItem redirect = Repository.AddRedirect(rootNodeId, url, destination, permanent, regex, forward);

                // Return the redirect
                return(redirect);
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
Example #21
0
        public object DeleteRedirect(string redirectId)
        {
            try {
                // Get a reference to the redirect
                RedirectItem redirect = Repository.GetRedirectById(redirectId);
                if (redirect == null)
                {
                    throw new RedirectNotFoundException();
                }

                // Delete the redirect
                Repository.DeleteRedirect(redirect);

                // Return the redirect
                return(redirect);
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
        public object GetRedirectsForMedia(int contentId)
        {
            IMedia media = ApplicationContext.Services.MediaService.GetById(contentId);

            if (media == null)
            {
                throw new RedirectsException(HttpStatusCode.NotFound, "A media item with the specified ID could not be found.");
            }

            try {
                return(JsonMetaResponse.GetSuccess(new {
                    media = new {
                        id = media.Id,
                        name = media.Name
                    },
                    redirects = Repository.GetRedirectsByMediaId(contentId)
                }));
            } catch (RedirectsException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }
        public object GetLastEditedData(int siteId, int max = 5)
        {
            try {
                // Look for the site with the specified ID
                IDashboardSite site = DashboardContext.Current.GetSiteById(siteId);

                // Throw an exception if the site wasn't found
                if (site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Det efterspurgte site blev ikke fundet.");
                }

                // Get a reference to the current user
                //User user = umbraco.BusinessLogic.User.GetCurrent();

                // Get the last editied pages
                var pages = LastEditedItem.GetLastEditedData(site, null, max);

                // Return a nice JSON response
                return(new
                {
                    culture = CultureInfo.CurrentCulture.Name,
                    data = pages,
                });
            } catch (DashboardException ex) {
                LogHelper.Error <DashboardController>("Unable to load last edited pages for site with ID " + siteId, ex);

                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            } catch (Exception ex) {
                LogHelper.Error <DashboardController>("Unable to load last edited pages for site with ID " + siteId + ": " + ex.Message, ex);

                return(Request.CreateResponse(JsonMetaResponse.GetError(
                                                  HttpStatusCode.InternalServerError,
                                                  "Unknown server error. Check the log for further information."
                                                  )));
            }
        }
        public object SetDefaultSite(int siteId)
        {
            try {
                // Look for the site with the specified ID
                IDashboardSite site = DashboardContext.Current.GetSiteById(siteId);

                // Throw an exception if the site wasn't found
                if (site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Det efterspurgte site blev ikke fundet.");
                }

                DashboardHelpers.UserSettings.SetDefaultSite(UmbracoContext.Security.CurrentUser, site);

                return(site);
            } catch (DashboardException ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            } catch (Exception ex) {
                return(Request.CreateResponse(JsonMetaResponse.GetError(
                                                  HttpStatusCode.InternalServerError,
                                                  "Unknown server error. Check the log for further information."
                                                  )));
            }
        }
Example #25
0
        public object GetBlocks(int pageId)
        {
            IPublishedContent content = Umbraco.Content(pageId);

            if (content == null)
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError("Page not found or not published.")));
            }

            return(new {
                blocks = new [] {
                    new {
                        title = "History",
                        view = "/App_Plugins/Skybrud.Analytics/Views/Blocks/History.html",
                        periods = new [] {
                            new { name = "Yesterday", alias = "yesterday" },
                            new { name = "Last week", alias = "lastweek" },
                            new { name = "Last month", alias = "lastmonth" },
                            new { name = "Last year", alias = "lastyear" }
                        }
                    }
                }
            });
        }
        public object GetBlocksForSite(int siteId, int save = 0)
        {
            try {
                // Look for the site with the specified ID
                IDashboardSite site = DashboardContext.Current.GetSiteById(siteId);

                // Throw an exception if the site wasn't found
                if (site == null)
                {
                    throw new DashboardException(HttpStatusCode.NotFound, "Det efterspurgte site blev ikke fundet.");
                }

                // Set the active site of the user.
                //if (save == 1) DashboardHelpers.UserSettings.SetCurrentSite(umbraco.helper.GetCurrentUmbracoUser(), site);

                // Get the blocks for the site
                IDashboardBlock[] blocks = site.GetBlocks();

                // Return the blocks
                return(new {
                    site,
                    blocks
                });
            } catch (DashboardException ex) {
                LogHelper.Error <DashboardController>("Unable to load blocks for site with ID " + siteId, ex);

                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            } catch (Exception ex) {
                LogHelper.Error <DashboardController>("Unable to load blocks for site with ID " + siteId, ex);

                return(Request.CreateResponse(JsonMetaResponse.GetError(
                                                  HttpStatusCode.InternalServerError,
                                                  "Unknown server error. Check the log for further information."
                                                  )));
            }
        }
        public object GetVideoFromUrl(string url)
        {
            // Validate that we have an URL
            if (String.IsNullOrWhiteSpace(url))
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.BadRequest, "No URL specified")));
            }

            Match m1 = Regex.Match(url, "vimeo.com/([0-9]+)$");
            Match m2 = Regex.Match(url, @"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);

            if (m1.Success)
            {
                string videoId = m1.Groups[1].Value;

                if (String.IsNullOrWhiteSpace(Config.VimeoConsumerKey))
                {
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Vimeo is not configured")));
                }
                if (String.IsNullOrWhiteSpace(Config.VimeoConsumerSecret))
                {
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Vimeo is not configured")));
                }

                VimeoService vimeo = VimeoService.CreateFromConsumerKey(Config.VimeoConsumerKey, Config.VimeoConsumerSecret);

                try {
                    VimeoVideoResponse response = vimeo.Videos.GetInfo(Int32.Parse(videoId));

                    VimeoVideo video = response.Video;

                    return(new {
                        url = "https://vimeo.com/" + videoId,
                        type = "vimeo",
                        details = new {
                            id = videoId,
                            published = TimeUtils.GetUnixTimeFromDateTime(video.UploadDate),
                            title = video.Title,
                            description = video.Description,
                            duration = (int)video.Duration.TotalSeconds,
                            thumbnails = (
                                from thumbnail in video.Thumbnails
                                select new {
                                url = thumbnail.Url,
                                width = thumbnail.Width,
                                height = thumbnail.Height
                            }
                                )
                        }
                    });
                } catch (VimeoException ex) {
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Something went wrong: " + ex.Message)));
                }
            }

            if (m2.Success)
            {
                if (String.IsNullOrWhiteSpace(Config.GoogleServerKey))
                {
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "YouTube is not configured")));
                }

                string videoId = m2.Groups[1].Value;

                GoogleService service = GoogleService.CreateFromServerKey(Config.GoogleServerKey);

                YouTubeVideoListResponse response = service.YouTube.Videos.GetVideos(new YouTubeVideoListOptions {
                    Part = YouTubeVideoPart.Snippet + YouTubeVideoPart.ContentDetails,
                    Ids  = new[] { videoId }
                });

                if (response.Body.Items.Length == 0)
                {
                    return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.BadRequest, "Video not found")));
                }

                YouTubeVideo video = response.Body.Items[0];

                return(new {
                    url = "https://www.youtube.com/watch?v=" + videoId,
                    type = "youtube",
                    details = new {
                        id = videoId,
                        published = TimeUtils.GetUnixTimeFromDateTime(video.Snippet.PublishedAt),
                        title = video.Snippet.Title,
                        description = video.Snippet.Description,
                        duration = (int)video.ContentDetails.Duration.Value.TotalSeconds,
                        thumbnails = new[] {
                            GetThumbnail("default", video.Snippet.Thumbnails.Default),
                            GetThumbnail("medium", video.Snippet.Thumbnails.Medium),
                            GetThumbnail("high", video.Snippet.Thumbnails.High),
                            GetThumbnail("standard", video.Snippet.Thumbnails.Standard)
                        }.WhereNotNull()
                    }
                });
            }

            return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.BadRequest, "Unknown URL syntax")));
        }
 /// <summary>
 /// Returns a new JSON based error response with the specified <paramref name="message"/>, <paramref name="message"/> and <paramref name="data"/>.
 /// </summary>
 /// <param name="statusCode">The status code to be used for the response.</param>
 /// <param name="message">The message of the error response.</param>
 /// <param name="data">The value of the <c>data</c> property in the JSON response.</param>
 /// <returns>An instance of <see cref="HttpResponseMessage"/>.</returns>
 protected virtual HttpResponseMessage ReturnError(HttpStatusCode statusCode, string message, object data)
 {
     return(CreateSpaResponse(JsonMetaResponse.GetError(statusCode, message, data)));
 }
Example #29
0
 /// <summary>
 /// Returns an instance of <see cref="HttpResponseMessage"/> representing a server error.
 /// </summary>
 /// <returns>An instance of <see cref="HttpResponseMessage"/>.</returns>
 protected virtual HttpResponseMessage ReturnServerError()
 {
     return(CreateSpaResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, "Internal server error")));
 }
Example #30
0
        public object EditRedirect(int rootNodeId, string redirectId, string url, string linkMode, int linkId, string linkUrl, string linkName = null, bool permanent = true, bool regex = false, bool forward = false)
        {
            try {
                // Get a reference to the redirect
                RedirectItem redirect = Repository.GetRedirectById(redirectId);
                if (redirect == null)
                {
                    throw new RedirectNotFoundException();
                }

                // Some input validation
                if (String.IsNullOrWhiteSpace(url))
                {
                    throw new RedirectsException(Localize("redirects/errorNoUrl"));
                }
                if (String.IsNullOrWhiteSpace(linkUrl))
                {
                    throw new RedirectsException(Localize("redirects/errorNoDestination"));
                }
                if (String.IsNullOrWhiteSpace(linkMode))
                {
                    throw new RedirectsException(Localize("redirects/errorNoDestination"));
                }

                // Parse the link mode
                RedirectLinkMode mode;
                switch (linkMode)
                {
                case "content": mode = RedirectLinkMode.Content; break;

                case "media": mode = RedirectLinkMode.Media; break;

                case "url": mode = RedirectLinkMode.Url; break;

                default: throw new RedirectsException(Localize("redirects/errorUnknownLinkMode"));
                }

                // Initialize a new link item
                RedirectLinkItem destination = new RedirectLinkItem(linkId, linkName, linkUrl, mode);

                // Split the URL and query string
                string[] urlParts = url.Split('?');
                url = urlParts[0].TrimEnd('/');
                string query = urlParts.Length == 2 ? urlParts[1] : "";

                // Update the properties of the redirect
                redirect.RootNodeId         = rootNodeId;
                redirect.Url                = url;
                redirect.QueryString        = query;
                redirect.Link               = destination;
                redirect.IsPermanent        = permanent;
                redirect.IsRegex            = regex;
                redirect.ForwardQueryString = forward;

                // Save/update the redirect
                Repository.SaveRedirect(redirect);

                // Return the redirect
                return(redirect);
            } catch (RedirectsException ex) {
                // Generate the error response
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.InternalServerError, ex.Message)));
            }
        }