use of org.b3log.symphony.service.UserQueryService in project symphony by b3log.
the class ChessGame method onMessage.
/**
* Called when a message received from the browser.
*
* @param message message
*/
@OnMessage
public void onMessage(final String message) throws JSONException {
JSONObject jsonObject = new JSONObject(message);
final String player = jsonObject.optString("player");
final String anti = getAntiPlayer(player);
JSONObject sendText = new JSONObject();
final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
switch(jsonObject.optInt("type")) {
case // 聊天
1:
LOGGER.debug(jsonObject.optString("message"));
final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
sendText.put("type", 1);
try {
sendText.put("player", userQueryService.getUser(player).optString(User.USER_NAME));
} catch (ServiceException e) {
LOGGER.error("service not avaliable");
}
sendText.put("message", jsonObject.optString("message"));
SESSIONS.get(anti).getAsyncRemote().sendText(sendText.toString());
break;
case // 落子
2:
ChessGame chessGame = chessPlaying.keySet().contains(player) ? chessPlaying.get(player) : chessPlaying.get(anti);
int x = jsonObject.optInt("x");
int y = jsonObject.optInt("y");
int size = jsonObject.optInt("size");
if (chessGame != null) {
if (chessGame.getChess()[x / size][y / size] != 0) {
return;
}
boolean flag = false;
if (player.equals(chessGame.getPlayer1())) {
if (chessGame.getStep() != 1) {
return;
} else {
sendText.put("color", "black");
chessGame.getChess()[x / size][y / size] = 1;
flag = chessGame.chessCheck(1);
chessGame.setStep(2);
}
} else {
if (chessGame.getStep() != 2) {
return;
} else {
sendText.put("color", "white");
chessGame.getChess()[x / size][y / size] = 2;
flag = chessGame.chessCheck(2);
chessGame.setStep(1);
}
}
sendText.put("type", 2);
sendText.put("player", player);
sendText.put("posX", x);
sendText.put("posY", y);
sendText.put("chess", chessGame.getChess());
sendText.put("step", chessGame.getStep());
// 总有一次能正确移除,分开写只是为了好看,没有逻辑原因
if (flag) {
sendText.put("result", "You Win");
chessPlaying.remove(player);
}
SESSIONS.get(player).getAsyncRemote().sendText(sendText.toString());
if (flag) {
sendText.put("result", "You Lose");
chessPlaying.remove(anti);
}
SESSIONS.get(anti).getAsyncRemote().sendText(sendText.toString());
if (flag) {
final ActivityMgmtService activityMgmtService = beanManager.getReference(ActivityMgmtService.class);
activityMgmtService.collectGobang(player, Pointtransfer.TRANSFER_SUM_C_ACTIVITY_GOBANG_START * 2);
SESSIONS.remove(player);
SESSIONS.remove(anti);
}
}
break;
case // 和棋
7:
if ("request".equals(jsonObject.optString("drawType"))) {
sendText.put("type", 7);
SESSIONS.get(anti).getAsyncRemote().sendText(sendText.toString());
} else if ("yes".equals(jsonObject.optString("drawType"))) {
sendText.put("type", 6);
sendText.put("message", "【系统】:双方和棋,积分返还,游戏结束");
chessPlaying.remove(player);
chessPlaying.remove(anti);
antiPlayer.remove(player);
antiPlayer.remove(anti);
final ActivityMgmtService activityMgmtService = beanManager.getReference(ActivityMgmtService.class);
activityMgmtService.collectGobang(player, Pointtransfer.TRANSFER_SUM_C_ACTIVITY_GOBANG_START);
activityMgmtService.collectGobang(anti, Pointtransfer.TRANSFER_SUM_C_ACTIVITY_GOBANG_START);
SESSIONS.get(player).getAsyncRemote().sendText(sendText.toString());
SESSIONS.get(anti).getAsyncRemote().sendText(sendText.toString());
SESSIONS.remove(player);
SESSIONS.remove(anti);
} else if ("no".equals(jsonObject.optString("drawType"))) {
sendText.put("type", 6);
sendText.put("message", "【系统】:对手拒绝和棋,请继续下棋");
SESSIONS.get(player).getAsyncRemote().sendText(sendText.toString());
}
break;
}
}
use of org.b3log.symphony.service.UserQueryService in project symphony by b3log.
the class Markdowns method toHTML.
/**
* Converts the specified markdown text to HTML.
*
* @param markdownText the specified markdown text
* @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
* 'markdownErrorLabel' if exception
*/
public static String toHTML(final String markdownText) {
if (Strings.isEmptyOrNull(markdownText)) {
return "";
}
final String cachedHTML = getHTML(markdownText);
if (null != cachedHTML) {
return cachedHTML;
}
final ExecutorService pool = Executors.newSingleThreadExecutor();
final long[] threadId = new long[1];
final Callable<String> call = () -> {
threadId[0] = Thread.currentThread().getId();
String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
if (MARKED_AVAILABLE) {
try {
html = toHtmlByMarked(markdownText);
if (!StringUtils.startsWith(html, "<p>")) {
html = "<p>" + html + "</p>";
}
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Failed to use [marked] for markdown [md=" + StringUtils.substring(markdownText, 0, 256) + "]: " + e.getMessage());
com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText);
html = RENDERER.render(document);
if (!StringUtils.startsWith(html, "<p>")) {
html = "<p>" + html + "</p>";
}
}
} else {
com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText);
html = RENDERER.render(document);
if (!StringUtils.startsWith(html, "<p>")) {
html = "<p>" + html + "</p>";
}
}
final Document doc = Jsoup.parse(html);
final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>();
doc.traverse(new NodeVisitor() {
@Override
public void head(final org.jsoup.nodes.Node node, int depth) {
if (node instanceof org.jsoup.nodes.TextNode) {
final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node;
final org.jsoup.nodes.Node parent = textNode.parent();
if (parent instanceof Element) {
final Element parentElem = (Element) parent;
if (!parentElem.tagName().equals("code")) {
String text = textNode.getWholeText();
boolean nextIsBr = false;
final org.jsoup.nodes.Node nextSibling = textNode.nextSibling();
if (nextSibling instanceof Element) {
nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName());
}
if (null != userQueryService) {
try {
final Set<String> userNames = userQueryService.getUserNames(text);
for (final String userName : userNames) {
text = text.replace('@' + userName + (nextIsBr ? "" : " "), "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a> ");
}
text = text.replace("@participants ", "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> ");
} finally {
JdbcRepository.dispose();
}
}
if (text.contains("@<a href=")) {
final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem, "");
final int index = textNode.siblingIndex();
parentElem.insertChildren(index, nodes);
toRemove.add(node);
} else {
textNode.text(Pangu.spacingText(text));
}
}
}
}
}
@Override
public void tail(org.jsoup.nodes.Node node, int depth) {
}
});
toRemove.forEach(node -> node.remove());
doc.select("pre>code").addClass("hljs");
doc.select("a").forEach(a -> {
String src = a.attr("href");
if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath())) {
try {
src = URLEncoder.encode(src, "UTF-8");
} catch (final Exception e) {
}
a.attr("href", Latkes.getServePath() + "/forward?goto=" + src);
a.attr("target", "_blank");
}
});
doc.outputSettings().prettyPrint(false);
String ret = doc.select("body").html();
ret = StringUtils.trim(ret);
// cache it
putHTML(markdownText, ret);
return ret;
};
Stopwatchs.start("Md to HTML");
try {
final Future<String> future = pool.submit(call);
return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (final TimeoutException e) {
LOGGER.log(Level.ERROR, "Markdown timeout [md=" + StringUtils.substring(markdownText, 0, 256) + "]");
Callstacks.printCallstack(Level.ERROR, new String[] { "org.b3log" }, null);
final Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (final Thread thread : threads) {
if (thread.getId() == threadId[0]) {
thread.stop();
break;
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Markdown failed [md=" + StringUtils.substring(markdownText, 0, 256) + "]", e);
} finally {
pool.shutdownNow();
Stopwatchs.end();
}
return LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
}
use of org.b3log.symphony.service.UserQueryService in project symphony by b3log.
the class SymphonyServletListener method resolveSkinDir.
/**
* Resolve skin (template) for the specified HTTP servlet request.
*
* @param request the specified HTTP servlet request
*/
private void resolveSkinDir(final HttpServletRequest request) {
Stopwatchs.start("Resolve skin");
request.setAttribute(Keys.TEMAPLTE_DIR_NAME, (Boolean) request.getAttribute(Common.IS_MOBILE) ? "mobile" : "classic");
try {
final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
final UserRepository userRepository = beanManager.getReference(UserRepository.class);
final OptionRepository optionRepository = beanManager.getReference(OptionRepository.class);
final JSONObject optionLang = optionRepository.get(Option.ID_C_MISC_LANGUAGE);
final String optionLangValue = optionLang.optString(Option.OPTION_VALUE);
if ("0".equals(optionLangValue)) {
Locales.setLocale(request.getLocale());
} else {
Locales.setLocale(Locales.getLocale(optionLangValue));
}
JSONObject user = userQueryService.getCurrentUser(request);
if (null == user) {
final Cookie[] cookies = request.getCookies();
if (null == cookies || 0 == cookies.length) {
return;
}
try {
for (final Cookie cookie : cookies) {
if (!Sessions.COOKIE_NAME.equals(cookie.getName())) {
continue;
}
final String value = Crypts.decryptByAES(cookie.getValue(), Symphonys.get("cookie.secret"));
if (StringUtils.isBlank(value)) {
break;
}
final JSONObject cookieJSONObject = new JSONObject(value);
final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
if (Strings.isEmptyOrNull(userId)) {
break;
}
user = userRepository.get(userId);
if (null == user) {
return;
} else {
break;
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Read cookie failed", e);
}
if (null == user) {
return;
}
}
request.setAttribute(Keys.TEMAPLTE_DIR_NAME, (Boolean) request.getAttribute(Common.IS_MOBILE) ? user.optString(UserExt.USER_MOBILE_SKIN) : user.optString(UserExt.USER_SKIN));
request.setAttribute(UserExt.USER_AVATAR_VIEW_MODE, user.optInt(UserExt.USER_AVATAR_VIEW_MODE));
request.setAttribute(User.USER, user);
final Locale locale = Locales.getLocale(user.optString(UserExt.USER_LANGUAGE));
Locales.setLocale(locale);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Resolves skin failed", e);
} finally {
Stopwatchs.end();
}
}
use of org.b3log.symphony.service.UserQueryService in project symphony by b3log.
the class ArticleChannel method notifyComment.
/**
* Notifies the specified comment message to browsers.
*
* @param message the specified message
*/
public static void notifyComment(final JSONObject message) {
message.put(Common.TYPE, Comment.COMMENT);
final LatkeBeanManager beanManager = LatkeBeanManagerImpl.getInstance();
final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
final ArticleRepository articleRepository = beanManager.getReference(ArticleRepository.class);
final RoleQueryService roleQueryService = beanManager.getReference(RoleQueryService.class);
final LangPropsService langPropsService = beanManager.getReference(LangPropsServiceImpl.class);
for (final Session session : SESSIONS) {
final String viewingArticleId = (String) Channels.getHttpParameter(session, Article.ARTICLE_T_ID);
if (Strings.isEmptyOrNull(viewingArticleId) || !viewingArticleId.equals(message.optString(Article.ARTICLE_T_ID))) {
continue;
}
final int articleType = Integer.valueOf(Channels.getHttpParameter(session, Article.ARTICLE_TYPE));
final JSONObject user = (JSONObject) Channels.getHttpSessionAttribute(session, User.USER);
final boolean isLoggedIn = null != user;
try {
if (Article.ARTICLE_TYPE_C_DISCUSSION == articleType) {
if (!isLoggedIn) {
continue;
}
final String userName = user.optString(User.USER_NAME);
final String userRole = user.optString(User.USER_ROLE);
final JSONObject article = articleRepository.get(viewingArticleId);
if (null == article) {
continue;
}
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final String userId = user.optString(Keys.OBJECT_ID);
if (!userId.equals(articleAuthorId)) {
final String articleContent = article.optString(Article.ARTICLE_CONTENT);
final Set<String> userNames = userQueryService.getUserNames(articleContent);
boolean invited = false;
for (final String inviteUserName : userNames) {
if (inviteUserName.equals(userName)) {
invited = true;
break;
}
}
if (Role.ROLE_ID_C_ADMIN.equals(userRole)) {
invited = true;
}
if (!invited) {
// next session
continue;
}
}
}
message.put(Comment.COMMENT_T_NICE, false);
message.put(Common.REWARED_COUNT, 0);
message.put(Comment.COMMENT_T_VOTE, -1);
message.put(Common.REWARDED, false);
message.put(Comment.COMMENT_REVISION_COUNT, 1);
final Map dataModel = new HashMap();
dataModel.put(Common.IS_LOGGED_IN, isLoggedIn);
dataModel.put(Common.CURRENT_USER, user);
dataModel.put(Common.CSRF_TOKEN, Channels.getHttpSessionAttribute(session, Common.CSRF_TOKEN));
Keys.fillServer(dataModel);
dataModel.put(Comment.COMMENT, message);
String templateDirName = Symphonys.get("skinDirName");
if (isLoggedIn) {
dataModel.putAll(langPropsService.getAll(Locales.getLocale(user.optString(UserExt.USER_LANGUAGE))));
final String userId = user.optString(Keys.OBJECT_ID);
final Map<String, JSONObject> permissions = roleQueryService.getUserPermissionsGrantMap(userId);
dataModel.put(Permission.PERMISSIONS, permissions);
templateDirName = user.optString(UserExt.USER_SKIN);
} else {
dataModel.putAll(langPropsService.getAll(Locales.getLocale()));
final Map<String, JSONObject> permissions = roleQueryService.getPermissionsGrantMap(Role.ROLE_ID_C_VISITOR);
dataModel.put(Permission.PERMISSIONS, permissions);
}
final Template template = SkinRenderer.getTemplate(templateDirName, "common/comment.ftl", false, user);
final StringWriter stringWriter = new StringWriter();
template.process(dataModel, stringWriter);
stringWriter.close();
message.put("cmtTpl", stringWriter.toString());
final String msgStr = message.toString();
if (session.isOpen()) {
session.getAsyncRemote().sendText(msgStr);
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Notify comment error", e);
} finally {
JdbcRepository.dispose();
}
}
}
Aggregations