Search in sources :

Example 31 with DataAccessor

use of com.pratilipi.data.DataAccessor in project pratilipi by Pratilipi.

the class PratilipiSite method createFbOpenGraphTags.

private List<String> createFbOpenGraphTags(Long pratilipiId) throws InsufficientAccessException, UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    Page page = dataAccessor.getPage(PageType.PRATILIPI, pratilipiId);
    PratilipiV2Api.GetRequest pratilipiRequest = new PratilipiV2Api.GetRequest();
    pratilipiRequest.setPratilipiId(pratilipiId);
    PratilipiV2Api.Response pratilipi = ApiRegistry.getApi(PratilipiV2Api.class).get(pratilipiRequest);
    String ogFbAppId = FacebookApi.getAppId();
    String ogLocale = pratilipi.getLanguage().getCode() + "_IN";
    String ogType = "books.book";
    String ogAuthor = "http://" + Website.ALL_LANGUAGE.getHostName() + (pratilipi.getAuthor() == null ? "/team-pratilipi" : pratilipi.getAuthor().getPageUrl());
    String ogBooksIsbn = pratilipi.getId().toString();
    // Warning: Changing it to anything else will cause loss of like-share count.
    String ogUrl = "http://" + Website.ALL_LANGUAGE.getHostName() + page.getUri();
    String ogTitle = createPratilipiPageTitle(pratilipi);
    String ogImage = pratilipi.getCoverImageUrl();
    String ogDescription = "";
    if (pratilipi.getSummary() != null)
        ogDescription = pratilipi.getSummary();
    List<String> fbOgTags = new LinkedList<String>();
    fbOgTags.add("<meta property='fb:app_id' content='" + ogFbAppId + "' />");
    fbOgTags.add("<meta property='og:locale' content='" + ogLocale + "' />");
    fbOgTags.add("<meta property='og:type' content='" + ogType + "' />");
    fbOgTags.add("<meta property='books:author' content='" + ogAuthor + "' />");
    fbOgTags.add("<meta property='books:isbn' content='" + ogBooksIsbn + "' />");
    fbOgTags.add("<meta property='og:url' content='" + ogUrl + "' />");
    fbOgTags.add("<meta property='og:title' content='" + ogTitle + "' />");
    fbOgTags.add("<meta property='og:image' content='" + ogImage + "' />");
    fbOgTags.add("<meta property='og:description' content='" + ogDescription + "' />");
    return fbOgTags;
}
Also used : DataAccessor(com.pratilipi.data.DataAccessor) PratilipiV2Api(com.pratilipi.api.impl.pratilipi.PratilipiV2Api) Page(com.pratilipi.data.type.Page) LinkedList(java.util.LinkedList)

Example 32 with DataAccessor

use of com.pratilipi.data.DataAccessor in project pratilipi by Pratilipi.

the class PratilipiSite method doGet.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    // Setting user's author profile's default language, if not set already
    if (UxModeFilter.getFilterLanguage() != null) {
        Author author = dataAccessor.getAuthorByUserId(AccessTokenFilter.getAccessToken().getUserId());
        if (author != null && author.getLanguage() == null) {
            author.setLanguage(UxModeFilter.getFilterLanguage());
            dataAccessor.createOrUpdateAuthor(author);
        }
    }
    String uri = request.getRequestURI();
    String canonicalUrl = "http://" + UxModeFilter.getWebsite().getHostName() + uri;
    String alternateUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
    // User
    UserData userData = UserDataUtil.getCurrentUser();
    // BasicMode
    boolean basicMode = UxModeFilter.isBasicMode();
    // Language
    Language displayLanguage = UxModeFilter.getDisplayLanguage();
    Language filterLanguage = UxModeFilter.getFilterLanguage();
    // Navigation List
    List<Navigation> navigationList = dataAccessor.getNavigationList(filterLanguage == null ? Language.ENGLISH : filterLanguage);
    // Common resource list
    Set<String> resourceList = getResourceList(basicMode);
    Set<String> deferredResourceList = new HashSet<>();
    if (basicMode) {
        resourceList.add(ThirdPartyResource.BOOTSTRAP_CSS.getTag());
    } else {
        deferredResourceList.add(ThirdPartyResource.BOOTSTRAP_CSS.getTag());
        deferredResourceList.add(ThirdPartyResource.GOOGLE_TRANSLITERATION.getTag());
    }
    // Load PWA
    boolean loadPWA = true;
    if (UxModeFilter.isCrawler())
        loadPWA = false;
    if (UxModeFilter.isBasicMode() && SystemProperty.STAGE.equals(SystemProperty.STAGE_PROD))
        loadPWA = false;
    if (uri.equals("/write") || uri.equals("/pratilipi-write") || uri.equals("/admin") || uri.startsWith("/admin/") || uri.equals("/edit-event") || uri.equals("/edit-blog"))
        loadPWA = false;
    if (uri.equals("/") && (UxModeFilter.getWebsite() == Website.ALL_LANGUAGE || UxModeFilter.getWebsite() == Website.GAMMA_ALL_LANGUAGE))
        loadPWA = false;
    // TODO: Hack - Remove it soon
    if (request.getParameter("loadPWA") != null) {
        loadPWA = Boolean.parseBoolean(request.getParameter("loadPWA"));
    }
    // Data Model for FreeMarker
    Map<String, Object> dataModel = null;
    String templateName = null;
    // ga_location
    String ga_location = null;
    try {
        // Search Engine Crawlers
        if (uri.equals("/sitemap") && SystemProperty.STAGE.equals(SystemProperty.STAGE_PROD)) {
            String content = PageDataUtil.getSitemap(request.getParameter(RequestParameter.SITEMAP_TYPE.getName()), request.getParameter(RequestParameter.SITEMAP_CURSOR.getName()), UxModeFilter.getWebsite(), basicMode);
            _dispatchResponse(content, "application/xml", "UTF-8", response);
            return;
        }
        // Robots.txt
        if (uri.equals("/robots.txt")) {
            dataModel = new HashMap<>();
            dataModel.put("stage", SystemProperty.STAGE);
            templateName = templateFilePrefix + "RobotsTxt.ftl";
            String robotsTxt = FreeMarkerUtil.processTemplate(dataModel, templateName);
            _dispatchResponse(robotsTxt, "text/plain", "UTF-8", response);
            return;
        }
        // PWA
        if (loadPWA) {
            templateName = "PWA.ftl";
            dataModel = new HashMap<>();
            // Hack: Not to minify the html file
            dataModel.put("stage", "pwa");
            dataModel.put("lang", displayLanguage.getCode());
            dataModel.put("language", displayLanguage);
            dataModel.put("templateName", templateName);
            String html = FreeMarkerUtil.processTemplate(dataModel, templateFilePrefix + "MainTemplate.ftl");
            logger.log(Level.INFO, "Website Version : Mark-7");
            _dispatchResponse(html, "text/html", "UTF-8", response);
            return;
        }
        // Page Entity
        Page page = dataAccessor.getPage(uri);
        // Hard-coded links
        if (uri.equals("/")) {
            if (UxModeFilter.getWebsite() == Website.ALL_LANGUAGE || UxModeFilter.getWebsite() == Website.GAMMA_ALL_LANGUAGE) {
                ga_location = "MasterHomePage";
                dataModel = createDataModelForMasterHomePage(filterLanguage);
                templateName = "MasterHome.ftl";
            } else {
                ga_location = "HomePage";
                dataModel = createDataModelForHomePage(basicMode, filterLanguage);
                templateName = (basicMode ? "HomeBasic.ftl" : "Home.ftl");
            }
        } else if (uri.equals("/library")) {
            ga_location = "LibraryPage";
            dataModel = createDataModelForLibraryPage(basicMode, filterLanguage);
            templateName = (basicMode ? "LibraryBasic.ftl" : "Library.ftl");
        } else if (uri.equals("/notifications")) {
            ga_location = "NotificationsPage";
            dataModel = createDataModelForNotificationsPage(filterLanguage, basicMode);
            if (request.getParameter("action") != null)
                dataModel.put("action", request.getParameter("action"));
            templateName = (basicMode ? "NotificationBasic.ftl" : "Notification.ftl");
        } else if (uri.equals("/search")) {
            ga_location = "SearchPage";
            if (request.getQueryString() != null) {
                canonicalUrl = canonicalUrl + "?" + request.getQueryString();
                alternateUrl = alternateUrl + "?" + request.getQueryString();
            }
            dataModel = createDataModelForSearchPage(basicMode, filterLanguage, request);
            templateName = (basicMode ? "SearchBasic.ftl" : "Search.ftl");
        } else if (uri.equals("/events")) {
            ga_location = "AllEventsPage";
            dataModel = createDataModelForEventsPage(filterLanguage, basicMode);
            templateName = (basicMode ? "EventListBasic.ftl" : "EventList.ftl");
        } else if (uri.equals("/followers")) {
            ga_location = "FollowersPage";
            Long authorId = null;
            if (request.getParameter(RequestParameter.AUTHOR_ID.getName()) != null) {
                authorId = Long.parseLong(request.getParameter(RequestParameter.AUTHOR_ID.getName()));
            } else {
                Long userId = AccessTokenFilter.getAccessToken().getUserId();
                if (userId != null && userId != 0L)
                    authorId = dataAccessor.getAuthorByUserId(userId).getId();
            }
            Integer currentPage = request.getParameter(RequestParameter.LIST_PAGE_NUMBER.getName()) != null && !request.getParameter(RequestParameter.LIST_PAGE_NUMBER.getName()).trim().isEmpty() ? Integer.parseInt(request.getParameter(RequestParameter.LIST_PAGE_NUMBER.getName())) : 1;
            if (authorId == null) {
                dataModel = new HashMap<String, Object>();
                dataModel.put("title", SEOTitleUtil.getFollowersPageTitle(authorId, filterLanguage));
            } else {
                dataModel = createDataModelForFollowersPage(authorId, currentPage, filterLanguage, basicMode);
            }
            templateName = (basicMode ? "FollowersListBasic.ftl" : "FollowersList.ftl");
        } else if (uri.equals("/following")) {
            ga_location = "FollowingPage";
            Long userId = null;
            if (request.getParameter(RequestParameter.USER_ID.getName()) != null)
                userId = Long.parseLong(request.getParameter(RequestParameter.USER_ID.getName()));
            else
                userId = AccessTokenFilter.getAccessToken().getUserId();
            Integer currentPage = request.getParameter(RequestParameter.LIST_PAGE_NUMBER.getName()) != null && !request.getParameter(RequestParameter.LIST_PAGE_NUMBER.getName()).trim().isEmpty() ? Integer.parseInt(request.getParameter(RequestParameter.LIST_PAGE_NUMBER.getName())) : 1;
            if (userId == null || userId == 0L) {
                dataModel = new HashMap<String, Object>();
                dataModel.put("title", SEOTitleUtil.getFollowersPageTitle(userId, filterLanguage));
            } else {
                dataModel = createDataModelForFollowingPage(userId, currentPage, filterLanguage, basicMode);
            }
            templateName = (basicMode ? "FollowingListBasic.ftl" : "FollowingList.ftl");
        } else if (uri.equals("/pratilipi-2016")) {
            ga_location = "Pratilipi2016Page";
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Pratilipi in 2016");
            templateName = (basicMode ? "Pratilipi2016Basic.ftl" : "Pratilipi2016.ftl");
        // Master website specific links
        } else if (filterLanguage == null && uri.equals("/books")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.BOOK, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (filterLanguage == null && uri.equals("/stories")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.STORY, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (filterLanguage == null && uri.equals("/poems")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.POEM, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (filterLanguage == null && uri.equals("/articles")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.ARTICLE, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (filterLanguage == null && uri.equals("/magazines")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.MAGAZINE, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        // Gujarati website specific links
        } else if (filterLanguage == Language.GUJARATI && uri.equals("/short-stories")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.STORY, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (filterLanguage == Language.GUJARATI && uri.equals("/poetry")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.POEM, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (filterLanguage == Language.GUJARATI && uri.equals("/non-fiction")) {
            ga_location = "ListPage";
            dataModel = createDataModelForListPage(PratilipiType.ARTICLE, basicMode, displayLanguage, filterLanguage, request);
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        // Standard Mode links only
        } else if (!basicMode && uri.equals("/pratilipi-write")) {
            ga_location = "Writer";
            if (request.getQueryString() != null) {
                canonicalUrl = canonicalUrl + "?" + request.getQueryString();
                alternateUrl = alternateUrl + "?" + request.getQueryString();
            }
            resourceList.remove(ThirdPartyResource.POLYMER_ELEMENTS.getTag());
            resourceList.add(ThirdPartyResource.BOOTSTRAP_CSS.getTag());
            resourceList.add(ThirdPartyResource.TINYMCE.getTag());
            Long authorId = request.getParameter(RequestParameter.AUTHOR_ID.getName()) != null ? Long.parseLong(request.getParameter(RequestParameter.AUTHOR_ID.getName())) : null;
            Long pratilipiId = Long.parseLong(request.getParameter(RequestParameter.CONTENT_ID.getName()));
            PratilipiV2Api.GetRequest pratilipiRequest = new PratilipiV2Api.GetRequest();
            pratilipiRequest.setPratilipiId(pratilipiId);
            PratilipiV2Api.Response pratilipiResponse = ApiRegistry.getApi(PratilipiV2Api.class).get(pratilipiRequest);
            PratilipiContentIndexApi.GetRequest indexReq = new PratilipiContentIndexApi.GetRequest();
            indexReq.setPratilipiId(pratilipiId);
            PratilipiContentIndexApi.Response indexResponse = ApiRegistry.getApi(PratilipiContentIndexApi.class).getIndex(indexReq);
            List<TagData> tags = TagDataUtil.getTags(pratilipiResponse.getLanguage(), pratilipiResponse.getType());
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", SEOTitleUtil.getWritePageTitle(pratilipiId, filterLanguage));
            dataModel.put("authorId", authorId);
            dataModel.put("pratilipiId", pratilipiId);
            dataModel.put("pratilipi", pratilipiResponse);
            dataModel.put("pratilipiJson", new Gson().toJson(pratilipiResponse));
            dataModel.put("indexJson", new Gson().toJson(indexResponse));
            dataModel.put("tags", tags);
            String action = request.getParameter("action");
            if (action != null)
                dataModel.put("action", action);
            templateName = "WriterV2.ftl";
        // Basic Mode links only
        } else if (basicMode && uri.equals("/account")) {
            ga_location = "AccountPage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "My Account");
            templateName = "AccountBasic.ftl";
        } else if (basicMode && uri.equals("/navigation")) {
            ga_location = "NavigationPage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Menu");
            dataModel.put("navigationList", navigationList);
            templateName = "NavigationBasic.ftl";
        } else if (basicMode && uri.equals("/updatepassword")) {
            ga_location = "UpdatePasswordPage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            if (request.getParameter(RequestParameter.PASSWORD_RESET_EMAIL_EMAIL.getName()) != null && request.getParameter(RequestParameter.PASSWORD_RESET_EMAIL_TOKEN.getName()) != null) {
                dataModel.put("passwordResetFromMail", true);
                dataModel.put("email", request.getParameter(RequestParameter.PASSWORD_RESET_EMAIL_EMAIL.getName()));
                dataModel.put("verificationToken", request.getParameter(RequestParameter.PASSWORD_RESET_EMAIL_TOKEN.getName()));
            }
            dataModel.put("title", "Update Password");
            templateName = "PasswordUpdateBasic.ftl";
        } else if (basicMode && uri.equals("/share")) {
            ga_location = "SharePage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Share");
            templateName = "ShareBasic.ftl";
        } else if (uri.equals("/register") && basicMode) {
            ga_location = "RegisterPage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Register");
            templateName = "RegisterBasic.ftl";
        } else if (uri.equals("/login") && basicMode) {
            ga_location = "LoginPage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Login");
            templateName = "LoginBasic.ftl";
        } else if (uri.equals("/forgot-password") && basicMode) {
            ga_location = "ForgotPasswordPage";
            canonicalUrl = "http://" + UxModeFilter.getWebsite().getMobileHostName() + uri;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Reset Password");
            templateName = "PasswordResetBasic.ftl";
        // Internal links - Standard Version only
        } else if (!basicMode && uri.startsWith("/admin")) {
            ga_location = "AdminPage";
            if (uri.equals("/admin")) {
                dataModel = new HashMap<>();
                dataModel.put("title", "Pratilipi - Admin Access");
                templateName = "Admin.ftl";
            } else if (uri.equals("/admin/authors")) {
                dataModel = createDataModelForAuthorsPage(filterLanguage);
                templateName = "AuthorList.ftl";
            } else if (uri.equals("/admin/batch-process")) {
                dataModel = createDataModelForBatchProcessListPage();
                templateName = "BatchProcessList.ftl";
            } else if (uri.equals("/admin/email-templates")) {
                dataModel = createDataModelForEmailTemplatesPage(filterLanguage);
                templateName = "EmailTemplate.ftl";
            } else if (uri.equals("/admin/translations")) {
                dataModel = new HashMap<>();
                templateName = "Translation.ftl";
            }
        } else if (!basicMode && uri.equals("/edit-event")) {
            ga_location = "EditEventPage";
            resourceList.add(ThirdPartyResource.CKEDITOR.getTag());
            Long eventId = request.getParameter(RequestParameter.CONTENT_ID.getName()) != null ? Long.parseLong(request.getParameter(RequestParameter.CONTENT_ID.getName())) : null;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Create or Edit Event");
            if (eventId != null) {
                EventApi.GetRequest eventRequest = new EventApi.GetRequest();
                eventRequest.setEventId(eventId);
                EventApi.Response eventResponse = ApiRegistry.getApi(EventApi.class).get(eventRequest);
                dataModel.put("eventJson", new Gson().toJson(eventResponse));
            }
            templateName = "EventEdit.ftl";
        } else if (!basicMode && uri.equals("/edit-blog")) {
            ga_location = "EditBlogPage";
            resourceList.add(ThirdPartyResource.CKEDITOR.getTag());
            Long blogPostId = request.getParameter(RequestParameter.CONTENT_ID.getName()) != null ? Long.parseLong(request.getParameter(RequestParameter.CONTENT_ID.getName())) : null;
            Long blogId = request.getParameter("blogId") != null ? Long.parseLong(request.getParameter("blogId")) : null;
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Create or Edit Blog");
            dataModel.put("blogId", blogId);
            if (blogPostId != null) {
                BlogPostApi.GetRequest blogPostRequest = new BlogPostApi.GetRequest();
                blogPostRequest.setBlogPostId(blogPostId);
                BlogPostApi.Response blogPostResponse = ApiRegistry.getApi(BlogPostApi.class).get(blogPostRequest);
                dataModel.put("blogPostJson", new Gson().toJson(blogPostResponse));
            }
            templateName = "BlogEdit.ftl";
        // Non - hardcoded links
        } else if (page != null && page.getType() == PageType.PRATILIPI) {
            ga_location = "PratilipiPage";
            resourceList.addAll(createFbOpenGraphTags(page.getPrimaryContentId()));
            dataModel = createDataModelForPratilipiPage(page.getPrimaryContentId(), filterLanguage, basicMode, request);
            templateName = (basicMode ? "PratilipiBasic.ftl" : "Pratilipi.ftl");
        } else if (page != null && page.getType() == PageType.AUTHOR) {
            ga_location = userData.getAuthor().getId() != null && userData.getAuthor().getId() == page.getPrimaryContentId() ? "UserPage" : "AuthorPage";
            dataModel = createDataModelForAuthorPage(page.getPrimaryContentId(), filterLanguage, basicMode, request);
            templateName = (basicMode ? "AuthorBasic.ftl" : "Author.ftl");
        } else if (page != null && page.getType() == PageType.EVENT) {
            ga_location = "EventPage";
            dataModel = createDataModelForEventPage(page.getPrimaryContentId(), filterLanguage, basicMode, request);
            templateName = (basicMode ? "EventBasic.ftl" : "Event.ftl");
        } else if (page != null && page.getType() == PageType.BLOG) {
            ga_location = page.getUri().equals("/blog") ? "AllBlogsPage" : "AllAuthorInterviewsPage";
            dataModel = createDataModelForBlogPage(page.getPrimaryContentId(), filterLanguage, basicMode);
            templateName = (basicMode ? "BlogPostListBasic.ftl" : "BlogPostList.ftl");
        } else if (page != null && page.getType() == PageType.BLOG_POST) {
            ga_location = page.getUri().startsWith("/blog") ? "BlogPage" : "AuthorInterviewPage";
            dataModel = createDataModelForBlogPostPage(page.getPrimaryContentId(), filterLanguage, basicMode);
            templateName = (basicMode ? "BlogPostBasic.ftl" : "BlogPost.ftl");
        } else if (page != null && page.getType() == PageType.READ) {
            ga_location = "Reader";
            if (request.getQueryString() != null) {
                canonicalUrl = canonicalUrl + "?" + request.getQueryString();
                alternateUrl = alternateUrl + "?" + request.getQueryString();
            }
            Long pratilipiId = Long.parseLong(request.getParameter(RequestParameter.CONTENT_ID.getName()));
            String fontSize = AccessTokenFilter.getCookieValue(RequestCookie.FONT_SIZE.getName(), request);
            String imageSize = AccessTokenFilter.getCookieValue(RequestCookie.IMAGE_SIZE.getName(), request);
            String action = request.getParameter("action") != null ? request.getParameter("action") : "read";
            String pageNoPattern = "reader_page_number_" + pratilipiId;
            Integer pageNo = null;
            if (request.getParameter(RequestParameter.READER_PAGE_NUMBER.getName()) != null)
                pageNo = Integer.parseInt(request.getParameter(RequestParameter.READER_PAGE_NUMBER.getName()));
            else if (AccessTokenFilter.getCookieValue(pageNoPattern, request) != null)
                pageNo = Integer.parseInt(AccessTokenFilter.getCookieValue(pageNoPattern, request));
            else
                pageNo = 1;
            dataModel = createDataModelForReadPage(pratilipiId, pageNo, request.getParameter(RequestParameter.API_VERSION.getName()), filterLanguage, basicMode);
            dataModel.put("fontSize", fontSize != null ? Integer.parseInt(fontSize) : 14);
            dataModel.put("imageSize", imageSize != null ? Integer.parseInt(imageSize) : 636);
            dataModel.put("action", action);
            templateName = (basicMode ? "ReadBasic.ftl" : "Read.ftl");
        } else if (uri.matches("^/[a-z0-9-]+$") && (dataModel = createDataModelForListPage(uri.substring(1), basicMode, displayLanguage, filterLanguage, request)) != null) {
            ga_location = "ListPage";
            templateName = (basicMode ? "ListBasic.ftl" : "List.ftl");
        } else if (uri.matches("^/[a-z0-9-/]+$") && (dataModel = createDataModelForStaticPage(uri.substring(1).replaceAll("/", "_"), displayLanguage)) != null) {
            ga_location = "StaticPage";
            templateName = (basicMode ? "StaticBasic.ftl" : "Static.ftl");
        } else if (uri.matches("^/[a-z0-9-/]+$") && (dataModel = createDataModelForStaticPage(uri.substring(1).replaceAll("/", "_"), Language.ENGLISH)) != null) {
            ga_location = "StaticPage";
            templateName = (basicMode ? "StaticBasic.ftl" : "Static.ftl");
        } else {
            ga_location = "PageNotFound";
            dataModel = new HashMap<String, Object>();
            dataModel.put("title", "Page Not Found !");
            templateName = (basicMode ? "error/PageNotFoundBasic.ftl" : "error/PageNotFound.ftl");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (InsufficientAccessException e) {
        ga_location = "UnauthorisedErrorPage";
        resourceList = getResourceList(basicMode);
        dataModel = new HashMap<String, Object>();
        dataModel.put("title", "Unauthorized Access !");
        templateName = (basicMode ? "error/AuthorizationErrorBasic.ftl" : "error/AuthorizationError.ftl");
        logger.log(Level.SEVERE, "Unauthorised Exception: ", e);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (InvalidArgumentException | UnexpectedServerException e) {
        ga_location = "ServerErrorPage";
        resourceList = getResourceList(basicMode);
        dataModel = new HashMap<String, Object>();
        dataModel.put("title", "Server Error !");
        templateName = (basicMode ? "error/ServerErrorBasic.ftl" : "error/ServerError.ftl");
        logger.log(Level.SEVERE, "Service Unavailable: ", e);
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
    // Adding common data to the Data Model
    Gson gson = new Gson();
    UserV1Api.Response userResponse = new UserV1Api.Response(userData, UserV1Api.class);
    Map<PratilipiType, Map<String, String>> pratilipiTypes = new HashMap<>();
    for (PratilipiType pratilipiType : PratilipiType.values()) {
        Map<String, String> pratilipiTypeMap = new HashMap<>();
        pratilipiTypeMap.put("name", I18n.getString(pratilipiType.getStringId(), displayLanguage));
        pratilipiTypeMap.put("namePlural", I18n.getString(pratilipiType.getPluralStringId(), displayLanguage));
        pratilipiTypes.put(pratilipiType, pratilipiTypeMap);
    }
    Map<String, String> languageMap = new HashMap<String, String>();
    for (Website website : Website.values()) {
        if (!website.toString().contains("GAMMA") && !website.toString().contains("DEVO") && !website.toString().contains("ALPHA") && website != Website.ALL_LANGUAGE) {
            languageMap.put(website.toString(), website.getFilterLanguage().getName());
        }
    }
    dataModel.put("ga_userId", userData.getId().toString());
    dataModel.put("ga_website", UxModeFilter.getWebsite().toString());
    dataModel.put("ga_websiteMode", UxModeFilter.isBasicMode() ? "Basic" : "Standard");
    dataModel.put("ga_websiteVersion", "Mark-6");
    dataModel.put("ga_location", ga_location);
    dataModel.put("lang", displayLanguage.getCode());
    dataModel.put("language", displayLanguage);
    dataModel.put("website_host", UxModeFilter.getWebsite().getHostName());
    dataModel.put("website_mobile_host", UxModeFilter.getWebsite().getMobileHostName());
    dataModel.put("canonical_url", canonicalUrl);
    dataModel.put("alternate_url", alternateUrl);
    dataModel.put("languageMap", gson.toJson(languageMap));
    dataModel.put("_strings", I18n.getStrings(displayLanguage));
    dataModel.put("resourceList", resourceList);
    dataModel.put("deferredResourceList", deferredResourceList);
    dataModel.put("user", userResponse);
    dataModel.put("userJson", gson.toJson(userResponse));
    dataModel.put("pratilipiTypesJson", gson.toJson(pratilipiTypes));
    dataModel.put("navigationListJson", gson.toJson(navigationList));
    dataModel.put("stage", SystemProperty.STAGE);
    dataModel.put("basicMode", basicMode);
    if (basicMode) {
        StringBuffer requestUrl = new StringBuffer(request.getRequestURI());
        if (request.getQueryString() != null)
            requestUrl.append('?').append(request.getQueryString());
        dataModel.put("requestUrl", URLEncoder.encode(requestUrl.toString(), "UTF-8"));
    }
    // Generating response html
    String html = null;
    for (int i = 0; i < 2 && html == null; i++) {
        try {
            dataModel.put("templateName", templateName);
            // The magic
            html = FreeMarkerUtil.processTemplate(dataModel, templateFilePrefix + "MainTemplate.ftl");
        } catch (UnexpectedServerException e) {
            logger.log(Level.SEVERE, "Exception occured while processing template.", e);
            resourceList = getResourceList(basicMode);
            templateName = (basicMode ? "error/ServerErrorBasic.ftl" : "error/ServerError.ftl");
        }
    }
    // Dispatching response
    logger.log(Level.INFO, "Website Version : Mark-6");
    _dispatchResponse(html, "text/html", "UTF-8", response);
}
Also used : UserData(com.pratilipi.data.client.UserData) HashMap(java.util.HashMap) DataAccessor(com.pratilipi.data.DataAccessor) Gson(com.google.gson.Gson) Website(com.pratilipi.common.type.Website) Page(com.pratilipi.data.type.Page) PratilipiType(com.pratilipi.common.type.PratilipiType) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) Language(com.pratilipi.common.type.Language) PratilipiV2Api(com.pratilipi.api.impl.pratilipi.PratilipiV2Api) TagData(com.pratilipi.data.client.TagData) HashSet(java.util.HashSet) Navigation(com.pratilipi.data.type.Navigation) BlogPostApi(com.pratilipi.api.impl.blogpost.BlogPostApi) UserV1Api(com.pratilipi.api.impl.user.UserV1Api) EventApi(com.pratilipi.api.impl.event.EventApi) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) PratilipiContentIndexApi(com.pratilipi.api.impl.pratilipi.PratilipiContentIndexApi) HttpServletResponse(javax.servlet.http.HttpServletResponse) Author(com.pratilipi.data.type.Author) JsonObject(com.google.gson.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 33 with DataAccessor

use of com.pratilipi.data.DataAccessor in project pratilipi by Pratilipi.

the class PratilipiSite method createDataModelForReadPage.

public Map<String, Object> createDataModelForReadPage(Long pratilipiId, Integer chapterNo, String version, Language language, boolean basicMode) throws InvalidArgumentException, UnexpectedServerException, InsufficientAccessException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    Pratilipi pratilipi = dataAccessor.getPratilipi(pratilipiId);
    PratilipiData pratilipiData = PratilipiDataUtil.createPratilipiData(pratilipi);
    PratilipiV2Api.Response pratilipiResponse = new PratilipiV2Api.Response(pratilipiData);
    UserPratilipiApi.GetRequest userPratilipiRequest = new UserPratilipiApi.GetRequest();
    userPratilipiRequest.setPratilipiId(pratilipiId);
    UserPratilipiApi.Response userPratilipiResponse = ApiRegistry.getApi(UserPratilipiApi.class).getUserPratilipi(userPratilipiRequest);
    String indexJson = null;
    Integer pageCount = null;
    Object content = null;
    // In case, version is not specified in URL
    if (version == null) {
        if (SystemProperty.STAGE.equals(SystemProperty.STAGE_PROD) && pratilipi.isOldContent() && pratilipi.getContentType() == PratilipiContentType.PRATILIPI) {
            version = "1";
        } else {
            version = "3";
        }
    }
    // Index and pageCount for all contents
    if (version.equals("1")) {
        indexJson = pratilipi.getIndex();
        pageCount = pratilipi.getPageCount() > 0 ? pratilipi.getPageCount() : 1;
    } else if (version.equals("2") || version.equals("3")) {
        // Json format
        PratilipiContentIndexApi.GetRequest indexReq = new PratilipiContentIndexApi.GetRequest();
        indexReq.setPratilipiId(pratilipiId);
        PratilipiContentIndexApi.Response indexRes = ApiRegistry.getApi(PratilipiContentIndexApi.class).getIndex(indexReq);
        indexJson = indexRes.getIndex().toString();
        pageCount = indexRes.getIndex().size() > 0 ? indexRes.getIndex().size() : 1;
    }
    if (pratilipi.getContentType() == PratilipiContentType.PRATILIPI) {
        if (chapterNo < 1)
            chapterNo = 1;
        if (chapterNo > pageCount)
            chapterNo = pageCount;
        if (version.equals("1")) {
            PratilipiContentV1Api.GetRequest req = new PratilipiContentV1Api.GetRequest();
            req.setPratilipiId(pratilipiId);
            req.setChapterNo(chapterNo);
            PratilipiContentV1Api.GetResponse res = (PratilipiContentV1Api.GetResponse) ApiRegistry.getApi(PratilipiContentV1Api.class).get(req);
            content = res.getContent();
        } else if (version.equals("2")) {
            PratilipiContentV2Api.GetRequest req = new PratilipiContentV2Api.GetRequest();
            req.setPratilipiId(pratilipiId);
            req.setChapterNo(chapterNo);
            PratilipiContentV2Api.GetResponse res = (PratilipiContentV2Api.GetResponse) ApiRegistry.getApi(PratilipiContentV2Api.class).get(req);
            content = res.getContent();
            if (res.getChapterTitle() != null)
                content = "<h1>" + res.getChapterTitle() + "</h1>" + content;
        } else if (version.equals("3")) {
            PratilipiContentV3Api.GetRequest req = new PratilipiContentV3Api.GetRequest();
            req.setPratilipiId(pratilipiId);
            req.setChapterNo(chapterNo);
            PratilipiContentV3Api.GetResponse res = (PratilipiContentV3Api.GetResponse) ApiRegistry.getApi(PratilipiContentV3Api.class).get(req);
            content = res.getContent();
            if (res.getChapterTitle() != null)
                content = "<h1>" + res.getChapterTitle() + "</h1>" + content;
        }
    } else if (pratilipi.getContentType() == PratilipiContentType.IMAGE) {
        PratilipiContentV2Api.GetRequest req = new PratilipiContentV2Api.GetRequest();
        req.setPratilipiId(pratilipiId);
        PratilipiContentV2Api.GetResponse res = (PratilipiContentV2Api.GetResponse) ApiRegistry.getApi(PratilipiContentV2Api.class).get(req);
        PratilipiContentDoc pcDoc = (PratilipiContentDoc) res.getContent();
        // Image books can have more than one page in a chapter
        pageCount = 0;
        for (Chapter chapter : pcDoc.getChapterList()) pageCount += chapter.getPageCount();
        if (chapterNo < 1)
            chapterNo = 1;
        if (chapterNo > pageCount)
            chapterNo = pageCount;
        if (basicMode) {
            JsonObject jsonObject = null;
            int c = 0;
            for (int i = 1; i <= pcDoc.getChapterCount(); i++) {
                for (int j = 1; j <= pcDoc.getChapter(i).getPageCount(); j++) {
                    if (++c == chapterNo) {
                        jsonObject = pcDoc.getChapter(i).getPage(j).getPageletList().get(0).getData();
                        break;
                    }
                }
            }
            content = PratilipiDocUtil._processImagePagelet(pratilipiId, jsonObject);
        } else {
            content = new Gson().toJson(res.getContent());
        }
    }
    Gson gson = new Gson();
    Map<String, Object> dataModel = new HashMap<String, Object>();
    dataModel.put("title", SEOTitleUtil.getReadPageTitle(pratilipiId, language));
    dataModel.put("pageNo", chapterNo);
    dataModel.put("pageCount", pageCount);
    dataModel.put("content", content);
    dataModel.put("version", version);
    dataModel.put("contentType", pratilipi.getContentType());
    if (basicMode) {
        dataModel.put("pratilipi", pratilipiResponse);
        dataModel.put("userpratilipi", userPratilipiResponse);
        dataModel.put("indexList", gson.fromJson(indexJson, Object.class));
    } else {
        dataModel.put("pratilipiJson", gson.toJson(pratilipiResponse));
        dataModel.put("userpratilipiJson", gson.toJson(userPratilipiResponse));
        dataModel.put("indexJson", gson.toJson(indexJson));
    }
    return dataModel;
}
Also used : HashMap(java.util.HashMap) DataAccessor(com.pratilipi.data.DataAccessor) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) PratilipiContentV2Api(com.pratilipi.api.impl.pratilipi.PratilipiContentV2Api) PratilipiV2Api(com.pratilipi.api.impl.pratilipi.PratilipiV2Api) PratilipiContentDoc(com.pratilipi.data.type.PratilipiContentDoc) Chapter(com.pratilipi.data.type.PratilipiContentDoc.Chapter) PratilipiContentV3Api(com.pratilipi.api.impl.pratilipi.PratilipiContentV3Api) HttpServletResponse(javax.servlet.http.HttpServletResponse) PratilipiContentIndexApi(com.pratilipi.api.impl.pratilipi.PratilipiContentIndexApi) PratilipiContentV1Api(com.pratilipi.api.impl.pratilipi.PratilipiContentV1Api) UserPratilipiApi(com.pratilipi.api.impl.userpratilipi.UserPratilipiApi) PratilipiData(com.pratilipi.data.client.PratilipiData) JsonObject(com.google.gson.JsonObject) Pratilipi(com.pratilipi.data.type.Pratilipi)

Example 34 with DataAccessor

use of com.pratilipi.data.DataAccessor in project pratilipi by Pratilipi.

the class UserDataUtil method loginUser.

public static UserData loginUser(String email, String password) throws InvalidArgumentException, InsufficientAccessException {
    // Do nothing if a user is already logged in
    if (!AccessTokenFilter.getAccessToken().getUserId().equals(0L))
        return getCurrentUser();
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    User user = dataAccessor.getUserByEmail(email.toLowerCase());
    if (user == null || user.getState() == UserState.REFERRAL || user.getState() == UserState.DELETED) {
        JsonObject errorMessages = new JsonObject();
        errorMessages.addProperty("email", GenericRequest.ERR_EMAIL_NOT_REGISTERED);
        throw new InvalidArgumentException(errorMessages);
    } else if (user.getState() == UserState.BLOCKED) {
        throw new InsufficientAccessException(GenericRequest.ERR_ACCOUNT_BLOCKED);
    }
    if (user.getPassword() == null && user.getFacebookId() != null)
        throw new InvalidArgumentException(GenericRequest.ERR_EMAIL_REGISTERED_WITH_FACEBOOK);
    if (user.getPassword() == null && user.getGoogleId() != null)
        throw new InvalidArgumentException(GenericRequest.ERR_EMAIL_REGISTERED_WITH_GOOGLE);
    if (PasswordUtil.check(password, user.getPassword())) {
        _loginUser(AccessTokenFilter.getAccessToken(), user);
        return createUserData(user);
    }
    if (_verifyToken(user, password)) {
        AuditLog auditLog = dataAccessor.newAuditLog(AccessTokenFilter.getAccessToken(), AccessType.USER_ADD, user);
        user.setVerificationToken(null);
        dataAccessor.createOrUpdateUser(user, auditLog);
        _loginUser(AccessTokenFilter.getAccessToken(), user);
        return createUserData(user);
    }
    throw new InvalidArgumentException(GenericRequest.ERR_INVALID_CREDENTIALS);
}
Also used : User(com.pratilipi.data.type.User) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) DataAccessor(com.pratilipi.data.DataAccessor) JsonObject(com.google.gson.JsonObject) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) AuditLog(com.pratilipi.data.type.AuditLog)

Example 35 with DataAccessor

use of com.pratilipi.data.DataAccessor in project pratilipi by Pratilipi.

the class UserDocUtil method updateUserFollows.

public static void updateUserFollows(Long userId) throws UnexpectedServerException {
    DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
    DocAccessor docAccessor = DataAccessorFactory.getDocAccessor();
    List<UserAuthorDoc> followingAuthorList = new ArrayList<>();
    List<UserAuthorDoc> unfollowedAuthorList = new ArrayList<>();
    List<UserAuthorDoc> ignoredAuthorList = new ArrayList<>();
    DataListIterator<UserAuthor> userAuthorListIterator = dataAccessor.getUserAuthorListIterator(userId, null, null, null, null);
    while (userAuthorListIterator.hasNext()) {
        UserAuthor userAuthor = userAuthorListIterator.next();
        UserAuthorDoc userAuthorDoc = docAccessor.newUserAuthorDoc();
        userAuthorDoc.setAuthorId(userAuthor.getAuthorId());
        userAuthorDoc.setFollowDate(userAuthor.getFollowDate());
        switch(userAuthor.getFollowState()) {
            case FOLLOWING:
                followingAuthorList.add(userAuthorDoc);
                break;
            case UNFOLLOWED:
                unfollowedAuthorList.add(userAuthorDoc);
                break;
            case IGNORED:
                ignoredAuthorList.add(userAuthorDoc);
                break;
        }
    }
    UserFollowsDoc userFollowingDoc = docAccessor.newUserFollowsDoc();
    userFollowingDoc.setFollows(UserFollowState.FOLLOWING, followingAuthorList);
    userFollowingDoc.setFollows(UserFollowState.UNFOLLOWED, unfollowedAuthorList);
    userFollowingDoc.setFollows(UserFollowState.IGNORED, ignoredAuthorList);
    docAccessor.save(userId, userFollowingDoc);
}
Also used : UserAuthorDoc(com.pratilipi.data.type.UserAuthorDoc) DataAccessor(com.pratilipi.data.DataAccessor) DocAccessor(com.pratilipi.data.DocAccessor) ArrayList(java.util.ArrayList) UserAuthor(com.pratilipi.data.type.UserAuthor) UserFollowsDoc(com.pratilipi.data.type.UserFollowsDoc)

Aggregations

DataAccessor (com.pratilipi.data.DataAccessor)162 Date (java.util.Date)53 InsufficientAccessException (com.pratilipi.common.exception.InsufficientAccessException)37 Pratilipi (com.pratilipi.data.type.Pratilipi)34 Author (com.pratilipi.data.type.Author)33 AuditLog (com.pratilipi.data.type.AuditLog)32 UserPratilipi (com.pratilipi.data.type.UserPratilipi)32 ArrayList (java.util.ArrayList)30 Page (com.pratilipi.data.type.Page)28 HashMap (java.util.HashMap)25 GenericResponse (com.pratilipi.api.shared.GenericResponse)24 DocAccessor (com.pratilipi.data.DocAccessor)22 User (com.pratilipi.data.type.User)22 Get (com.pratilipi.api.annotation.Get)20 InvalidArgumentException (com.pratilipi.common.exception.InvalidArgumentException)19 PratilipiData (com.pratilipi.data.client.PratilipiData)15 UserData (com.pratilipi.data.client.UserData)14 BlobAccessor (com.pratilipi.data.BlobAccessor)13 Email (com.pratilipi.data.type.Email)13 JsonObject (com.google.gson.JsonObject)12