diff options
Diffstat (limited to 'juick-www/src/main/java')
28 files changed, 1510 insertions, 1562 deletions
diff --git a/juick-www/src/main/java/com/juick/www/Errors.java b/juick-www/src/main/java/com/juick/www/Errors.java deleted file mode 100644 index 75fdddde..00000000 --- a/juick-www/src/main/java/com/juick/www/Errors.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.juick.www; - -import com.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; -import org.springframework.jdbc.core.JdbcTemplate; - -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.HashMap; -import java.util.Map; - -/** - * - * @author ugnich - */ -public class Errors { - - public static void doGet404(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("views/404.html"); - Map<String, Object> context = new HashMap<>(); - context.put("title", "404 Страница не найдена"); - context.put("visitor", visitor); - template.evaluate(out, context); - } catch (PebbleException e) { - // log("pebble exception", e); - } - } -} diff --git a/juick-www/src/main/java/com/juick/www/Help.java b/juick-www/src/main/java/com/juick/www/Help.java deleted file mode 100644 index 301d2edc..00000000 --- a/juick-www/src/main/java/com/juick/www/Help.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 <http://www.gnu.org/licenses/>. - */ -package com.juick.www; - -import com.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Ugnich Anton - */ -public class Help { - - protected void doRedirectToHelpIndex(HttpServletResponse response) throws ServletException, IOException { - Utils.sendTemporaryRedirect(response, "/help/ru/"); - } - - protected void doGetHelp(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, PebbleException, URISyntaxException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - - String path[] = request.getRequestURI().split("/"); - String page; - if (path.length < 3 || path.length > 4 || path[2].length() != 2 || !path[2].matches("^[a-z]+$")) { - Errors.doGet404(sql, request, response); - return; - } - - if (path.length == 4) { - page = path[3]; - if (!page.matches("^[a-zA-Z0-9\\-]*$") || page.equals("navigation") || page.equals("index")) { - Errors.doGet404(sql, request, response); - return; - } - } else { - page = "index"; - } - - URL f = getClass().getResource("/help/" + path[2] + "/" + page); - if (f == null) { - Errors.doGet404(sql, request, response); - return; - } - - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("views/help.html"); - Map<String, Object> context = new HashMap<>(); - context.put("title", "Помощь"); - context.put("visitor", visitor); - context.put("content", new String(Files.readAllBytes(Paths.get(f.toURI())))); - context.put("navigation", new String(Files.readAllBytes( - new File(getClass().getResource("/help/" + path[2] + "/navigation").toURI()).toPath()))); - template.evaluate(out, context); - } - } -} diff --git a/juick-www/src/main/java/com/juick/www/HelpService.java b/juick-www/src/main/java/com/juick/www/HelpService.java new file mode 100644 index 00000000..8ece4cfb --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/HelpService.java @@ -0,0 +1,48 @@ +package com.juick.www; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.cache.annotation.Cacheable; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.regex.Pattern; + +/** + * Created by aalexeev on 12/11/16. + */ +public class HelpService { + private static final Pattern LANG_PATTERN = Pattern.compile("[a-z]{2}"); + + private static final Pattern PAGE_PATTERN = Pattern.compile("[a-zA-Z0-9\\-_]+"); + + private final String helpPath; + + + public HelpService(String helpPath) { + this.helpPath = helpPath; + } + + @Cacheable("help") + public String getHelp(final String page, final String lang) { + if (canBePage(page) && canBeLang(lang)) { + String path = StringUtils.joinWith("/", helpPath, lang, page); + + try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) { + if (is != null) + return IOUtils.toString(is, StandardCharsets.UTF_8); + } catch (IOException e) { + } + } + return null; + } + + public boolean canBePage(final String anything) { + return anything != null && PAGE_PATTERN.matcher(anything).matches(); + } + + public boolean canBeLang(final String anything) { + return anything != null && LANG_PATTERN.matcher(anything).matches(); + } +} diff --git a/juick-www/src/main/java/com/juick/www/Main.java b/juick-www/src/main/java/com/juick/www/Main.java deleted file mode 100644 index 4fb13290..00000000 --- a/juick-www/src/main/java/com/juick/www/Main.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - * 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 <http://www.gnu.org/licenses/>. - */ -package com.juick.www; - -import com.juick.Message; -import com.juick.server.UserQueries; -import com.mitchellbosecke.pebble.error.PebbleException; -import org.apache.commons.dbcp2.BasicDataSource; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.CharEncoding; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.springframework.jdbc.core.JdbcTemplate; -import rocks.xmpp.addr.Jid; -import rocks.xmpp.core.XmppException; -import rocks.xmpp.core.session.Extension; -import rocks.xmpp.core.session.XmppSessionConfiguration; -import rocks.xmpp.core.session.debug.LogbackDebugger; -import rocks.xmpp.extensions.component.accept.ExternalComponent; -import ru.sape.Sape; - -import javax.servlet.ServletException; -import javax.servlet.annotation.MultipartConfig; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.util.Objects; -import java.util.Properties; - -/** - * - * @author Ugnich Anton - */ -@WebServlet(name = "Main", urlPatterns = {"/"}) -@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxRequestSize = 1024 * 1024 * 10) -public class Main extends HttpServlet { - - JdbcTemplate sql; - JdbcTemplate sqlSearch; - String sqlSearchConnStr = "jdbc:mysql://127.0.0.1:9306?autoReconnect=true&useUnicode=yes&characterEncoding=utf8&maxAllowedPacket=512000"; - ExternalComponent xmpp; - Home home = new Home(); - Discover discover = new Discover(); - PM pm = new PM(); - Login login = new Login(); - Help help = new Help(); - User pagesUser = new User(); - UserThread pagesUserThread = new UserThread(); - NewMessage pagesNewMessage; - XMPPPost xmppPost = new XMPPPost(); - FacebookLogin loginFacebook; - VKontakteLogin loginVK = new VKontakteLogin(); - TwitterAuth twitterAuth; - SignUp signup = new SignUp(); - Settings settings; - RSS rss = new RSS(); - - @Override - public void init() throws ServletException { - - super.init(); - try { - Properties conf = new Properties(); - conf.load(getServletContext().getResourceAsStream("/WEB-INF/juick.conf")); - - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); - dataSource.setUrl(conf.getProperty("datasource_url")); - BasicDataSource dataSourceSearch = new BasicDataSource(); - dataSourceSearch.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); - dataSourceSearch.setUrl(sqlSearchConnStr); - sql = new JdbcTemplate(dataSource); - sqlSearch = new JdbcTemplate(dataSourceSearch); - boolean isXmppDisabled = BooleanUtils.toBoolean(conf.getProperty("xmpp_disabled")); - if (!isXmppDisabled) { - setupXmppComponent(Jid.of(conf.getProperty("www_xmpp_jid", "www.juick.local")), - conf.getProperty("xmpp_password"), NumberUtils.toInt(conf.getProperty("xmpp_port", StringUtils.EMPTY), 5347)); - } - twitterAuth = new TwitterAuth(conf.getProperty("twitter_consumer_key"), - conf.getProperty("twitter_consumer_secret")); - loginFacebook = new FacebookLogin(conf.getProperty("facebook_appid"), conf.getProperty("facebook_secret")); - String tmpDir = conf.getProperty("upload_tmp_dir", "/var/www/juick.com/i/tmp/"); - Utils.setTmpDir(tmpDir); - String imgPath = conf.getProperty("img_path", "/var/www/juick.com/i/"); - pagesNewMessage = new NewMessage(tmpDir, imgPath); - settings = new Settings(imgPath); - String sapeUser = conf.getProperty("sape_user", StringUtils.EMPTY); - if (!Objects.equals(sapeUser, StringUtils.EMPTY)) { - PageTemplates.sape = new Sape(sapeUser, "juick.com", 2000, 3600); - } else { - log("Sape is not initialized"); - } - } catch (Exception e) { - log(null, e); - } - } - - @Override - public void destroy() { - try { - if (xmpp != null) - xmpp.close(); - log("ExternalComponent on WWW destroyed"); - } catch (Exception e) { - log("exception on destroy", e); - } - } - - public void setupXmppComponent(final Jid componentJid, final String password, final int port) { - XmppSessionConfiguration configuration = XmppSessionConfiguration.builder() - .extensions(Extension.of(Message.class)) - .debugger(LogbackDebugger.class) - .build(); - xmpp = ExternalComponent.create(componentJid.toString(), password, configuration, "localhost", port); - xmpp.addConnectionListener(e -> log(e.toString(), e.getCause())); - try { - xmpp.connect(); - } catch (XmppException e) { - log("xmpp extension", e); - } - } - - /** - * Handles the HTTP <code>GET</code> method. - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getCharacterEncoding() == null) { - request.setCharacterEncoding(CharEncoding.UTF_8); - } - String uri = request.getRequestURI(); - - if (uri.equals("/")) { - String tag = request.getParameter("tag"); - if (tag != null) { - Utils.sendPermanentRedirect(response, "/tag/" + URLEncoder.encode(tag, CharEncoding.UTF_8)); - } else { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - home.doGet(sql, sqlSearch, request, response, visitor); - } - } else if (uri.equals("/post")) { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() > 0) { - pagesNewMessage.doGetNewMessage(sql, request, response, visitor); - } else { - Utils.sendTemporaryRedirect(response, "/login"); - } - } else if (uri.equals("/login")) { - if (request.getQueryString() == null) { - login.doGetLoginForm(sql, request, response); - } else { - login.doGetLogin(sql, request, response); - } - } else if (uri.startsWith("/pm/")) { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() == 0) { - Utils.sendTemporaryRedirect(response, "/login"); - } else { - switch (uri) { - case "/pm/inbox": - try { - pm.doGetInbox(sql, request, response, visitor); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - break; - case "/pm/sent": - try { - pm.doGetSent(sql, request, response, visitor); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - break; - default: - Errors.doGet404(sql, request, response); - break; - } - } - } else if (uri.startsWith("/rss/")) { - String uname = uri.substring(5); - int uid = UserQueries.getUIDbyName(sql, uname); - if (uid > 0) { - try { - rss.doGet(sql, response, uid); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } else { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - } - } else if (uri.equals("/logout")) { - login.doGetLogout(sql, request, response); - } else if (uri.equals("/settings")) { - try { - settings.doGet(sql, request, response); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } else if (uri.equals("/_fblogin")) { - loginFacebook.doGet(sql, request, response); - } else if (uri.equals("/_vklogin")) { - loginVK.doGet(sql, request, response); - } else if (uri.startsWith("/_twitter")) { - twitterAuth.doGet(sql, request, response); - } else if (uri.equals("/signup")) { - try { - signup.doGet(sql, request, response); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } else if (uri.equals("/help") || uri.equals("/help/")) { - help.doRedirectToHelpIndex(response); - } else if (uri.startsWith("/help/")) { - try { - help.doGetHelp(sql, request, response); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } catch (URISyntaxException e) { - log("help exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } else if (uri.startsWith("/tag/")) { - discover.doGet(sql, sqlSearch, request, response); - } else if (uri.matches("^/\\d+$")) { - String strID = request.getRequestURI().substring(1); - int mid = 0; - try { - mid = Integer.parseInt(strID); - } catch (NumberFormatException e) { - } - if (mid > 0) { - com.juick.User author = com.juick.server.MessagesQueries.getMessageAuthor(sql, mid); - if (author != null) { - Utils.sendPermanentRedirect(response, "/" + author.getName() + "/" + mid); - return; - } - } - Errors.doGet404(sql, request, response); - } else if (uri.matches("^/[^/]+$")) { - com.juick.User user = com.juick.server.UserQueries.getUserByName(sql, request.getRequestURI().substring(1)); - if (user != null) { - Utils.sendPermanentRedirect(response, "/" + user.getName() + "/"); - } else { - Errors.doGet404(sql, request, response); - } - } else if (uri.matches("^/.+/.*")) { - String uriparts[] = uri.split("/"); - com.juick.User user = com.juick.server.UserQueries.getUserByName(sql, uriparts[1]); - if (user != null && user.getName().equals(uriparts[1]) && !user.isBanned()) { - if (uriparts.length == 2) { // http://juick.com/username/ - pagesUser.doGetBlog(sql, sqlSearch, request, response, user); - } else if (uriparts[2].equals("tags")) { - pagesUser.doGetTags(sql, request, response, user); - } else if (uriparts[2].equals("friends")) { - pagesUser.doGetFriends(sql, request, response, user); - } else if (uriparts[2].equals("readers")) { - pagesUser.doGetReaders(sql, request, response, user); - } else { - int mid = 0; - try { - mid = Integer.parseInt(uriparts[2]); - } catch (NumberFormatException e) { - } - if (mid > 0) { - com.juick.User author = com.juick.server.MessagesQueries.getMessageAuthor(sql, mid); - if (author != null) { - if (!author.getName().equals(user.getName())) { - Utils.sendPermanentRedirect(response, "/" + author.getName() + "/" + mid); - } else { - pagesUserThread.doGetThread(sql, request, response, mid); - } - } else { - Errors.doGet404(sql, request, response); - } - } else { - Errors.doGet404(sql, request, response); - } - } - } else if (user != null && !user.isBanned()) { - Utils.sendPermanentRedirect(response, "/" + user.getName() + "/" + (uriparts.length > 2 ? uriparts[2] : StringUtils.EMPTY)); - } else { - Errors.doGet404(sql, request, response); - } - } else { - Errors.doGet404(sql, request, response); - } - } - - /** - * Handles the HTTP <code>POST</code> method. - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getCharacterEncoding() == null) { - request.setCharacterEncoding(CharEncoding.UTF_8); - } - - String uri = request.getRequestURI(); - switch (uri) { - case "/post": { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() > 0 && !visitor.isBanned()) { - pagesNewMessage.doPostMessage(sql, request, response, xmpp, visitor); - } else { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } - break; - } - case "/comment": { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() > 0 && !visitor.isBanned()) { - pagesNewMessage.doPostComment(sql, request, response, xmpp, visitor); - } else { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } - break; - } - case "/like": { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() > 0 && !visitor.isBanned()) { - pagesNewMessage.doPostRecomm(sql, request, response, xmpp, visitor); - } else { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } - break; - } - case "/pm/send": { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() > 0 && !visitor.isBanned()) { - pm.doPostPM(sql, request, response, xmpp, visitor); - } else { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } - break; - } - case "/login": - login.doPostLogin(sql, request, response); - break; - case "/signup": - signup.doPost(sql, request, response); - break; - case "/settings": - try { - settings.doPost(sql, request, response); - } catch (PebbleException e) { - log("pebble exception", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - break; - case "/post2": - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - if (visitor.getUid() > 0 && !visitor.isBanned()) { - xmppPost.doPostMessage(sql, request, response, xmpp, visitor); - } else { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } - break; - default: - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - break; - } - } -} diff --git a/juick-www/src/main/java/com/juick/www/RSS.java b/juick-www/src/main/java/com/juick/www/RSS.java deleted file mode 100644 index 91ba9380..00000000 --- a/juick-www/src/main/java/com/juick/www/RSS.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 <http://www.gnu.org/licenses/>. - */ -package com.juick.www; - -import com.juick.Message; -import com.juick.server.MessagesQueries; -import com.juick.util.DateFormattersHolder; -import com.juick.util.MessageUtils; -import com.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author ugnich - */ -public class RSS { - - protected void doGet(JdbcTemplate sql, HttpServletResponse response, int uid) throws ServletException, IOException, PebbleException { - List<Integer> mids = MessagesQueries.getUserBlog(sql, uid, 0, 0); - if (mids.isEmpty()) { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } - - List<Message> msgs = MessagesQueries.getMessages(sql, mids); - - msgs.forEach(m -> MessageUtils.formatMessage(m.getText())); - - response.setContentType("application/rss+xml; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("layouts/rss.xml"); - Map<String, Object> context = new HashMap<>(); - context.put("user", msgs.stream().findFirst().get().getUser()); - context.put("msgs", msgs); - context.put("sdfRSS", DateFormattersHolder.getRssFormatterInstance()); - template.evaluate(out, context); - } - } -} diff --git a/juick-www/src/main/java/com/juick/www/SignUp.java b/juick-www/src/main/java/com/juick/www/SignUp.java deleted file mode 100644 index ea40c810..00000000 --- a/juick-www/src/main/java/com/juick/www/SignUp.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * 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 <http://www.gnu.org/licenses/>. - */ -package com.juick.www; - -import com.juick.server.UserQueries; -import com.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; -import org.apache.commons.lang3.tuple.Pair; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; - -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.io.PrintWriter; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Ugnich Anton - */ -public class SignUp { - - protected void doGet(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, PebbleException { - com.juick.User visitor = Utils.getVisitorUser(sql, 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\\-]+$")) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - String account = null; - switch (type) { - case "fb": - account = getFacebookNameByHash(sql, hash); - break; - case "vk": - account = getVKNameByHash(sql, hash); - break; - case "xmpp": - account = getJIDByHash(sql, hash); - break; - case "durov": - account = getTelegramNameByHash(sql, hash); - break; - } - if (account == null) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("views/signup.html"); - Map<String, Object> context = new HashMap<>(); - context.put("title", "Новый пользователь"); - context.put("visitor", visitor); - context.put("account", account); - context.put("type", type); - context.put("hash", hash); - template.evaluate(out, context); - } - } - - protected void doPost(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, 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\\-]+$")) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - 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()) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - uid = com.juick.server.UserQueries.checkPassword(sql, username, password); - } else { - uid = visitor.getUid(); - } - - if (uid <= 0) { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - return; - } - - if (!(type.charAt(0) == 'f' && setFacebookUser(sql, hash, uid)) - && !(type.charAt(0) == 'v' && setVKUser(sql, hash, uid)) - && !(type.charAt(0) == 'd' && setTelegramUser(sql, hash, uid)) - && !(type.charAt(0) == 'x' && setJIDUser(sql, hash, uid))) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - - } 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) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - // CHECK USERNAME - - uid = UserQueries.createUser(sql, username, password); - if (uid <= 0) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - - if (!(type.charAt(0) == 'f' && setFacebookUser(sql, hash, uid)) - && !(type.charAt(0) == 'v' && setVKUser(sql, hash, uid)) - && !(type.charAt(0) == 'd' && setTelegramUser(sql, hash, uid)) - && !(type.charAt(0) == 'x' && setJIDUser(sql, hash, uid))) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - - int ref = 0; - String sRef = Utils.getCookie(request, "ref"); - if (sRef != null) { - try { - ref = Integer.parseInt(sRef); - } catch (Exception e) { - } - } - - if (ref > 0) { - setUserRef(sql, uid, ref); - } - - visitor = null; - } - - if (visitor == null) { - hash = com.juick.server.UserQueries.getHashByUID(sql, uid); - Cookie c = new Cookie("hash", hash); - c.setMaxAge(365 * 24 * 60 * 60); - response.addCookie(c); - } - - response.sendRedirect("/"); - } - - private boolean setUserRef(JdbcTemplate sql, int uid, int ref) { - return sql.update("INSERT INTO users_refs(user_id,ref) VALUES (?,?)", uid, ref) > 0; - } - - private String getFacebookNameByHash(JdbcTemplate sql, String hash) { - try { - List<Pair<String, String>> fb = sql.query("SELECT fb_name,fb_link FROM facebook WHERE loginhash=?", - (rs, num) -> Pair.of(rs.getString(1), rs.getString(2)), hash); - if (fb.size() > 0) { - return "<a href=\"" + fb.get(0).getRight() + "\" rel=\"nofollow\">" + fb.get(0).getLeft() + "</a>"; - } - return null; - } catch (EmptyResultDataAccessException e) { - return null; - } - } - private String getTelegramNameByHash(JdbcTemplate sql, String hash) { - try { - String name = sql.queryForObject("SELECT tg_name FROM telegram WHERE loginhash=?", String.class, hash); - return "<a href=\"https://telegram.me/" + name + "\" rel=\"nofollow\">" + name + "</a>"; - } catch (EmptyResultDataAccessException e) { - return null; - } - } - - private boolean setFacebookUser(JdbcTemplate sql, String hash, int uid) { - return sql.update("UPDATE facebook SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0; - } - - private String getVKNameByHash(JdbcTemplate sql, String hash) { - List<Pair<String, String>> logins = sql.query("SELECT vk_name,vk_link FROM vk WHERE loginhash=?", - (rs, num) -> Pair.of(rs.getString(1), rs.getString(2)), hash); - if (logins.size() > 0) { - return "<a href=\"http://vk.com/" + logins.get(0).getRight() + "\" rel=\"nofollow\">" + logins.get(0).getLeft() + "</a>"; - } - return null; - } - - private boolean setVKUser(JdbcTemplate sql, String hash, int uid) { - return sql.update("UPDATE vk SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0; - } - private boolean setTelegramUser(JdbcTemplate sql, String hash, int uid) { - return sql.update("UPDATE telegram SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0; - } - - private String getJIDByHash(JdbcTemplate sql, String hash) { - try { - return sql.queryForObject("SELECT jid FROM jids WHERE loginhash=?", String.class, hash); - } catch (EmptyResultDataAccessException e) { - return null; - } - } - - private boolean setJIDUser(JdbcTemplate sql, String hash, int uid) { - return sql.update("UPDATE jids SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0; - } -} diff --git a/juick-www/src/main/java/com/juick/www/Utils.java b/juick-www/src/main/java/com/juick/www/Utils.java index ca3535fd..37016ed2 100644 --- a/juick-www/src/main/java/com/juick/www/Utils.java +++ b/juick-www/src/main/java/com/juick/www/Utils.java @@ -17,31 +17,21 @@ */ package com.juick.www; -import com.juick.Tag; -import com.juick.User; -import com.juick.server.TagQueries; -import com.mitchellbosecke.pebble.PebbleEngine; -import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; -import java.nio.file.Paths; -import java.util.*; +import java.util.Arrays; /** * @@ -51,9 +41,6 @@ public class Utils { private static final Logger logger = LoggerFactory.getLogger(Utils.class); - private static final PebbleEngine engine = new PebbleEngine.Builder().build(); - private static String tmpDir = "/var/www/juick.com/i/tmp/"; - public static String getCookie(HttpServletRequest request, String name) { Cookie cookies[] = request.getCookies(); if (cookies != null) { @@ -63,40 +50,7 @@ public class Utils { return null; } - public static String receiveMultiPartFile(Part filePart) throws IOException, ServletException { - String attachmentFName = null; - - if (filePart != null) { - String partname = Utils.getPartFilename(filePart); - if (partname != null && partname.length() > 0) { - String attachmentType = partname.substring(partname.length() - 3).toLowerCase(); - if (attachmentType.equals("jpg") || attachmentType.equals("peg") || attachmentType.equals("png")) { - if (attachmentType.equals("peg")) { - attachmentType = "jpg"; - } - attachmentFName = DigestUtils.md5Hex(UUID.randomUUID().toString()) + "." + attachmentType; - filePart.write(Paths.get(getTmpDir(), attachmentFName).toString()); - } else { - throw new IOException("Wrong file type"); - } - } - } - - return attachmentFName; - } - public static com.juick.User getVisitorUser(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) { - String hash = getCookie(request, "hash"); - if (hash != null) { - com.juick.User visitor = com.juick.server.UserQueries.getUserByHash(sql, hash); - if (response != null && visitor.getUid() > 0) { - response.setHeader("X-Username", visitor.getName()); - } - return visitor; - } else { - return new User(); - } - } public static void sendTemporaryRedirect(HttpServletResponse response, String location) { response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); @@ -154,96 +108,4 @@ public class Utils { return null; } } - - public static String downloadImage(URL url) throws Exception { - String attachmentFName = null; - Exception ex = null; - - InputStream is = null; - FileOutputStream fos = null; - try { - URLConnection urlConn = url.openConnection(); - is = urlConn.getInputStream(); - String mime = urlConn.getContentType(); - - String attachmentType; - if (mime != null && mime.equals("image/jpeg")) { - attachmentType = "jpg"; - } else if (mime != null && mime.equals("image/png")) { - attachmentType = "png"; - } else { - throw new Exception("Wrong file type"); - } - - attachmentFName = DigestUtils.md5Hex(UUID.randomUUID().toString()) + "." + attachmentType; - fos = new FileOutputStream("/var/www/juick.com/i/tmp/" + attachmentFName); - byte[] buffer = new byte[10240]; - int len; - while ((len = is.read(buffer)) > 0) { - fos.write(buffer, 0, len); - } - } catch (Exception e) { - ex = e; - attachmentFName = null; - } finally { - try { - if (is != null) { - is.close(); - } - } finally { - if (fos != null) { - fos.close(); - } - } - } - - if (ex != null) { - throw ex; - } else { - return attachmentFName; - } - } - - public static List<Tag> parseTags(JdbcTemplate sql, String tagsStr) { - List<com.juick.Tag> tags = new ArrayList<>(); - String tagsArr[]; - if (tagsStr != null && !tagsStr.isEmpty()) { - tagsArr = tagsStr.split("[ \\,]"); - for (int i = 0; i < tagsArr.length; i++) { - if (tagsArr[i].startsWith("*")) { - tagsArr[i] = tagsArr[i].substring(1); - } - if (tagsArr[i].length() > 64) { - tagsArr[i] = tagsArr[i].substring(0, 64); - } - } - tags = TagQueries.getTags(sql, tagsArr, true); - while (tags.size() > 5) { - tags.remove(5); - } - } - return tags; - } - - public static String receiveAttachment(Part part, String paramImg) throws Exception { - String attachmentFName = receiveMultiPartFile(part); - - if (attachmentFName == null && paramImg != null && paramImg.length() > 10) { - URL imgUrl = new URL(paramImg); - attachmentFName = downloadImage(imgUrl); - } - return attachmentFName; - } - - public static PebbleEngine getEngine() { - return engine; - } - - public static String getTmpDir() { - return tmpDir; - } - - public static void setTmpDir(String tmpDir) { - Utils.tmpDir = tmpDir; - } } diff --git a/juick-www/src/main/java/com/juick/www/WebApp.java b/juick-www/src/main/java/com/juick/www/WebApp.java new file mode 100644 index 00000000..85ae64d4 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/WebApp.java @@ -0,0 +1,154 @@ +/* + * 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 <http://www.gnu.org/licenses/>. + */ +package com.juick.www; + +import com.juick.Message; +import com.juick.Tag; +import com.juick.User; +import com.juick.service.TagService; +import com.juick.service.UserService; +import com.juick.www.controllers.PageTemplates; +import org.apache.commons.lang3.BooleanUtils; +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 rocks.xmpp.addr.Jid; +import rocks.xmpp.core.XmppException; +import rocks.xmpp.core.session.Extension; +import rocks.xmpp.core.session.XmppSessionConfiguration; +import rocks.xmpp.core.session.debug.LogbackDebugger; +import rocks.xmpp.extensions.component.accept.ExternalComponent; +import ru.sape.Sape; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * + * @author Ugnich Anton + */ +public class WebApp implements AutoCloseable { + private static Logger logger = LoggerFactory.getLogger(WebApp.class); + + private ExternalComponent xmpp; + + Environment env; + PageTemplates templates; + UserService userService; + TagService tagService; + + private String imgDir; + private String tmpDir; + + public WebApp(Environment env, PageTemplates templates, UserService userService, TagService tagService) { + this.env = env; + this.templates = templates; + this.userService = userService; + this.tagService = tagService; + tmpDir = env.getProperty("upload_tmp_dir", "/var/www/juick.com/i/tmp/"); + imgDir = env.getProperty("img_path", "/var/www/juick.com/i/"); + boolean isXmppDisabled = BooleanUtils.toBoolean(env.getProperty("xmpp_disabled")); + if (!isXmppDisabled) { + setupXmppComponent(Jid.of(env.getProperty("www_xmpp_jid", "www.juick.local")), + env.getProperty("xmpp_password"), NumberUtils.toInt(env.getProperty("xmpp_port", StringUtils.EMPTY), 5347)); + } + String sapeUser = env.getProperty("sape_user", StringUtils.EMPTY); + if (!Objects.equals(sapeUser, StringUtils.EMPTY)) { + templates.sape = new Sape(sapeUser, "juick.com", 2000, 3600); + } else { + logger.error("Sape is not initialized"); + } + } + + @Override + public void close() { + try { + if (xmpp != null) + xmpp.close(); + logger.error("ExternalComponent on WWW destroyed"); + } catch (Exception e) { + logger.error("exception on destroy", e); + } + } + + public void setupXmppComponent(final Jid componentJid, final String password, final int port) { + XmppSessionConfiguration configuration = XmppSessionConfiguration.builder() + .extensions(Extension.of(Message.class)) + .debugger(LogbackDebugger.class) + .build(); + xmpp = ExternalComponent.create(componentJid.toString(), password, configuration, "localhost", port); + xmpp.addConnectionListener(e -> logger.error(e.toString(), e.getCause())); + try { + xmpp.connect(); + } catch (XmppException e) { + logger.error("xmpp extension", e); + } + } + + public ExternalComponent getXmpp() { + return xmpp; + } + + + public com.juick.User getVisitorUser(HttpServletRequest request, HttpServletResponse response) { + String hash = Utils.getCookie(request, "hash"); + if (hash != null) { + com.juick.User visitor = userService.getUserByHash(hash); + if (response != null && visitor.getUid() > 0) { + response.setHeader("X-Username", visitor.getName()); + } + return visitor; + } else { + return new User(); + } + } + + public String getImgDir() { + return imgDir; + } + + public String getTmpDir() { + return tmpDir; + } + + public List<Tag> parseTags(String tagsStr) { + List<Tag> tags = new ArrayList<>(); + String tagsArr[]; + if (tagsStr != null && !tagsStr.isEmpty()) { + tagsArr = tagsStr.split("[ \\,]"); + for (int i = 0; i < tagsArr.length; i++) { + if (tagsArr[i].startsWith("*")) { + tagsArr[i] = tagsArr[i].substring(1); + } + if (tagsArr[i].length() > 64) { + tagsArr[i] = tagsArr[i].substring(0, 64); + } + } + tags = tagService.getTags(tagsArr, true); + while (tags.size() > 5) { + tags.remove(5); + } + } + return tags; + } +} diff --git a/juick-www/src/main/java/com/juick/www/XMPPPost.java b/juick-www/src/main/java/com/juick/www/XMPPPost.java deleted file mode 100644 index c2ec42d7..00000000 --- a/juick-www/src/main/java/com/juick/www/XMPPPost.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.juick.www; - -import com.juick.Tag; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import rocks.xmpp.addr.Jid; -import rocks.xmpp.core.session.XmppSession; -import rocks.xmpp.core.stanza.model.Message; -import rocks.xmpp.extensions.oob.model.x.OobX; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Created by vitalyster on 08.12.2016. - */ -public class XMPPPost { - private final static Logger logger = LoggerFactory.getLogger(XMPPPost.class); - - public void doPostMessage(JdbcTemplate sql, HttpServletRequest request, - HttpServletResponse response, XmppSession xmpp, com.juick.User visitor) - throws ServletException, IOException { - if (visitor.getUid() == 0) { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - return; - } - String body = request.getParameter("body").replace("\r", StringUtils.EMPTY); - int mid = NumberUtils.toInt(request.getParameter("mid"), 0); - int rid = NumberUtils.toInt(request.getParameter("rid"), 0); - if (mid > 0 && rid > 0) { - body = String.format("#%d/%d %s", mid, rid, body); - } else if (mid > 0) { - body = String.format("#%d %s", mid, body); - } else { - // is a post - List<Tag> tags = Utils.parseTags(sql, request.getParameter("tags")); - body = String.format("%s %s", tags.stream() - .map(t -> "*" + t.getName()).collect(Collectors.joining(" ")), body); - } - String attachmentFName; - try { - attachmentFName = Utils.receiveAttachment(request.getPart("attach"), request.getParameter("img")); - } catch (Exception e) { - logger.error("MULTIPART ERROR", e); - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - 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 (attachmentFName != null) { - String attachmentUrl = String.format("juick://%s", attachmentFName); - msg.addExtension(new OobX(new URI(attachmentUrl), "!!!!Juick!!")); - } - xmpp.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); - } -} diff --git a/juick-www/src/main/java/com/juick/www/configuration/WebAppConfiguration.java b/juick-www/src/main/java/com/juick/www/configuration/WebAppConfiguration.java new file mode 100644 index 00000000..cd681190 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/configuration/WebAppConfiguration.java @@ -0,0 +1,50 @@ +package com.juick.www.configuration; + +import com.juick.service.TagService; +import com.juick.service.UserService; +import com.juick.www.HelpService; +import com.juick.www.controllers.PageTemplates; +import com.juick.www.WebApp; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.guava.GuavaCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; + +import javax.annotation.Resource; +import javax.inject.Inject; + +/** + * Created by aalexeev on 11/22/16. + */ +@Configuration +@PropertySource("classpath:juick.conf") +@EnableCaching +public class WebAppConfiguration { + @Resource + private Environment env; + @Inject + private UserService userService; + @Inject + private TagService tagService; + + @Bean + public WebApp webApp() { + return new WebApp(env, templates(), userService, tagService); + } + @Bean + public PageTemplates templates() { + return new PageTemplates(); + } + @Bean + public GuavaCacheManager cacheManager() { + return new GuavaCacheManager("help"); + } + + @Bean + public HelpService helpService() { + return new HelpService("help"); + } + +} diff --git a/juick-www/src/main/java/com/juick/www/configuration/WwwInitializer.java b/juick-www/src/main/java/com/juick/www/configuration/WwwInitializer.java new file mode 100644 index 00000000..cd5429c2 --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/configuration/WwwInitializer.java @@ -0,0 +1,52 @@ +package com.juick.www.configuration; + +import com.juick.configuration.DataConfiguration; +import com.juick.configuration.SearchConfiguration; +import org.apache.commons.lang3.CharEncoding; +import org.springframework.web.filter.CharacterEncodingFilter; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +/** + * Created by aalexeev on 11/20/16. + */ +public class WwwInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class<?>[] getRootConfigClasses() { + return new Class<?>[]{ + WebAppConfiguration.class, + DataConfiguration.class, + SearchConfiguration.class + }; + } + + @Override + protected Class<?>[] getServletConfigClasses() { + return new Class<?>[]{WwwServletConfiguration.class}; + } + + @Override + protected String[] getServletMappings() { + return new String[]{"/"}; + } + + @Override + protected String getServletName() { + return "WWW-spring dispatcher servlet"; + } + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + super.onStartup(servletContext); + + FilterRegistration.Dynamic registration = servletContext.addFilter( + "encodingFilter", new CharacterEncodingFilter(CharEncoding.UTF_8, true)); + + registration.addMappingForUrlPatterns(null, true, "/*"); + } +} + diff --git a/juick-www/src/main/java/com/juick/www/configuration/WwwServletConfiguration.java b/juick-www/src/main/java/com/juick/www/configuration/WwwServletConfiguration.java new file mode 100644 index 00000000..c4e6c07c --- /dev/null +++ b/juick-www/src/main/java/com/juick/www/configuration/WwwServletConfiguration.java @@ -0,0 +1,99 @@ +package com.juick.www.configuration; + +import com.mitchellbosecke.pebble.PebbleEngine; +import com.mitchellbosecke.pebble.loader.Loader; +import com.mitchellbosecke.pebble.loader.ServletLoader; +import com.mitchellbosecke.pebble.spring4.PebbleViewResolver; +import com.mitchellbosecke.pebble.spring4.extension.SpringExtension; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.http.CacheControl; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import org.springframework.web.servlet.resource.PathResourceResolver; + +import javax.inject.Inject; +import javax.servlet.ServletContext; +import java.util.concurrent.TimeUnit; + +/** + * Created by vitalyster on 28.06.2016. + */ +@Configuration +@ComponentScan(basePackages = {"com.juick.www.controllers"}) +@PropertySource("classpath:juick.conf") +public class WwwServletConfiguration extends WebMvcConfigurationSupport { + @Inject + private Environment env; + + @Override + protected void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.setOrder(0); + registry.addResourceHandler( + "/scripts.js*", + "/style.css*", + "/*.png", + "/favicon.ico") + .addResourceLocations("/") + .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS)) + .resourceChain(true) + .addResolver(new PathResourceResolver()); + + registry.addResourceHandler("/static/**") + .addResourceLocations("/static/") + .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS)); + } + + @Override + public RequestMappingHandlerMapping requestMappingHandlerMapping() { + RequestMappingHandlerMapping result = super.requestMappingHandlerMapping(); + + result.setOrder(1); + + return result; + } + + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver resolver = new CommonsMultipartResolver(); + resolver.setMaxUploadSize(10000000); + return resolver; + } + + @Inject + private ServletContext servletContext; + + @Bean + public Loader templateLoader(){ + return new ServletLoader(servletContext); + } + + @Bean + public SpringExtension springExtension() { + return new SpringExtension(); + } + + @Bean + public PebbleEngine pebbleEngine() { + return new PebbleEngine.Builder() + .loader(this.templateLoader()) + .extension(springExtension()) + .build(); + } + + @Bean + public ViewResolver viewResolver() { + PebbleViewResolver viewResolver = new PebbleViewResolver(); + viewResolver.setPrefix("/WEB-INF/"); + viewResolver.setSuffix(".html"); + viewResolver.setPebbleEngine(pebbleEngine()); + return viewResolver; + } +} diff --git a/juick-www/src/main/java/com/juick/www/Discover.java b/juick-www/src/main/java/com/juick/www/controllers/Discover.java index af2b6659..e5d17501 100644 --- a/juick-www/src/main/java/com/juick/www/Discover.java +++ b/juick-www/src/main/java/com/juick/www/controllers/Discover.java @@ -15,17 +15,21 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; -import com.juick.server.AdsQueries; -import com.juick.server.MessagesQueries; -import com.juick.server.TagQueries; +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.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; -import javax.servlet.ServletException; +import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -38,18 +42,30 @@ import java.util.List; * * @author Ugnich Anton */ +@Controller public class Discover { - - protected void doGet(JdbcTemplate sql, JdbcTemplate sqlSearch, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); + @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 = TagQueries.getTag(sql, paramTagStr, false); + com.juick.Tag paramTag = tagService.getTag(paramTagStr, false); if (paramTag == null) { - Errors.doGet404(sql, request, response); + response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } else if (paramTag.SynonymID > 0 && paramTag.TID != paramTag.SynonymID) { - com.juick.Tag synTag = TagQueries.getTag(sql, 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(); @@ -77,32 +93,32 @@ public class Discover { int visitor_uid = visitor.getUid(); String title = "*" + StringEscapeUtils.escapeHtml4(paramTag.getName()); - List<Integer> mids = MessagesQueries.getTag(sql, paramTag.TID, visitor_uid, paramBefore, (visitor_uid == 0) ? 40 : 20); + List<Integer> 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 (TagQueries.getTagNoIndex(sql, paramTag.TID)) { + if (tagService.getTagNoIndex(paramTag.TID)) { head = "<meta name=\"robots\" content=\"noindex,nofollow\"/>"; } else if (paramBefore > 0 || mids.size() < 5) { head = "<meta name=\"robots\" content=\"noindex\"/>"; } - PageTemplates.pageHead(out, visitor, title, head); - PageTemplates.pageNavigation(out, visitor, null); + templates.pageHead(out, visitor, title, head); + templates.pageNavigation(out, visitor, null); out.println("<section id=\"content\">"); if (mids.size() > 0) { int vuid = visitor.getUid(); - int ad_mid = AdsQueries.getAdMID(sql, vuid); + int ad_mid = adsService.getAdMid(vuid); if (ad_mid > 0 && mids.indexOf(ad_mid) == -1) { mids.add(0, ad_mid); - AdsQueries.logAdMID(sql, vuid, ad_mid); + adsService.logAdMid(vuid, ad_mid); } else { ad_mid = 0; } - PageTemplates.printMessages(out, sql, null, mids, visitor, visitor_uid == 0 ? 2 : 3, ad_mid); + templates.printMessages(out, null, mids, visitor, visitor_uid == 0 ? 2 : 3, ad_mid); } if (mids.size() >= 20) { @@ -112,11 +128,11 @@ public class Discover { out.println("</section>"); - PageTemplates.pageHomeColumn(out, sql, visitor); + templates.pageHomeColumn(out, visitor); - PageTemplates.pageFooter(request, out, visitor, true); + templates.pageFooter(request, out, visitor, true); - PageTemplates.pageEnd(out); + templates.pageEnd(out); } } } diff --git a/juick-www/src/main/java/com/juick/www/FacebookLogin.java b/juick-www/src/main/java/com/juick/www/controllers/FacebookLogin.java index ba7ab29f..cc11f99a 100644 --- a/juick-www/src/main/java/com/juick/www/FacebookLogin.java +++ b/juick-www/src/main/java/com/juick/www/controllers/FacebookLogin.java @@ -15,25 +15,29 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; -import com.juick.server.UserQueries; +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.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; +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.servlet.ServletException; +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.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.UUID; @@ -41,6 +45,7 @@ import java.util.UUID; * * @author Ugnich Anton */ +@Controller public class FacebookLogin { private static final Logger logger = LoggerFactory.getLogger(FacebookLogin.class); @@ -50,16 +55,24 @@ public class FacebookLogin { private final String FACEBOOK_REDIRECT = "http://juick.com/_fblogin"; private final ObjectMapper mapper; - public FacebookLogin(String ApplicationID, String secret) { - this.FACEBOOK_APPID = ApplicationID; - this.FACEBOOK_SECRET = secret; + @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); } - protected void doGet(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @RequestMapping(value = "/_fblogin", method = RequestMethod.GET) + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { String fbstate; String code = request.getParameter("code"); @@ -111,19 +124,19 @@ public class FacebookLogin { throw new Exception(); } - int uid = getUIDbyFBID(sql, fbID); + int uid = crosspostService.getUIDbyFBID(fbID); if (uid > 0) { - if (!updateDB(sql, fbID, token, fb.getName(), fb.getLink())) { + if (!crosspostService.updateFacebookUser(fbID, token, fb.getName(), fb.getLink())) { throw new Exception(); } - Cookie c = new Cookie("hash", UserQueries.getHashByUID(sql, uid)); + 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 (!insertDB(sql, fbID, loginhash, token, fb.getName(), fb.getLink())) { + if (!crosspostService.createFacebookUser(fbID, loginhash, token, fb.getName(), fb.getLink())) { throw new Exception(); } response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); @@ -137,23 +150,4 @@ public class FacebookLogin { return; } } - - private int getUIDbyFBID(JdbcTemplate sql, long fbID) { - try { - return sql.queryForObject("SELECT user_id FROM facebook WHERE fb_id=? AND user_id IS NOT NULL", - Integer.class, fbID); - } catch (EmptyResultDataAccessException e) { - return 0; - } - } - - private boolean insertDB(JdbcTemplate sql, long fbID, String loginhash, String token, String fbName, String fbLink) { - return sql.update("INSERT INTO facebook(fb_id,loginhash,access_token,fb_name,fb_link) VALUES (?,?,?,?,?)", - fbID, loginhash, token, fbName, fbLink) > 0; - } - - private boolean updateDB(JdbcTemplate sql, long fbID, String token, String fbName, String fbLink) { - return sql.update("UPDATE facebook SET access_token=?,fb_name=?,fb_link=? WHERE fb_id=?", - token, fbName, fbLink, fbID) > 0; - } } 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<String> langParam, + @PathVariable("page") Optional<String> pageParam, + @PathVariable("langOrPage") Optional<String> 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/Home.java b/juick-www/src/main/java/com/juick/www/controllers/Home.java index 1d4fd521..2f9dc903 100644 --- a/juick-www/src/main/java/com/juick/www/Home.java +++ b/juick-www/src/main/java/com/juick/www/controllers/Home.java @@ -15,17 +15,25 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; - -import com.juick.server.AdsQueries; -import com.juick.server.MessagesQueries; +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.jdbc.core.JdbcTemplate; +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.servlet.ServletException; +import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -37,9 +45,62 @@ 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; + } + } - protected void doGet(JdbcTemplate sql, JdbcTemplate sqlSearch, HttpServletRequest request, HttpServletResponse response, com.juick.User visitor) throws ServletException, IOException { + @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"); @@ -53,14 +114,14 @@ public class Home { String paramShow = request.getParameter("show"); if (paramSearch != null) { title = "Поиск: " + StringEscapeUtils.escapeHtml4(paramSearch); - mids = MessagesQueries.getSearch(sql, sqlSearch, Utils.encodeSphinx(paramSearch), paramBefore); + mids = messagesService.getSearch(Utils.encodeSphinx(paramSearch), paramBefore); } else if (paramShow == null) { if (visitor.getUid() > 0) { title = "Популярные"; - mids = MessagesQueries.getPopular(sql, visitor.getUid(), paramBefore); + mids = messagesService.getPopular(visitor.getUid(), paramBefore); } else { title = "Микроблоги Juick: популярные записи"; - mids = MessagesQueries.getPopular(sql, 0, paramBefore); + mids = messagesService.getPopular(0, paramBefore); } } else if (paramShow.equals("top")) { @@ -68,32 +129,32 @@ public class Home { return; } else if (paramShow.equals("my") && visitor != null) { title = "Моя лента"; - mids = MessagesQueries.getMyFeed(sql, visitor.getUid(), paramBefore); + mids = messagesService.getMyFeed(visitor.getUid(), paramBefore); } else if (paramShow.equals("private") && visitor != null) { title = "Приватные"; - mids = MessagesQueries.getPrivate(sql, visitor.getUid(), paramBefore); + mids = messagesService.getPrivate(visitor.getUid(), paramBefore); } else if (paramShow.equals("discuss") && visitor != null) { title = "Обсуждения"; - mids = MessagesQueries.getDiscussions(sql, visitor.getUid(), paramBefore); + mids = messagesService.getDiscussions(visitor.getUid(), paramBefore); } else if (paramShow.equals("recommended") && visitor != null) { title = "Рекомендации"; - mids = MessagesQueries.getRecommended(sql, visitor.getUid(), paramBefore); + mids = messagesService.getRecommended(visitor.getUid(), paramBefore); } else if (paramShow.equals("photos")) { title = "Фотографии"; if (visitor != null) { - mids = MessagesQueries.getPhotos(sql, visitor.getUid(), paramBefore); + mids = messagesService.getPhotos(visitor.getUid(), paramBefore); } else { - mids = MessagesQueries.getPhotos(sql, 0, paramBefore); + mids = messagesService.getPhotos(0, paramBefore); } } else if (paramShow.equals("all")) { title = "Все сообщения"; if (visitor != null) { - mids = MessagesQueries.getAll(sql, visitor.getUid(), paramBefore); + mids = messagesService.getAll(visitor.getUid(), paramBefore); } else { - mids = MessagesQueries.getAll(sql, 0, paramBefore); + mids = messagesService.getAll(0, paramBefore); } } else { - Errors.doGet404(sql, request, response); + response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } @@ -103,8 +164,8 @@ public class Home { if (paramBefore > 0 || paramShow != null) { head = "<meta name=\"robots\" content=\"noindex\"/>"; } - PageTemplates.pageHead(out, visitor, title, head); - PageTemplates.pageNavigation(out, visitor, paramSearch); + templates.pageHead(out, visitor, title, head); + templates.pageNavigation(out, visitor, paramSearch); out.println("<section id=\"content\">"); @@ -132,16 +193,16 @@ public class Home { int ad_mid = 0; if (paramShow == null || paramShow.equals("top") || paramShow.equals("all")) { int vuid = visitor.getUid(); - ad_mid = AdsQueries.getAdMID(sql, vuid); + ad_mid = adsService.getAdMid(vuid); if (ad_mid > 0 && mids.indexOf(ad_mid) == -1) { mids.add(0, ad_mid); - AdsQueries.logAdMID(sql, vuid, ad_mid); + adsService.logAdMid(vuid, ad_mid); } else { ad_mid = 0; } } - PageTemplates.printMessages(out, sql, null, mids, visitor, visitor.getUid() == 0 ? 2 : 3, ad_mid); + templates.printMessages(out, null, mids, visitor, visitor.getUid() == 0 ? 2 : 3, ad_mid); } if (mids.size() >= 20) { @@ -162,10 +223,10 @@ public class Home { out.println("</section>"); - PageTemplates.pageHomeColumn(out, sql, visitor, paramShow == null && paramBefore == 0 && paramSearch == null && visitor.getUid() == 0); + templates.pageHomeColumn(out, visitor, paramShow == null && paramBefore == 0 && paramSearch == null && visitor.getUid() == 0); - PageTemplates.pageFooter(request, out, visitor, true); - PageTemplates.pageEnd(out); + templates.pageFooter(request, out, visitor, true); + templates.pageEnd(out); } } } diff --git a/juick-www/src/main/java/com/juick/www/Login.java b/juick-www/src/main/java/com/juick/www/controllers/Login.java index 27f34c1c..bce3e000 100644 --- a/juick-www/src/main/java/com/juick/www/Login.java +++ b/juick-www/src/main/java/com/juick/www/controllers/Login.java @@ -15,25 +15,52 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; -import org.springframework.jdbc.core.JdbcTemplate; +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 java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; +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; + } - protected void doGetLoginForm(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); + 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; @@ -183,24 +210,8 @@ public class Login { } } - protected void doGetLogin(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String hash = request.getQueryString(); - if (hash.length() > 32) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - if (com.juick.server.UserQueries.getUIDbyHash(sql, 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); - } - } - - protected void doPostLogin(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @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()) { @@ -208,9 +219,9 @@ public class Login { return; } - int uid = com.juick.server.UserQueries.checkPassword(sql, username, password); + int uid = userService.checkPassword(username, password); if (uid > 0) { - String hash = com.juick.server.UserQueries.getHashByUID(sql, uid); + String hash = userService.getHashByUID(uid); Cookie c = new Cookie("hash", hash); c.setMaxAge(365 * 24 * 60 * 60); response.addCookie(c); @@ -226,10 +237,11 @@ public class Login { } } - protected void doGetLogout(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); + @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) { - sql.update("DELETE FROM logins WHERE user_id=?", visitor.getUid()); + userService.logout(visitor.getUid()); } Cookie c = new Cookie("hash", "-"); diff --git a/juick-www/src/main/java/com/juick/www/NewMessage.java b/juick-www/src/main/java/com/juick/www/controllers/NewMessage.java index 43ea039c..dacd54a3 100644 --- a/juick-www/src/main/java/com/juick/www/NewMessage.java +++ b/juick-www/src/main/java/com/juick/www/controllers/NewMessage.java @@ -15,11 +15,15 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; import com.juick.Tag; -import com.juick.server.*; 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; @@ -27,14 +31,18 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; +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.session.XmppSession; import rocks.xmpp.core.stanza.model.Message; import rocks.xmpp.extensions.nick.model.Nickname; import rocks.xmpp.extensions.oob.model.x.OobX; -import javax.servlet.ServletException; +import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -52,26 +60,42 @@ import java.util.List; /** * @author Ugnich Anton */ +@Controller public class NewMessage { - private static final Logger logger = LoggerFactory.getLogger(NewMessage.class); - - private String tmpDir, imgDir; + @Inject + Environment env; + @Inject + TagService tagService; + @Inject + MessagesService messagesService; + @Inject + UserService userService; + @Inject + SubscriptionService subscriptionService; + @Inject + CrosspostService crosspostService; + @Inject + WebApp webApp; + @Inject + PageTemplates templates; - public NewMessage(String tmpDir, String imgDir) { - this.tmpDir = tmpDir; - this.imgDir = imgDir; - } + private static final Logger logger = LoggerFactory.getLogger(NewMessage.class); - protected void doGetNewMessage(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, - com.juick.User visitor) throws ServletException, IOException { + @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()) { - PageTemplates.pageHead(out, visitor, "Написать", "<script src=\"//maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAVVtPtxkw4soCEHg44FsNChRB4OFYjAXt73He16Zkp6a_0tPs2RTU6i6UlcMs4QvPBYvIY8rWvcxqOg\" type=\"text/javascript\"></script>" + templates.pageHead(out, visitor, "Написать", "<script src=\"//maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAVVtPtxkw4soCEHg44FsNChRB4OFYjAXt73He16Zkp6a_0tPs2RTU6i6UlcMs4QvPBYvIY8rWvcxqOg\" type=\"text/javascript\"></script>" + "<script src=\"//static.juick.com/mc.js\" type=\"text/javascript\" defer=\"defer\"></script>" + "<script src=\"//static.juick.com/maps.js?2010111500\" type=\"text/javascript\" defer=\"defer\"></script>" + "<script src=\"//static.juick.com/post3.js\" type=\"text/javascript\" defer=\"defer\"></script>"); - PageTemplates.pageNavigation(out, visitor, null); + templates.pageNavigation(out, visitor, null); out.println("<section id=\"content\" class=\"pagetext\">"); out.println("<form action=\"/post2\" method=\"post\" id=\"postmsg\" enctype=\"multipart/form-data\">"); @@ -93,16 +117,16 @@ public class NewMessage { out.println("</form>"); out.println("<div id=\"geomap\"></div>"); out.println("<p style=\"text-align: left\"><b>Теги:</b></p>"); - printUserTags(sql, out, visitor); + printUserTags(out, visitor); out.println("</section>"); - PageTemplates.pageFooter(request, out, visitor, false); - PageTemplates.pageEnd(out); + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); } } - void printUserTags(JdbcTemplate sql, PrintWriter out, com.juick.User visitor) { - List<TagStats> tags = TagQueries.getTagsStats(sql, visitor.getUid()); + void printUserTags(PrintWriter out, com.juick.User visitor) { + List<TagStats> tags = tagService.getUserTagStats(visitor.getUid()); if (tags.isEmpty()) { return; @@ -149,7 +173,15 @@ public class NewMessage { out.println("</p>"); } - public void doPostMessage(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, XmppSession xmpp, com.juick.User visitor) throws ServletException, IOException { + @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); @@ -157,41 +189,44 @@ public class NewMessage { } body = body.replace("\r", StringUtils.EMPTY); - List<Tag> tags = Utils.parseTags(sql, request.getParameter("tags")); + List<Tag> tags = webApp.parseTags(request.getParameter("tags")); - String attachmentFName; - try { - attachmentFName = Utils.receiveAttachment(request.getPart("attach"), request.getParameter("img")); - } catch (Exception e) { - logger.error("MULTIPART ERROR", e); - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - 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 = attachmentFName != null ? attachmentFName.substring(attachmentFName.length() - 3) : null; - int mid = MessagesQueries.createMessage(sql, visitor.getUid(), body, attachmentType, tags); - SubscriptionsQueries.subscribeMessage(sql, mid, visitor.getUid()); + 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 = MessagesQueries.getMessage(sql, mid); + com.juick.Message jmsg = messagesService.getMessage(mid); xmsg.addExtension(jmsg); xmsg.addExtension(new Nickname("@" + jmsg.getUser().getName())); - if (attachmentFName != null) { + if (StringUtils.isNotEmpty(attachmentFName)) { String fname = mid + "." + attachmentType; String attachmentURL = "http://i.juick.com/photos-1024/" + fname; - Path origName = Paths.get(imgDir, "p", fname); - Files.move(Paths.get(tmpDir, attachmentFName), origName); + 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(imgDir, "photos-1024", fname).toFile()); + .toFile(Paths.get(webApp.getImgDir(), "photos-1024", fname).toFile()); Thumbnails.of(origName.toFile()).size(512, 512).outputQuality(0.9) - .toFile(Paths.get(imgDir, "photos-512", fname).toFile()); + .toFile(Paths.get(webApp.getImgDir(), "photos-512", fname).toFile()); Thumbnails.of(origName.toFile()).size(160, 120).outputQuality(0.9) - .toFile(Paths.get(imgDir, "ps", fname).toFile()); + .toFile(Paths.get(webApp.getImgDir(), "ps", fname).toFile()); body = attachmentURL + "\n" + body; try { @@ -200,26 +235,26 @@ public class NewMessage { logger.warn("invalid uri: {} exception {}", attachmentURL, e); } } - if (xmpp != null) { + 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")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("juick@ws.juick.com")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("juick@push.juick.com")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("twitter@crosspost.juick.com")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("fb@crosspost.juick.com")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("jubo@nologin.ru")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); } else { logger.warn("XMPP unavailable"); } @@ -228,8 +263,8 @@ public class NewMessage { response.setContentType("text/html; charset=UTF-8"); try (PrintWriter out = response.getWriter()) { - PageTemplates.pageHead(out, visitor, "Сообщение опубликовано", null); - PageTemplates.pageNavigation(out, visitor, null); + templates.pageHead(out, visitor, "Сообщение опубликовано", null); + templates.pageNavigation(out, visitor, null); String hashtags = StringUtils.EMPTY; String tagscomma = StringUtils.EMPTY; @@ -253,32 +288,40 @@ public class NewMessage { out.println("<section id=\"content\">"); out.println("<h1>Сообщение опубликовано</h1>"); out.println("<p>Поделитесь своим новым постом в социальных сетях:</p>"); - if (CrosspostQueries.getTwitterTokens(sql, visitor.getUid()).isPresent()) { + if (crosspostService.getTwitterTokens(visitor.getUid()).isPresent()) { out.println("<p class=\"social\"><a href=\"https://twitter.com/intent/tweet?text=" + URLEncoder.encode(sharetwi, CharEncoding.UTF_8) + "\" class=\"ico32-twi sharenew\">Отправить в Twitter</a></p>"); } out.println("<p class=\"social\"><a href=\"http://www.livejournal.com/update.bml?subject=" + URLEncoder.encode(hashtags, CharEncoding.UTF_8) + "&event=" + sharelj + "&prop_taglist=" + URLEncoder.encode(tagscomma, CharEncoding.UTF_8) + "\" target=\"_blank\" class=\"ico32-lj sharenew\">Отправить в LiveJournal</a></p>"); out.println("<p class=\"social\"><a href=\"https://vk.com/share.php?url=" + url + "\" class=\"ico32-vk sharenew\">Отправить в ВКонтакте</a></p>"); - if (CrosspostQueries.getFacebookToken(sql, visitor.getUid()).isPresent()) { + if (crosspostService.getFacebookToken(visitor.getUid()).isPresent()) { out.println("<p class=\"social\"><a href=\"https://www.facebook.com/sharer/sharer.php?u=" + url + "\" class=\"ico32-fb sharenew\">Отправить в Facebook</a></p>"); } out.println("<p class=\"social\"><a href=\"https://plus.google.com/share?url=" + url + "\" class=\"ico32-gp sharenew\">Отправить в Google+</a></p>"); out.println("<p>Ссылка на сообщение: <a href=\"http://juick.com/" + mid + "\">http://juick.com/" + mid + "</a></p>"); out.println("</section>"); - PageTemplates.pageHomeColumn(out, sql, visitor); + templates.pageHomeColumn(out, visitor); - PageTemplates.pageFooter(request, out, visitor, false); - PageTemplates.pageEnd(out); + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); } } - public void doPostComment(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, XmppSession xmpp, com.juick.User visitor) throws ServletException, IOException { + @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 = MessagesQueries.getMessage(sql, mid); + com.juick.Message msg = messagesService.getMessage(mid); if (msg == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; @@ -287,7 +330,7 @@ public class NewMessage { int rid = NumberUtils.toInt(request.getParameter("rid"), 0); com.juick.Message reply = null; if (rid > 0) { - reply = MessagesQueries.getReply(sql, mid, rid); + reply = messagesService.getReply(mid, rid); if (reply == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; @@ -301,41 +344,35 @@ public class NewMessage { } body = body.replace("\r", StringUtils.EMPTY); - if ((msg.ReadOnly && msg.getUser().getUid() != visitor.getUid()) || UserQueries.isInBLAny(sql, msg.getUser().getUid(), visitor.getUid()) || (reply != null && UserQueries.isInBLAny(sql, reply.getUser().getUid(), visitor.getUid()))) { + 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 = null; - try { - attachmentFName = Utils.receiveMultiPartFile(request.getPart("attach")); - } catch (Exception e) { - logger.error("MULTIPART ERROR", e); - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } + String attachmentFName = HttpUtils.receiveMultiPartFile(attach, webApp.getTmpDir()); - String paramImg = request.getParameter("img"); - if (attachmentFName == null && paramImg != null && paramImg.length() > 10) { + if (StringUtils.isBlank(attachmentFName) && img != null && img.length() > 10) { try { - attachmentFName = Utils.downloadImage(new URL(paramImg)); + URL imgUrl = new URL(img); + attachmentFName = HttpUtils.downloadImage(imgUrl); } catch (Exception e) { logger.error("DOWNLOAD ERROR", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; + throw new HttpBadRequestException(); } } - String attachmentType = attachmentFName != null ? attachmentFName.substring(attachmentFName.length() - 3) : null; - int ridnew = MessagesQueries.createReply(sql, mid, rid, visitor.getUid(), body, attachmentType); - SubscriptionsQueries.subscribeMessage(sql, mid, visitor.getUid()); + 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 = MessagesQueries.getReply(sql, mid, ridnew); + com.juick.Message jmsg = messagesService.getReply(mid, ridnew); xmsg.addExtension(jmsg); String quote = reply != null ? reply.getText() : msg.getText(); @@ -344,18 +381,18 @@ public class NewMessage { } xmsg.addExtension(new Nickname("@" + jmsg.getUser().getName())); - if (attachmentFName != null) { + if (StringUtils.isNotEmpty(attachmentFName)) { String fname = mid + "-" + ridnew + "." + attachmentType; String attachmentURL = "http://i.juick.com/photos-1024/" + fname; - Path origName = Paths.get(imgDir, "p", fname); - Files.move(Paths.get(tmpDir, attachmentFName), origName); + 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(imgDir, "photos-1024", fname).toFile()); + .toFile(Paths.get(webApp.getImgDir(), "photos-1024", fname).toFile()); Thumbnails.of(origName.toFile()).size(512, 512).outputQuality(0.9) - .toFile(Paths.get(imgDir, "photos-512", fname).toFile()); + .toFile(Paths.get(webApp.getImgDir(), "photos-512", fname).toFile()); Thumbnails.of(origName.toFile()).size(160, 120).outputQuality(0.9) - .toFile(Paths.get(imgDir, "ps", fname).toFile()); + .toFile(Paths.get(webApp.getImgDir(), "ps", fname).toFile()); body = attachmentURL + "\n" + body; try { @@ -365,19 +402,19 @@ public class NewMessage { } } - if (xmpp != null) { + 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")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("juick@ws.juick.com")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); xmsg.setTo(Jid.of("juick@push.juick.com")); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); } else { logger.warn("XMPP unavailable"); } @@ -385,13 +422,19 @@ public class NewMessage { Utils.sendTemporaryRedirect(response, "/" + msg.getUser().getName() + "/" + mid + "#" + ridnew); } - public void doPostRecomm(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, XmppSession xmpp, com.juick.User visitor) throws ServletException, IOException { + @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 = MessagesQueries.getMessage(sql, mid); + com.juick.Message msg = messagesService.getMessage(mid); if (msg == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; @@ -401,10 +444,10 @@ public class NewMessage { return; } - boolean res = MessagesQueries.recommendMessage(sql, mid, visitor.getUid()); + boolean res = messagesService.recommendMessage(mid, visitor.getUid()); if (res) { - if (xmpp != null) { + if (webApp.getXmpp() != null) { Message xmsg = new Message(); xmsg.setFrom(Jid.of("juick@juick.com")); xmsg.setTo(Jid.of("recomm@s2s.juick.com")); @@ -412,7 +455,7 @@ public class NewMessage { jmsg.setMid(mid); jmsg.setUser(visitor); xmsg.addExtension(jmsg); - xmpp.send(xmsg); + webApp.getXmpp().send(xmsg); } else { logger.warn("XMPP unavailable"); } diff --git a/juick-www/src/main/java/com/juick/www/PM.java b/juick-www/src/main/java/com/juick/www/controllers/PM.java index d0aa26e9..56b688cf 100644 --- a/juick-www/src/main/java/com/juick/www/PM.java +++ b/juick-www/src/main/java/com/juick/www/controllers/PM.java @@ -15,87 +15,100 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; -import com.juick.server.PMQueries; -import com.juick.server.TagQueries; -import com.juick.server.UserQueries; +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.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; +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.jdbc.core.JdbcTemplate; +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.session.XmppSession; import rocks.xmpp.core.stanza.model.Message; -import javax.servlet.ServletException; +import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * * @author Ugnich Anton */ +@Controller public class PM { private static final Logger logger = LoggerFactory.getLogger(PM.class); - protected void doGetInbox(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, com.juick.User visitor) throws ServletException, IOException, PebbleException { - + @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<com.juick.Message> msgs = PMQueries.getLastPMInbox(sql, visitor.getUid()); + List<com.juick.Message> msgs = pmQueriesService.getLastPMInbox(visitor.getUid()); msgs.forEach(m -> m.setText(MessageUtils.formatMessage(m.getText()))); - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("views/pm_inbox.html"); - Map<String, Object> context = new HashMap<>(); - context.put("title", title); - context.put("visitor", visitor); - context.put("msgs", msgs); - context.put("tags", TagQueries.getPopularTags(sql)); - template.evaluate(out, context); - } + model.addAttribute("title", title); + model.addAttribute("visitor", visitor); + model.addAttribute("msgs", msgs); + model.addAttribute("tags", tagService.getPopularTags()); + return "views/pm_inbox"; } - protected void doGetSent(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, com.juick.User visitor) throws ServletException, IOException, PebbleException { - + @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<com.juick.Message> msgs = PMQueries.getLastPMSent(sql, visitor.getUid()); + List<com.juick.Message> msgs = pmQueriesService.getLastPMSent(visitor.getUid()); String uname = request.getParameter("uname"); if (WebUtils.isNotUserName(uname)) { uname = StringUtils.EMPTY; } - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("views/pm_sent.html"); - Map<String, Object> context = new HashMap<>(); - context.put("title", title); - context.put("visitor", visitor); - context.put("msgs", msgs); - context.put("tags", TagQueries.getPopularTags(sql)); - context.put("uname", uname); - template.evaluate(out, context); - } + 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"; } - public void doPostPM(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, XmppSession xmpp, com.juick.User visitor) throws ServletException, IOException { + @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 = UserQueries.getUIDbyName(sql, uname); + uid = userService.getUIDbyName(uname); } String body = request.getParameter("body"); @@ -104,13 +117,13 @@ public class PM { return; } - if (UserQueries.isInBLAny(sql, uid, visitor.getUid())) { + if (userService.isInBLAny(uid, visitor.getUid())) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } - if (PMQueries.createPM(sql, visitor.getUid(), uid, body)) { - if (xmpp != null) { + 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))); @@ -118,24 +131,24 @@ public class PM { jmsg.setUser(visitor); jmsg.setText(body); msg.addExtension(jmsg); - xmpp.send(msg); + webApp.getXmpp().send(msg); msg.setTo(Jid.of(String.format("%d@ws.juick.com", uid))); - xmpp.send(msg); + webApp.getXmpp().send(msg); - List<String> jids = UserQueries.getJIDsbyUID(sql, uid); + List<String> jids = userService.getJIDsbyUID(uid); for (String jid : jids) { Message mm = new Message(); mm.setTo(Jid.of(jid)); mm.setType(Message.Type.CHAT); - if (PMQueries.havePMinRoster(sql, visitor.getUid(), jid)) { + 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); } - xmpp.send(mm); + webApp.getXmpp().send(mm); } } else { logger.warn("XMPP unavailable"); diff --git a/juick-www/src/main/java/com/juick/www/PageTemplates.java b/juick-www/src/main/java/com/juick/www/controllers/PageTemplates.java index 4a625acc..3152d5fc 100644 --- a/juick-www/src/main/java/com/juick/www/PageTemplates.java +++ b/juick-www/src/main/java/com/juick/www/controllers/PageTemplates.java @@ -15,22 +15,22 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; import com.juick.Message; -import com.juick.server.MessagesQueries; -import com.juick.server.TagQueries; -import com.juick.server.UserQueries; 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.jdbc.core.JdbcTemplate; 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; @@ -49,13 +49,20 @@ public class PageTemplates { private static final Logger logger = LoggerFactory.getLogger(PageTemplates.class); - public static Sape sape = null; + 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; - public static void pageHead(PrintWriter out, com.juick.User visitor, String title, String headers) { + @Inject + TagService tagService; + @Inject + MessagesService messagesService; + @Inject + UserService userService; + + public void pageHead(PrintWriter out, com.juick.User visitor, String title, String headers) { out.println("<!DOCTYPE html>"); out.print("<html>"); out.print("<head>"); @@ -80,7 +87,7 @@ public class PageTemplates { } } - public static void pageNavigation(PrintWriter out, com.juick.User visitor, String search) { + public void pageNavigation(PrintWriter out, com.juick.User visitor, String search) { out.println("<header>"); out.println(" <div id=\"logo\"><a href=\"/\">Juick</a></div>"); out.print(" <nav id=\"global\"><ul>"); @@ -113,13 +120,13 @@ public class PageTemplates { out.println("</header>"); } - public static void pageHomeColumn(PrintWriter out, JdbcTemplate sql, com.juick.User visitor) { - pageHomeColumn(out, sql, visitor, false); + public void pageHomeColumn(PrintWriter out, com.juick.User visitor) { + pageHomeColumn(out, visitor, false); } - public static void pageHomeColumn(PrintWriter out, JdbcTemplate sql, com.juick.User visitor, boolean showAdv) { + public void pageHomeColumn(PrintWriter out, com.juick.User visitor, boolean showAdv) { if (tagsHTML == null) { - tagsHTML = PageTemplates.formatPopularTags(sql, 80); + tagsHTML = formatPopularTags(80); } out.println("<aside id=\"column\">"); @@ -134,13 +141,13 @@ public class PageTemplates { out.println("</aside>"); } - public static String formatPopularTags(JdbcTemplate sql, int cnt) { - List<String> popularTags = TagQueries.getPopularTags(sql).stream() + public String formatPopularTags(int cnt) { + List<String> popularTags = tagService.getPopularTags().stream() .map(t -> "<a href=\"/tag/" + URLEncoder.encode(t) + "\">" + StringEscapeUtils.escapeHtml4(t) + "</a>").collect(Collectors.toList()); return StringUtils.collectionToDelimitedString(popularTags, " "); } - public static void pageFooter(HttpServletRequest request, PrintWriter out, com.juick.User visitor, boolean sapeon) { + public void pageFooter(HttpServletRequest request, PrintWriter out, com.juick.User visitor, boolean sapeon) { out.println("<div id=\"footer\">"); out.println(" <div id=\"footer-right\"><a href=\"/settings\" rel=\"nofollow\">Настройки</a> · <a href=\"/help/ru/contacts\" rel=\"nofollow\">Контакты</a> · <a href=\"/help/\" rel=\"nofollow\">Справка</a> · <a href=\"/help/ru/adv\" rel=\"nofollow\">Реклама</a></div>"); out.print(" <div id=\"footer-social\">"); @@ -182,11 +189,11 @@ public class PageTemplates { out.println("</script>"); } - public static void pageEnd(PrintWriter out) { + public void pageEnd(PrintWriter out) { out.println("</body></html>"); } - public static String formatTags(List<TagStats> tags) { + public String formatTags(List<TagStats> tags) { String ret = org.apache.commons.lang3.StringUtils.EMPTY; for (TagStats tag : tags) { String tagName = StringEscapeUtils.escapeHtml4(tag.getTag().getName()); @@ -203,7 +210,7 @@ public class PageTemplates { return ret; } - public static String formatDate(int minutes, Date fulldate) { + public String formatDate(int minutes, Date fulldate) { if (minutes < 1) { return "сейчас"; } else if (minutes < 60) { @@ -261,14 +268,14 @@ public class PageTemplates { } } - public static String formatJSLocalTime(Date ts) { + public String formatJSLocalTime(Date ts) { return "<script type=\"text/javascript\">" + "var d=new Date(" + ts.getTime() + ");" + "document.write((d.getDate()<10?'0':'')+d.getDate()+'.'+(d.getMonth()<9?'0':'')+(d.getMonth()+1)+'.'+d.getFullYear()+' '+(d.getHours()<10?'0':'')+d.getHours()+':'+(d.getMinutes()<10?'0':'')+d.getMinutes());" + "</script>"; } - public static String formatReplies(int replies) { + public String formatReplies(int replies) { int ld = replies % 10; int lh = replies % 100; if ((lh < 10 || lh > 20) && ld == 1) { @@ -280,8 +287,8 @@ public class PageTemplates { } } - public static void printMessages(PrintWriter out, JdbcTemplate sql, com.juick.User user, List<Integer> mids, com.juick.User visitor, int YandexID, int ad_mid) { - List<com.juick.Message> msgs = MessagesQueries.getMessages(sql, mids); + public void printMessages(PrintWriter out, com.juick.User user, List<Integer> mids, com.juick.User visitor, int YandexID, int ad_mid) { + List<com.juick.Message> msgs = messagesService.getMessages(mids); for (int i = 0; i < msgs.size(); i++) { com.juick.Message msg = msgs.get(i); @@ -297,12 +304,12 @@ public class PageTemplates { for (Message msg : msgs) { blUIDs.add(msg.getUser().getUid()); } - blUIDs = UserQueries.checkBL(sql, visitor.getUid(), blUIDs); + blUIDs = userService.checkBL(visitor.getUid(), blUIDs); } for (Message msg : msgs) { - List<TagStats> tags = MessagesQueries.getMessageTags(sql, msg.getMid()); + List<TagStats> tags = tagService.getMessageTags(msg.getMid()); String tagsStr = formatTags(tags); if (msg.ReadOnly) { tagsStr += "<a>readonly</a>"; 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 <http://www.gnu.org/licenses/>. + */ +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<Integer> mids = messagesService.getUserBlog(uid, 0, 0); + if (mids.isEmpty()) { + throw new HttpNotFoundException(); + } + + List<Message> 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/Settings.java b/juick-www/src/main/java/com/juick/www/controllers/Settings.java index 1b2a6c8d..63cf99e6 100644 --- a/juick-www/src/main/java/com/juick/www/Settings.java +++ b/juick-www/src/main/java/com/juick/www/controllers/Settings.java @@ -15,25 +15,29 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; -import com.juick.server.CrosspostQueries; -import com.juick.server.SubscriptionsQueries; -import com.juick.server.TagQueries; -import com.juick.server.UserQueries; 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.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; +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.jdbc.core.JdbcTemplate; +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; @@ -45,15 +49,12 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.io.PrintWriter; import java.nio.file.Files; -import java.nio.file.StandardCopyOption; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -61,16 +62,28 @@ import java.util.stream.IntStream; * * @author Ugnich Anton */ +@Controller public class Settings { private static final Logger logger = LoggerFactory.getLogger(Settings.class); - private final String imgPath; - public Settings(String avatarsPath) { - this.imgPath = avatarsPath; - } + @Inject + WebApp webApp; + @Inject + TagService tagService; + @Inject + UserService userService; + @Inject + CrosspostService crosspostService; + @Inject + SubscriptionService subscriptionService; + @Inject + EmailService emailService; + @Inject + TelegramService telegramService; - protected void doGet(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, PebbleException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); + @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"); } @@ -80,61 +93,55 @@ public class Settings { page = "main"; } - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate(String.format("views/settings_%s.html", page)); - Map<String, Object> context = new HashMap<>(); - context.put("title", "Настройки"); - context.put("visitor", visitor); - context.put("tags", TagQueries.getPopularTags(sql)); - context.put("auths", UserQueries.getAuthCodes(sql, visitor)); - context.put("eopts", UserQueries.getEmailOpts(sql, visitor)); - context.put("ehash", UserQueries.getEmailHash(sql, visitor)); - context.put("emails", UserQueries.getEmails(sql, visitor)); - context.put("jids", UserQueries.getAllJIDs(sql, visitor)); - List<String> hours = IntStream.rangeClosed(0, 23).boxed() - .map(i -> StringUtils.leftPad(String.format("%d", i), 2, "0")).collect(Collectors.toList()); - context.put("hours", hours); - context.put("fbstatus", CrosspostQueries.isFBCrossPostEnabled(sql, visitor.getUid())); - context.put("twitter_name", CrosspostQueries.getTwitterName(sql, visitor.getUid())); - context.put("telegram_name", CrosspostQueries.getTelegramName(sql, visitor.getUid())); - context.put("notify_options", SubscriptionsQueries.getNotifyOptions(sql, visitor)); - context.put("userinfo", UserQueries.getUserInfo(sql, visitor)); - if (page.equals("auth-email")) { - try { - String account = sql.queryForObject("SELECT account FROM auth WHERE user_id=? AND protocol='email' AND authcode=?", - String.class, visitor.getUid(), request.getParameter("code")); - sql.update("INSERT INTO emails(user_id,email) VALUES (?,?)", visitor.getUid(), account); - sql.update("DELETE FROM auth WHERE user_id=? AND authcode=?", visitor.getUid(), request.getParameter("code")); - context.put("result", "OK!"); - } catch (EmptyResultDataAccessException e) { - context.put("result", "Sorry, code unknown."); - } + 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<String> 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."); } - template.evaluate(out, context); } + return String.format("views/settings_%s", page); } - protected void doPost(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, PebbleException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); + @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) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; + throw new HttpBadRequestException(); } List<String> 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)) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; + throw new HttpBadRequestException(); } String result = StringUtils.EMPTY; switch (page) { case "password": - if (UserQueries.updatePassword(sql, visitor, request.getParameter("password"))) { + if (userService.updatePassword(visitor, request.getParameter("password"))) { result = "<p>Password has been changed.</p>"; - String hash = com.juick.server.UserQueries.getHashByUID(sql, visitor.getUid()); + String hash = userService.getHashByUID(visitor.getUid()); Cookie c = new Cookie("hash", hash); c.setMaxAge(365 * 24 * 60 * 60); response.addCookie(c); @@ -145,7 +152,7 @@ public class Settings { opts.setRepliesEnabled(StringUtils.isNotEmpty(request.getParameter("jnotify"))); opts.setSubscriptionsEnabled(StringUtils.isNotEmpty(request.getParameter("subscr_notify"))); opts.setRecommendationsEnabled(StringUtils.isNotEmpty(request.getParameter("recomm"))); - if (SubscriptionsQueries.setNotifyOptions(sql, visitor, opts)) { + if (subscriptionService.setNotifyOptions(visitor, opts)) { result = "<p>Notification options has been updated</p>"; } break; @@ -155,54 +162,52 @@ public class Settings { info.setCountry(request.getParameter("country")); info.setUrl(request.getParameter("url")); info.setDescription(request.getParameter("descr")); - String avatarTmpPath = Utils.receiveMultiPartFile(request.getPart("avatar")); + 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(imgPath, "ao", originalName); - Path a = Paths.get(imgPath, "a", targetName); - Path as = Paths.get(imgPath, "as", targetName); - Files.move(Paths.get(Utils.getTmpDir(), avatarTmpPath), ao, StandardCopyOption.REPLACE_EXISTING); + 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 (UserQueries.updateUserInfo(sql, visitor, info)) { + if (userService.updateUserInfo(visitor, info)) { result = String.format("<p>Your info is updated.</p><p><a href='/%s/'>Back to blog</a>.</p>", visitor.getName()); } break; case "jid-del": + // FIXME: stop using ugnich-csv in parameters String[] params = request.getParameter("delete").split(";", 2); - int res = -1; + boolean res = false; if (params[0].equals("xmpp")) { - res = sql.update("DELETE FROM jids WHERE user_id=? AND jid=?", visitor.getUid(), params[1]); + res = userService.deleteJID(visitor.getUid(), params[1]); } else if (params[0].equals("xmpp-unauth")) { - res = sql.update("DELETE FROM auth WHERE user_id=? AND protocol='xmpp' AND account=?", visitor.getUid(), params[1]); + res = userService.unauthJID(visitor.getUid(), params[1]); } - if (res == 1) { + if (res) { result = "<p>Deleted. <a href=\"/settings\">Back</a>.</p>"; } else { result = "<p>Error</p>"; } break; case "email": - String newHash = UserQueries.updateSecretEmail(sql, visitor); + String newHash = userService.updateSecretEmail(visitor); if (StringUtils.isNotEmpty(newHash)) { result = String.format("<p>New secret email: <strong>%s@mail.juick.com</strong></p>" + "<p><a href=\"/settings\">Back</a>.</p>", newHash); } else { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; + throw new HttpBadRequestException(); } break; case "email-add": try { - sql.queryForObject("SELECT authcode FROM auth WHERE user_id=? AND protocol='email' " + - "AND account=?", String.class, visitor.getUid(), request.getParameter("account")); + emailService.verifyAddressByCode(visitor.getUid(), request.getParameter("account")); } catch (EmptyResultDataAccessException e) { String authCode = UserUtils.generateHash(8); - if (sql.update("INSERT INTO auth(user_id,protocol,account,authcode) VALUES (?,'email',?,?)", - visitor.getUid(), request.getParameter("account"), authCode) > 0) { + if (emailService.addVerificationCode(visitor.getUid(), request.getParameter("account"), authCode)) { Session session = Session.getDefaultInstance(System.getProperties()); try { MimeMessage message = new MimeMessage(session); @@ -218,34 +223,30 @@ public class Settings { } catch (MessagingException ex) { logger.error("mail exception", ex); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; + throw new HttpBadRequestException(); } } } break; case "email-del": - if (sql.update("DELETE FROM emails WHERE user_id=? AND email=?", visitor.getUid(), request.getParameter("account")) > 0) { + if (emailService.deleteEmail(visitor.getUid(), request.getParameter("account"))) { result = "<p>Deleted. <a href=\"/settings\">Back</a>.</p>"; } else { result = "<p>An error occured while deleting.</p>"; } break; case "email-subscr": - sql.update("UPDATE emails SET subscr_hour=NULL WHERE user_id=?", visitor.getUid()); - String email = request.getParameter("account"); - if (StringUtils.isNotEmpty(email)) { - sql.update("UPDATE emails SET subscr_hour=? WHERE user_id=? AND email=?", - request.getParameter("time"), visitor.getUid(), email); + if (emailService.setSubscriptionHour(visitor.getUid(), request.getParameter("account"), + request.getParameter("time"))) { result = String.format("<p>Saved! Will send to <strong>%s</strong> at <strong>%s:00 GMT</strong>." + - "</p><p><a href=\"/settings\">Back</a></p>", email, request.getParameter("time")); + "</p><p><a href=\"/settings\">Back</a></p>", request.getParameter("account"), + request.getParameter("time")); } else { result = "<p>Disabled.</p><p><a href=\"/settings\">Back</a></p>"; } break; case "twitter-del": - sql.update("DELETE FROM twitter WHERE user_id=?", visitor.getUid()); - sql.update("DELETE FROM subscr_users WHERE user_id=? AND suser_id=1741", visitor.getUid()); + crosspostService.deleteTwitterToken(visitor.getUid()); for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals("request_token")) { cookie.setMaxAge(0); @@ -259,35 +260,28 @@ public class Settings { result = "<p><a href=\"/settings\">Back</a></p>"; break; case "telegram-del": - sql.update("DELETE FROM telegram WHERE user_id=?", visitor.getUid()); + telegramService.deleteTelegramUser(visitor.getUid()); result = "<p><a href=\"/settings\">Back</a></p>"; break; case "facebook-disable": - sql.update("UPDATE facebook SET crosspost=0 WHERE user_id=?", visitor.getUid()); - sql.update("DELETE FROM subscr_users WHERE user_id=? AND suser_id=5863", visitor.getUid()); + crosspostService.disableFBCrosspost(visitor.getUid()); result = "<p><a href=\"/settings\">Back</a></p>"; break; case "facebook-enable": - sql.update("UPDATE facebook SET crosspost=1 WHERE user_id=?", visitor.getUid()); - sql.update("INSERT INTO subscr_users(user_id,suser_id,jid,active) VALUES (?,5863,'juick@facebook.juick.com',1)", visitor.getUid()); + crosspostService.enableFBCrosspost(visitor.getUid()); result = "<p><a href=\"/settings\">Back</a></p>"; break; case "vk-del": - sql.update("DELETE FROM vk WHERE user_id=?", visitor.getUid()); + crosspostService.deleteVKUser(visitor.getUid()); result = "<p><a href=\"/settings\">Back</a></p>"; break; default: - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - response.setContentType("text/html; charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - PebbleTemplate template = Utils.getEngine().getTemplate("views/settings_result.html"); - Map<String, Object> context = new HashMap<>(); - context.put("title", "Настройки"); - context.put("visitor", visitor); - context.put("result", result); - template.evaluate(out, context); + 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 <http://www.gnu.org/licenses/>. + */ +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/TwitterAuth.java b/juick-www/src/main/java/com/juick/www/controllers/TwitterAuth.java index 35e00efc..901a8362 100644 --- a/juick-www/src/main/java/com/juick/www/TwitterAuth.java +++ b/juick-www/src/main/java/com/juick/www/controllers/TwitterAuth.java @@ -1,4 +1,4 @@ -package com.juick.www; +package com.juick.www.controllers; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; @@ -9,11 +9,14 @@ 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.server.UserQueries; +import com.juick.service.UserService; import org.apache.commons.lang3.StringUtils; -import org.springframework.jdbc.core.JdbcTemplate; +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.servlet.ServletException; +import javax.inject.Inject; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -22,6 +25,7 @@ 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"; @@ -30,17 +34,22 @@ public class TwitterAuth { private final ObjectMapper mapper; - public TwitterAuth(String consumerKey, String consumerSecret) { - this.consumerKey = consumerKey; - this.consumerSecret = consumerSecret; + @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); } - protected void doGet(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + @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(); @@ -55,7 +64,7 @@ public class TwitterAuth { request_token_secret = cookie.getValue(); } } - com.juick.User user = UserQueries.getUserByHash(sql, hash); + com.juick.User user = userService.getUserByHash(hash); if ( user == null || user.getUid() == 0) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; @@ -81,7 +90,7 @@ public class TwitterAuth { 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 (UserQueries.linkTwitterAccount(sql, user, accessToken.getToken(), accessToken.getTokenSecret(), + if (userService.linkTwitterAccount(user, accessToken.getToken(), accessToken.getTokenSecret(), twitterUser.getScreenName())) { response.setStatus(HttpServletResponse.SC_FOUND); response.setHeader("Location", "http://juick.com/settings"); diff --git a/juick-www/src/main/java/com/juick/www/User.java b/juick-www/src/main/java/com/juick/www/controllers/User.java index 926ce3e3..d3406f4e 100644 --- a/juick-www/src/main/java/com/juick/www/User.java +++ b/juick-www/src/main/java/com/juick/www/controllers/User.java @@ -15,19 +15,24 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; -import com.juick.server.MessagesQueries; -import com.juick.server.TagQueries; -import com.juick.server.UserQueries; 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.jdbc.core.JdbcTemplate; +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.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -42,10 +47,28 @@ import java.util.stream.Collectors; * * @author Ugnich Anton */ +@Controller public class User { - - protected void doGetBlog(JdbcTemplate sql, JdbcTemplate sqlSearch, HttpServletRequest request, HttpServletResponse response, com.juick.User user) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); + @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<Integer> mids; @@ -55,10 +78,10 @@ public class User { String paramTagStr = request.getParameter("tag"); if (paramTagStr != null) { if (paramTagStr.length() < 64) { - paramTag = TagQueries.getTag(sql, paramTagStr, false); + paramTag = tagService.getTag(paramTagStr, false); } if (paramTag == null) { - Errors.doGet404(sql, request, response); + 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); @@ -85,7 +108,7 @@ public class User { if (visitor.getUid() > 0) { if (user.getUid() == visitor.getUid() || visitor.getUid() == 1) { privacy = -3; - } else if (UserQueries.isInWL(sql, user.getUid(), visitor.getUid())) { + } else if (userService.isInWL(user.getUid(), visitor.getUid())) { privacy = -2; } } @@ -94,41 +117,37 @@ public class User { if (paramShow == null) { if (paramTag != null) { title = "Блог " + user.getName() + ": *" + StringEscapeUtils.escapeHtml4(paramTag.getName()); - mids = MessagesQueries.getUserTag(sql, user.getUid(), paramTag.TID, privacy, paramBefore); + mids = messagesService.getUserTag(user.getUid(), paramTag.TID, privacy, paramBefore); } else if (paramSearch != null) { title = "Блог " + user.getName() + ": " + StringEscapeUtils.escapeHtml4(paramSearch); - mids = MessagesQueries.getUserSearch(sql, sqlSearch, user.getUid(), Utils.encodeSphinx(paramSearch), privacy, paramBefore); + mids = messagesService.getUserSearch(user.getUid(), Utils.encodeSphinx(paramSearch), privacy, paramBefore); } else { title = "Блог " + user.getName(); - mids = MessagesQueries.getUserBlog(sql, user.getUid(), privacy, paramBefore); + mids = messagesService.getUserBlog(user.getUid(), privacy, paramBefore); } } else if (paramShow.equals("recomm")) { title = "Рекомендации " + user.getName(); - mids = MessagesQueries.getUserRecommendations(sql, user.getUid(), paramBefore); + mids = messagesService.getUserRecommendations(user.getUid(), paramBefore); } else if (paramShow.equals("photos")) { title = "Фотографии " + user.getName(); - mids = MessagesQueries.getUserPhotos(sql, user.getUid(), privacy, paramBefore); + mids = messagesService.getUserPhotos(user.getUid(), privacy, paramBefore); } else { - Errors.doGet404(sql, request, response); + response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - if (visitor.getUid() == 0) { - pageUserRefCookie(request, response, user.getUid()); - } - response.setContentType("text/html; charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String head = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"@" + user.getName() + "\" href=\"//rss.juick.com/" + user.getName() + "/blog\"/>"; - if (paramTag != null && TagQueries.getTagNoIndex(sql, paramTag.TID)) { + if (paramTag != null && tagService.getTagNoIndex(paramTag.TID)) { head += "<meta name=\"robots\" content=\"noindex,nofollow\"/>"; } else if (paramBefore > 0 || paramShow != null) { head += "<meta name=\"robots\" content=\"noindex\"/>"; } - PageTemplates.pageHead(out, visitor, title, head); - PageTemplates.pageNavigation(out, visitor, null); - pageUserColumn(out, sql, user, visitor); + templates.pageHead(out, visitor, title, head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); if (mids.size() > 0) { out.println("<section id=\"content\">"); @@ -139,7 +158,7 @@ public class User { StringEscapeUtils.escapeHtml4(paramTag.getName()) + "</b></a></p>"); } - PageTemplates.printMessages(out, sql, user, mids, visitor, visitor.getUid() == 0 ? 4 : 5, 0); + templates.printMessages(out, user, mids, visitor, visitor.getUid() == 0 ? 4 : 5, 0); if (mids.size() >= 20) { String nextpage = "?before=" + mids.get(mids.size() - 1); @@ -158,52 +177,58 @@ public class User { out.println("</section>"); } - PageTemplates.pageFooter(request, out, visitor, true); - PageTemplates.pageEnd(out); + templates.pageFooter(request, out, visitor, true); + templates.pageEnd(out); } } - protected void doGetTags(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, com.juick.User user) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - - if (visitor.getUid() == 0) { - pageUserRefCookie(request, response, user.getUid()); + @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 = "<meta name=\"robots\" content=\"noindex,nofollow\"/>"; - PageTemplates.pageHead(out, visitor, "Теги " + user.getName(), head); - PageTemplates.pageNavigation(out, visitor, null); - pageUserColumn(out, sql, user, visitor); + templates.pageHead(out, visitor, "Теги " + user.getName(), head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); out.println("<section id=\"content\">"); - out.println("<p>" + pageUserTags(sql, user, visitor, 0) + "</p>"); + out.println("<p>" + pageUserTags(user, visitor, 0) + "</p>"); out.println("</section>"); - PageTemplates.pageFooter(request, out, visitor, false); - PageTemplates.pageEnd(out); + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); } } - protected void doGetFriends(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, com.juick.User user) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - - if (visitor.getUid() == 0) { - pageUserRefCookie(request, response, user.getUid()); + @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 = "<meta name=\"robots\" content=\"noindex\"/>"; - PageTemplates.pageHead(out, visitor, "Подписки " + user.getName(), head); - PageTemplates.pageNavigation(out, visitor, null); - pageUserColumn(out, sql, user, visitor); + templates.pageHead(out, visitor, "Подписки " + user.getName(), head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); out.println("<section id=\"content\">"); out.println("<table class=\"users\"><tr>"); - List<com.juick.User> friends = UserQueries.getUserFriends(sql, user.getUid()); + List<com.juick.User> friends = userService.getUserFriends(user.getUid()); for (int i = 0; i < friends.size(); i++) { if (i % 3 == 0 && i > 0) { out.print("</tr><tr>"); @@ -216,29 +241,32 @@ public class User { out.println("</tr></table>"); out.println("</section>"); - PageTemplates.pageFooter(request, out, visitor, false); - PageTemplates.pageEnd(out); + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); } } - protected void doGetReaders(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, com.juick.User user) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - - if (visitor.getUid() == 0) { - pageUserRefCookie(request, response, user.getUid()); + @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 = "<meta name=\"robots\" content=\"noindex\"/>"; - PageTemplates.pageHead(out, visitor, "Читатели " + user.getName(), head); - PageTemplates.pageNavigation(out, visitor, null); - pageUserColumn(out, sql, user, visitor); + templates.pageHead(out, visitor, "Читатели " + user.getName(), head); + templates.pageNavigation(out, visitor, null); + pageUserColumn(out, user, visitor); out.println("<section id=\"content\">"); out.println("<table class=\"users\"><tr>"); - List<com.juick.User> readers = UserQueries.getUserReaders(sql, user.getUid()); + List<com.juick.User> readers = userService.getUserReaders(user.getUid()); for (int i = 0; i < readers.size(); i++) { if (i % 3 == 0 && i > 0) { out.print("</tr><tr>"); @@ -251,39 +279,27 @@ public class User { out.println("</tr></table>"); out.println("</section>"); - PageTemplates.pageFooter(request, out, visitor, false); - PageTemplates.pageEnd(out); - } - } - - public static void pageUserRefCookie(HttpServletRequest request, HttpServletResponse response, int uid) { - String hReferer = request.getHeader("Referer"); - String ref = Utils.getCookie(request, "ref"); - - if (ref == null && (hReferer == null || !(hReferer.startsWith("http://juick.com/") || hReferer.startsWith("https://juick.com/")))) { - Cookie c = new Cookie("ref", Integer.toString(uid)); - c.setMaxAge(7 * 24 * 60 * 60); - c.setPath("/"); - response.addCookie(c); + templates.pageFooter(request, out, visitor, false); + templates.pageEnd(out); } } - public static void pageUserColumn(PrintWriter out, JdbcTemplate sql, com.juick.User user, com.juick.User visitor) { + public void pageUserColumn(PrintWriter out, com.juick.User user, com.juick.User visitor) { out.println("<aside id=\"column\">"); out.println(" <div id=\"ctitle\"><a href=\"./\"><img src=\"//i.juick.com/as/" + user.getUid() + ".png\" alt=\"\"/>" + user.getName() + "</a></div>"); if (visitor.getUid() > 0 && visitor.getUid() != user.getUid()) { out.println(" <ul id=\"ctoolbar\">"); - if (UserQueries.isSubscribed(sql, visitor.getUid(), user.getUid())) { + if (userService.isSubscribed(visitor.getUid(), user.getUid())) { out.println(" <li><a href=\"/post?body=U+%40" + user.getName() + "\" title=\"Подписан\"><div style=\"background-position: -48px 0\"></div></a></li>"); } else { out.println(" <li><a href=\"/post?body=S+%40" + user.getName() + "\" title=\"Подписаться\"><div style=\"background-position: -16px 0\"></div></a></li>"); } - if (UserQueries.isInBL(sql, visitor.getUid(), user.getUid())) { + if (userService.isInBL(visitor.getUid(), user.getUid())) { out.println(" <li><a href=\"/post?body=BL+%40" + user.getName() + "\" title=\"Разблокировать\"><div style=\"background-position: -96px 0\"></div></a></li>"); } else { out.println(" <li><a href=\"/post?body=BL+%40" + user.getName() + "\" title=\"Заблокировать\"><div style=\"background-position: -80px 0\"></div></a></li>"); } - if (!UserQueries.isInBLAny(sql, user.getUid(), visitor.getUid())) { + if (!userService.isInBLAny(user.getUid(), visitor.getUid())) { out.println(" <li><a href=\"/pm/sent?uname=" + user.getName() + "\" title=\"Написать приватное сообщение\"><div style=\"background-position: -112px 0\"></div></a></li>"); } out.println(" </ul>"); @@ -299,16 +315,16 @@ public class User { out.println(" <form action=\"./\">"); out.println(" <p><input type=\"text\" name=\"search\" class=\"inp\" placeholder=\"Поиск\"/></p>"); out.println(" </form>"); - out.println(" <p class=\"tags\">" + pageUserTags(sql, user, visitor, 20) + "<a href=\"./tags\" rel=\"nofollow\">...</a></p>"); + out.println(" <p class=\"tags\">" + pageUserTags(user, visitor, 20) + "<a href=\"./tags\" rel=\"nofollow\">...</a></p>"); out.println(" <hr/>"); out.println(" <div id=\"ustats\"><ul>"); - out.println(" <li><a href=\"./friends\">Я читаю: " + UserQueries.getStatsIRead(sql, user.getUid()) + "</a></li>"); - out.println(" <li><a href=\"./readers\">Мои подписчики: " + UserQueries.getStatsMyReaders(sql, user.getUid()) + "</a></li>"); - out.println(" <li>Сообщений: " + UserQueries.getStatsMessages(sql, user.getUid()) + "</li>"); - out.println(" <li>Комментариев: " + UserQueries.getStatsReplies(sql, user.getUid()) + "</li>"); + out.println(" <li><a href=\"./friends\">Я читаю: " + userService.getStatsIRead(user.getUid()) + "</a></li>"); + out.println(" <li><a href=\"./readers\">Мои подписчики: " + userService.getStatsMyReaders(user.getUid()) + "</a></li>"); + out.println(" <li>Сообщений: " + userService.getStatsMessages(user.getUid()) + "</li>"); + out.println(" <li>Комментариев: " + userService.getStatsReplies(user.getUid()) + "</li>"); out.println(" </ul>"); - List<com.juick.User> iread = UserQueries.getUserReadLeastPopular(sql, user.getUid(), 8); + List<com.juick.User> iread = userService.getUserReadLeastPopular(user.getUid(), 8); if (!iread.isEmpty()) { out.println("<table class=\"iread\"><tr>"); for (int i = 0; i < iread.size(); i++) { @@ -325,8 +341,8 @@ public class User { out.println("</aside>"); } - public static String pageUserTags(JdbcTemplate sql, com.juick.User user, com.juick.User visitor, int cnt) { - List<TagStats> tags = TagQueries.getTagsStats(sql, user.getUid()).stream() + public String pageUserTags(com.juick.User user, com.juick.User visitor, int cnt) { + List<TagStats> 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; diff --git a/juick-www/src/main/java/com/juick/www/UserThread.java b/juick-www/src/main/java/com/juick/www/controllers/UserThread.java index 79ec42fc..4020e149 100644 --- a/juick-www/src/main/java/com/juick/www/UserThread.java +++ b/juick-www/src/main/java/com/juick/www/controllers/UserThread.java @@ -15,15 +15,21 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; import com.juick.Message; -import com.juick.server.MessagesQueries; -import com.juick.server.UserQueries; 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.springframework.jdbc.core.JdbcTemplate; +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; @@ -36,17 +42,31 @@ import java.util.List; * * @author Ugnich Anton */ +@Controller public class UserThread { - protected void doGetThread(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, int MID) throws ServletException, IOException { - com.juick.User visitor = Utils.getVisitorUser(sql, request, response); - - if (!MessagesQueries.canViewThread(sql, MID, visitor.getUid())) { + @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 = MessagesQueries.getMessage(sql, MID); + com.juick.Message msg = messagesService.getMessage(mid); boolean listview = false; String paramView = request.getParameter("view"); @@ -54,21 +74,17 @@ public class UserThread { if (paramView.equals("list")) { listview = true; if (visitor.getUid() > 0) { - UserQueries.setUserOptionInt(sql, visitor.getUid(), "repliesview", 1); + userService.setUserOptionInt(visitor.getUid(), "repliesview", 1); } } else if (paramView.equals("tree") && visitor.getUid() > 0) { - UserQueries.setUserOptionInt(sql, visitor.getUid(), "repliesview", 0); + userService.setUserOptionInt(visitor.getUid(), "repliesview", 0); } - } else if (visitor.getUid() > 0 && UserQueries.getUserOptionInt(sql, visitor.getUid(), "repliesview", 0) == 1) { + } else if (visitor.getUid() > 0 && userService.getUserOptionInt(visitor.getUid(), "repliesview", 0) == 1) { listview = true; } String title = msg.getUser().getName() + ": " + msg.getTagsString(); - if (visitor.getUid() > 0) { - User.pageUserRefCookie(request, response, msg.getUser().getUid()); - } - response.setContentType("text/html; charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String headers = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"@" + msg.getUser().getName() + "\" href=\"//rss.juick.com/" + msg.getUser().getName() + "/blog\"/>"; @@ -78,25 +94,25 @@ public class UserThread { if (msg.Hidden) { headers += "<meta name=\"robots\" content=\"noindex\"/>"; } - PageTemplates.pageHead(out, visitor, title, headers); - PageTemplates.pageNavigation(out, visitor, null); + templates.pageHead(out, visitor, title, headers); + templates.pageNavigation(out, visitor, null); out.println("<section id=\"content\" data-mid=\"" + msg.getMid() + "\" style=\"margin-left: 0; width: 100%\">"); - printMessage(out, sql, msg, visitor); - printReplies(out, sql, msg, visitor, listview); + printMessage(out, msg, visitor); + printReplies(out, msg, visitor, listview); out.println("</section>"); - PageTemplates.pageFooter(request, out, visitor, false); + templates.pageFooter(request, out, visitor, false); - PageTemplates.pageEnd(out); + templates.pageEnd(out); } } - public static com.juick.Message printMessage(PrintWriter out, JdbcTemplate sql, com.juick.Message msg, com.juick.User visitor) { + public com.juick.Message printMessage(PrintWriter out, com.juick.Message msg, com.juick.User visitor) { msg.VisitorCanComment = visitor.getUid() > 0; - List<TagStats> tags = MessagesQueries.getMessageTags(sql, msg.getMid()); - String tagsStr = PageTemplates.formatTags(tags); + List<TagStats> tags = tagService.getMessageTags(msg.getMid()); + String tagsStr = templates.formatTags(tags); if (msg.ReadOnly) { tagsStr += "<a>readonly</a>"; msg.VisitorCanComment = false; @@ -120,7 +136,7 @@ public class UserThread { out.println(" <li id=\"msg-" + msg.getMid() + "\" data-mid=\"" + msg.getMid() + "\" class=\"msg msgthread\">"); out.println(" <div class=\"msg-cont\">"); out.println(" <div class=\"msg-menu\"><a href=\"#\"></a></div>"); - out.println(" <div class=\"msg-ts\">" + PageTemplates.formatJSLocalTime(msg.getDate()) + "</div>"); + out.println(" <div class=\"msg-ts\">" + templates.formatJSLocalTime(msg.getDate()) + "</div>"); out.println(" <div class=\"msg-avatar\"><a href=\"/" + msg.getUser().getName() + "/\"><img src=\"//i.juick.com/a/" + msg.getUser().getUid() + ".png\" alt=\"" + msg.getUser().getName() + "\"/></a></div>"); out.println(" <div class=\"msg-header\">@<a href=\"/" + msg.getUser().getName() + "/\">" + msg.getUser().getName() + "</a>:" + tagsStr + "</div>"); out.println(" <div class=\"msg-txt\">" + txt + "</div>"); @@ -134,7 +150,7 @@ public class UserThread { if (visitor.getUid() == msg.getUser().getUid()) { msg.VisitorCanComment = true; } else { - visitorInBL = UserQueries.isInBL(sql, msg.getUser().getUid(), visitor.getUid()); + visitorInBL = userService.isInBL(msg.getUser().getUid(), visitor.getUid()); if (visitorInBL) { msg.VisitorCanComment = false; } @@ -147,7 +163,7 @@ public class UserThread { out.println(" </form>"); } - List<String> recomm = MessagesQueries.getMessageRecommendations(sql, msg.getMid()); + List<String> recomm = messagesService.getMessageRecommendations(msg.getMid()); if (!recomm.isEmpty()) { out.print(" <div class=\"msg-recomms\">Рекомендовали (" + recomm.size() + "): "); for (int i = 0; i < recomm.size(); i++) { @@ -165,7 +181,7 @@ public class UserThread { out.println(" <li><a href=\"/" + msg.getMid() + "\"><div style=\"background-position: -64px 0\"></div>" + msg.getMid() + "</a></li>"); if (visitor.getUid() > 0) { if (visitor.getUid() != msg.getUser().getUid()) { - if (MessagesQueries.isSubscribed(sql, visitor.getUid(), msg.getMid())) { + if (messagesService.isSubscribed(visitor.getUid(), msg.getMid())) { out.println(" <li><a href=\"/post?body=U+%23" + msg.getMid() + "\"><div style=\"background-position: -48px 0\"></div>Подписан</a></li>"); } else { out.println(" <li><a href=\"/post?body=S+%23" + msg.getMid() + "\"><div style=\"background-position: -16px 0\"></div>Подписаться</a></li>"); @@ -183,8 +199,8 @@ public class UserThread { return msg; } - public static void printReplies(PrintWriter out, JdbcTemplate sql, com.juick.Message msg, com.juick.User visitor, boolean listview) { - List<com.juick.Message> replies = MessagesQueries.getReplies(sql, msg.getMid()); + public void printReplies(PrintWriter out, com.juick.Message msg, com.juick.User visitor, boolean listview) { + List<com.juick.Message> replies = messagesService.getReplies(msg.getMid()); List<Integer> blUIDs = new ArrayList<Integer>(); for (int i = 0; i < replies.size(); i++) { @@ -213,7 +229,7 @@ public class UserThread { reply.VisitorCanComment = true; } } else if (visitor.getUid() > 0 && msg.VisitorCanComment) { - blUIDs = UserQueries.checkBL(sql, visitor.getUid(), blUIDs); + blUIDs = userService.checkBL(visitor.getUid(), blUIDs); for (Message reply : replies) { reply.VisitorCanComment = reply.getUser().getUid() == visitor.getUid() || !blUIDs.contains(reply.getUser().getUid()); } @@ -262,7 +278,7 @@ public class UserThread { } } - public static void printTree(PrintWriter out, List<com.juick.Message> replies, com.juick.User visitor, int ReplyTo, int margin, boolean hidden) { + public void printTree(PrintWriter out, List<com.juick.Message> replies, com.juick.User visitor, int ReplyTo, int margin, boolean hidden) { if (margin > 240) { margin = 240; } @@ -289,7 +305,7 @@ public class UserThread { out.println(" <div class=\"msg-avatar\"><img src=\"//i.juick.com/av-96.png\"/></div>"); } out.println(" <div class=\"msg-menu\"><a href=\"#\" class=\"a-thread-links\"></a></div>"); - out.println(" <div class=\"msg-ts\"><a href=\"/" + msg.getMid() + "#" + msg.getRid() + "\" title=\"" + PageTemplates.sdfSQL.format(msg.getDate()) + " GMT\">" + PageTemplates.formatDate(msg.TimeAgo, msg.getDate()) + "</a></div>"); + out.println(" <div class=\"msg-ts\"><a href=\"/" + msg.getMid() + "#" + msg.getRid() + "\" title=\"" + templates.sdfSQL.format(msg.getDate()) + " GMT\">" + templates.formatDate(msg.TimeAgo, msg.getDate()) + "</a></div>"); out.println(" </div>"); out.println(" <div class=\"msg-txt\">" + MessageUtils.formatMessage(msg.getText()) + "</div>"); if (msg.getAttachmentType() != null) { @@ -308,7 +324,7 @@ public class UserThread { int childs = msg.getChildsCount(); if (ReplyTo == 0 && childs > 1 && replies.size() > 10) { - out.println(" <div class=\"msg-comments\"><a href=\"#\">" + PageTemplates.formatReplies(childs) + "</a></div>"); + out.println(" <div class=\"msg-comments\"><a href=\"#\">" + templates.formatReplies(childs) + "</a></div>"); } out.println(" </div>"); out.println(" </li>"); @@ -322,7 +338,7 @@ public class UserThread { } } - public static void printList(PrintWriter out, List<com.juick.Message> replies, com.juick.User visitor) { + public void printList(PrintWriter out, List<com.juick.Message> replies, com.juick.User visitor) { for (Message msg : replies) { out.print(" <li id=\"" + msg.getRid() + "\" class=\"msg\">"); out.println(" <div class=\"msg-cont\">"); @@ -335,7 +351,7 @@ public class UserThread { out.println(" <div class=\"msg-avatar\"><img src=\"//i.juick.com/av-96.png\"/></div>"); } out.println(" <div class=\"msg-menu\"><a href=\"#\" class=\"a-thread-links\"></a></div>"); - out.println(" <div class=\"msg-ts\"><a href=\"/" + msg.getMid() + "#" + msg.getRid() + "\" title=\"" + PageTemplates.sdfSQL.format(msg.getDate()) + " GMT\">" + PageTemplates.formatDate(msg.TimeAgo, msg.getDate()) + "</a></div>"); + out.println(" <div class=\"msg-ts\"><a href=\"/" + msg.getMid() + "#" + msg.getRid() + "\" title=\"" + PageTemplates.sdfSQL.format(msg.getDate()) + " GMT\">" + templates.formatDate(msg.TimeAgo, msg.getDate()) + "</a></div>"); out.println(" </div>"); out.println(" <div class=\"msg-txt\">" + MessageUtils.formatMessage(msg.getText()) + "</div>"); if (msg.getAttachmentType() != null) { diff --git a/juick-www/src/main/java/com/juick/www/VKontakteLogin.java b/juick-www/src/main/java/com/juick/www/controllers/VKontakteLogin.java index 2184fc9a..d860a7bc 100644 --- a/juick-www/src/main/java/com/juick/www/VKontakteLogin.java +++ b/juick-www/src/main/java/com/juick/www/controllers/VKontakteLogin.java @@ -15,21 +15,24 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -package com.juick.www; +package com.juick.www.controllers; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; -import com.juick.server.UserQueries; +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.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; -import javax.servlet.ServletException; +import javax.inject.Inject; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -40,12 +43,18 @@ 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); @@ -55,7 +64,8 @@ public class VKontakteLogin { private final ObjectMapper mapper; - protected void doGet(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @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); @@ -97,16 +107,16 @@ public class VKontakteLogin { throw new Exception(); } - int uid = getUIDbyVKID(sql, vkID); + int uid = crosspostService.getUIDbyVKID(vkID); if (uid > 0) { - Cookie c = new Cookie("hash", UserQueries.getHashByUID(sql, uid)); + 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 (!insertDB(sql, vkID, loginhash, token, vkName, vkLink)) { + if (!crosspostService.createVKUser(vkID, loginhash, token, vkName, vkLink)) { throw new Exception(); } response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); @@ -117,17 +127,4 @@ public class VKontakteLogin { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } - - private int getUIDbyVKID(JdbcTemplate sql, long vkID) { - try { - return sql.queryForObject("SELECT user_id FROM vk WHERE vk_id=? AND user_id IS NOT NULL", Integer.class, vkID); - } catch (EmptyResultDataAccessException e) { - return 0; - } - } - - private boolean insertDB(JdbcTemplate sql, long vkID, String loginhash, String token, String vkName, String vkLink) { - return sql.update("INSERT INTO vk(vk_id,loginhash,access_token,vk_name,vk_link) VALUES (?,?,?,?,?)", - vkID, loginhash, token, vkName, vkLink) > 0; - } } 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); + } +} |