Commit b6baf3ad authored by Liang Ding's avatar Liang Ding

Fixed #276

重构了获取评论人头像的代码
parent 8109d3b1
......@@ -19,6 +19,7 @@ Without this configuration present, some functionality in the IDE may be limited
<word>datastore</word>
<word>ftl</word>
<word>Gmail</word>
<word>Gravatar</word>
<word>http</word>
<word>json</word>
<word>Latke</word>
......
......@@ -16,17 +16,14 @@
package org.b3log.solo.api.symphony;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateFormatUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.event.Event;
import org.b3log.latke.event.EventManager;
import org.b3log.latke.logging.Level;
......@@ -38,12 +35,8 @@ import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.JSONRenderer;
import org.b3log.latke.urlfetch.HTTPHeader;
import org.b3log.latke.urlfetch.HTTPRequest;
import org.b3log.latke.urlfetch.HTTPResponse;
import org.b3log.latke.urlfetch.URLFetchService;
import org.b3log.latke.urlfetch.URLFetchServiceFactory;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Strings;
import org.b3log.solo.event.EventTypes;
......@@ -56,9 +49,9 @@ import org.b3log.solo.service.ArticleMgmtService;
import org.b3log.solo.service.CommentMgmtService;
import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.service.StatisticMgmtService;
import org.b3log.solo.util.Comments;
import org.b3log.solo.util.QueryResults;
import org.b3log.solo.util.TimeZones;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -66,7 +59,7 @@ import org.json.JSONObject;
* Comment receiver (from B3log Symphony).
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.6, Mar 18, 2013
* @version 1.0.0.7, Jul 10, 2013
* @since 0.5.5
*/
@RequestProcessor
......@@ -249,13 +242,13 @@ public class CommentReceiver {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
}
setCommentThumbnailURL(comment);
CommentMgmtService.setCommentThumbnailURL(comment);
ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL));
// Sets comment on article....
comment.put(Comment.COMMENT_ON_ID, articleId);
comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
final String commentSharpURL = getCommentSharpURLForArticle(article, commentId);
final String commentSharpURL = Comments.getCommentSharpURLForArticle(article, commentId);
comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
......@@ -296,83 +289,4 @@ public class CommentReceiver {
jsonObject.put(Keys.MSG, e.getMessage());
}
}
/**
* Gets comment sharp URL with the specified article and comment id.
*
* @param article the specified article
* @param commentId the specified comment id
* @return comment sharp URL
* @throws JSONException json exception
*/
private static String getCommentSharpURLForArticle(final JSONObject article,
final String commentId)
throws JSONException {
final String articleLink = article.getString(Article.ARTICLE_PERMALINK);
return articleLink + "#" + commentId;
}
/**
* Sets commenter thumbnail URL for the specified comment.
*
* @param comment the specified comment
* @throws Exception exception
*/
private static void setCommentThumbnailURL(final JSONObject comment)
throws Exception {
final String commentEmail = comment.getString(Comment.COMMENT_EMAIL);
final String id = commentEmail.split("@")[0];
final String domain = commentEmail.split("@")[1];
String thumbnailURL = null;
// Try to set thumbnail URL using Gravatar service
final String hashedEmail = MD5.hash(commentEmail.toLowerCase());
final int size = 60;
final URL gravatarURL = new URL(
"http://secure.gravatar.com/avatar/" + hashedEmail + "?s=" + size + "&d=" + Latkes.getServePath()
+ "/images/default-user-thumbnail.png");
try {
final HTTPRequest request = new HTTPRequest();
request.setURL(gravatarURL);
final HTTPResponse response = urlFetchService.fetch(request);
final int statusCode = response.getResponseCode();
if (HttpServletResponse.SC_OK == statusCode) {
final List<HTTPHeader> headers = response.getHeaders();
boolean defaultFileLengthMatched = false;
for (final HTTPHeader httpHeader : headers) {
if ("Content-Length".equalsIgnoreCase(httpHeader.getName())) {
if (httpHeader.getValue().equals("2147")) {
defaultFileLengthMatched = true;
}
}
}
if (!defaultFileLengthMatched) {
thumbnailURL = "http://secure.gravatar.com/avatar/" + hashedEmail + "?s=" + size + "&d=" + Latkes.getServePath()
+ "/images/default-user-thumbnail.png";
comment.put(Comment.COMMENT_THUMBNAIL_URL, thumbnailURL);
LOGGER.log(Level.TRACE, "Comment thumbnail[URL={0}]", thumbnailURL);
return;
}
} else {
LOGGER.log(Level.WARN, "Can not fetch thumbnail from Gravatar[commentEmail={0}, statusCode={1}]",
new Object[] {commentEmail, statusCode});
}
} catch (final IOException e) {
LOGGER.warn(e.getMessage());
LOGGER.log(Level.WARN, "Can not fetch thumbnail from Gravatar[commentEmail={0}]", commentEmail);
}
if (null == thumbnailURL) {
LOGGER.log(Level.WARN, "Not supported yet for comment thumbnail for email[{0}]", commentEmail);
thumbnailURL = "/images/" + DEFAULT_USER_THUMBNAIL;
comment.put(Comment.COMMENT_THUMBNAIL_URL, thumbnailURL);
}
}
}
......@@ -15,6 +15,8 @@
*/
package org.b3log.solo.model;
import org.b3log.solo.util.Thumbnails;
/**
* This class defines all common model relevant keys.
......@@ -311,6 +313,11 @@ public final class Common {
*/
public static final String ARTICLES_VIEW_PWD = "articlesViewPwd";
/**
* Key of Gravatar.
*/
public static final String GRAVATAR = "gravatar";
/**
* Private default constructor.
*/
......
......@@ -45,7 +45,6 @@ import org.b3log.latke.servlet.renderer.TextHTMLRenderer;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.Dates;
import org.b3log.latke.util.Locales;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Stopwatchs;
......@@ -57,6 +56,7 @@ import org.b3log.solo.processor.renderer.FrontRenderer;
import org.b3log.solo.processor.util.Filler;
import org.b3log.solo.service.*;
import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Thumbnails;
import org.b3log.solo.util.comparator.Comparators;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -1191,8 +1191,7 @@ public class ArticleProcessor {
dataModel.put(Keys.OBJECT_ID, authorId);
dataModel.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME));
final String thumbnailURL = "http://secure.gravatar.com/avatar/" + MD5.hash(author.optString(User.USER_EMAIL)) + "?s=60&d="
+ Latkes.getStaticServePath() + "/images/default-user-thumbnail.png";
final String thumbnailURL = Thumbnails.getGravatarURL(author.optString(User.USER_EMAIL), "60");
dataModel.put(Common.AUTHOR_THUMBNAIL_URL, thumbnailURL);
......
......@@ -53,7 +53,6 @@ import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.service.TagQueryService;
import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Tags;
import org.b3log.solo.util.comparator.Comparators;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -110,11 +109,6 @@ public class TagProcessor {
@Inject
private TagQueryService tagQueryService;
/**
* Tag utilities.
*/
private Tags tagUtils = Tags.getInstance();
/**
* Shows articles related with a tag with the specified context.
*
......@@ -304,7 +298,7 @@ public class TagProcessor {
final List<JSONObject> tags = tagQueryService.getTags();
tagUtils.removeForUnpublishedArticles(tags);
tagQueryService.removeForUnpublishedArticles(tags);
Collections.sort(tags, Comparators.TAG_REF_CNT_COMPARATOR);
dataModel.put(Tag.TAGS, tags);
......
......@@ -55,7 +55,7 @@ import org.b3log.solo.service.ArticleQueryService;
import org.b3log.solo.service.StatisticQueryService;
import org.b3log.solo.service.TagQueryService;
import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Tags;
import org.b3log.solo.util.Thumbnails;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -65,7 +65,7 @@ import org.json.JSONObject;
* Filler utilities.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.6.5, May 17, 2013
* @version 1.0.6.6, Jul 10, 2013
* @since 0.3.1
*/
@Service
......@@ -100,11 +100,6 @@ public class Filler {
@Inject
private TagRepository tagRepository;
/**
* Tag utilities.
*/
private Tags tagUtils = Tags.getInstance();
/**
* Link repository.
*/
......@@ -158,36 +153,6 @@ public class Filler {
@Inject
private FillTagArticles fillTagArticles;
/**
* default page.
*/
private static final int DEFAULT_PAGE = 0;
/**
* default page size.
*/
private static final int DEFAULT_PAGESIZE = 10;
/**
* march1.
*/
private static final int MARCH1 = 1;
/**
* march2.
*/
private static final int MARCH2 = 2;
/**
* march3.
*/
private static final int MARCH3 = 3;
/**
* march4.
*/
private static final int MARCH4 = 4;
/**
* Fills articles in index.ftl.
*
......@@ -323,7 +288,7 @@ public class Filler {
final List<JSONObject> tags = tagRepository.getMostUsedTags(mostUsedTagDisplayCnt);
tagUtils.removeForUnpublishedArticles(tags);
tagQueryService.removeForUnpublishedArticles(tags);
dataModel.put(Common.MOST_USED_TAGS, tags);
} catch (final JSONException e) {
......@@ -544,6 +509,8 @@ public class Filler {
dataModel.put(Keys.Server.STATIC_SERVER, Latkes.getStaticServer());
dataModel.put(Keys.Server.SERVER, Latkes.getServer());
dataModel.put(Common.GRAVATAR, Thumbnails.GRAVATAR);
// Activates plugins
try {
final ViewLoadEventData data = new ViewLoadEventData();
......
......@@ -38,7 +38,6 @@ import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.urlfetch.*;
import org.b3log.latke.util.Ids;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Strings;
import org.b3log.solo.SoloServletListener;
import org.b3log.solo.event.EventTypes;
......@@ -47,6 +46,7 @@ import org.b3log.solo.repository.ArticleRepository;
import org.b3log.solo.repository.CommentRepository;
import org.b3log.solo.repository.PageRepository;
import org.b3log.solo.util.Comments;
import org.b3log.solo.util.Thumbnails;
import org.b3log.solo.util.TimeZones;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -415,8 +415,8 @@ public class CommentMgmtService {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
} else {
LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]",
new String[] {originalCommentId, commentName, commentContent});
LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", originalCommentId,
commentName, commentContent);
}
}
setCommentThumbnailURL(comment);
......@@ -592,8 +592,7 @@ public class CommentMgmtService {
* @param commentId the given comment id
* @throws ServiceException service exception
*/
public void removePageComment(final String commentId)
throws ServiceException {
public void removePageComment(final String commentId) throws ServiceException {
final Transaction transaction = commentRepository.beginTransaction();
try {
......@@ -719,10 +718,7 @@ public class CommentMgmtService {
public static void setCommentThumbnailURL(final JSONObject comment) throws Exception {
final String commentEmail = comment.getString(Comment.COMMENT_EMAIL);
final String hashedEmail = MD5.hash(commentEmail.toLowerCase());
String thumbnailURL = "http://secure.gravatar.com/avatar/" + hashedEmail + "?s=60&d=" + Latkes.getStaticServePath()
+ "/images/default-user-thumbnail.png";
String thumbnailURL = Thumbnails.getGravatarURL(commentEmail.toLowerCase(), "60");
final URL gravatarURL = new URL(thumbnailURL);
int statusCode = HttpServletResponse.SC_OK;
......
......@@ -50,6 +50,7 @@ import org.b3log.solo.model.Preference.Default;
import org.b3log.solo.repository.*;
import org.b3log.solo.util.Comments;
import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Thumbnails;
import org.b3log.solo.util.TimeZones;
import org.json.JSONArray;
import org.json.JSONException;
......@@ -295,7 +296,7 @@ public class InitService {
comment.put(Comment.COMMENT_CONTENT, StringEscapeUtils.escapeHtml(langPropsService.get("helloWorld.comment.content")));
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
comment.put(Comment.COMMENT_THUMBNAIL_URL, "http://secure.gravatar.com/avatar/59a5e8209c780307dbe9c9ba728073f5??s=60&r=G");
comment.put(Comment.COMMENT_THUMBNAIL_URL, Thumbnails.GRAVATAR + "59a5e8209c780307dbe9c9ba728073f5??s=60&r=G");
comment.put(Comment.COMMENT_DATE, date);
comment.put(Comment.COMMENT_ON_ID, articleId);
comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
......
......@@ -16,6 +16,7 @@
package org.b3log.solo.service;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import org.b3log.latke.Keys;
......@@ -29,6 +30,7 @@ import org.b3log.latke.util.CollectionUtils;
import org.b3log.solo.model.Tag;
import org.b3log.solo.repository.TagRepository;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -134,6 +136,25 @@ public class TagQueryService {
}
}
/**
* Removes tags of unpublished articles from the specified tags.
*
* @param tags the specified tags
* @throws JSONException json exception
* @throws RepositoryException repository exception
*/
public void removeForUnpublishedArticles(final List<JSONObject> tags) throws JSONException, RepositoryException {
final Iterator<JSONObject> iterator = tags.iterator();
while (iterator.hasNext()) {
final JSONObject tag = iterator.next();
if (0 == tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT)) {
iterator.remove();
}
}
}
/**
* Sets the tag repository with the specified tag repository.
*
......
......@@ -16,72 +16,42 @@
package org.b3log.solo.util;
import java.util.Iterator;
import java.util.List;
import org.b3log.solo.model.Tag;
import org.b3log.latke.repository.RepositoryException;
import org.json.JSONException;
import org.json.JSONObject;
import org.b3log.latke.Latkes;
import org.b3log.latke.util.MD5;
/**
* Tag utilities.
* Thumbnail utilities.
*
* <p>
* By using <a href="http://gravatar.com">Gravatar</a> for user thumbnail.
* </p>
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.6, Mar 8, 2011
* @since 0.3.1
* @version 1.0.0.0, Jul 10, 2013
* @since 0.6.1
*/
public final class Tags {
public final class Thumbnails {
/**
* Removes tags of unpublished articles from the specified tags.
*
* @param tags the specified tags
* @throws JSONException json exception
* @throws RepositoryException repository exception
* Gravatar address.
*/
public static void removeForUnpublishedArticles(final List<JSONObject> tags) throws JSONException, RepositoryException {
final Iterator<JSONObject> iterator = tags.iterator();
while (iterator.hasNext()) {
final JSONObject tag = iterator.next();
if (0 == tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT)) {
iterator.remove();
}
}
}
public static final String GRAVATAR = "http://secure.gravatar.com/avatar/";
/**
* Gets the {@link Tags} singleton.
* Gets the Gravatar URL for the specified email with the specified size.
*
* @return the singleton
* @param email the specified email
* @param size the specified size
* @return the Gravatar URL
*/
public static Tags getInstance() {
return SingletonHolder.SINGLETON;
public static String getGravatarURL(final String email, final String size) {
return Thumbnails.GRAVATAR + MD5.hash(email) + "?s=" + size + "&d=" + Latkes.getStaticServePath()
+ "/images/default-user-thumbnail.png";
}
/**
* Private default constructor.
* Private constructor.
*/
private Tags() {}
/**
* Singleton holder.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.0, Jan 12, 2011
*/
private static final class SingletonHolder {
/**
* Singleton.
*/
private static final Tags SINGLETON = new Tags();
/**
* Private default constructor.
*/
private SingletonHolder() {}
}
private Thumbnails() {}
}
/*
* Copyright (c) 2009, 2010, 2011, 2012, 2013, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Util={error:function(){$("#tipMsg").text("Error: "+arguments[0]+" File: "+arguments[1]+"\nLine: "+arguments[2]+" please report this issue on https://github.com/b3log/b3log-solo/issues/new");$("#loadMsg").text("")},killIE:function(){if($.browser.msie){if($.browser.version==="6.0"||$.browser.version==="7.0"){window.location=latkeConfig.servePath+"/kill-browser.html";return}if(window.external&&window.external.twGetRunPath){var path=external.twGetRunPath();if(path&&path.toLowerCase().indexOf("360se")>-1&&window.location.href.indexOf("admin-index")>-1){window.location=latkeConfig.servePath+"/kill-browser.html";return}}}},replaceEmString:function(str){var commentSplited=str.split("[em");if(commentSplited.length===1){return str}str=commentSplited[0];for(var j=1;j<commentSplited.length;j++){var key=commentSplited[j].substr(0,2);str+="<img src='"+latkeConfig.staticServePath+"/skins/"+Label.skinDirName+"/images/emotions/em"+key+".png' alt='"+Label["em"+key+"Label"]+"' title='"+Label["em"+key+"Label"]+"'/>"+commentSplited[j].substr(3)}return str},proessURL:function(url){if(!/^\w+:\/\//.test(url)){url="http://"+url}return url},switchMobile:function(skin){Cookie.createCookie("btouch_switch_toggle",skin,365);setTimeout(function(){location.reload()},1250)},setTopBar:function(){var $top=$("#top");if($top.length===1){var $showTop=$("#showTop");$showTop.click(function(){$top.slideDown();$showTop.hide()});$("#hideTop").click(function(){$top.slideUp();$showTop.show()})}},goTop:function(){var acceleration=acceleration||0.1;var y=$(window).scrollTop();var speed=1+acceleration;window.scrollTo(0,Math.floor(y/speed));if(y>0){var invokeFunction="Util.goTop("+acceleration+")";window.setTimeout(invokeFunction,16)}},goBottom:function(bottom){if(!bottom){bottom=0}window.scrollTo(0,$("body").height()-$(window).height()-bottom)},init:function(){Util.killIE();Util.setTopBar()},clearCache:function(all){var data="";if(all==="all"){data='{"all": "all", "URI": ""}'}else{data='{"all": "all", "URI": "'+window.location.pathname+'"}'}$.ajax({type:"POST",url:latkeConfig.servePath+"/clear-cache.do",cache:false,contentType:"application/json",data:data,success:function(result){window.location.reload()}})},replaceSideEm:function(comments){for(var i=0;i<comments.length;i++){var $comment=$(comments[i]);$comment.html(Util.replaceEmString($comment.html()))}},buildTags:function(id){id=id||"tags";var classes=["tags1","tags2","tags3","tags4","tags5"],bList=$("#"+id+" b").get();var max=parseInt($("#"+id+" b").last().text());var distance=Math.ceil(max/classes.length);for(var i=0;i<bList.length;i++){var num=parseInt(bList[i].innerHTML);for(var j=0;j<classes.length;j++){if(num>j*distance&&num<=(j+1)*distance){bList[i].parentNode.className=classes[j];break}}}$("#"+id).html($("#"+id+" li").get().sort(function(a,b){var valA=$(a).find("span").text().toLowerCase();var valB=$(b).find("span").text().toLowerCase();return valA.localeCompare(valB)}))},toDate:function(time,format){var dateTime=new Date(time);var o={"M+":dateTime.getMonth()+1,"d+":dateTime.getDate(),"H+":dateTime.getHours(),"m+":dateTime.getMinutes(),"s+":dateTime.getSeconds(),"q+":Math.floor((dateTime.getMonth()+3)/3),S:dateTime.getMilliseconds()};if(/(y+)/.test(format)){format=format.replace(RegExp.$1,(dateTime.getFullYear()+"").substr(4-RegExp.$1.length))}for(var k in o){if(new RegExp("("+k+")").test(format)){format=format.replace(RegExp.$1,RegExp.$1.length==1?o[k]:("00"+o[k]).substr((""+o[k]).length))}}return format}};if(!Cookie){var Cookie={readCookie:function(name){var nameEQ=name+"=";var ca=document.cookie.split(";");for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==" "){c=c.substring(1,c.length)}if(c.indexOf(nameEQ)==0){return decodeURIComponent(c.substring(nameEQ.length,c.length))}}return""},eraseCookie:function(name){this.createCookie(name,"",-1)},createCookie:function(name,value,days){var expires="";if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));expires="; expires="+date.toGMTString()}document.cookie=name+"="+encodeURIComponent(value)+expires+"; path=/"}}};
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment