示例#1
0
  /**
   * Resets forgotten password.
   *
   * <p>Renders the response with a json object, for example,
   *
   * <pre>
   * {
   *     "isLoggedIn": boolean,
   *     "msg": "" // optional, exists if isLoggedIn equals to false
   * }
   * </pre>
   *
   * @param context the specified context
   */
  @RequestProcessing(value = "/reset", method = HTTPRequestMethod.POST)
  public void reset(final HTTPRequestContext context) {
    final HttpServletRequest request = context.getRequest();
    final JSONRenderer renderer = new JSONRenderer();

    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();

    renderer.setJSONObject(jsonObject);

    try {
      final JSONObject requestJSONObject;

      requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
      final String userEmail = requestJSONObject.getString(User.USER_EMAIL);
      final String newPwd = requestJSONObject.getString("newPwd");
      final JSONObject user = userQueryService.getUserByEmail(userEmail);

      user.put(User.USER_PASSWORD, newPwd);
      userMgmtService.updateUser(user);
      LOGGER.log(Level.DEBUG, "[{0}]'s password updated successfully.", new Object[] {userEmail});

      jsonObject.put("succeed", true);
      jsonObject.put("to", Latkes.getServePath() + "/login?from=reset");
      jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessMsg"));
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, e.getMessage(), e);
    }
  }
示例#2
0
  /**
   * Render a page template with the destination URL.
   *
   * @param context the context
   * @param pageTemplate the page template
   * @param destinationURL the destination URL
   * @param request for reset password page
   * @throws JSONException the JSONException
   * @throws ServiceException the ServiceException
   */
  private void renderPage(
      final HTTPRequestContext context,
      final String pageTemplate,
      final String destinationURL,
      final HttpServletRequest request)
      throws JSONException, ServiceException {
    final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();

    renderer.setTemplateName(pageTemplate);
    context.setRenderer(renderer);

    final Map<String, Object> dataModel = renderer.getDataModel();
    final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
    final JSONObject preference = preferenceQueryService.getPreference();

    dataModel.putAll(langs);
    dataModel.put(Common.GOTO, destinationURL);
    dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
    dataModel.put(Common.VERSION, SoloServletListener.VERSION);
    dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
    dataModel.put(Preference.BLOG_TITLE, preference.getString(Preference.BLOG_TITLE));

    final String token = request.getParameter("token");
    final String email = request.getParameter("login");
    final JSONObject tokenObj = optionQueryService.getOptionById(token);

    if (tokenObj == null) {
      dataModel.put("inputType", "email");
    } else {
      // TODO verify the expired time in the tokenObj
      dataModel.put("inputType", "password");
      dataModel.put("userEmailHidden", email);
    }

    final String from = request.getParameter("from");

    if ("forgot".equals(from)) {
      dataModel.put("resetMsg", langPropsService.get("resetPwdSuccessSend"));
    } else if ("reset".equals(from)) {
      dataModel.put("resetMsg", langPropsService.get("resetPwdSuccessMsg"));
    } else {
      dataModel.put("resetMsg", "");
    }

    Keys.fillRuntime(dataModel);
    filler.fillMinified(dataModel);
  }
示例#3
0
  /**
   * Logins.
   *
   * <p>Renders the response with a json object, for example,
   *
   * <pre>
   * {
   *     "isLoggedIn": boolean,
   *     "msg": "" // optional, exists if isLoggedIn equals to false
   * }
   * </pre>
   *
   * @param context the specified context
   */
  @RequestProcessing(value = "/login", method = HTTPRequestMethod.POST)
  public void login(final HTTPRequestContext context) {
    final HttpServletRequest request = context.getRequest();

    final JSONRenderer renderer = new JSONRenderer();

    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();

    renderer.setJSONObject(jsonObject);

    try {
      jsonObject.put(Common.IS_LOGGED_IN, false);
      final String loginFailLabel = langPropsService.get("loginFailLabel");

      jsonObject.put(Keys.MSG, loginFailLabel);

      final JSONObject requestJSONObject =
          Requests.parseRequestJSONObject(request, context.getResponse());
      final String userEmail = requestJSONObject.getString(User.USER_EMAIL);
      final String userPwd = requestJSONObject.getString(User.USER_PASSWORD);

      if (Strings.isEmptyOrNull(userEmail) || Strings.isEmptyOrNull(userPwd)) {
        return;
      }

      LOGGER.log(Level.INFO, "Login[email={0}]", userEmail);

      final JSONObject user = userQueryService.getUserByEmail(userEmail);

      if (null == user) {
        LOGGER.log(Level.WARN, "Not found user[email={0}]", userEmail);
        return;
      }

      if (MD5.hash(userPwd).equals(user.getString(User.USER_PASSWORD))) {
        Sessions.login(request, context.getResponse(), user);

        LOGGER.log(Level.INFO, "Logged in[email={0}]", userEmail);

        jsonObject.put(Common.IS_LOGGED_IN, true);

        if (Role.VISITOR_ROLE.equals(user.optString(User.USER_ROLE))) {
          jsonObject.put("to", Latkes.getServePath());
        } else {
          jsonObject.put("to", Latkes.getServePath() + Common.ADMIN_INDEX_URI);
        }

        jsonObject.remove(Keys.MSG);

        return;
      }

      LOGGER.log(Level.WARN, "Wrong password[{0}]", userPwd);
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, e.getMessage(), e);
    }
  }
  /**
   * Gets the latest comments with the specified fetch size.
   *
   * <p>The returned comments content is plain text.
   *
   * @param fetchSize the specified fetch size
   * @return the latest comments, returns an empty list if not found
   * @throws ServiceException service exception
   */
  public List<JSONObject> getLatestComments(final int fetchSize) throws ServiceException {
    final Query query =
        new Query()
            .addSort(Comment.COMMENT_CREATE_TIME, SortDirection.DESCENDING)
            .setCurrentPageNum(1)
            .setPageSize(fetchSize)
            .setPageCount(1);
    try {
      final JSONObject result = commentRepository.get(query);
      final List<JSONObject> ret =
          CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));

      for (final JSONObject comment : ret) {
        comment.put(Comment.COMMENT_CREATE_TIME, comment.optLong(Comment.COMMENT_CREATE_TIME));
        final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
        final JSONObject article = articleRepository.get(articleId);
        comment.put(
            Comment.COMMENT_T_ARTICLE_TITLE,
            Emotions.clear(article.optString(Article.ARTICLE_TITLE)));
        comment.put(
            Comment.COMMENT_T_ARTICLE_PERMALINK, article.optString(Article.ARTICLE_PERMALINK));

        final String commenterId = comment.optString(Comment.COMMENT_AUTHOR_ID);
        final JSONObject commenter = userRepository.get(commenterId);

        if (UserExt.USER_STATUS_C_INVALID == commenter.optInt(UserExt.USER_STATUS)
            || Comment.COMMENT_STATUS_C_INVALID == comment.optInt(Comment.COMMENT_STATUS)) {
          comment.put(Comment.COMMENT_CONTENT, langPropsService.get("commentContentBlockLabel"));
        }

        if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)) {
          comment.put(Comment.COMMENT_CONTENT, "....");
        }

        String content = comment.optString(Comment.COMMENT_CONTENT);
        content = Emotions.clear(content);
        content = Jsoup.clean(content, Whitelist.none());
        if (StringUtils.isBlank(content)) {
          comment.put(Comment.COMMENT_CONTENT, "....");
        } else {
          comment.put(Comment.COMMENT_CONTENT, content);
        }

        final String commenterEmail = comment.optString(Comment.COMMENT_AUTHOR_EMAIL);
        final String avatarURL = avatarQueryService.getAvatarURL(commenterEmail);
        commenter.put(UserExt.USER_AVATAR_URL, avatarURL);

        comment.put(Comment.COMMENT_T_COMMENTER, commenter);
      }

      return ret;
    } catch (final RepositoryException e) {
      LOGGER.log(Level.ERROR, "Gets user comments failed", e);
      throw new ServiceException(e);
    }
  }
示例#5
0
  /**
   * Sends the password resetting URL with a random token.
   *
   * @param userEmail the given email
   * @param jsonObject return code and message object
   * @throws JSONException the JSONException
   * @throws ServiceException the ServiceException
   * @throws IOException the IOException
   * @throws RepositoryException the RepositoryException
   */
  private void sendResetUrl(final String userEmail, final JSONObject jsonObject)
      throws JSONException, ServiceException, IOException, RepositoryException {
    final JSONObject preference = preferenceQueryService.getPreference();
    final String token = new Randoms().nextStringWithMD5();
    final String adminEmail = preference.getString(Preference.ADMIN_EMAIL);
    final String mailSubject = langPropsService.get("resetPwdMailSubject");
    final String mailBody =
        langPropsService.get("resetPwdMailBody")
            + " "
            + Latkes.getServePath()
            + "/forgot?token="
            + token
            + "&login="******"passwordReset");
    option.put(Option.OPTION_VALUE, System.currentTimeMillis());

    final Transaction transaction = optionRepository.beginTransaction();

    optionRepository.add(option);
    transaction.commit();

    message.setFrom(adminEmail);
    message.addRecipient(userEmail);
    message.setSubject(mailSubject);
    message.setHtmlBody(mailBody);

    mailService.send(message);

    jsonObject.put("succeed", true);
    jsonObject.put("to", Latkes.getServePath() + "/login?from=forgot");
    jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessSend"));

    LOGGER.log(
        Level.DEBUG,
        "Sent a mail[mailSubject={0}, mailBody=[{1}] to [{2}]",
        new Object[] {mailSubject, mailBody, userEmail});
  }
示例#6
0
  /**
   * Resets forgotten password.
   *
   * <p>Renders the response with a json object, for example,
   *
   * <pre>
   * {
   *     "isLoggedIn": boolean,
   *     "msg": "" // optional, exists if isLoggedIn equals to false
   * }
   * </pre>
   *
   * @param context the specified context
   */
  @RequestProcessing(value = "/forgot", method = HTTPRequestMethod.POST)
  public void forgot(final HTTPRequestContext context) {
    final HttpServletRequest request = context.getRequest();

    final JSONRenderer renderer = new JSONRenderer();

    context.setRenderer(renderer);
    final JSONObject jsonObject = new JSONObject();

    renderer.setJSONObject(jsonObject);

    try {
      jsonObject.put("succeed", false);
      jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessMsg"));

      final JSONObject requestJSONObject =
          Requests.parseRequestJSONObject(request, context.getResponse());
      final String userEmail = requestJSONObject.getString(User.USER_EMAIL);

      if (Strings.isEmptyOrNull(userEmail)) {
        LOGGER.log(Level.WARN, "Why user's email is empty");
        return;
      }

      LOGGER.log(Level.INFO, "Login[email={0}]", userEmail);

      final JSONObject user = userQueryService.getUserByEmail(userEmail);

      if (null == user) {
        LOGGER.log(Level.WARN, "Not found user[email={0}]", userEmail);
        jsonObject.put(Keys.MSG, langPropsService.get("userEmailNotFoundMsg"));
        return;
      }

      sendResetUrl(userEmail, jsonObject);
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, e.getMessage(), e);
    }
  }
  /**
   * Article rewards.
   *
   * @param request the specified http servlet request
   * @param response the specified http servlet response
   * @param context the specified http request context
   * @throws Exception exception
   */
  @RequestProcessing(value = "/article/reward", method = HTTPRequestMethod.POST)
  @Before(adviceClass = StopwatchStartAdvice.class)
  @After(adviceClass = StopwatchEndAdvice.class)
  public void reward(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final HTTPRequestContext context)
      throws Exception {
    final JSONObject currentUser = userQueryService.getCurrentUser(request);
    if (null == currentUser) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);

      return;
    }

    final String articleId = request.getParameter(Article.ARTICLE_T_ID);
    if (Strings.isEmptyOrNull(articleId)) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);

      return;
    }

    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject result = Results.falseResult();
    renderer.setJSONObject(result);

    try {
      articleMgmtService.reward(articleId, currentUser.optString(Keys.OBJECT_ID));
    } catch (final ServiceException e) {
      result.put(Keys.MSG, langPropsService.get("transferFailLabel"));

      return;
    }

    final JSONObject article = articleQueryService.getArticle(articleId);
    if (null == article) {
      return;
    }

    result.put(Keys.STATUS_CODE, true);
    articleQueryService.processArticleContent(article, request);
    result.put(Article.ARTICLE_REWARD_CONTENT, article.optString(Article.ARTICLE_REWARD_CONTENT));
  }
  /**
   * Processes the specified comment content.
   *
   * <ul>
   *   <li>Generates &#64;username home URL
   *   <li>Markdowns
   *   <li>Blocks comment if need
   *   <li>Generates emotion images
   *   <li>Generates article link with article id
   * </ul>
   *
   * @param comment the specified comment, for example,
   *     <pre>
   * {
   *     "commentContent": "",
   *     ....,
   *     "commenter": {}
   * }
   * </pre>
   */
  private void processCommentContent(final JSONObject comment) {
    final JSONObject commenter = comment.optJSONObject(Comment.COMMENT_T_COMMENTER);

    if (Comment.COMMENT_STATUS_C_INVALID == comment.optInt(Comment.COMMENT_STATUS)
        || UserExt.USER_STATUS_C_INVALID == commenter.optInt(UserExt.USER_STATUS)) {
      comment.put(Comment.COMMENT_CONTENT, langPropsService.get("commentContentBlockLabel"));

      return;
    }

    genCommentContentUserName(comment);

    String commentContent = comment.optString(Comment.COMMENT_CONTENT);

    commentContent = shortLinkQueryService.linkArticle(commentContent);
    commentContent = shortLinkQueryService.linkTag(commentContent);
    commentContent = Emotions.convert(commentContent);
    commentContent = Markdowns.toHTML(commentContent);
    commentContent = Markdowns.clean(commentContent, "");

    comment.put(Comment.COMMENT_CONTENT, commentContent);
  }
  /**
   * Shows article with the specified article id.
   *
   * @param context the specified context
   * @param request the specified request
   * @param response the specified response
   * @param articleId the specified article id
   * @throws Exception exception
   */
  @RequestProcessing(value = "/article/{articleId}", method = HTTPRequestMethod.GET)
  @Before(adviceClass = StopwatchStartAdvice.class)
  @After(adviceClass = {CSRFToken.class, StopwatchEndAdvice.class})
  public void showArticle(
      final HTTPRequestContext context,
      final HttpServletRequest request,
      final HttpServletResponse response,
      final String articleId)
      throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);

    renderer.setTemplateName("/article.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();

    final JSONObject article = articleQueryService.getArticleById(articleId);
    if (null == article) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);

      return;
    }

    final HttpSession session = request.getSession(false);
    if (null != session) {
      session.setAttribute(Article.ARTICLE_T_ID, articleId);
    }

    filler.fillHeaderAndFooter(request, response, dataModel);

    final String authorEmail = article.optString(Article.ARTICLE_AUTHOR_EMAIL);
    final JSONObject author = userQueryService.getUserByEmail(authorEmail);
    article.put(Article.ARTICLE_T_AUTHOR_NAME, author.optString(User.USER_NAME));
    article.put(Article.ARTICLE_T_AUTHOR_URL, author.optString(User.USER_URL));
    article.put(Article.ARTICLE_T_AUTHOR_INTRO, author.optString(UserExt.USER_INTRO));
    dataModel.put(Article.ARTICLE, article);

    article.put(Common.IS_MY_ARTICLE, false);
    article.put(Article.ARTICLE_T_AUTHOR, author);
    article.put(Common.REWARDED, false);

    articleQueryService.processArticleContent(article, request);

    final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
    JSONObject currentUser;
    String currentUserId = null;
    if (isLoggedIn) {
      currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
      currentUserId = currentUser.optString(Keys.OBJECT_ID);

      article.put(
          Common.IS_MY_ARTICLE, currentUserId.equals(article.optString(Article.ARTICLE_AUTHOR_ID)));

      final boolean isFollowing = followQueryService.isFollowing(currentUserId, articleId);
      dataModel.put(Common.IS_FOLLOWING, isFollowing);

      final int vote = voteQueryService.isVoted(currentUserId, articleId);
      dataModel.put(Vote.VOTE, vote);

      if (currentUserId.equals(author.optString(Keys.OBJECT_ID))) {
        article.put(Common.REWARDED, true);
      } else {
        article.put(
            Common.REWARDED,
            rewardQueryService.isRewarded(currentUserId, articleId, Reward.TYPE_C_ARTICLE));
      }
    }

    if (!(Boolean) request.getAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT)) {
      articleMgmtService.incArticleViewCount(articleId);
    }

    filler.fillRelevantArticles(dataModel, article);
    filler.fillRandomArticles(dataModel);
    filler.fillHotArticles(dataModel);

    // Qiniu file upload authenticate
    final Auth auth =
        Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey"));
    final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket"));
    dataModel.put("qiniuUploadToken", uploadToken);
    dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain"));

    dataModel.put(Common.DISCUSSION_VIEWABLE, article.optBoolean(Common.DISCUSSION_VIEWABLE));
    if (!article.optBoolean(Common.DISCUSSION_VIEWABLE)) {
      article.put(Article.ARTICLE_T_COMMENTS, (Object) Collections.emptyList());

      return;
    }

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
      pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);
    final int pageSize = Symphonys.getInt("articleCommentsPageSize");
    final int windowSize = Symphonys.getInt("articleCommentsWindowSize");

    final List<JSONObject> articleComments =
        commentQueryService.getArticleComments(articleId, pageNum, pageSize);
    article.put(Article.ARTICLE_T_COMMENTS, (Object) articleComments);

    // Fill reward(thank)
    for (final JSONObject comment : articleComments) {
      String thankTemplate = langPropsService.get("thankConfirmLabel");
      thankTemplate =
          thankTemplate
              .replace("{point}", String.valueOf(Symphonys.getInt("pointThankComment")))
              .replace(
                  "{user}",
                  comment.optJSONObject(Comment.COMMENT_T_COMMENTER).optString(User.USER_NAME));
      comment.put(Comment.COMMENT_T_THANK_LABEL, thankTemplate);

      final String commentId = comment.optString(Keys.OBJECT_ID);
      if (isLoggedIn) {
        comment.put(
            Common.REWARDED,
            rewardQueryService.isRewarded(currentUserId, commentId, Reward.TYPE_C_COMMENT));
      }

      comment.put(
          Common.REWARED_COUNT, rewardQueryService.rewardedCount(commentId, Reward.TYPE_C_COMMENT));
    }

    final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_CNT);
    final int pageCount = (int) Math.ceil((double) commentCnt / (double) pageSize);

    final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
    if (!pageNums.isEmpty()) {
      dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
      dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
    }

    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
    dataModel.put(Common.ARTICLE_COMMENTS_PAGE_SIZE, pageSize);
  }
示例#10
0
  /**
   * Gets article preview content.
   *
   * <p>Renders the response with a json object, for example,
   *
   * <pre>
   * {
   *     "html": ""
   * }
   * </pre>
   *
   * @param request the specified http servlet request
   * @param response the specified http servlet response
   * @param context the specified http request context
   * @param articleId the specified article id
   * @throws Exception exception
   */
  @RequestProcessing(value = "/article/{articleId}/preview", method = HTTPRequestMethod.GET)
  @Before(adviceClass = StopwatchStartAdvice.class)
  @After(adviceClass = StopwatchEndAdvice.class)
  public void getArticlePreviewContent(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final HTTPRequestContext context,
      final String articleId)
      throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject result = Results.trueResult();
    renderer.setJSONObject(result);

    result.put("html", "");

    final JSONObject article = articleQueryService.getArticle(articleId);
    if (null == article) {
      result.put(Keys.STATUS_CODE, false);

      return;
    }

    final int length = Integer.valueOf("150");
    String content = article.optString(Article.ARTICLE_CONTENT);
    final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
    final JSONObject author = userQueryService.getUser(authorId);

    if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)
        || Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
      result.put("html", langPropsService.get("articleContentBlockLabel"));

      return;
    }

    final Set<String> userNames = userQueryService.getUserNames(content);
    final JSONObject currentUser = userQueryService.getCurrentUser(request);
    final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME);
    final String authorName = author.optString(User.USER_NAME);
    if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
        && !authorName.equals(currentUserName)) {
      boolean invited = false;
      for (final String userName : userNames) {
        if (userName.equals(currentUserName)) {
          invited = true;

          break;
        }
      }

      if (!invited) {
        String blockContent = langPropsService.get("articleDiscussionLabel");
        blockContent =
            blockContent.replace(
                "{user}",
                "<a href='"
                    + Latkes.getServePath()
                    + "/member/"
                    + authorName
                    + "'>"
                    + authorName
                    + "</a>");

        result.put("html", blockContent);

        return;
      }
    }

    content = Emotions.convert(content);
    content = Markdowns.toHTML(content);

    content = Jsoup.clean(content, Whitelist.none());
    if (content.length() >= length) {
      content = StringUtils.substring(content, 0, length) + " ....";
    }

    result.put("html", content);
  }
示例#11
0
  /**
   * Try to write response from cache.
   *
   * @param request the specified request
   * @param response the specified response
   * @param chain filter chain
   * @throws IOException io exception
   * @throws ServletException servlet exception
   */
  @Override
  public void doFilter(
      final ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
      final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
      LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
      request.getRequestDispatcher(path).forward(request, response);

      return;
    }

    if (!Latkes.isPageCacheEnabled()) {
      LOGGER.log(Level.FINEST, "Page cache is disabled");
      chain.doFilter(request, response);

      return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
      // Mobile request, bypasses page caching
      chain.doFilter(request, response);

      return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
      pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
      request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject =
        PageCaches.get(pageCacheKey, httpServletRequest, (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
      LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
      chain.doFilter(request, response);

      return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
      // If cached an article that has view password, dispatches the password form
      if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
          && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
        JSONObject article = new JSONObject();

        final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

        article.put(Keys.OBJECT_ID, articleId);
        article.put(
            Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

        if (articles.needViewPwd(httpServletRequest, article)) {
          article = articleRepository.get(articleId); // Loads the article entity

          final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
          try {
            httpServletResponse.sendRedirect(
                Latkes.getServePath()
                    + "/console/article-pwd"
                    + articles.buildArticleViewPwdFormParameters(article));
            return;
          } catch (final Exception e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
          }
        }
      }
    } catch (final Exception e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    }

    try {
      LOGGER.log(
          Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
      response.setContentType("text/html");
      response.setCharacterEncoding("UTF-8");
      final PrintWriter writer = response.getWriter();
      String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
      final String topBarHTML =
          TopBars.getTopBarHTML((HttpServletRequest) request, (HttpServletResponse) response);
      cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

      final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
      LOGGER.log(
          Level.FINEST,
          "Cached value[key={0}, type={1}, title={2}]",
          new Object[] {pageCacheKey, cachedType, cachedTitle});

      statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

      final long endimeMillis = System.currentTimeMillis();
      final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
      final String msg =
          String.format(
              "<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
              endimeMillis - startTimeMillis, dateString);
      LOGGER.finer(msg);
      cachedPageContent += Strings.LINE_SEPARATOR + msg;
      writer.write(cachedPageContent);
      writer.flush();
      writer.close();
    } catch (final JSONException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    } catch (final RepositoryException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    } catch (final ServiceException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    }
  }
  @Override
  public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args)
      throws RequestProcessAdviceException {
    final HttpServletRequest request = context.getRequest();

    JSONObject requestJSONObject;
    try {
      requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
      request.setAttribute(Keys.REQUEST, requestJSONObject);
    } catch (final Exception e) {
      throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, e.getMessage()));
    }

    final String userURL = requestJSONObject.optString(User.USER_URL);
    if (!Strings.isEmptyOrNull(userURL) && invalidUserURL(userURL)) {
      throw new RequestProcessAdviceException(
          new JSONObject()
              .put(
                  Keys.MSG,
                  "URL"
                      + langPropsService.get("colonLabel")
                      + langPropsService.get("invalidUserURLLabel")));
    }

    final String userQQ = requestJSONObject.optString(UserExt.USER_QQ);
    if (!Strings.isEmptyOrNull(userQQ)
        && (!Strings.isNumeric(userQQ) || userQQ.length() > MAX_USER_QQ_LENGTH)) {
      throw new RequestProcessAdviceException(
          new JSONObject().put(Keys.MSG, langPropsService.get("invalidUserQQLabel")));
    }

    final String userIntro = requestJSONObject.optString(UserExt.USER_INTRO);
    if (!Strings.isEmptyOrNull(userIntro) && userIntro.length() > MAX_USER_INTRO_LENGTH) {
      throw new RequestProcessAdviceException(
          new JSONObject().put(Keys.MSG, langPropsService.get("invalidUserIntroLabel")));
    }

    final String tagErrMsg =
        langPropsService.get("selfTagLabel")
            + langPropsService.get("colonLabel")
            + langPropsService.get("tagsErrorLabel");

    String userTags = requestJSONObject.optString(UserExt.USER_TAGS);
    if (Strings.isEmptyOrNull(userTags)) {
      throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, tagErrMsg));
    }

    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class);

    userTags = userMgmtService.formatUserTags(userTags);
    String[] tagTitles = userTags.split(",");
    if (null == tagTitles || 0 == tagTitles.length) {
      throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, tagErrMsg));
    }

    tagTitles = new LinkedHashSet<String>(Arrays.asList(tagTitles)).toArray(new String[0]);

    final StringBuilder tagBuilder = new StringBuilder();
    for (int i = 0; i < tagTitles.length; i++) {
      final String tagTitle = tagTitles[i].trim();

      if (Strings.isEmptyOrNull(tagTitle)) {
        throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, tagErrMsg));
      }

      if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) {
        throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, tagErrMsg));
      }

      if (Strings.isEmptyOrNull(tagTitle)
          || tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH
          || tagTitle.length() < 1) {
        throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, tagErrMsg));
      }

      final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
      if (!Role.ADMIN_ROLE.equals(currentUser.optString(User.USER_ROLE))
          && ArrayUtils.contains(Symphonys.RESERVED_TAGS, tagTitle)) {
        throw new RequestProcessAdviceException(
            new JSONObject()
                .put(
                    Keys.MSG,
                    langPropsService.get("selfTagLabel")
                        + langPropsService.get("colonLabel")
                        + langPropsService.get("articleTagReservedLabel")
                        + " ["
                        + tagTitle
                        + "]"));
      }

      tagBuilder.append(tagTitle).append(",");
    }
    if (tagBuilder.length() > 0) {
      tagBuilder.deleteCharAt(tagBuilder.length() - 1);
    }

    requestJSONObject.put(UserExt.USER_TAGS, tagBuilder.toString());
  }
示例#13
0
  @Override
  public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(
        Level.DEBUG,
        "Processing an event[type={0}, data={1}] in listener[className={2}]",
        new Object[] {event.getType(), data, ArticleNotifier.class.getName()});

    try {
      final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
      final String articleId = originalArticle.optString(Keys.OBJECT_ID);

      final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
      final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId);
      final String articleAuthorName = articleAuthor.optString(User.USER_NAME);

      final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);
      final Set<String> atUserNames = userQueryService.getUserNames(articleContent);
      atUserNames.remove(articleAuthorName); // Do not notify the author itself

      final Set<String> atedUserIds = new HashSet<String>();

      // 'At' Notification
      for (final String userName : atUserNames) {
        final JSONObject user = userQueryService.getUserByName(userName);

        if (null == user) {
          LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName);

          continue;
        }

        final JSONObject requestJSONObject = new JSONObject();
        final String atedUserId = user.optString(Keys.OBJECT_ID);
        requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId);
        requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId);

        notificationMgmtService.addAtNotification(requestJSONObject);

        atedUserIds.add(atedUserId);
      }

      // 'FollowingUser' Notification
      final JSONObject followerUsersResult =
          followQueryService.getFollowerUsers(articleAuthorId, 1, Integer.MAX_VALUE);
      @SuppressWarnings("unchecked")
      final List<JSONObject> followerUsers = (List) followerUsersResult.opt(Keys.RESULTS);
      for (final JSONObject followerUser : followerUsers) {
        final JSONObject requestJSONObject = new JSONObject();
        final String followerUserId = followerUser.optString(Keys.OBJECT_ID);

        if (atedUserIds.contains(followerUserId)) {
          continue;
        }

        requestJSONObject.put(Notification.NOTIFICATION_USER_ID, followerUserId);
        requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId);

        notificationMgmtService.addFollowingUserNotification(requestJSONObject);
      }

      // Timeline
      final String articleTitle =
          StringUtils.substring(
              Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text(), 0, 28);
      final String articlePermalink =
          Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK);

      final JSONObject timeline = new JSONObject();
      timeline.put(Common.TYPE, Article.ARTICLE);
      String content = langPropsService.get("timelineArticleLabel");
      content =
          content
              .replace(
                  "{user}",
                  "<a target='_blank' rel='nofollow' href='"
                      + Latkes.getServePath()
                      + "/member/"
                      + articleAuthorName
                      + "'>"
                      + articleAuthorName
                      + "</a>")
              .replace(
                  "{article}",
                  "<a target='_blank' rel='nofollow' href='"
                      + articlePermalink
                      + "'>"
                      + articleTitle
                      + "</a>");
      timeline.put(Common.CONTENT, content);

      timelineMgmtService.addTimeline(timeline);

      // 'Broadcast' Notification
      if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE)) {
        final String city = originalArticle.optString(Article.ARTICLE_CITY);

        if (StringUtils.isNotBlank(city)) {
          final JSONObject requestJSONObject = new JSONObject();
          requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1);
          requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE);
          requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE);

          final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime();
          requestJSONObject.put(UserExt.USER_LATEST_LOGIN_TIME, latestLoginTime);
          requestJSONObject.put(UserExt.USER_CITY, city);

          final JSONObject result = userQueryService.getUsersByCity(requestJSONObject);
          final JSONArray users = result.optJSONArray(User.USERS);

          for (int i = 0; i < users.length(); i++) {
            final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID);

            if (userId.equals(articleAuthorId)) {
              continue;
            }

            final JSONObject notification = new JSONObject();
            notification.put(Notification.NOTIFICATION_USER_ID, userId);
            notification.put(Notification.NOTIFICATION_DATA_ID, articleId);

            notificationMgmtService.addBroadcastNotification(notification);
          }

          LOGGER.info("City broadcast [" + users.length() + "]");
        }
      }
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, "Sends the article notification failed", e);
    }
  }
  /**
   * Gets comments by the specified request json object.
   *
   * @param requestJSONObject the specified request json object, for example,
   *     <pre>
   * {
   *     "paginationCurrentPageNum": 1,
   *     "paginationPageSize": 20,
   *     "paginationWindowSize": 10,
   * }, see {@link Pagination} for more details
   * </pre>
   *
   * @param commentFields the specified article fields to return
   * @return for example,
   *     <pre>
   * {
   *     "pagination": {
   *         "paginationPageCount": 100,
   *         "paginationPageNums": [1, 2, 3, 4, 5]
   *     },
   *     "comments": [{
   *         "oId": "",
   *         "commentContent": "",
   *         "commentCreateTime": "",
   *         ....
   *      }, ....]
   * }
   * </pre>
   *
   * @throws ServiceException service exception
   * @see Pagination
   */
  public JSONObject getComments(
      final JSONObject requestJSONObject, final Map<String, Class<?>> commentFields)
      throws ServiceException {
    final JSONObject ret = new JSONObject();

    final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
    final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE);
    final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE);
    final Query query =
        new Query()
            .setCurrentPageNum(currentPageNum)
            .setPageSize(pageSize)
            .addSort(Comment.COMMENT_CREATE_TIME, SortDirection.DESCENDING);
    for (final Map.Entry<String, Class<?>> commentField : commentFields.entrySet()) {
      query.addProjection(commentField.getKey(), commentField.getValue());
    }

    JSONObject result = null;

    try {
      result = commentRepository.get(query);
    } catch (final RepositoryException e) {
      LOGGER.log(Level.ERROR, "Gets comments failed", e);

      throw new ServiceException(e);
    }

    final int pageCount =
        result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);

    final JSONObject pagination = new JSONObject();
    ret.put(Pagination.PAGINATION, pagination);
    final List<Integer> pageNums =
        Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
    pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);

    final JSONArray data = result.optJSONArray(Keys.RESULTS);
    final List<JSONObject> comments = CollectionUtils.<JSONObject>jsonArrayToList(data);

    try {
      for (final JSONObject comment : comments) {
        organizeComment(comment);

        final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
        final JSONObject article = articleRepository.get(articleId);

        comment.put(
            Comment.COMMENT_T_ARTICLE_TITLE,
            Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)
                ? langPropsService.get("articleTitleBlockLabel")
                : Emotions.convert(article.optString(Article.ARTICLE_TITLE)));
        comment.put(
            Comment.COMMENT_T_ARTICLE_PERMALINK, article.optString(Article.ARTICLE_PERMALINK));
      }
    } catch (final RepositoryException e) {
      LOGGER.log(Level.ERROR, "Organizes comments failed", e);

      throw new ServiceException(e);
    }

    ret.put(Comment.COMMENTS, comments);

    return ret;
  }
  /**
   * Gets the user comments with the specified user id, page number and page size.
   *
   * @param userId the specified user id
   * @param currentPageNum the specified page number
   * @param pageSize the specified page size
   * @param viewer the specified viewer, may be {@code null}
   * @return user comments, return an empty list if not found
   * @throws ServiceException service exception
   */
  public List<JSONObject> getUserComments(
      final String userId, final int currentPageNum, final int pageSize, final JSONObject viewer)
      throws ServiceException {
    final Query query =
        new Query()
            .addSort(Comment.COMMENT_CREATE_TIME, SortDirection.DESCENDING)
            .setCurrentPageNum(currentPageNum)
            .setPageSize(pageSize)
            .setFilter(new PropertyFilter(Comment.COMMENT_AUTHOR_ID, FilterOperator.EQUAL, userId));
    try {
      final JSONObject result = commentRepository.get(query);
      final List<JSONObject> ret =
          CollectionUtils.<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));

      for (final JSONObject comment : ret) {
        comment.put(
            Comment.COMMENT_CREATE_TIME, new Date(comment.optLong(Comment.COMMENT_CREATE_TIME)));

        final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
        final JSONObject article = articleRepository.get(articleId);

        comment.put(
            Comment.COMMENT_T_ARTICLE_TITLE,
            Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)
                ? langPropsService.get("articleTitleBlockLabel")
                : Emotions.convert(article.optString(Article.ARTICLE_TITLE)));
        comment.put(Comment.COMMENT_T_ARTICLE_TYPE, article.optInt(Article.ARTICLE_TYPE));
        comment.put(
            Comment.COMMENT_T_ARTICLE_PERMALINK, article.optString(Article.ARTICLE_PERMALINK));

        final JSONObject commenter = userRepository.get(userId);
        comment.put(Comment.COMMENT_T_COMMENTER, commenter);

        final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
        final JSONObject articleAuthor = userRepository.get(articleAuthorId);
        final String articleAuthorName = articleAuthor.optString(User.USER_NAME);
        final String articleAuthorURL = "/member/" + articleAuthor.optString(User.USER_NAME);
        comment.put(Comment.COMMENT_T_ARTICLE_AUTHOR_NAME, articleAuthorName);
        comment.put(Comment.COMMENT_T_ARTICLE_AUTHOR_URL, articleAuthorURL);
        final String articleAuthorEmail = articleAuthor.optString(User.USER_EMAIL);
        final String articleAuthorThumbnailURL =
            avatarQueryService.getAvatarURL(articleAuthorEmail);
        comment.put(Comment.COMMENT_T_ARTICLE_AUTHOR_THUMBNAIL_URL, articleAuthorThumbnailURL);

        if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)) {
          final String msgContent =
              langPropsService
                  .get("articleDiscussionLabel")
                  .replace(
                      "{user}",
                      "<a href='"
                          + Latkes.getServePath()
                          + "/member/"
                          + articleAuthorName
                          + "'>"
                          + articleAuthorName
                          + "</a>");

          if (null == viewer) {
            comment.put(Comment.COMMENT_CONTENT, msgContent);
          } else {
            final String commenterName = commenter.optString(User.USER_NAME);
            final String viewerUserName = viewer.optString(User.USER_NAME);
            final String viewerRole = viewer.optString(User.USER_ROLE);

            if (!commenterName.equals(viewerUserName) && !Role.ADMIN_ROLE.equals(viewerRole)) {
              final String articleContent = article.optString(Article.ARTICLE_CONTENT);
              final Set<String> userNames = userQueryService.getUserNames(articleContent);

              boolean invited = false;
              for (final String userName : userNames) {
                if (userName.equals(viewerUserName)) {
                  invited = true;

                  break;
                }
              }

              if (!invited) {
                comment.put(Comment.COMMENT_CONTENT, msgContent);
              }
            }
          }
        }

        processCommentContent(comment);
      }

      return ret;
    } catch (final RepositoryException e) {
      LOGGER.log(Level.ERROR, "Gets user comments failed", e);
      throw new ServiceException(e);
    }
  }
示例#16
0
  /**
   * Updates an article locally.
   *
   * <p>The request json object (an article):
   *
   * <pre>
   * {
   *   "articleTitle": "",
   *   "articleTags": "", // Tags spliting by ','
   *   "articleContent": "",
   *   "articleCommentable": boolean,
   *   "articleType": int,
   *   "articleRewardContent": "",
   *   "articleRewardPoint": int
   * }
   * </pre>
   *
   * @param context the specified context
   * @param request the specified request
   * @param response the specified response
   * @param id the specified article id
   * @throws Exception exception
   */
  @RequestProcessing(value = "/article/{id}", method = HTTPRequestMethod.PUT)
  @Before(
      adviceClass = {
        StopwatchStartAdvice.class,
        LoginCheck.class,
        CSRFCheck.class,
        ArticleUpdateValidation.class
      })
  @After(adviceClass = StopwatchEndAdvice.class)
  public void updateArticle(
      final HTTPRequestContext context,
      final HttpServletRequest request,
      final HttpServletResponse response,
      final String id)
      throws Exception {
    if (Strings.isEmptyOrNull(id)) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);

      return;
    }

    final JSONObject oldArticle = articleQueryService.getArticleById(id);
    if (null == oldArticle) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);

      return;
    }

    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);

    final JSONObject ret = Results.falseResult();
    renderer.setJSONObject(ret);

    final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);

    final String articleTitle = requestJSONObject.optString(Article.ARTICLE_TITLE);
    String articleTags = requestJSONObject.optString(Article.ARTICLE_TAGS);
    final String articleContent = requestJSONObject.optString(Article.ARTICLE_CONTENT);
    // final boolean articleCommentable = requestJSONObject.optBoolean(Article.ARTICLE_COMMENTABLE);
    final boolean articleCommentable = true;
    final int articleType =
        requestJSONObject.optInt(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL);
    final String articleRewardContent = requestJSONObject.optString(Article.ARTICLE_REWARD_CONTENT);
    final int articleRewardPoint = requestJSONObject.optInt(Article.ARTICLE_REWARD_POINT);

    final JSONObject article = new JSONObject();
    article.put(Keys.OBJECT_ID, id);
    article.put(Article.ARTICLE_TITLE, articleTitle);
    article.put(Article.ARTICLE_CONTENT, articleContent);
    article.put(Article.ARTICLE_EDITOR_TYPE, 0);
    article.put(Article.ARTICLE_COMMENTABLE, articleCommentable);
    article.put(Article.ARTICLE_TYPE, articleType);
    article.put(Article.ARTICLE_REWARD_CONTENT, articleRewardContent);
    article.put(Article.ARTICLE_REWARD_POINT, articleRewardPoint);

    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
    if (null == currentUser
        || !currentUser
            .optString(Keys.OBJECT_ID)
            .equals(oldArticle.optString(Article.ARTICLE_AUTHOR_ID))) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);

      return;
    }

    article.put(Article.ARTICLE_AUTHOR_ID, currentUser.optString(Keys.OBJECT_ID));

    final String authorEmail = currentUser.optString(User.USER_EMAIL);
    article.put(Article.ARTICLE_AUTHOR_EMAIL, authorEmail);

    if (!Role.ADMIN_ROLE.equals(currentUser.optString(User.USER_ROLE))) {
      articleTags = articleMgmtService.filterReservedTags(articleTags);
    }

    try {
      if (Strings.isEmptyOrNull(articleTags)) {
        throw new ServiceException(langPropsService.get("articleTagReservedLabel"));
      }

      article.put(Article.ARTICLE_TAGS, articleTags);

      articleMgmtService.updateArticle(article);
      ret.put(Keys.STATUS_CODE, true);
    } catch (final ServiceException e) {
      final String msg = e.getMessage();
      LOGGER.log(
          Level.ERROR, "Adds article[title=" + articleTitle + "] failed: {0}", e.getMessage());

      ret.put(Keys.MSG, msg);
    }
  }
示例#17
0
  /**
   * Updates an article remotely.
   *
   * <p>This interface will be called by Rhythm, so here is no article data validation, just only
   * validate the B3 key.
   *
   * <p>The request json object, for example,
   *
   * <pre>
   * {
   *     "article": {
   *         "articleAuthorEmail": "*****@*****.**",
   *         "articleContent": "&lt;p&gt;test&lt;\/p&gt;",
   *         "articleCreateDate": 1350635469922,
   *         "articlePermalink": "/articles/2012/10/19/1350635469866.html",
   *         "articleTags": "test",
   *         "articleTitle": "test",
   *         "clientArticleId": "1350635469866",
   *         "oId": "1350635469866"
   *     },
   *     "clientAdminEmail": "*****@*****.**",
   *     "clientHost": "http://localhost:11099",
   *     "clientName": "B3log Solo",
   *     "clientTitle": "简约设计の艺术",
   *     "clientRuntimeEnv": "LOCAL",
   *     "clientVersion": "0.5.0",
   *     "symphonyKey": "....",
   *     "userB3Key": "Your key"
   * }
   * </pre>
   *
   * @param context the specified context
   * @param request the specified request
   * @param response the specified response
   * @throws Exception exception
   */
  @RequestProcessing(value = "/rhythm/article", method = HTTPRequestMethod.PUT)
  @Before(adviceClass = StopwatchStartAdvice.class)
  @After(adviceClass = StopwatchEndAdvice.class)
  public void updateArticleFromRhythm(
      final HTTPRequestContext context,
      final HttpServletRequest request,
      final HttpServletResponse response)
      throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);

    final JSONObject ret = Results.falseResult();
    renderer.setJSONObject(ret);

    final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);

    final String userB3Key = requestJSONObject.getString(UserExt.USER_B3_KEY);
    final String symphonyKey = requestJSONObject.getString(Common.SYMPHONY_KEY);
    final String clientAdminEmail = requestJSONObject.getString(Client.CLIENT_ADMIN_EMAIL);
    final String clientName = requestJSONObject.getString(Client.CLIENT_NAME);
    final String clientTitle = requestJSONObject.getString(Client.CLIENT_T_TITLE);
    final String clientVersion = requestJSONObject.getString(Client.CLIENT_VERSION);
    final String clientHost = requestJSONObject.getString(Client.CLIENT_HOST);
    final String clientRuntimeEnv = requestJSONObject.getString(Client.CLIENT_RUNTIME_ENV);

    final String maybeIP = StringUtils.substringBetween(clientHost, "://", ":");
    if (Networks.isIPv4(maybeIP)) {
      LOGGER.log(
          Level.WARN,
          "Sync update article error, caused by the client host [{0}] is invalid",
          clientHost);

      return;
    }

    final JSONObject user = userQueryService.getUserByEmail(clientAdminEmail);
    if (null == user) {
      LOGGER.log(
          Level.WARN,
          "The user[email={0}, host={1}] not found in community",
          clientAdminEmail,
          clientHost);

      return;
    }

    final String userName = user.optString(User.USER_NAME);

    if (!Symphonys.get("keyOfSymphony").equals(symphonyKey)
        || !user.optString(UserExt.USER_B3_KEY).equals(userB3Key)) {
      LOGGER.log(
          Level.WARN,
          "B3 key not match, ignored update article [name={0}, host={1}]",
          userName,
          clientHost);

      return;
    }

    if (UserExt.USER_STATUS_C_VALID != user.optInt(UserExt.USER_STATUS)) {
      LOGGER.log(
          Level.WARN, "The user[name={0}, host={1}] has been forbidden", userName, clientHost);

      return;
    }

    final JSONObject originalArticle = requestJSONObject.getJSONObject(Article.ARTICLE);

    final String articleTitle = originalArticle.optString(Article.ARTICLE_TITLE);
    String articleTags =
        articleMgmtService.formatArticleTags(originalArticle.optString(Article.ARTICLE_TAGS));
    String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);

    final String permalink = originalArticle.optString(Article.ARTICLE_PERMALINK);
    articleContent +=
        "<p class='fn-clear'><span class='fn-right'><span class='ft-small'>该文章同步自</span> "
            + "<i style='margin-right:5px;'><a target='_blank' href='"
            + clientHost
            + permalink
            + "'>"
            + clientTitle
            + "</a></i></span></p>";

    final String authorId = user.optString(Keys.OBJECT_ID);
    final String clientArticleId = originalArticle.optString(Keys.OBJECT_ID);
    final JSONObject oldArticle =
        articleQueryService.getArticleByClientArticleId(authorId, clientArticleId);
    if (null == oldArticle) {
      LOGGER.log(
          Level.WARN,
          "Not found article [clientHost={0}, clientArticleId={1}] to update",
          clientHost,
          clientArticleId);

      return;
    }

    final JSONObject article = new JSONObject();
    article.put(Keys.OBJECT_ID, oldArticle.optString(Keys.OBJECT_ID));
    article.put(Article.ARTICLE_TITLE, articleTitle);
    article.put(Article.ARTICLE_CONTENT, articleContent);
    article.put(Article.ARTICLE_EDITOR_TYPE, 0);
    article.put(Article.ARTICLE_SYNC_TO_CLIENT, false);
    article.put(Article.ARTICLE_CLIENT_ARTICLE_ID, clientArticleId);
    article.put(Article.ARTICLE_AUTHOR_ID, authorId);
    article.put(Article.ARTICLE_AUTHOR_EMAIL, clientAdminEmail.toLowerCase().trim());
    article.put(Article.ARTICLE_T_IS_BROADCAST, false);

    if (!Role.ADMIN_ROLE.equals(user.optString(User.USER_ROLE))) {
      articleTags = articleMgmtService.filterReservedTags(articleTags);
    }

    try {
      if (Strings.isEmptyOrNull(articleTags)) {
        throw new ServiceException(langPropsService.get("articleTagReservedLabel"));
      }

      article.put(Article.ARTICLE_TAGS, articleTags);

      articleMgmtService.updateArticle(article);

      ret.put(Keys.STATUS_CODE, true);
    } catch (final ServiceException e) {
      final String msg = langPropsService.get("updateFailLabel") + " - " + e.getMessage();
      LOGGER.log(Level.ERROR, msg, e);

      ret.put(Keys.MSG, msg);
    }

    // Updates client record
    JSONObject client = clientQueryService.getClientByAdminEmail(clientAdminEmail);
    if (null == client) {
      client = new JSONObject();
      client.put(Client.CLIENT_ADMIN_EMAIL, clientAdminEmail);
      client.put(Client.CLIENT_HOST, clientHost);
      client.put(Client.CLIENT_NAME, clientName);
      client.put(Client.CLIENT_RUNTIME_ENV, clientRuntimeEnv);
      client.put(Client.CLIENT_VERSION, clientVersion);
      client.put(Client.CLIENT_LATEST_ADD_COMMENT_TIME, 0L);
      client.put(Client.CLIENT_LATEST_ADD_ARTICLE_TIME, System.currentTimeMillis());

      clientMgmtService.addClient(client);
    } else {
      client.put(Client.CLIENT_ADMIN_EMAIL, clientAdminEmail);
      client.put(Client.CLIENT_HOST, clientHost);
      client.put(Client.CLIENT_NAME, clientName);
      client.put(Client.CLIENT_RUNTIME_ENV, clientRuntimeEnv);
      client.put(Client.CLIENT_VERSION, clientVersion);
      client.put(Client.CLIENT_LATEST_ADD_ARTICLE_TIME, System.currentTimeMillis());

      clientMgmtService.updateClient(client);
    }
  }
示例#18
0
  @Override
  public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(
        Level.DEBUG,
        "Processing an event[type={0}, data={1}] in listener[className={2}]",
        new Object[] {event.getType(), data, CommentNotifier.class.getName()});

    try {
      final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
      final JSONObject originalComment = data.getJSONObject(Comment.COMMENT);
      final String commentContent = originalComment.optString(Comment.COMMENT_CONTENT);
      final JSONObject commenter =
          userQueryService.getUser(originalComment.optString(Comment.COMMENT_AUTHOR_ID));
      final String commenterName = commenter.optString(User.USER_NAME);

      // 0. Data channel (WebSocket)
      final JSONObject chData = new JSONObject();
      chData.put(Article.ARTICLE_T_ID, originalArticle.optString(Keys.OBJECT_ID));
      chData.put(Comment.COMMENT_T_ID, originalComment.optString(Keys.OBJECT_ID));
      chData.put(Comment.COMMENT_T_AUTHOR_NAME, commenterName);

      final String userEmail = commenter.optString(User.USER_EMAIL);
      chData.put(
          Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURL(userEmail));
      chData.put(Common.THUMBNAIL_UPDATE_TIME, commenter.optLong(UserExt.USER_UPDATE_TIME));

      chData.put(
          Comment.COMMENT_CREATE_TIME,
          DateFormatUtils.format(
              new Date(originalComment.optLong(Comment.COMMENT_CREATE_TIME)), "yyyy-MM-dd HH:mm"));
      String cc = shortLinkQueryService.linkArticle(commentContent);
      cc = shortLinkQueryService.linkTag(cc);
      cc = Emotions.convert(cc);
      cc = Markdowns.toHTML(cc);
      cc = Markdowns.clean(cc, "");
      try {
        final Set<String> userNames = userQueryService.getUserNames(commentContent);
        for (final String userName : userNames) {
          cc =
              cc.replace(
                  '@' + userName,
                  "@<a href='"
                      + Latkes.getServePath()
                      + "/member/"
                      + userName
                      + "'>"
                      + userName
                      + "</a>");
        }
      } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Generates @username home URL for comment content failed", e);
      }
      chData.put(Comment.COMMENT_CONTENT, cc);

      ArticleChannel.notifyComment(chData);

      // + Article Heat
      final JSONObject articleHeat = new JSONObject();
      articleHeat.put(Article.ARTICLE_T_ID, originalArticle.optString(Keys.OBJECT_ID));
      articleHeat.put(Common.OPERATION, "+");
      ArticleListChannel.notifyHeat(articleHeat);

      final boolean isDiscussion =
          originalArticle.optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION;

      // Timeline
      if (!isDiscussion) {
        final String articleTitle =
            StringUtils.substring(
                Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text(), 0, 28);
        final String articlePermalink =
            Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK);

        final JSONObject timeline = new JSONObject();
        timeline.put(Common.TYPE, Comment.COMMENT);
        String content = langPropsService.get("timelineCommentLabel");
        content =
            content
                .replace(
                    "{user}",
                    "<a target='_blank' rel='nofollow' href='"
                        + Latkes.getServePath()
                        + "/member/"
                        + commenterName
                        + "'>"
                        + commenterName
                        + "</a>")
                .replace(
                    "{article}",
                    "<a target='_blank' rel='nofollow' href='"
                        + articlePermalink
                        + "'>"
                        + articleTitle
                        + "</a>")
                .replace("{comment}", StringUtils.substring(Jsoup.parse(cc).text(), 0, 28));
        timeline.put(Common.CONTENT, content);

        timelineMgmtService.addTimeline(timeline);
      }

      // 1. 'Commented' Notification
      final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
      final Set<String> atUserNames = userQueryService.getUserNames(commentContent);
      final boolean commenterIsArticleAuthor =
          articleAuthorId.equals(originalComment.optString(Comment.COMMENT_AUTHOR_ID));
      if (commenterIsArticleAuthor && atUserNames.isEmpty()) {
        return;
      }

      atUserNames.remove(commenterName); // Do not notify commenter itself

      if (!commenterIsArticleAuthor) {
        final JSONObject requestJSONObject = new JSONObject();
        requestJSONObject.put(Notification.NOTIFICATION_USER_ID, articleAuthorId);
        requestJSONObject.put(
            Notification.NOTIFICATION_DATA_ID, originalComment.optString(Keys.OBJECT_ID));

        notificationMgmtService.addCommentedNotification(requestJSONObject);
      }

      final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);
      final Set<String> articleContentAtUserNames = userQueryService.getUserNames(articleContent);

      // 2. 'At' Notification
      for (final String userName : atUserNames) {
        if (isDiscussion && !articleContentAtUserNames.contains(userName)) {
          continue;
        }

        final JSONObject user = userQueryService.getUserByName(userName);

        if (null == user) {
          LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName);

          continue;
        }

        if (user.optString(Keys.OBJECT_ID).equals(articleAuthorId)) {
          continue; // Has added in step 1
        }

        final JSONObject requestJSONObject = new JSONObject();
        requestJSONObject.put(Notification.NOTIFICATION_USER_ID, user.optString(Keys.OBJECT_ID));
        requestJSONObject.put(
            Notification.NOTIFICATION_DATA_ID, originalComment.optString(Keys.OBJECT_ID));

        notificationMgmtService.addAtNotification(requestJSONObject);
      }
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, "Sends the comment notification failed", e);
    }
  }