From 2f682b5e3cfc3fc5f961b60129be7bc90e0d6a03 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 28 Dec 2016 22:38:21 +0300 Subject: juick-www: now on spring-webmvc --- .../java/com/juick/www/controllers/Discover.java | 138 ++++++ .../com/juick/www/controllers/FacebookLogin.java | 153 +++++++ .../main/java/com/juick/www/controllers/Help.java | 74 ++++ .../main/java/com/juick/www/controllers/Home.java | 232 ++++++++++ .../main/java/com/juick/www/controllers/Login.java | 258 ++++++++++++ .../java/com/juick/www/controllers/NewMessage.java | 468 +++++++++++++++++++++ .../main/java/com/juick/www/controllers/PM.java | 163 +++++++ .../com/juick/www/controllers/PageTemplates.java | 381 +++++++++++++++++ .../main/java/com/juick/www/controllers/RSS.java | 66 +++ .../java/com/juick/www/controllers/Settings.java | 287 +++++++++++++ .../java/com/juick/www/controllers/SignUp.java | 170 ++++++++ .../com/juick/www/controllers/TwitterAuth.java | 103 +++++ .../main/java/com/juick/www/controllers/User.java | 368 ++++++++++++++++ .../java/com/juick/www/controllers/UserThread.java | 374 ++++++++++++++++ .../com/juick/www/controllers/VKontakteLogin.java | 130 ++++++ .../java/com/juick/www/controllers/XMPPPost.java | 84 ++++ 16 files changed, 3449 insertions(+) create mode 100644 juick-www/src/main/java/com/juick/www/controllers/Discover.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/FacebookLogin.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/Help.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/Home.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/Login.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/NewMessage.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/PM.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/PageTemplates.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/RSS.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/Settings.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/SignUp.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/TwitterAuth.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/User.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/UserThread.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/VKontakteLogin.java create mode 100644 juick-www/src/main/java/com/juick/www/controllers/XMPPPost.java (limited to 'juick-www/src/main/java/com/juick/www/controllers') diff --git a/juick-www/src/main/java/com/juick/www/controllers/Discover.java b/juick-www/src/main/java/com/juick/www/controllers/Discover.java new file mode 100644 index 00000000..e5d17501 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/Discover.java @@ -0,0 +1,138 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.service.AdsService; +import com.juick.service.MessagesService; +import com.juick.service.TagService; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.List; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class Discover { + @Inject + WebApp webApp; + @Inject + MessagesService messagesService; + @Inject + TagService tagService; + @Inject + AdsService adsService; + @Inject + PageTemplates templates; + + @RequestMapping(value = "/tag/{tagName}", method = RequestMethod.GET) + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + + String paramTagStr = URLDecoder.decode(request.getRequestURI().substring(5), CharEncoding.UTF_8); + com.juick.Tag paramTag = tagService.getTag(paramTagStr, false); + if (paramTag == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } else if (paramTag.SynonymID > 0 && paramTag.TID != paramTag.SynonymID) { + com.juick.Tag synTag = tagService.getTag(paramTag.SynonymID); + String url = "/tag/" + URLEncoder.encode(synTag.getName(), CharEncoding.UTF_8); + if (request.getQueryString() != null) { + url += "?" + request.getQueryString(); + } + Utils.sendPermanentRedirect(response, url); + return; + } else if (!paramTag.getName().equals(paramTagStr)) { + String url = "/tag/" + URLEncoder.encode(paramTag.getName(), CharEncoding.UTF_8); + if (request.getQueryString() != null) { + url += "?" + request.getQueryString(); + } + Utils.sendPermanentRedirect(response, url); + return; + } + + int paramBefore = 0; + String paramBeforeStr = request.getParameter("before"); + if (paramBeforeStr != null) { + try { + paramBefore = Integer.parseInt(paramBeforeStr); + } catch (NumberFormatException e) { + } + } + + int visitor_uid = visitor.getUid(); + + String title = "*" + StringEscapeUtils.escapeHtml4(paramTag.getName()); + List mids = messagesService.getTag(paramTag.TID, visitor_uid, paramBefore, (visitor_uid == 0) ? 40 : 20); + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String head = StringUtils.EMPTY; + if (tagService.getTagNoIndex(paramTag.TID)) { + head = ""; + } else if (paramBefore > 0 || mids.size() < 5) { + head = ""; + } + templates.pageHead(out, visitor, title, head); + templates.pageNavigation(out, visitor, null); + + out.println("
"); + + if (mids.size() > 0) { + int vuid = visitor.getUid(); + int ad_mid = adsService.getAdMid(vuid); + if (ad_mid > 0 && mids.indexOf(ad_mid) == -1) { + mids.add(0, ad_mid); + adsService.logAdMid(vuid, ad_mid); + } else { + ad_mid = 0; + } + + templates.printMessages(out, null, mids, visitor, visitor_uid == 0 ? 2 : 3, ad_mid); + } + + if (mids.size() >= 20) { + String nextpage = "/tag/" + URLEncoder.encode(paramTag.getName(), CharEncoding.UTF_8) + "?before=" + mids.get(mids.size() - 1); + out.println("

Читать дальше →

"); + } + + out.println("
"); + + templates.pageHomeColumn(out, visitor); + + templates.pageFooter(request, out, visitor, true); + + templates.pageEnd(out); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/FacebookLogin.java b/juick-www/src/main/java/com/juick/www/controllers/FacebookLogin.java new file mode 100644 index 00000000..cc11f99a --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/FacebookLogin.java @@ -0,0 +1,153 @@ +/* + * Juick + * Copyright (C) 2008-2013, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.juick.service.CrosspostService; +import com.juick.service.UserService; +import com.juick.www.Utils; +import com.juick.www.facebook.Graph; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.UUID; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class FacebookLogin { + + private static final Logger logger = LoggerFactory.getLogger(FacebookLogin.class); + + private final String FACEBOOK_APPID; + private final String FACEBOOK_SECRET; + private final String FACEBOOK_REDIRECT = "http://juick.com/_fblogin"; + private final ObjectMapper mapper; + + @Inject + CrosspostService crosspostService; + @Inject + UserService userService; + + @Inject + public FacebookLogin(Environment env) { + FACEBOOK_APPID = env.getProperty("facebook_appid"); + FACEBOOK_SECRET = env.getProperty("facebook_secret"); + + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); + } + + @RequestMapping(value = "/_fblogin", method = RequestMethod.GET) + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { + String fbstate; + + String code = request.getParameter("code"); + if (StringUtils.isBlank(code)) { + fbstate = UUID.randomUUID().toString(); + + Cookie c = new Cookie("fbstate", fbstate); + response.addCookie(c); + + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", "https://www.facebook.com/dialog/oauth?scope=publish_stream&client_id=" + FACEBOOK_APPID + "&redirect_uri=" + URLEncoder.encode(FACEBOOK_REDIRECT, CharEncoding.UTF_8) + "&state=" + fbstate); + return; + } + + fbstate = Utils.getCookie(request, "fbstate"); + if (fbstate == null || fbstate.isEmpty() || !fbstate.equals(request.getParameter("state"))) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } else { + Cookie c = new Cookie("fbstate", "-"); + c.setMaxAge(0); + response.addCookie(c); + } + + String token = Utils.fetchURL("https://graph.facebook.com/oauth/access_token?client_id=" + FACEBOOK_APPID + "&redirect_uri=" + URLEncoder.encode(FACEBOOK_REDIRECT, CharEncoding.UTF_8) + "&client_secret=" + FACEBOOK_SECRET + "&code=" + URLEncoder.encode(code, CharEncoding.UTF_8)); + if (token == null || token.isEmpty() || !token.startsWith("access_token=")) { + logger.error("FACEBOOK TOKEN ERROR: {}", token); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + token = token.substring(13); // access_token=... + int tokenamp = token.indexOf('&'); // &expires= + if (tokenamp > 0) { + token = token.substring(0, tokenamp); + } + + String graph = Utils.fetchURL("https://graph.facebook.com/me?access_token=" + token); + if (graph == null || graph.isEmpty()) { + logger.error("FACEBOOK GRAPH ERROR"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + + try { + Graph fb = mapper.readValue(graph, Graph.class); + + long fbID = NumberUtils.toLong(fb.getId(), 0); + if (fbID == 0 || StringUtils.isBlank(fb.getName()) || StringUtils.isBlank(fb.getLink())) { + throw new Exception(); + } + + int uid = crosspostService.getUIDbyFBID(fbID); + if (uid > 0) { + if (!crosspostService.updateFacebookUser(fbID, token, fb.getName(), fb.getLink())) { + throw new Exception(); + } + Cookie c = new Cookie("hash", userService.getHashByUID(uid)); + c.setMaxAge(50 * 24 * 60 * 60); + response.addCookie(c); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", "/"); + } else if (fb.getVerified()) { + String loginhash = UUID.randomUUID().toString(); + if (!crosspostService.createFacebookUser(fbID, loginhash, token, fb.getName(), fb.getLink())) { + throw new Exception(); + } + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", "/signup?type=fb&hash=" + loginhash); + } else { + throw new Exception(); + } + } catch (Exception e) { + logger.error("fb error", e); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/Help.java b/juick-www/src/main/java/com/juick/www/controllers/Help.java new file mode 100644 index 00000000..58949827 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/Help.java @@ -0,0 +1,74 @@ +package com.juick.www.controllers; + +import com.juick.server.util.HttpNotFoundException; +import com.juick.www.HelpService; +import com.juick.www.WebApp; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; + +/** + * Created by aalexeev on 11/21/16. + */ +@Controller +public class Help { + @Inject + private HelpService helpService; + @Inject + private WebApp webApp; + + @RequestMapping({"/help/", "/help", "/help/{langOrPage}", "/help/{lang}/{page}"}) + public String showHelp( + HttpServletRequest request, + HttpServletResponse response, + Locale locale, + @PathVariable("lang") Optional langParam, + @PathVariable("page") Optional pageParam, + @PathVariable("langOrPage") Optional langOrPageParam, + Model model) throws IOException, URISyntaxException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + String page = pageParam.orElse("index"); + String lang = langParam.orElse(locale.getLanguage()); + + String navigation = null; + + if (langOrPageParam.isPresent()) { + String langOrPage = langOrPageParam.get(); + + if (helpService.canBeLang(langOrPage)) { + navigation = helpService.getHelp("navigation", langOrPage); + if (navigation != null) + lang = langOrPage; + } + + if (navigation == null && helpService.canBePage(langOrPage)) + page = langOrPage; + } + + String content = helpService.getHelp(page, lang); + if (content == null && !Objects.equals("index", page)) + content = helpService.getHelp("index", lang); + + if (navigation == null) + navigation = helpService.getHelp("navigation", lang); + + if (content == null || navigation == null) + throw new HttpNotFoundException(); + + model.addAttribute("navigation", navigation); + model.addAttribute("content", content); + model.addAttribute("visitor", visitor); + + return "views/help"; + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/Home.java b/juick-www/src/main/java/com/juick/www/controllers/Home.java new file mode 100644 index 00000000..2f9dc903 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/Home.java @@ -0,0 +1,232 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.service.AdsService; +import com.juick.service.MessagesService; +import com.juick.service.UserService; +import com.juick.util.WebUtils; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URLEncoder; +import java.util.List; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class Home { + @Inject + UserService userService; + @Inject + MessagesService messagesService; + @Inject + AdsService adsService; + @Inject + PageTemplates templates; + @Inject + WebApp webApp; + + @RequestMapping(value = "/{anything}/**", method = RequestMethod.GET) + protected void parseAnyThing(HttpServletResponse response, @PathVariable String anything, + @RequestParam(required = false, defaultValue = "0") int before) throws IOException { + if (before == 0) { + boolean isPostNumber = WebUtils.isPostNumber(anything); + int messageId = isPostNumber ? + NumberUtils.toInt(anything) : 0; + + if (isPostNumber && anything.equals(Integer.toString(messageId))) { + if (messageId > 0) { + com.juick.User author = messagesService.getMessageAuthor(messageId); + + if (author != null) { + Utils.sendPermanentRedirect(response, "/" + author.getName() + "/" + anything); + return; + } + } + } + com.juick.User user = userService.getUserByName(anything); + if (user.getUid() > 0) { + Utils.sendPermanentRedirect(response, "/" + user.getName() + "/"); + return; + } + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + com.juick.User user = userService.getUserByName(anything); + if (user.getUid() > 0) { + Utils.sendPermanentRedirect(response, "/" + user.getName() + "/?before=" + before); + return; + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + String tag = request.getParameter("tag"); + if (tag != null) { + Utils.sendPermanentRedirect(response, "/tag/" + URLEncoder.encode(tag, CharEncoding.UTF_8)); + } + com.juick.User visitor = webApp.getVisitorUser(request, response); + int paramBefore = NumberUtils.toInt(request.getParameter("before"), 0); + + String paramSearch = request.getParameter("search"); + if (paramSearch != null && paramSearch.length() > 64) { + paramSearch = null; + } + + String title; + List mids; + + String paramShow = request.getParameter("show"); + if (paramSearch != null) { + title = "Поиск: " + StringEscapeUtils.escapeHtml4(paramSearch); + mids = messagesService.getSearch(Utils.encodeSphinx(paramSearch), paramBefore); + } else if (paramShow == null) { + if (visitor.getUid() > 0) { + title = "Популярные"; + mids = messagesService.getPopular(visitor.getUid(), paramBefore); + } else { + title = "Микроблоги Juick: популярные записи"; + mids = messagesService.getPopular(0, paramBefore); + } + + } else if (paramShow.equals("top")) { + Utils.sendPermanentRedirect(response, "/"); + return; + } else if (paramShow.equals("my") && visitor != null) { + title = "Моя лента"; + mids = messagesService.getMyFeed(visitor.getUid(), paramBefore); + } else if (paramShow.equals("private") && visitor != null) { + title = "Приватные"; + mids = messagesService.getPrivate(visitor.getUid(), paramBefore); + } else if (paramShow.equals("discuss") && visitor != null) { + title = "Обсуждения"; + mids = messagesService.getDiscussions(visitor.getUid(), paramBefore); + } else if (paramShow.equals("recommended") && visitor != null) { + title = "Рекомендации"; + mids = messagesService.getRecommended(visitor.getUid(), paramBefore); + } else if (paramShow.equals("photos")) { + title = "Фотографии"; + if (visitor != null) { + mids = messagesService.getPhotos(visitor.getUid(), paramBefore); + } else { + mids = messagesService.getPhotos(0, paramBefore); + } + } else if (paramShow.equals("all")) { + title = "Все сообщения"; + if (visitor != null) { + mids = messagesService.getAll(visitor.getUid(), paramBefore); + } else { + mids = messagesService.getAll(0, paramBefore); + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String head = StringUtils.EMPTY; + if (paramBefore > 0 || paramShow != null) { + head = ""; + } + templates.pageHead(out, visitor, title, head); + templates.pageNavigation(out, visitor, paramSearch); + + out.println("
"); + + if (paramShow == null && paramBefore == 0) { + out.println(""); + } + + if (visitor.getUid() > 0) { + out.println("
"); + out.println("
"); + out.println(" "); + out.println("
"); + out.println(" " + + "или загрузить
"); + out.println("
"); + out.println(" "); + out.println("
"); + out.println("
"); + out.println("
"); + } + + if (mids.size() > 0) { + int ad_mid = 0; + if (paramShow == null || paramShow.equals("top") || paramShow.equals("all")) { + int vuid = visitor.getUid(); + ad_mid = adsService.getAdMid(vuid); + if (ad_mid > 0 && mids.indexOf(ad_mid) == -1) { + mids.add(0, ad_mid); + adsService.logAdMid(vuid, ad_mid); + } else { + ad_mid = 0; + } + } + + templates.printMessages(out, null, mids, visitor, visitor.getUid() == 0 ? 2 : 3, ad_mid); + } + + if (mids.size() >= 20) { + String nextpage = "?before=" + mids.get(mids.size() - 1); + if (paramShow != null) { + nextpage += "&show=" + paramShow; + } + if (paramSearch != null) { + nextpage += "&search=" + URLEncoder.encode(paramSearch, CharEncoding.UTF_8); + } + + out.println("

Читать дальше →

"); + } + + if (paramShow == null && paramBefore == 0) { + out.println(""); + } + + out.println("
"); + + templates.pageHomeColumn(out, visitor, paramShow == null && paramBefore == 0 && paramSearch == null && visitor.getUid() == 0); + + templates.pageFooter(request, out, visitor, true); + templates.pageEnd(out); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/Login.java b/juick-www/src/main/java/com/juick/www/controllers/Login.java new file mode 100644 index 00000000..bce3e000 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/Login.java @@ -0,0 +1,258 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.service.UserService; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class Login { + @Inject + UserService userService; + @Inject + WebApp webApp; + + @RequestMapping(value = "/login", method = RequestMethod.GET) + protected void doGetLoginForm(HttpServletRequest request, HttpServletResponse response) throws IOException { + String hash = request.getQueryString(); + if (hash != null) { + if (hash.length() > 32) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + if (userService.getUIDbyHash(hash) > 0) { + Cookie c = new Cookie("hash", hash); + c.setMaxAge(365 * 24 * 60 * 60); + response.addCookie(c); + response.sendRedirect("/"); + } else { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } + } + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() > 0) { + Utils.sendTemporaryRedirect(response, "/"); + return; + } + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + out.println(""); + out.println(""); + out.println(""); + out.println("Juick"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + + out.println(""); + + out.println(""); + + out.println("
juick.com © 2008-2014   Контакты · Помощь
"); + + out.println("
"); + out.println(" Зарегистрироваться:"); + out.println(" "); + out.println(" "); + out.println("
XMPP"); + out.println("
Отправьте LOGIN на juick@juick.com
"); + out.println("
"); + out.println("
"); + out.println("
Уже зарегистрированы?"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + + out.println(""); + out.println(""); + } + } + + @RequestMapping(value = "/login", method = RequestMethod.POST) + protected void doPostLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { + String username = request.getParameter("username"); + String password = request.getParameter("password"); + if (username == null || password == null || username.length() > 32 || password.isEmpty()) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + int uid = userService.checkPassword(username, password); + if (uid > 0) { + String hash = userService.getHashByUID(uid); + Cookie c = new Cookie("hash", hash); + c.setMaxAge(365 * 24 * 60 * 60); + response.addCookie(c); + + String referer = request.getHeader("Referer"); + if (referer != null && referer.startsWith("http://juick.com/") && !referer.equals("http://juick.com/login")) { + response.sendRedirect(referer); + } else { + response.sendRedirect("/"); + } + } else { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } + } + + @RequestMapping(value = "/logout", method = RequestMethod.GET) + protected void doGetLogout(HttpServletRequest request, HttpServletResponse response) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() > 0) { + userService.logout(visitor.getUid()); + } + + Cookie c = new Cookie("hash", "-"); + c.setDomain(".juick.com"); + c.setMaxAge(0); + response.addCookie(c); + + Cookie c2 = new Cookie("hash", "-"); + c2.setMaxAge(0); + response.addCookie(c2); + + response.sendRedirect("/"); + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/NewMessage.java b/juick-www/src/main/java/com/juick/www/controllers/NewMessage.java new file mode 100644 index 00000000..dacd54a3 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/NewMessage.java @@ -0,0 +1,468 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.Tag; +import com.juick.server.helpers.TagStats; +import com.juick.server.util.HttpBadRequestException; +import com.juick.server.util.HttpUtils; +import com.juick.service.*; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import net.coobird.thumbnailator.Thumbnails; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; +import rocks.xmpp.addr.Jid; +import rocks.xmpp.core.stanza.model.Message; +import rocks.xmpp.extensions.nick.model.Nickname; +import rocks.xmpp.extensions.oob.model.x.OobX; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +/** + * @author Ugnich Anton + */ +@Controller +public class NewMessage { + + @Inject + Environment env; + @Inject + TagService tagService; + @Inject + MessagesService messagesService; + @Inject + UserService userService; + @Inject + SubscriptionService subscriptionService; + @Inject + CrosspostService crosspostService; + @Inject + WebApp webApp; + @Inject + PageTemplates templates; + + private static final Logger logger = LoggerFactory.getLogger(NewMessage.class); + + @RequestMapping(value = "/post", method = RequestMethod.GET) + protected void doGetNewMessage(HttpServletRequest request, HttpServletResponse response) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + Utils.sendTemporaryRedirect(response, "/login"); + return; + } + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + templates.pageHead(out, visitor, "Написать", "" + + "" + + "" + + ""); + templates.pageNavigation(out, visitor, null); + + out.println("
"); + out.println("
"); + out.println("

Место: Отменить

"); + out.println("

Фото: (JPG, PNG, до 10Мб)

"); + + String body = request.getParameter("body"); + if (body == null) { + body = StringUtils.EMPTY; + } else { + if (body.length() > 4096) { + body = body.substring(0, 4096); + } + body = StringEscapeUtils.escapeHtml4(body); + } + out.println("


"); + + out.println("" + "" + "

"); + out.println("
"); + out.println("
"); + out.println("

Теги:

"); + printUserTags(out, visitor); + out.println("
"); + + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); + } + } + + void printUserTags(PrintWriter out, com.juick.User visitor) { + List tags = tagService.getUserTagStats(visitor.getUid()); + + if (tags.isEmpty()) { + return; + } + + int min = tags.get(0).getUsageCount(); + int max = tags.get(0).getUsageCount(); + for (int i = 1; i < tags.size(); i++) { + int usagecnt = tags.get(i).getUsageCount(); + if (usagecnt < min) { + min = usagecnt; + } + if (usagecnt > max) { + max = usagecnt; + } + } + max -= min; + + out.print("

"); + for (int i = 0; i < tags.size(); i++) { + if (i > 0) { + out.print(" "); + } + String taglink = StringUtils.EMPTY; + try { + taglink = "" + StringEscapeUtils.escapeHtml4(tags.get(i).getTag().getName()) + ""; + } catch (UnsupportedEncodingException e) { + } + int usagecnt = tags.get(i).getUsageCount(); + if (usagecnt <= max / 5 + min) { + out.print("" + taglink + ""); + } else if (usagecnt <= max / 5 * 2 + min) { + out.print(taglink); + } else if (usagecnt <= max / 5 * 3 + min) { + out.print("" + taglink + ""); + } else if (usagecnt <= max / 5 * 4 + min) { + out.print("" + taglink + ""); + } else { + out.print("" + taglink + ""); + } + } + out.println("

"); + } + + @RequestMapping(value = "/post", method = RequestMethod.POST) + public void doPostMessage(HttpServletRequest request, HttpServletResponse response, + @RequestParam(required = false) String img, + @RequestParam(required = false) MultipartFile attach) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + String body = request.getParameter("body"); + if (body == null || body.length() < 1 || body.length() > 4096) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + body = body.replace("\r", StringUtils.EMPTY); + + List tags = webApp.parseTags(request.getParameter("tags")); + + String attachmentFName = HttpUtils.receiveMultiPartFile(attach, webApp.getTmpDir()); + + if (StringUtils.isBlank(attachmentFName) && img != null && img.length() > 10) { + try { + URL imgUrl = new URL(img); + attachmentFName = HttpUtils.downloadImage(imgUrl); + } catch (Exception e) { + logger.error("DOWNLOAD ERROR", e); + throw new HttpBadRequestException(); + } + } + + String attachmentType = StringUtils.isNotEmpty(attachmentFName) ? attachmentFName.substring(attachmentFName.length() - 3) : null; + int mid = messagesService.createMessage(visitor.getUid(), body, attachmentType, tags); + subscriptionService.subscribeMessage(mid, visitor.getUid()); + + Message xmsg = new Message(); + xmsg.setFrom(Jid.of("juick@juick.com")); + xmsg.setType(Message.Type.CHAT); + xmsg.setThread("juick-" + mid); + com.juick.Message jmsg = messagesService.getMessage(mid); + xmsg.addExtension(jmsg); + xmsg.addExtension(new Nickname("@" + jmsg.getUser().getName())); + + if (StringUtils.isNotEmpty(attachmentFName)) { + String fname = mid + "." + attachmentType; + String attachmentURL = "http://i.juick.com/photos-1024/" + fname; + + Path origName = Paths.get(webApp.getImgDir(), "p", fname); + Files.move(Paths.get(webApp.getTmpDir(), attachmentFName), origName); + Thumbnails.of(origName.toFile()).size(1024, 1024).outputQuality(0.9) + .toFile(Paths.get(webApp.getImgDir(), "photos-1024", fname).toFile()); + Thumbnails.of(origName.toFile()).size(512, 512).outputQuality(0.9) + .toFile(Paths.get(webApp.getImgDir(), "photos-512", fname).toFile()); + Thumbnails.of(origName.toFile()).size(160, 120).outputQuality(0.9) + .toFile(Paths.get(webApp.getImgDir(), "ps", fname).toFile()); + + body = attachmentURL + "\n" + body; + try { + xmsg.addExtension(new OobX(new URI(attachmentURL))); + } catch (URISyntaxException e) { + logger.warn("invalid uri: {} exception {}", attachmentURL, e); + } + } + if (webApp.getXmpp() != null) { + + xmsg.setBody("@" + jmsg.getUser().getName() + ":" + jmsg.getTagsString() + "\n" + body + "\n\n#" + mid + " http://juick.com/" + mid); + + xmsg.setTo(Jid.of("juick@s2s.juick.com")); + webApp.getXmpp().send(xmsg); + + xmsg.setTo(Jid.of("juick@ws.juick.com")); + webApp.getXmpp().send(xmsg); + + xmsg.setTo(Jid.of("juick@push.juick.com")); + webApp.getXmpp().send(xmsg); + + xmsg.setTo(Jid.of("twitter@crosspost.juick.com")); + webApp.getXmpp().send(xmsg); + xmsg.setTo(Jid.of("fb@crosspost.juick.com")); + webApp.getXmpp().send(xmsg); + + xmsg.setTo(Jid.of("jubo@nologin.ru")); + webApp.getXmpp().send(xmsg); + } else { + logger.warn("XMPP unavailable"); + } + + // + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + templates.pageHead(out, visitor, "Сообщение опубликовано", null); + templates.pageNavigation(out, visitor, null); + + String hashtags = StringUtils.EMPTY; + String tagscomma = StringUtils.EMPTY; + for (int i = 0; i < jmsg.getTags().size(); i++) { + if (i > 0) { + hashtags += " "; + tagscomma += ","; + } + hashtags += "#" + jmsg.getTags().get(i); + tagscomma += jmsg.getTags().get(i); + } + + String url = URLEncoder.encode("http://juick.com/" + mid, CharEncoding.UTF_8); + String sharetwi = hashtags + " " + body; + if (sharetwi.length() > 115) { + sharetwi = sharetwi.substring(0, 114) + "…"; + } + sharetwi += " http://juick.com/" + mid; + String sharelj = URLEncoder.encode(body + "\n", CharEncoding.UTF_8) + url; + + out.println("
"); + out.println("

Сообщение опубликовано

"); + out.println("

Поделитесь своим новым постом в социальных сетях:

"); + if (crosspostService.getTwitterTokens(visitor.getUid()).isPresent()) { + out.println("

Отправить в Twitter

"); + } + out.println("

Отправить в LiveJournal

"); + out.println("

Отправить в ВКонтакте

"); + if (crosspostService.getFacebookToken(visitor.getUid()).isPresent()) { + out.println("

Отправить в Facebook

"); + } + out.println("

Отправить в Google+

"); + out.println("

Ссылка на сообщение: http://juick.com/" + mid + "

"); + out.println("
"); + + templates.pageHomeColumn(out, visitor); + + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); + } + } + + @RequestMapping(value = "/comment", method = RequestMethod.POST) + public void doPostComment(HttpServletRequest request, HttpServletResponse response, + @RequestParam(required = false) String img, + @RequestParam(required = false) MultipartFile attach) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + int mid = NumberUtils.toInt(request.getParameter("mid"), 0); + if (mid == 0) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + com.juick.Message msg = messagesService.getMessage(mid); + if (msg == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + int rid = NumberUtils.toInt(request.getParameter("rid"), 0); + com.juick.Message reply = null; + if (rid > 0) { + reply = messagesService.getReply(mid, rid); + if (reply == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + } + + String body = request.getParameter("body"); + if (body == null || body.length() < 1 || body.length() > 4096) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + body = body.replace("\r", StringUtils.EMPTY); + + if ((msg.ReadOnly && msg.getUser().getUid() != visitor.getUid()) + || userService.isInBLAny(msg.getUser().getUid(), visitor.getUid()) + || (reply != null && userService.isInBLAny(reply.getUser().getUid(), visitor.getUid()))) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + + String attachmentFName = HttpUtils.receiveMultiPartFile(attach, webApp.getTmpDir()); + + if (StringUtils.isBlank(attachmentFName) && img != null && img.length() > 10) { + try { + URL imgUrl = new URL(img); + attachmentFName = HttpUtils.downloadImage(imgUrl); + } catch (Exception e) { + logger.error("DOWNLOAD ERROR", e); + throw new HttpBadRequestException(); + } + } + + String attachmentType = StringUtils.isNotEmpty(attachmentFName) ? attachmentFName.substring(attachmentFName.length() - 3) : null; + int ridnew = messagesService.createReply(mid, rid, visitor.getUid(), body, attachmentType); + subscriptionService.subscribeMessage(mid, visitor.getUid()); + + Message xmsg = new Message(); + xmsg.setFrom(Jid.of("juick@juick.com")); + xmsg.setType(Message.Type.CHAT); + xmsg.setThread("juick-" + mid); + + com.juick.Message jmsg = messagesService.getReply(mid, ridnew); + xmsg.addExtension(jmsg); + + String quote = reply != null ? reply.getText() : msg.getText(); + if (quote.length() >= 50) { + quote = quote.substring(0, 47) + "..."; + } + xmsg.addExtension(new Nickname("@" + jmsg.getUser().getName())); + + if (StringUtils.isNotEmpty(attachmentFName)) { + String fname = mid + "-" + ridnew + "." + attachmentType; + String attachmentURL = "http://i.juick.com/photos-1024/" + fname; + + Path origName = Paths.get(webApp.getImgDir(), "p", fname); + Files.move(Paths.get(webApp.getTmpDir(), attachmentFName), origName); + Thumbnails.of(origName.toFile()).size(1024, 1024).outputQuality(0.9) + .toFile(Paths.get(webApp.getImgDir(), "photos-1024", fname).toFile()); + Thumbnails.of(origName.toFile()).size(512, 512).outputQuality(0.9) + .toFile(Paths.get(webApp.getImgDir(), "photos-512", fname).toFile()); + Thumbnails.of(origName.toFile()).size(160, 120).outputQuality(0.9) + .toFile(Paths.get(webApp.getImgDir(), "ps", fname).toFile()); + + body = attachmentURL + "\n" + body; + try { + xmsg.addExtension(new OobX(new URI(attachmentURL))); + } catch (URISyntaxException e) { + logger.warn("invalid uri: {}, exception {}", attachmentURL, e); + } + } + + if (webApp.getXmpp() != null) { + + xmsg.setBody("Reply by @" + jmsg.getUser().getName() + ":\n>" + quote + "\n" + body + "\n\n#" + + mid + "/" + ridnew + " http://juick.com/" + mid + "#" + ridnew); + + xmsg.setTo(Jid.of("juick@s2s.juick.com")); + webApp.getXmpp().send(xmsg); + + xmsg.setTo(Jid.of("juick@ws.juick.com")); + webApp.getXmpp().send(xmsg); + + xmsg.setTo(Jid.of("juick@push.juick.com")); + webApp.getXmpp().send(xmsg); + } else { + logger.warn("XMPP unavailable"); + } + + Utils.sendTemporaryRedirect(response, "/" + msg.getUser().getName() + "/" + mid + "#" + ridnew); + } + + @RequestMapping(value = "/like", method = RequestMethod.POST) + public void doPostRecomm(HttpServletRequest request, HttpServletResponse response) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + int mid = NumberUtils.toInt(request.getParameter("mid"), 0); + if (mid == 0) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + com.juick.Message msg = messagesService.getMessage(mid); + if (msg == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + if (msg.getUser().getUid() == visitor.getUid()) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + + boolean res = messagesService.recommendMessage(mid, visitor.getUid()); + + if (res) { + if (webApp.getXmpp() != null) { + Message xmsg = new Message(); + xmsg.setFrom(Jid.of("juick@juick.com")); + xmsg.setTo(Jid.of("recomm@s2s.juick.com")); + com.juick.Message jmsg = new com.juick.Message(); + jmsg.setMid(mid); + jmsg.setUser(visitor); + xmsg.addExtension(jmsg); + webApp.getXmpp().send(xmsg); + } else { + logger.warn("XMPP unavailable"); + } + + Utils.replyJSON(request, response, "{\"status\":\"ok\"}"); + } else { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/PM.java b/juick-www/src/main/java/com/juick/www/controllers/PM.java new file mode 100644 index 00000000..56b688cf --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/PM.java @@ -0,0 +1,163 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.service.PMQueriesService; +import com.juick.service.TagService; +import com.juick.service.UserService; +import com.juick.util.MessageUtils; +import com.juick.util.WebUtils; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import rocks.xmpp.addr.Jid; +import rocks.xmpp.core.stanza.model.Message; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class PM { + private static final Logger logger = LoggerFactory.getLogger(PM.class); + + @Inject + PMQueriesService pmQueriesService; + @Inject + TagService tagService; + @Inject + UserService userService; + @Inject + WebApp webApp; + + @RequestMapping(value = "/pm/inbox", method = RequestMethod.GET) + protected String doGetInbox(HttpServletRequest request, HttpServletResponse response, ModelMap model) { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + Utils.sendTemporaryRedirect(response, "/login"); + } + String title = "PM: Inbox"; + List msgs = pmQueriesService.getLastPMInbox(visitor.getUid()); + msgs.forEach(m -> m.setText(MessageUtils.formatMessage(m.getText()))); + model.addAttribute("title", title); + model.addAttribute("visitor", visitor); + model.addAttribute("msgs", msgs); + model.addAttribute("tags", tagService.getPopularTags()); + return "views/pm_inbox"; + } + + @RequestMapping(value = "/pm/sent", method = RequestMethod.GET) + protected String doGetSent(HttpServletRequest request, HttpServletResponse response, ModelMap model) { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + Utils.sendTemporaryRedirect(response, "/login"); + } + String title = "PM: Sent"; + List msgs = pmQueriesService.getLastPMSent(visitor.getUid()); + + String uname = request.getParameter("uname"); + if (WebUtils.isNotUserName(uname)) { + uname = StringUtils.EMPTY; + } + + model.addAttribute("title", title); + model.addAttribute("visitor", visitor); + model.addAttribute("msgs", msgs); + model.addAttribute("tags", tagService.getPopularTags()); + model.addAttribute("uname", uname); + return "views/pm_sent"; + } + + @RequestMapping(value = "/pm/send", method = RequestMethod.POST) + public void doPostPM(HttpServletRequest request, HttpServletResponse response) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0 || visitor.isBanned()) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + String uname = request.getParameter("uname"); + if (uname.startsWith("@")) { + uname = uname.substring(1); + } + int uid = 0; + if (WebUtils.isUserName(uname)) { + uid = userService.getUIDbyName(uname); + } + + String body = request.getParameter("body"); + if (uid == 0 || body == null || body.length() < 1 || body.length() > 10240) { + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + if (userService.isInBLAny(uid, visitor.getUid())) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + + if (pmQueriesService.createPM(visitor.getUid(), uid, body)) { + if (webApp.getXmpp() != null) { + Message msg = new Message(); + msg.setFrom(Jid.of("juick@juick.com")); + msg.setTo(Jid.of(String.format("%d@push.juick.com", uid))); + com.juick.Message jmsg = new com.juick.Message(); + jmsg.setUser(visitor); + jmsg.setText(body); + msg.addExtension(jmsg); + webApp.getXmpp().send(msg); + + msg.setTo(Jid.of(String.format("%d@ws.juick.com", uid))); + webApp.getXmpp().send(msg); + + List jids = userService.getJIDsbyUID(uid); + for (String jid : jids) { + Message mm = new Message(); + mm.setTo(Jid.of(jid)); + mm.setType(Message.Type.CHAT); + if (pmQueriesService.havePMinRoster(visitor.getUid(), jid)) { + mm.setFrom(Jid.of(jmsg.getUser().getName(), "juick.com", "Juick")); + mm.setBody(body); + } else { + mm.setFrom(Jid.of("juick", "juick.com", "Juick")); + mm.setBody("Private message from @" + jmsg.getUser().getName() + ":\n" + body); + } + webApp.getXmpp().send(mm); + } + } else { + logger.warn("XMPP unavailable"); + } + + Utils.sendTemporaryRedirect(response, "/pm/sent"); + + } else { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/PageTemplates.java b/juick-www/src/main/java/com/juick/www/controllers/PageTemplates.java new file mode 100644 index 00000000..3152d5fc --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/PageTemplates.java @@ -0,0 +1,381 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.Message; +import com.juick.server.helpers.TagStats; +import com.juick.service.MessagesService; +import com.juick.service.TagService; +import com.juick.service.UserService; +import com.juick.util.MessageUtils; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.StringUtils; +import ru.sape.Sape; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author Ugnich Anton + */ +public class PageTemplates { + + private static final Logger logger = LoggerFactory.getLogger(PageTemplates.class); + + public Sape sape = null; + protected static final SimpleDateFormat sdfSQL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private static SimpleDateFormat sdfSimple = new SimpleDateFormat("d MMM"); + private static SimpleDateFormat sdfFull = new SimpleDateFormat("d MMM yyyy"); + private static String tagsHTML = null; + + @Inject + TagService tagService; + @Inject + MessagesService messagesService; + @Inject + UserService userService; + + public void pageHead(PrintWriter out, com.juick.User visitor, String title, String headers) { + out.println(""); + out.print(""); + out.print(""); + out.println(""); + out.print(""); + out.print(""); + if (headers != null) { + out.print(headers); + } + out.print("" + title + ""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.flush(); + if (visitor.getUid() > 0) { + out.println(""); + } else { + out.println(""); + } + } + + public void pageNavigation(PrintWriter out, com.juick.User visitor, String search) { + out.println("
"); + out.println(" "); + out.print(" "); + out.print("
"); + out.println("
"); + if (visitor.getUid() > 0) { + out.print(" "); + out.print(" "); + } else { + out.println("

Чтобы добавлять сообщения и комментарии, представьтесь.

"); + } + out.println("
"); + out.println("
"); + } + + public void pageHomeColumn(PrintWriter out, com.juick.User visitor) { + pageHomeColumn(out, visitor, false); + } + + public void pageHomeColumn(PrintWriter out, com.juick.User visitor, boolean showAdv) { + if (tagsHTML == null) { + tagsHTML = formatPopularTags(80); + } + + out.println(""); + } + + public String formatPopularTags(int cnt) { + List popularTags = tagService.getPopularTags().stream() + .map(t -> "" + StringEscapeUtils.escapeHtml4(t) + "").collect(Collectors.toList()); + return StringUtils.collectionToDelimitedString(popularTags, " "); + } + + public void pageFooter(HttpServletRequest request, PrintWriter out, com.juick.User visitor, boolean sapeon) { + out.println("
"); + out.println(" "); + out.print("
"); + out.print("Twitter"); + out.print("ВКонтакте"); + out.print("Facebook"); + out.println("
"); + out.print("
juick.com © 2008-2016"); + + String queryString = request.getQueryString(); + String requestURI = request.getRequestURI(); + if (sapeon && sape != null && (visitor.getUid() == 0 || visitor.getUid() == 1) && queryString == null) { + String links = sape.getPageLinks(requestURI, request.getCookies()).render(); + if (links != null && !links.isEmpty()) { + out.print("
Спонсоры: " + links); + } + } + + out.println("
"); + out.println("
"); + + out.println(""); + } + + public void pageEnd(PrintWriter out) { + out.println(""); + } + + public String formatTags(List tags) { + String ret = org.apache.commons.lang3.StringUtils.EMPTY; + for (TagStats tag : tags) { + String tagName = StringEscapeUtils.escapeHtml4(tag.getTag().getName()); + try { + ret += ""; + } catch (UnsupportedEncodingException e) { + } + } + + return ret; + } + + public String formatDate(int minutes, Date fulldate) { + if (minutes < 1) { + return "сейчас"; + } else if (minutes < 60) { + String unit; + int ld = minutes % 10; + if ((minutes < 10 || minutes > 20) && ld == 1) { + unit = "минуту"; + } else if ((minutes < 10 || minutes > 20) && ld > 1 && ld < 5) { + unit = "минуты"; + } else { + unit = "минут"; + } + return minutes + " " + unit + " назад"; + } else if (minutes < 1440) { + int hours = (minutes / 60); + String unit; + int ld = hours % 10; + if ((hours < 10 || hours > 20) && ld == 1) { + unit = "час"; + } else if ((hours < 10 || hours > 20) && ld > 1 && ld < 5) { + unit = "часа"; + } else { + unit = "часов"; + } + return hours + " " + unit + " назад"; + } else if (minutes < 20160) { + int days = (minutes / 1440); + String unit; + int ld = days % 10; + if ((days < 10 || days > 20) && ld == 1) { + unit = "день"; + } else if ((days < 10 || days > 20) && ld > 1 && ld < 5) { + unit = "дня"; + } else { + unit = "дней"; + } + return days + " " + unit + " назад"; + } else { + String ret = sdfFull.format(fulldate); + synchronized (sdfSQL) { + try { + Calendar c = Calendar.getInstance(); + int curyear = c.get(Calendar.YEAR); + c.setTime(fulldate); + if (c.get(Calendar.YEAR) == curyear) { + ret = sdfSimple.format(fulldate); + } else { + ret = sdfFull.format(fulldate); + } + } catch (Exception e) { + logger.error("PARSE EXCEPTION: {}, exception {}", fulldate, e); + } + } + return ret; + } + } + + public String formatJSLocalTime(Date ts) { + return ""; + } + + public String formatReplies(int replies) { + int ld = replies % 10; + int lh = replies % 100; + if ((lh < 10 || lh > 20) && ld == 1) { + return replies + " ответ"; + } else if ((lh < 10 || lh > 20) && ld > 1 && ld < 5) { + return replies + " ответа"; + } else { + return replies + " ответов"; + } + } + + public void printMessages(PrintWriter out, com.juick.User user, List mids, com.juick.User visitor, int YandexID, int ad_mid) { + List msgs = messagesService.getMessages(mids); + + for (int i = 0; i < msgs.size(); i++) { + com.juick.Message msg = msgs.get(i); + if (msg.getMid() == ad_mid) { + msgs.remove(i); + msgs.add(0, msg); + break; + } + } + + List blUIDs = new ArrayList(20); + if (visitor != null) { + for (Message msg : msgs) { + blUIDs.add(msg.getUser().getUid()); + } + blUIDs = userService.checkBL(visitor.getUid(), blUIDs); + } + + for (Message msg : msgs) { + + List tags = tagService.getMessageTags(msg.getMid()); + String tagsStr = formatTags(tags); + if (msg.ReadOnly) { + tagsStr += "readonly"; + } + if (msg.getPrivacy() < 0) { + tagsStr += "friends"; + } + if (msg.getMid() == ad_mid) { + tagsStr += "реклама"; + } + + String txt; + if (msg.getTags().stream().anyMatch(t -> t.getName().equals("code"))) { + txt = MessageUtils.formatMessageCode(msg.getText()); + } else { + txt = MessageUtils.formatMessage(msg.getText()); + } + + out.println("
"); + out.println("
"); + out.println(" @" + msg.getUser().getName() + ":"); + out.println("
\""
"); + out.println(" "); + + out.println("
" + tagsStr + "
"); + out.println("
"); + + if (msg.getAttachmentType() != null) { + String fname = msg.getMid() + "." + msg.getAttachmentType(); + out.println("

\"\"/

"); + } + out.println("

" + txt + "

"); + if (msg.getAttachmentType() != null) { + out.println("
"); + } + out.print(" "); + + out.print(" "); + out.print("
"); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/RSS.java b/juick-www/src/main/java/com/juick/www/controllers/RSS.java new file mode 100644 index 00000000..79fd8e67 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/RSS.java @@ -0,0 +1,66 @@ +/* + * Juick + * Copyright (C) 2008-2013, ugnich + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.Message; +import com.juick.server.util.HttpNotFoundException; +import com.juick.service.MessagesService; +import com.juick.service.UserService; +import com.juick.util.DateFormattersHolder; +import com.juick.util.MessageUtils; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * + * @author ugnich + */ +@Controller +public class RSS { + @Inject + UserService userService; + @Inject + MessagesService messagesService; + + @RequestMapping(value = "/rss/{uname}", method = RequestMethod.GET) + protected String doGet(JdbcTemplate sql, HttpServletResponse response, + @PathVariable String uname, ModelMap model) { + int uid = userService.getUIDbyName(uname); + List mids = messagesService.getUserBlog(uid, 0, 0); + if (mids.isEmpty()) { + throw new HttpNotFoundException(); + } + + List msgs = messagesService.getMessages(mids); + + msgs.forEach(m -> MessageUtils.formatMessage(m.getText())); + + model.addAttribute("user", msgs.stream().findFirst().get().getUser()); + model.addAttribute("msgs", msgs); + model.addAttribute("sdfRSS", DateFormattersHolder.getRssFormatterInstance()); + return "webapp/WEB-INF/layouts/rss"; + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/Settings.java b/juick-www/src/main/java/com/juick/www/controllers/Settings.java new file mode 100644 index 00000000..63cf99e6 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/Settings.java @@ -0,0 +1,287 @@ +/* + * Juick + * Copyright (C) 2008-2013, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.server.helpers.NotifyOpts; +import com.juick.server.helpers.UserInfo; +import com.juick.server.util.HttpBadRequestException; +import com.juick.server.util.HttpUtils; +import com.juick.service.*; +import com.juick.util.UserUtils; +import com.juick.www.WebApp; +import net.coobird.thumbnailator.Thumbnails; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import javax.inject.Inject; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class Settings { + private static final Logger logger = LoggerFactory.getLogger(Settings.class); + + @Inject + WebApp webApp; + @Inject + TagService tagService; + @Inject + UserService userService; + @Inject + CrosspostService crosspostService; + @Inject + SubscriptionService subscriptionService; + @Inject + EmailService emailService; + @Inject + TelegramService telegramService; + + @RequestMapping(value = "/settings", method = RequestMethod.GET) + protected String doGet(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + response.sendRedirect("/login"); + } + List pages = Arrays.asList("main", "password", "about", "auth-email", "privacy"); + String page = request.getParameter("page"); + if (StringUtils.isEmpty(page) || !pages.contains(page)) { + page = "main"; + } + + model.addAttribute("title", "Настройки"); + model.addAttribute("visitor", visitor); + model.addAttribute("tags", tagService.getPopularTags()); + model.addAttribute("auths", userService.getAuthCodes(visitor)); + model.addAttribute("eopts", userService.getEmailOpts(visitor)); + model.addAttribute("ehash", userService.getEmailHash(visitor)); + model.addAttribute("emails", userService.getEmails(visitor)); + model.addAttribute("jids", userService.getAllJIDs(visitor)); + List hours = IntStream.rangeClosed(0, 23).boxed() + .map(i -> StringUtils.leftPad(String.format("%d", i), 2, "0")).collect(Collectors.toList()); + model.addAttribute("hours", hours); + model.addAttribute("fbstatus", crosspostService.getFbCrossPostStatus(visitor.getUid()).isCrosspostEnabled()); + model.addAttribute("twitter_name", crosspostService.getTwitterName(visitor.getUid())); + model.addAttribute("telegram_name", crosspostService.getTelegramName(visitor.getUid())); + model.addAttribute("notify_options", subscriptionService.getNotifyOptions(visitor)); + model.addAttribute("userinfo", userService.getUserInfo(visitor)); + if (page.equals("auth-email")) { + if (emailService.verifyAddressByCode(visitor.getUid(), request.getParameter("code"))) { + ; + model.addAttribute("result", "OK!"); + } else { + model.addAttribute("result", "Sorry, code unknown."); + } + } + return String.format("views/settings_%s", page); + } + + @RequestMapping(value = "/settings", method = RequestMethod.POST) + protected String doPost(HttpServletRequest request, HttpServletResponse response, + @RequestParam(required = false) MultipartFile avatar, + ModelMap model) + throws IOException, ServletException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0) { + throw new HttpBadRequestException(); + } + List pages = Arrays.asList("main", "password", "about", "email", "email-add", "email-del", + "email-subscr", "auth-email", "privacy", "jid-del", "twitter-del", "telegram-del", "facebook-disable", + "facebook-enable", "vk-del"); + String page = request.getParameter("page"); + if (StringUtils.isEmpty(page) || !pages.contains(page)) { + throw new HttpBadRequestException(); + } + String result = StringUtils.EMPTY; + switch (page) { + case "password": + if (userService.updatePassword(visitor, request.getParameter("password"))) { + result = "

Password has been changed.

"; + String hash = userService.getHashByUID(visitor.getUid()); + Cookie c = new Cookie("hash", hash); + c.setMaxAge(365 * 24 * 60 * 60); + response.addCookie(c); + } + break; + case "main": + NotifyOpts opts = new NotifyOpts(); + opts.setRepliesEnabled(StringUtils.isNotEmpty(request.getParameter("jnotify"))); + opts.setSubscriptionsEnabled(StringUtils.isNotEmpty(request.getParameter("subscr_notify"))); + opts.setRecommendationsEnabled(StringUtils.isNotEmpty(request.getParameter("recomm"))); + if (subscriptionService.setNotifyOptions(visitor, opts)) { + result = "

Notification options has been updated

"; + } + break; + case "about": + UserInfo info = new UserInfo(); + info.setFullName(request.getParameter("fullname")); + info.setCountry(request.getParameter("country")); + info.setUrl(request.getParameter("url")); + info.setDescription(request.getParameter("descr")); + String avatarTmpPath = HttpUtils.receiveMultiPartFile(avatar, webApp.getTmpDir()); + if (StringUtils.isNotEmpty(avatarTmpPath)) { + String originalExtension = FilenameUtils.getExtension(avatarTmpPath); + String originalName = String.format("%s.%s", visitor.getUid(), originalExtension); + String targetName = String.format("%s.png", visitor.getUid()); + Path ao = Paths.get(webApp.getImgDir(), "ao", originalName); + Path a = Paths.get(webApp.getImgDir(), "a", targetName); + Path as = Paths.get(webApp.getImgDir(), "as", targetName); + Files.move(Paths.get(webApp.getTmpDir(), avatarTmpPath), ao, StandardCopyOption.REPLACE_EXISTING); + Thumbnails.of(ao.toFile()).size(96, 96).toFile(a.toFile()); + Thumbnails.of(ao.toFile()).size(32, 32).toFile(as.toFile()); + } + if (userService.updateUserInfo(visitor, info)) { + result = String.format("

Your info is updated.

Back to blog.

", visitor.getName()); + } + break; + case "jid-del": + // FIXME: stop using ugnich-csv in parameters + String[] params = request.getParameter("delete").split(";", 2); + boolean res = false; + if (params[0].equals("xmpp")) { + res = userService.deleteJID(visitor.getUid(), params[1]); + } else if (params[0].equals("xmpp-unauth")) { + res = userService.unauthJID(visitor.getUid(), params[1]); + } + if (res) { + result = "

Deleted. Back.

"; + } else { + result = "

Error

"; + } + break; + case "email": + String newHash = userService.updateSecretEmail(visitor); + if (StringUtils.isNotEmpty(newHash)) { + result = String.format("

New secret email: %s@mail.juick.com

" + + "

Back.

", newHash); + } else { + throw new HttpBadRequestException(); + } + break; + case "email-add": + try { + emailService.verifyAddressByCode(visitor.getUid(), request.getParameter("account")); + } catch (EmptyResultDataAccessException e) { + String authCode = UserUtils.generateHash(8); + if (emailService.addVerificationCode(visitor.getUid(), request.getParameter("account"), authCode)) { + Session session = Session.getDefaultInstance(System.getProperties()); + try { + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress("noreply@mail.juick.com")); + message.addRecipient(Message.RecipientType.TO, new InternetAddress(request.getParameter("account"))); + message.setSubject("Juick authorization link"); + message.setText(String.format("Follow link to attach this email to Juick account:\n" + + "http://juick.com/settings?page=auth-email&code=%s\n\n" + + "If you don't know, what this mean - just ignore this mail.\n", authCode)); + Transport.send(message); + result = "

Authorization link has been sent to your email. Follow it to proceed.

" + + "

Back

"; + + } catch (MessagingException ex) { + logger.error("mail exception", ex); + throw new HttpBadRequestException(); + } + } + } + break; + case "email-del": + if (emailService.deleteEmail(visitor.getUid(), request.getParameter("account"))) { + result = "

Deleted. Back.

"; + } else { + result = "

An error occured while deleting.

"; + } + break; + case "email-subscr": + if (emailService.setSubscriptionHour(visitor.getUid(), request.getParameter("account"), + request.getParameter("time"))) { + result = String.format("

Saved! Will send to %s at %s:00 GMT." + + "

Back

", request.getParameter("account"), + request.getParameter("time")); + } else { + result = "

Disabled.

Back

"; + } + break; + case "twitter-del": + crosspostService.deleteTwitterToken(visitor.getUid()); + for (Cookie cookie : request.getCookies()) { + if (cookie.getName().equals("request_token")) { + cookie.setMaxAge(0); + response.addCookie(cookie); + } + if (cookie.getName().equals("request_token_secret")) { + cookie.setMaxAge(0); + response.addCookie(cookie); + } + } + result = "

Back

"; + break; + case "telegram-del": + telegramService.deleteTelegramUser(visitor.getUid()); + result = "

Back

"; + break; + case "facebook-disable": + crosspostService.disableFBCrosspost(visitor.getUid()); + result = "

Back

"; + break; + case "facebook-enable": + crosspostService.enableFBCrosspost(visitor.getUid()); + result = "

Back

"; + break; + case "vk-del": + crosspostService.deleteVKUser(visitor.getUid()); + result = "

Back

"; + break; + default: + throw new HttpBadRequestException(); + } + + model.addAttribute("title", "Настройки"); + model.addAttribute("visitor", visitor); + model.addAttribute("result", result); + return "views/settings_result"; + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/SignUp.java b/juick-www/src/main/java/com/juick/www/controllers/SignUp.java new file mode 100644 index 00000000..937a3242 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/SignUp.java @@ -0,0 +1,170 @@ +/* + * Juick + * Copyright (C) 2008-2013, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.server.util.HttpBadRequestException; +import com.juick.server.util.HttpForbiddenException; +import com.juick.service.CrosspostService; +import com.juick.service.UserService; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class SignUp { + + @Inject + WebApp webApp; + @Inject + UserService userService; + @Inject + CrosspostService crosspostService; + + + @RequestMapping(value = "/signup", method = RequestMethod.GET) + protected String doGet(HttpServletRequest request, HttpServletResponse response, ModelMap model) { + com.juick.User visitor = webApp.getVisitorUser(request, response); + + String type = request.getParameter("type"); + String hash = request.getParameter("hash"); + if (type == null || type.isEmpty() || hash == null || hash.isEmpty() || hash.length() > 36 + || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) { + throw new HttpBadRequestException(); + } + + String account = null; + switch (type) { + case "fb": + account = crosspostService.getFacebookNameByHash(hash); + break; + case "vk": + account = crosspostService.getVKNameByHash(hash); + break; + case "xmpp": + account = crosspostService.getJIDByHash(hash); + break; + case "durov": + account = crosspostService.getTelegramNameByHash(hash); + break; + } + if (account == null) { + throw new HttpBadRequestException(); + } + + model.addAttribute("title", "Новый пользователь"); + model.addAttribute("visitor", visitor); + model.addAttribute("account", account); + model.addAttribute("type", type); + model.addAttribute("hash", hash); + return "views/signup"; + } + + @RequestMapping(value = "/signup", method = RequestMethod.POST) + protected String doPost(HttpServletRequest request, HttpServletResponse response) { + com.juick.User visitor = webApp.getVisitorUser(request, response); + int uid = 0; + + String type = request.getParameter("type"); + String hash = request.getParameter("hash"); + if (type == null || type.isEmpty() || hash == null || hash.isEmpty() || hash.length() > 36 || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) { + throw new HttpBadRequestException(); + } + + String action = request.getParameter("action"); + if (action.charAt(0) == 'l') { + + if (visitor.getUid() == 0) { + String username = request.getParameter("username"); + String password = request.getParameter("password"); + if (username == null || password == null || username.length() > 32 || password.isEmpty()) { + throw new HttpBadRequestException(); + } + uid = userService.checkPassword(username, password); + } else { + uid = visitor.getUid(); + } + + if (uid <= 0) { + throw new HttpForbiddenException(); + } + + if (!(type.charAt(0) == 'f' && crosspostService.setFacebookUser(hash, uid)) + && !(type.charAt(0) == 'v' && crosspostService.setVKUser(hash, uid)) + && !(type.charAt(0) == 'd' && crosspostService.setTelegramUser(hash, uid)) + && !(type.charAt(0) == 'x' && crosspostService.setJIDUser(hash, uid))) { + throw new HttpBadRequestException(); + } + + } else { // Create new account + String username = request.getParameter("username"); + String password = request.getParameter("password"); + if (username == null || password == null || username.length() < 2 || username.length() > 16 || !username.matches("^[a-zA-Z0-9\\-]+$") || password.length() < 6 || password.length() > 32) { + throw new HttpBadRequestException(); + } + + // CHECK USERNAME + + uid = userService.createUser(username, password); + if (uid <= 0) { + throw new HttpBadRequestException(); + } + + if (!(type.charAt(0) == 'f' && crosspostService.setFacebookUser(hash, uid)) + && !(type.charAt(0) == 'v' && crosspostService.setVKUser(hash, uid)) + && !(type.charAt(0) == 'd' && crosspostService.setTelegramUser(hash, uid)) + && !(type.charAt(0) == 'x' && crosspostService.setJIDUser(hash, uid))) { + throw new HttpBadRequestException(); + } + + int ref = 0; + String sRef = Utils.getCookie(request, "ref"); + if (sRef != null) { + try { + ref = Integer.parseInt(sRef); + } catch (Exception e) { + } + } + + if (ref > 0) { + crosspostService.setUserRef(uid, ref); + } + + visitor = null; + } + + if (visitor == null) { + hash = userService.getHashByUID(uid); + Cookie c = new Cookie("hash", hash); + c.setMaxAge(365 * 24 * 60 * 60); + response.addCookie(c); + } + return "redirect:/"; + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/TwitterAuth.java b/juick-www/src/main/java/com/juick/www/controllers/TwitterAuth.java new file mode 100644 index 00000000..901a8362 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/TwitterAuth.java @@ -0,0 +1,103 @@ +package com.juick.www.controllers; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.scribejava.apis.TwitterApi; +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Verb; +import com.github.scribejava.core.oauth.OAuth10aService; +import com.juick.service.UserService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by vt on 01.12.2015. + */ +@Controller +public class TwitterAuth { + + private final static String VERIFY_URL = "https://api.twitter.com/1.1/account/verify_credentials.json"; + + private String consumerKey, consumerSecret; + + private final ObjectMapper mapper; + + @Inject + UserService userService; + + @Inject + public TwitterAuth(Environment env) { + this.consumerKey = env.getProperty("twitter_consumer_key"); + this.consumerSecret = env.getProperty("twitter_consumer_secret"); + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); + } + + @RequestMapping(value = "/_twitter", method = RequestMethod.GET) + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + String hash = StringUtils.EMPTY, request_token = StringUtils.EMPTY, request_token_secret = StringUtils.EMPTY; + String verifier = request.getParameter("oauth_verifier"); + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { + if (cookie.getName().equals("hash")) { + hash = cookie.getValue(); + } + if (cookie.getName().equals("request_token")) { + request_token = cookie.getValue(); + } + if (cookie.getName().equals("request_token_secret")) { + request_token_secret = cookie.getValue(); + } + } + com.juick.User user = userService.getUserByHash(hash); + if ( user == null || user.getUid() == 0) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + OAuth10aService oAuthService = new ServiceBuilder() + .apiKey(consumerKey) + .apiSecret(consumerSecret) + .callback("http://juick.com/_twitter") + .build(TwitterApi.instance()); + + if (request_token.isEmpty() && request_token_secret.isEmpty() + && (verifier == null || verifier.isEmpty())) { + OAuth1RequestToken requestToken = oAuthService.getRequestToken(); + String authUrl = oAuthService.getAuthorizationUrl(requestToken); + response.addCookie(new Cookie("request_token", requestToken.getToken())); + response.addCookie(new Cookie("request_token_secret", requestToken.getTokenSecret())); + response.setStatus(HttpServletResponse.SC_FOUND); + response.setHeader("Location", authUrl); + } else { + if (verifier != null && verifier.length() > 0) { + OAuth1RequestToken requestToken = new OAuth1RequestToken(request_token, request_token_secret); + OAuth1AccessToken accessToken = oAuthService.getAccessToken(requestToken, verifier); + OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, VERIFY_URL, oAuthService.getConfig()); + oAuthService.signRequest(accessToken, oAuthRequest); + com.juick.www.twitter.User twitterUser = mapper.readValue(oAuthRequest.send().getBody(), com.juick.www.twitter.User.class); + if (userService.linkTwitterAccount(user, accessToken.getToken(), accessToken.getTokenSecret(), + twitterUser.getScreenName())) { + response.setStatus(HttpServletResponse.SC_FOUND); + response.setHeader("Location", "http://juick.com/settings"); + } else { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/User.java b/juick-www/src/main/java/com/juick/www/controllers/User.java new file mode 100644 index 00000000..d3406f4e --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/User.java @@ -0,0 +1,368 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.server.helpers.TagStats; +import com.juick.service.MessagesService; +import com.juick.service.TagService; +import com.juick.service.UserService; +import com.juick.www.Utils; +import com.juick.www.WebApp; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class User { + @Inject + WebApp webApp; + @Inject + UserService userService; + @Inject + TagService tagService; + @Inject + MessagesService messagesService; + @Inject + PageTemplates templates; + + @RequestMapping("/{uname}/") + protected void doGetBlog(HttpServletRequest request, HttpServletResponse response, + @PathVariable String uname) throws IOException { + com.juick.User user = userService.getUserByName(uname); + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.isBanned()) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + List mids; + + String paramShow = request.getParameter("show"); + + com.juick.Tag paramTag = null; + String paramTagStr = request.getParameter("tag"); + if (paramTagStr != null) { + if (paramTagStr.length() < 64) { + paramTag = tagService.getTag(paramTagStr, false); + } + if (paramTag == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } else if (!paramTag.getName().equals(paramTagStr)) { + String url = "/" + user.getName() + "/?tag=" + URLEncoder.encode(paramTag.getName(), CharEncoding.UTF_8); + Utils.sendPermanentRedirect(response, url); + return; + } + } + + int paramBefore = 0; + String paramBeforeStr = request.getParameter("before"); + if (paramBeforeStr != null) { + try { + paramBefore = Integer.parseInt(paramBeforeStr); + } catch (NumberFormatException e) { + } + } + + String paramSearch = request.getParameter("search"); + if (paramSearch != null && paramSearch.length() > 64) { + paramSearch = null; + } + + int privacy = 0; + if (visitor.getUid() > 0) { + if (user.getUid() == visitor.getUid() || visitor.getUid() == 1) { + privacy = -3; + } else if (userService.isInWL(user.getUid(), visitor.getUid())) { + privacy = -2; + } + } + + String title; + if (paramShow == null) { + if (paramTag != null) { + title = "Блог " + user.getName() + ": *" + StringEscapeUtils.escapeHtml4(paramTag.getName()); + mids = messagesService.getUserTag(user.getUid(), paramTag.TID, privacy, paramBefore); + } else if (paramSearch != null) { + title = "Блог " + user.getName() + ": " + StringEscapeUtils.escapeHtml4(paramSearch); + mids = messagesService.getUserSearch(user.getUid(), Utils.encodeSphinx(paramSearch), privacy, paramBefore); + } else { + title = "Блог " + user.getName(); + mids = messagesService.getUserBlog(user.getUid(), privacy, paramBefore); + } + } else if (paramShow.equals("recomm")) { + title = "Рекомендации " + user.getName(); + mids = messagesService.getUserRecommendations(user.getUid(), paramBefore); + } else if (paramShow.equals("photos")) { + title = "Фотографии " + user.getName(); + mids = messagesService.getUserPhotos(user.getUid(), privacy, paramBefore); + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String head = ""; + if (paramTag != null && tagService.getTagNoIndex(paramTag.TID)) { + head += ""; + } else if (paramBefore > 0 || paramShow != null) { + head += ""; + } + templates.pageHead(out, visitor, title, head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); + + if (mids.size() > 0) { + out.println("
"); + + if (paramTag != null) { + out.println("

← Все записи с тегом " + + StringEscapeUtils.escapeHtml4(paramTag.getName()) + "

"); + } + + templates.printMessages(out, user, mids, visitor, visitor.getUid() == 0 ? 4 : 5, 0); + + if (mids.size() >= 20) { + String nextpage = "?before=" + mids.get(mids.size() - 1); + if (paramShow != null) { + nextpage += "&show=" + paramShow; + } + if (paramTag != null) { + nextpage += "&tag=" + URLEncoder.encode(paramTag.getName(), CharEncoding.UTF_8); + } + if (paramSearch != null) { + nextpage += "&search=" + URLEncoder.encode(paramSearch, CharEncoding.UTF_8); + } + out.println("

Читать дальше →

"); + } + + out.println("
"); + } + + templates.pageFooter(request, out, visitor, true); + templates.pageEnd(out); + } + } + + @RequestMapping(value = "/{uname}/tags", method = RequestMethod.GET) + protected void doGetTags(HttpServletRequest request, HttpServletResponse response, + @PathVariable String uname) throws IOException { + com.juick.User user = userService.getUserByName(uname); + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.isBanned()) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String head = ""; + templates.pageHead(out, visitor, "Теги " + user.getName(), head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); + + out.println("
"); + out.println("

" + pageUserTags(user, visitor, 0) + "

"); + out.println("
"); + + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); + } + } + + @RequestMapping(value = "/{uname}/friends", method = RequestMethod.GET) + protected void doGetFriends(HttpServletRequest request, HttpServletResponse response, + @PathVariable String uname) throws ServletException, IOException { + com.juick.User user = userService.getUserByName(uname); + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.isBanned()) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String head = ""; + templates.pageHead(out, visitor, "Подписки " + user.getName(), head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); + + out.println("
"); + out.println(""); + + List friends = userService.getUserFriends(user.getUid()); + for (int i = 0; i < friends.size(); i++) { + if (i % 3 == 0 && i > 0) { + out.print(""); + } + out.print(""); + } + + out.println("
" + + friends.get(i).getName() + "
"); + out.println("
"); + + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); + } + } + + @RequestMapping(value = "/{uname}/readers", method = RequestMethod.GET) + protected void doGetReaders(HttpServletRequest request, HttpServletResponse response, + @PathVariable String uname) throws ServletException, IOException { + com.juick.User user = userService.getUserByName(uname); + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.isBanned()) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String head = ""; + templates.pageHead(out, visitor, "Читатели " + user.getName(), head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); + + out.println("
"); + out.println(""); + + List readers = userService.getUserReaders(user.getUid()); + for (int i = 0; i < readers.size(); i++) { + if (i % 3 == 0 && i > 0) { + out.print(""); + } + out.print(""); + } + + out.println("
" + + readers.get(i).getName() + "
"); + out.println("
"); + + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); + } + } + + public void pageUserColumn(PrintWriter out, com.juick.User user, com.juick.User visitor) { + out.println(""); + } + + public String pageUserTags(com.juick.User user, com.juick.User visitor, int cnt) { + List tags = tagService.getUserTagStats(user.getUid()).stream() + .sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())).collect(Collectors.toList()); + int maxUsageCnt = tags.stream().map(TagStats::getUsageCount).max(Comparator.naturalOrder()).orElse(0); + String ret = StringUtils.EMPTY; + int count = cnt > 0 ? Math.min(tags.size(), cnt) : tags.size(); + for (int i = 0; i < count; i++) { + String tag = StringEscapeUtils.escapeHtml4(tags.get(i).getTag().getName()); + try { + tag = "" + tag + ""; + } catch (UnsupportedEncodingException e) { + } + + if (tags.get(i).getUsageCount() > maxUsageCnt / 3 * 2) { + ret += "" + tag + " "; + } else if (tags.get(i).getUsageCount() > maxUsageCnt / 3) { + ret += "" + tag + " "; + } else { + ret += tag + " "; + } + } + return ret; + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/UserThread.java b/juick-www/src/main/java/com/juick/www/controllers/UserThread.java new file mode 100644 index 00000000..4020e149 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/UserThread.java @@ -0,0 +1,374 @@ +/* + * Juick + * Copyright (C) 2008-2011, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.juick.Message; +import com.juick.server.helpers.TagStats; +import com.juick.service.MessagesService; +import com.juick.service.TagService; +import com.juick.service.UserService; +import com.juick.util.MessageUtils; +import com.juick.www.WebApp; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author Ugnich Anton + */ +@Controller +public class UserThread { + + @Inject + WebApp webApp; + @Inject + MessagesService messagesService; + @Inject + UserService userService; + @Inject + TagService tagService; + @Inject + PageTemplates templates; + + @RequestMapping(value = "/{uname}/{mid}", method = RequestMethod.GET) + protected void doGetThread(HttpServletRequest request, HttpServletResponse response, + @PathVariable int mid) throws ServletException, IOException { + com.juick.User visitor = webApp.getVisitorUser(request, response); + + if (!messagesService.canViewThread(mid, visitor.getUid())) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + + com.juick.Message msg = messagesService.getMessage(mid); + + boolean listview = false; + String paramView = request.getParameter("view"); + if (paramView != null) { + if (paramView.equals("list")) { + listview = true; + if (visitor.getUid() > 0) { + userService.setUserOptionInt(visitor.getUid(), "repliesview", 1); + } + } else if (paramView.equals("tree") && visitor.getUid() > 0) { + userService.setUserOptionInt(visitor.getUid(), "repliesview", 0); + } + } else if (visitor.getUid() > 0 && userService.getUserOptionInt(visitor.getUid(), "repliesview", 0) == 1) { + listview = true; + } + + String title = msg.getUser().getName() + ": " + msg.getTagsString(); + + response.setContentType("text/html; charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + String headers = ""; + if (paramView != null) { + headers += ""; + } + if (msg.Hidden) { + headers += ""; + } + templates.pageHead(out, visitor, title, headers); + templates.pageNavigation(out, visitor, null); + + out.println("
"); + printMessage(out, msg, visitor); + printReplies(out, msg, visitor, listview); + out.println("
"); + + templates.pageFooter(request, out, visitor, false); + + templates.pageEnd(out); + } + } + + public com.juick.Message printMessage(PrintWriter out, com.juick.Message msg, com.juick.User visitor) { + msg.VisitorCanComment = visitor.getUid() > 0; + + List tags = tagService.getMessageTags(msg.getMid()); + String tagsStr = templates.formatTags(tags); + if (msg.ReadOnly) { + tagsStr += "readonly"; + msg.VisitorCanComment = false; + } + if (msg.getPrivacy() < 0) { + tagsStr += "friends"; + } + + String txt; + if (msg.getTags().stream().anyMatch(t -> t.getName().equals("code"))) { + txt = MessageUtils.formatMessageCode(msg.getText()); + } else { + txt = MessageUtils.formatMessage(msg.getText()); + } + + if (!tags.isEmpty()) { + tagsStr = "
" + tagsStr + "
"; + } + + out.println("
    "); + out.println("
  • "); + out.println("
    "); + out.println("
    "); + out.println("
    " + templates.formatJSLocalTime(msg.getDate()) + "
    "); + out.println("
    \""
    "); + out.println(" "); + out.println("
    " + txt + "
    "); + + if (msg.getAttachmentType() != null) { + out.println("
    \"\"/
    "); + } + + boolean visitorInBL = false; + if (visitor.getUid() > 0) { + if (visitor.getUid() == msg.getUser().getUid()) { + msg.VisitorCanComment = true; + } else { + visitorInBL = userService.isInBL(msg.getUser().getUid(), visitor.getUid()); + if (visitorInBL) { + msg.VisitorCanComment = false; + } + } + } + + if (msg.VisitorCanComment) { + out.println("
    "); + out.println("
    "); + out.println("
    "); + } + + List recomm = messagesService.getMessageRecommendations(msg.getMid()); + if (!recomm.isEmpty()) { + out.print("
    Рекомендовали (" + recomm.size() + "): "); + for (int i = 0; i < recomm.size(); i++) { + if (i > 0) { + out.print(", "); + } + out.print("@" + recomm.get(i) + ""); + } + out.println("
    "); + } + out.println("
    "); + out.println("
  • "); + + out.println("
  • "); + out.println("
"); + + return msg; + } + + public void printReplies(PrintWriter out, com.juick.Message msg, com.juick.User visitor, boolean listview) { + List replies = messagesService.getReplies(msg.getMid()); + + List blUIDs = new ArrayList(); + for (int i = 0; i < replies.size(); i++) { + com.juick.Message reply = replies.get(i); + if (reply.getUser().getUid() != msg.getUser().getUid() && !blUIDs.contains(reply.getUser().getUid())) { + blUIDs.add(reply.getUser().getUid()); + } + if (reply.getReplyto() > 0) { + boolean added = false; + for (int n = 0; n < replies.size(); n++) { + if (replies.get(n).getRid() == reply.getReplyto()) { + replies.get(n).childs.add(reply); + added = true; + break; + } + } + if (!added) { + reply.setReplyto(0); + } + } + } + + if (!replies.isEmpty()) { + if (visitor.getUid() > 0 && msg.getUser().getUid() == visitor.getUid()) { + for (Message reply : replies) { + reply.VisitorCanComment = true; + } + } else if (visitor.getUid() > 0 && msg.VisitorCanComment) { + blUIDs = userService.checkBL(visitor.getUid(), blUIDs); + for (Message reply : replies) { + reply.VisitorCanComment = reply.getUser().getUid() == visitor.getUid() || !blUIDs.contains(reply.getUser().getUid()); + } + } else { + for (Message reply : replies) { + reply.VisitorCanComment = false; + } + } + + boolean foldable = false; + if (replies.size() > 10) { + for (int i = 0; i < replies.size() - 1; i++) { + if (replies.get(i).getChildsCount() > 1) { + foldable = true; + break; + } + } + } + + out.println("
"); + out.print("
"); + if (listview) { + out.print("Показать деревом"); + } else { + if (foldable) { + out.print("Раскрыть все · "); + } + out.print("Показать списком"); + } + out.print("
"); + out.println("

Ответы (" + replies.size() + ")

"); + out.println("
"); + + out.println("
    "); + if (listview) { + printList(out, replies, visitor); + } else { + printTree(out, replies, visitor, 0, 0, false); + } + out.println("
"); + + for (Message reply : replies) { + reply.cleanupChilds(); + } + replies.clear(); + } + } + + public void printTree(PrintWriter out, List replies, com.juick.User visitor, int ReplyTo, int margin, boolean hidden) { + if (margin > 240) { + margin = 240; + } + + for (int i = 0; i < replies.size(); i++) { + com.juick.Message msg = replies.get(i); + if (msg.getReplyto() == ReplyTo) { + + out.print("
  • 0) { + out.print("margin-left: " + margin + "px;"); + } + if (hidden) { + out.print("display:none;"); + } + out.println("\">"); + out.println("
    "); + out.println("
    "); + if (!msg.getUser().isBanned()) { + out.println(" @" + msg.getUser().getName() + ":"); + out.println("
    \""
    "); + } else { + out.println(" [удалено]:"); + out.println("
    "); + } + out.println("
    "); + out.println(" "); + out.println("
    "); + out.println("
    " + MessageUtils.formatMessage(msg.getText()) + "
    "); + if (msg.getAttachmentType() != null) { + out.println("
    \"\"/
    "); + } + out.print("
    /" + msg.getRid()); + if (msg.getReplyto() > 0) { + out.print(" в ответ на /" + msg.getReplyto() + ""); + } + if (msg.VisitorCanComment) { + out.println(" · Ответить
    "); + out.println("
    "); + } else if (visitor == null) { + out.println(" · Ответить
    "); + } + + int childs = msg.getChildsCount(); + if (ReplyTo == 0 && childs > 1 && replies.size() > 10) { + out.println(" "); + } + out.println(" "); + out.println("
  • "); + + if (ReplyTo == 0 && childs > 1 && replies.size() > 10) { + printTree(out, msg.childs, visitor, msg.getRid(), margin + 20, true); + } else if (childs > 0) { + printTree(out, msg.childs, visitor, msg.getRid(), margin + 20, hidden); + } + } + } + } + + public void printList(PrintWriter out, List replies, com.juick.User visitor) { + for (Message msg : replies) { + out.print("
  • "); + out.println("
    "); + out.println("
    "); + if (!msg.getUser().isBanned()) { + out.println(" @" + msg.getUser().getName() + ":"); + out.println("
    \""
    "); + } else { + out.println(" [удалено]:"); + out.println("
    "); + } + out.println("
    "); + out.println(" "); + out.println("
    "); + out.println("
    " + MessageUtils.formatMessage(msg.getText()) + "
    "); + if (msg.getAttachmentType() != null) { + out.println("
    \"\"/
    "); + } + out.print("
    /" + msg.getRid()); + if (msg.getReplyto() > 0) { + out.print(" в ответ на /" + msg.getReplyto() + ""); + } + if (msg.VisitorCanComment) { + out.println(" · Ответить
    "); + out.println("
    "); + } else if (visitor.getUid() == 0) { + out.println(" "); + } + out.println("
    "); + out.println("
  • "); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/VKontakteLogin.java b/juick-www/src/main/java/com/juick/www/controllers/VKontakteLogin.java new file mode 100644 index 00000000..d860a7bc --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/VKontakteLogin.java @@ -0,0 +1,130 @@ +/* + * Juick + * Copyright (C) 2008-2013, Ugnich Anton + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package com.juick.www.controllers; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.juick.service.CrosspostService; +import com.juick.service.UserService; +import com.juick.www.Utils; +import com.juick.www.vk.Token; +import com.juick.www.vk.UsersResponse; +import org.apache.commons.lang3.CharEncoding; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.inject.Inject; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URLEncoder; +import java.util.UUID; + +/** + * @author Ugnich Anton + */ +@Controller +public class VKontakteLogin { + private static final Logger logger = LoggerFactory.getLogger(VKontakteLogin.class); + private static final String VK_APPID = "3544101"; + private static final String VK_SECRET = "z2afNI8jA5lIpZ2jsTm1"; + private static final String VK_REDIRECT = "http://juick.com/_vklogin"; + + @Inject + CrosspostService crosspostService; + @Inject + UserService userService; + + public VKontakteLogin() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); + } + + private final ObjectMapper mapper; + + @RequestMapping(value = "/_vklogin", method = RequestMethod.GET) + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + String code = request.getParameter("code"); + if (StringUtils.isBlank(code)) { + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", "https://oauth.vk.com/authorize?client_id=" + VK_APPID + "&redirect_uri=" + URLEncoder.encode(VK_REDIRECT, CharEncoding.UTF_8) + "&scope=friends,wall,offline&response_type=code"); + return; + } + + + String tokenjson = Utils.fetchURL("https://oauth.vk.com/access_token?client_id=" + VK_APPID + "&redirect_uri=" + URLEncoder.encode(VK_REDIRECT, CharEncoding.UTF_8) + "&client_secret=" + VK_SECRET + "&code=" + URLEncoder.encode(code, CharEncoding.UTF_8)); + if (tokenjson == null || tokenjson.isEmpty()) { + logger.error("VK TOKEN EMPTY"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + String token = null; + long vkID = 0; + Token json = mapper.readValue(tokenjson, Token.class); + token = json.getAccessToken(); + vkID = json.getUserId(); + if (token == null || vkID == 0) { + logger.error("VK TOKEN EMPTY: {}", tokenjson); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + + String graph = Utils.fetchURL("https://api.vk.com/method/users.get?uids=" + vkID + "&fields=screen_name&access_token=" + token); + if (graph == null || graph.isEmpty()) { + logger.error("VK GRAPH ERROR"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + + try { + com.juick.www.vk.User jsonUser = mapper.readValue(graph, UsersResponse.class).getUsers().get(0); + String vkName = jsonUser.getFirstName() + " " + jsonUser.getLastName(); + String vkLink = jsonUser.getScreenName(); + + if (vkName == null || vkLink == null || vkName.isEmpty() || vkName.length() == 1 || vkLink.isEmpty()) { + throw new Exception(); + } + + int uid = crosspostService.getUIDbyVKID(vkID); + if (uid > 0) { + Cookie c = new Cookie("hash", userService.getHashByUID(uid)); + c.setMaxAge(50 * 24 * 60 * 60); + response.addCookie(c); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", "/"); + } else { + String loginhash = UUID.randomUUID().toString(); + if (!crosspostService.createVKUser(vkID, loginhash, token, vkName, vkLink)) { + throw new Exception(); + } + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", "/signup?type=vk&hash=" + loginhash); + } + } catch (Exception e) { + logger.error("JSON ERROR", e); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } +} diff --git a/juick-www/src/main/java/com/juick/www/controllers/XMPPPost.java b/juick-www/src/main/java/com/juick/www/controllers/XMPPPost.java new file mode 100644 index 00000000..f64907b2 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/controllers/XMPPPost.java @@ -0,0 +1,84 @@ +package com.juick.www.controllers; + +import com.juick.server.util.HttpBadRequestException; +import com.juick.server.util.HttpUtils; +import com.juick.service.TagService; +import com.juick.www.WebApp; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; +import rocks.xmpp.addr.Jid; +import rocks.xmpp.core.stanza.model.Message; +import rocks.xmpp.extensions.oob.model.x.OobX; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +/** + * Created by vitalyster on 08.12.2016. + */ +@Controller +public class XMPPPost { + private final static Logger logger = LoggerFactory.getLogger(XMPPPost.class); + + @Inject + WebApp webApp; + @Inject + TagService tagService; + + @RequestMapping(value = "/post2", method = RequestMethod.POST) + public void doPostMessage(HttpServletRequest request, HttpServletResponse response, + @RequestParam(required = false) String img, + @RequestParam(required = false) MultipartFile attach) throws IOException { + + com.juick.User visitor = webApp.getVisitorUser(request, response); + if (visitor.getUid() == 0 || visitor.isBanned()) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + String body = request.getParameter("body").replace("\r", StringUtils.EMPTY); + + String attachmentFName = HttpUtils.receiveMultiPartFile(attach, webApp.getTmpDir()); + + if (StringUtils.isBlank(attachmentFName) && img != null && img.length() > 10) { + try { + URL imgUrl = new URL(img); + attachmentFName = HttpUtils.downloadImage(imgUrl); + } catch (Exception e) { + logger.error("DOWNLOAD ERROR", e); + throw new HttpBadRequestException(); + } + } + Message msg = new Message(); + msg.setType(Message.Type.CHAT); + msg.setFrom(Jid.of(String.valueOf(visitor.getUid()), "uid.juick.com", "perl")); + msg.setTo(Jid.of("juick@juick.com/Juick")); + msg.setBody(body); + try { + if (StringUtils.isNotEmpty(attachmentFName)) { + String attachmentUrl = String.format("juick://%s", attachmentFName); + msg.addExtension(new OobX(new URI(attachmentUrl), "!!!!Juick!!")); + } + webApp.getXmpp().sendMessage(msg); + } catch (URISyntaxException e1) { + logger.warn("attachment error", e1); + } + String referer = request.getHeader("referer"); + if (StringUtils.isBlank(referer) || referer.substring(0, 21).equals("http://juick.com/post") + || referer.substring(0, 22).equals("https://juick.com/post")) { + response.sendRedirect("/?show=my"); + return; + } + response.sendRedirect(referer); + } +} -- cgit v1.2.3