From a4897522174fb48864a4ef7d6276167f9da61f3b Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Sat, 31 Oct 2015 01:36:15 +0300
Subject: moved to Gradle
---
src/main/java/com/juick/api/Main.java | 231 ++++++++++++++++++++++++++++++
src/main/java/com/juick/api/Messages.java | 89 ++++++++++++
src/main/java/com/juick/api/Others.java | 45 ++++++
src/main/java/com/juick/api/PM.java | 101 +++++++++++++
src/main/java/com/juick/api/Users.java | 120 ++++++++++++++++
src/main/java/com/juick/api/Utils.java | 149 +++++++++++++++++++
6 files changed, 735 insertions(+)
create mode 100644 src/main/java/com/juick/api/Main.java
create mode 100644 src/main/java/com/juick/api/Messages.java
create mode 100644 src/main/java/com/juick/api/Others.java
create mode 100644 src/main/java/com/juick/api/PM.java
create mode 100644 src/main/java/com/juick/api/Users.java
create mode 100644 src/main/java/com/juick/api/Utils.java
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
new file mode 100644
index 00000000..5ee4027b
--- /dev/null
+++ b/src/main/java/com/juick/api/Main.java
@@ -0,0 +1,231 @@
+/*
+ * Juick
+ * Copyright (C) 2008-2013, Ugnich Anton
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+package com.juick.api;
+
+import com.juick.xmpp.JID;
+import com.juick.xmpp.Stream;
+import com.juick.xmpp.StreamComponent;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.Socket;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+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;
+
+/**
+ *
+ * @author Ugnich Anton
+ */
+@WebServlet(name = "Main", urlPatterns = {"/"})
+@MultipartConfig
+public class Main extends HttpServlet implements Stream.StreamListener {
+
+ Connection sql;
+ Connection sqlSearch;
+ Stream xmpp;
+ Messages messages;
+ Users users;
+ PM pm;
+ Others others;
+
+ @Override
+ public void init() throws ServletException {
+ super.init();
+ try {
+ Properties conf = new Properties();
+ conf.load(new FileInputStream("/etc/juick/api.conf"));
+
+ Class.forName("com.mysql.jdbc.Driver");
+ sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", ""));
+ sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password=");
+
+ messages = new Messages(sql);
+ users = new Users(sql);
+ pm = new PM(sql);
+ others = new Others(sql);
+
+ setupXmppComponent(conf.getProperty("xmpp_password"));
+
+ } catch (Exception e) {
+ log(null, e);
+ }
+ }
+
+ public void setupXmppComponent(final String password) {
+ Thread thr = new Thread(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ Socket socket = new Socket("localhost", 5347);
+ xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password);
+ xmpp.addListener(Main.this);
+ xmpp.startParsing();
+ } catch (IOException e) {
+ System.err.println(e);
+ }
+ }
+ });
+ thr.start();
+ }
+
+ @Override
+ public void onStreamFail(String msg) {
+ System.err.println("XMPP STREAM FAIL: " + msg);
+ }
+
+ @Override
+ public void onStreamReady() {
+ System.err.println("XMPP STREAM READY");
+ }
+
+ @Override
+ public void destroy() {
+ super.destroy();
+ if (sql != null) {
+ try {
+ sql.close();
+ sql = null;
+ } catch (SQLException e) {
+ log(null, e);
+ }
+ }
+ if (sqlSearch != null) {
+ try {
+ sqlSearch.close();
+ sqlSearch = null;
+ } catch (SQLException e) {
+ log(null, e);
+ }
+ }
+ }
+
+ /**
+ * Handles the HTTP GET
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("UTF-8");
+ }
+
+ int vuid = Utils.getHttpAuthUID(sql, request);
+ if (vuid == 0) {
+ vuid = Utils.getVisitorQueryStringUID(sql, request);
+ }
+
+ String uri = request.getRequestURI();
+ if (uri.equals("/home")) {
+ if (vuid > 0) {
+ messages.doGetHome(request, response, vuid);
+ } else {
+ response.sendError(401);
+ }
+ } else if (uri.equals("/users")) {
+ users.doGetUsers(request, response, vuid);
+ } else if (uri.equals("/users/read")) {
+ users.doGetUserRead(request, response, vuid);
+ } else if (uri.equals("/users/readers")) {
+ users.doGetUserReaders(request, response, vuid);
+ } else if (uri.equals("/pm")) {
+ if (vuid > 0) {
+ pm.doGetPM(request, response, vuid);
+ } else {
+ response.sendError(401);
+ }
+ } else if (uri.equals("/groups_pms")) {
+ if (vuid > 0) {
+ others.doGetGroupsPMs(request, response, vuid);
+ } else {
+ response.sendError(401);
+ }
+ } else if (uri.equals("/messages/set_popular") && vuid == 1) {
+ messages.doSetPopular(request, response, xmpp);
+ } else if (uri.equals("/messages/set_privacy") && vuid > 0) {
+ messages.doSetPrivacy(request, response, xmpp, vuid);
+ } else {
+ response.sendError(404);
+ }
+ }
+
+ /**
+ * Handles the HTTP POST
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("UTF-8");
+ }
+
+ int vuid = Utils.getHttpAuthUID(sql, request);
+ if (vuid == 0) {
+ vuid = Utils.getVisitorQueryStringUID(sql, request);
+ }
+ if (vuid == 0) {
+ response.sendError(401);
+ return;
+ }
+
+ String uri = request.getRequestURI();
+ if (uri.equals("/post")) {
+ } else if (uri.equals("/pm")) {
+ pm.doPostPM(request, response, xmpp, vuid);
+ } else {
+ response.sendError(405);
+ }
+ }
+
+ public static void replyJSON(HttpServletRequest request, HttpServletResponse response, String json) throws IOException {
+ response.setContentType("application/json; charset=UTF-8");
+ response.setHeader("Access-Control-Allow-Origin", "*");
+
+ String callback = request.getParameter("callback");
+ if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-\\_]+"))) {
+ callback = null;
+ }
+
+ PrintWriter out = response.getWriter();
+ try {
+ if (callback != null) {
+ out.print(callback + "(");
+ out.print(json);
+ out.print(")");
+ } else {
+ out.print(json);
+ }
+ } finally {
+ out.close();
+ }
+ }
+}
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
new file mode 100644
index 00000000..b5462258
--- /dev/null
+++ b/src/main/java/com/juick/api/Messages.java
@@ -0,0 +1,89 @@
+package com.juick.api;
+
+import com.juick.server.MessagesQueries;
+import com.juick.xmpp.JID;
+import com.juick.xmpp.Message;
+import com.juick.xmpp.Stream;
+import com.juick.xmpp.extensions.JuickMessage;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.ArrayList;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ *
+ * @author ugnich
+ */
+public class Messages {
+
+ Connection sql;
+
+ public Messages(Connection sql) {
+ this.sql = sql;
+ }
+
+ public void doGetHome(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+
+ ArrayList mids = MessagesQueries.getMyFeed(sql, vuid, before_mid);
+ if (mids != null && !mids.isEmpty()) {
+ ArrayList msgs = MessagesQueries.getMessages(sql, mids);
+ if (msgs != null && !msgs.isEmpty()) {
+ String json = com.juick.json.Messages.arrayToString(msgs);
+ Main.replyJSON(request, response, json);
+ } else {
+ response.sendError(404);
+ }
+ } else {
+ response.sendError(404);
+ }
+ }
+
+ public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid);
+ if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) {
+ Main.replyJSON(request, response, "{\"status\":\"ok\"}");
+ } else {
+ response.sendError(400);
+ }
+ }
+
+ public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException {
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ int popular = Utils.parseInt(request.getParameter("popular"), 0);
+
+ if (mid > 0) {
+ boolean ret = MessagesQueries.setMessagePopular(sql, mid, popular);
+
+ if (ret && popular == 2) {
+ try {
+ com.juick.Message m = MessagesQueries.getMessage(sql, mid);
+ if (m != null) {
+ Message msg = new Message();
+ msg.from = new JID("juick", "juick.com", null);
+ msg.to = new JID(null, "crosspost.juick.com", null);
+ JuickMessage jmsg = new JuickMessage(m);
+ jmsg.User.UID = 11574;
+ msg.childs.add(jmsg);
+
+ msg.to.Username = "twitter";
+ xmpp.send(msg);
+ msg.to.Username = "fb";
+ xmpp.send(msg);
+ msg.to.Username = "vk";
+ xmpp.send(msg);
+ } else {
+ throw new Exception("Message not found");
+ }
+ } catch (Exception e) {
+ System.err.println("SETPOPULAR ERROR: " + e.toString());
+ }
+ }
+
+ Main.replyJSON(request, response, "{\"status\":\"ok\"}");
+ }
+ }
+}
diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java
new file mode 100644
index 00000000..25df5bf4
--- /dev/null
+++ b/src/main/java/com/juick/api/Others.java
@@ -0,0 +1,45 @@
+package com.juick.api;
+
+import com.juick.server.PMQueries;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.ArrayList;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ *
+ * @author ugnich
+ */
+public class Others {
+
+ Connection sql;
+
+ public Others(Connection sql) {
+ this.sql = sql;
+ }
+
+ public void doGetGroupsPMs(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ int cnt = 5;
+ try {
+ String cntStr = request.getParameter("cnt");
+ cnt = Integer.parseInt(cntStr);
+ if (cnt < 3) {
+ cnt = 3;
+ }
+ if (cnt > 10) {
+ cnt = 10;
+ }
+ } catch (Exception e) {
+ }
+
+ ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt);
+ if (lastconv != null && !lastconv.isEmpty()) {
+ String json = "{\"pms\":" + com.juick.json.Users.arrayToString(lastconv) + "}";
+ Main.replyJSON(request, response, json);
+ } else {
+ response.sendError(404);
+ }
+ }
+}
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
new file mode 100644
index 00000000..2722526d
--- /dev/null
+++ b/src/main/java/com/juick/api/PM.java
@@ -0,0 +1,101 @@
+package com.juick.api;
+
+import com.juick.server.PMQueries;
+import com.juick.server.UserQueries;
+import com.juick.xmpp.JID;
+import com.juick.xmpp.Message;
+import com.juick.xmpp.Stream;
+import com.juick.xmpp.extensions.JuickMessage;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.ArrayList;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ *
+ * @author ugnich
+ */
+public class PM {
+
+ Connection sql;
+
+ public PM(Connection sql) {
+ this.sql = sql;
+ }
+
+ public void doGetPM(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ String uname = request.getParameter("uname");
+ int uid = 0;
+ if (uname != null && uname.matches("^[a-zA-Z0-9\\-]{2,16}$")) {
+ uid = UserQueries.getUIDbyName(sql, uname);
+ }
+
+ if (uid == 0) {
+ response.sendError(400);
+ return;
+ }
+
+ ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid);
+ if (msgs != null && !msgs.isEmpty()) {
+ String json = com.juick.json.Messages.arrayToString(msgs);
+ Main.replyJSON(request, response, json);
+ } else {
+ response.sendError(404);
+ }
+ }
+
+ public void doPostPM(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
+ String uname = request.getParameter("uname");
+ int uid = 0;
+ if (UserQueries.checkUserNameValid(uname)) {
+ uid = UserQueries.getUIDbyName(sql, uname);
+ }
+
+ String body = request.getParameter("body");
+ if (uid == 0 || body == null || body.length() < 1 || body.length() > 10240) {
+ response.sendError(400);
+ return;
+ }
+
+ if (UserQueries.isInBLAny(sql, uid, vuid)) {
+ response.sendError(403);
+ return;
+ }
+
+ if (PMQueries.createPM(sql, vuid, uid, body)) {
+ Message msg = new Message();
+ msg.from = new JID("juick", "juick.com", null);
+ msg.to = new JID(Integer.toString(uid), "push.juick.com", null);
+ JuickMessage jmsg = new JuickMessage();
+ jmsg.User = UserQueries.getUserByUID(sql, vuid);
+ jmsg.Text = body;
+ msg.childs.add(jmsg);
+ xmpp.send(msg);
+
+ msg.to.Host = "ws.juick.com";
+ xmpp.send(msg);
+
+ Main.replyJSON(request, response, com.juick.json.Message.toJSON(jmsg).toString());
+
+ String jid = UserQueries.getJIDbyUID(sql, uid);
+ if (jid != null) {
+ Message mm = new Message();
+ mm.to = new JID(jid);
+ mm.type = Message.Type.chat;
+ if (PMQueries.havePMinRoster(sql, vuid, jid)) {
+ mm.from = new JID(jmsg.User.UName, "juick.com", "Juick");
+ mm.body = body;
+ } else {
+ mm.from = new JID("juick", "juick.com", "Juick");
+ mm.body = "Private message from @" + jmsg.User.UName + ":\n" + body;
+ }
+ xmpp.send(mm);
+ }
+
+ } else {
+ response.sendError(500);
+ }
+ }
+}
diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java
new file mode 100644
index 00000000..cdd48fd6
--- /dev/null
+++ b/src/main/java/com/juick/api/Users.java
@@ -0,0 +1,120 @@
+package com.juick.api;
+
+import com.juick.User;
+import com.juick.server.UserQueries;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ *
+ * @author ugnich
+ */
+public class Users {
+
+ Connection sql;
+
+ public Users(Connection sql) {
+ this.sql = sql;
+ }
+
+ public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ ArrayList users = new ArrayList();
+
+ String punames[] = request.getParameterValues("uname");
+ if (punames != null) {
+ ArrayList unames = new ArrayList(Arrays.asList(punames));
+ Iterator i = unames.iterator();
+ while (i.hasNext()) {
+ if (!i.next().matches("^[a-zA-Z0-9\\-]{2,16}$")) {
+ i.remove();
+ }
+ }
+ if (!unames.isEmpty() && unames.size() < 20) {
+ users.addAll(UserQueries.getUsersByName(sql, unames));
+ }
+ }
+
+ String pjids[] = request.getParameterValues("jid");
+ if (pjids != null) {
+ ArrayList jids = new ArrayList(Arrays.asList(pjids));
+ Iterator ii = jids.iterator();
+ while (ii.hasNext()) {
+ if (!ii.next().matches("^[a-zA-Z0-9\\-\\_\\@\\.]{6,64}$")) {
+ ii.remove();
+ }
+ }
+ if (!jids.isEmpty() && jids.size() < 20) {
+ users.addAll(UserQueries.getUsersByJID(sql, jids));
+ }
+ }
+
+ if (!users.isEmpty()) {
+ String json = com.juick.json.Users.arrayToString(users);
+ Main.replyJSON(request, response, json);
+ } else {
+ response.sendError(404);
+ }
+ }
+
+ public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ int uid = 0;
+ String uname = request.getParameter("uname");
+ if (uname == null) {
+ uid = vuid;
+ } else {
+ if (UserQueries.checkUserNameValid(uname)) {
+ com.juick.User u = UserQueries.getUserByName(sql, uname);
+ if (u != null && u.UID > 0) {
+ uid = u.UID;
+ }
+ }
+ }
+
+ if (uid > 0) {
+ ArrayList uids = UserQueries.getUserRead(sql, uid);
+ if (uids.size() > 0) {
+ ArrayList users = UserQueries.getUsersByID(sql, uids);
+ if (users.size() > 0) {
+ String json = com.juick.json.Users.arrayToString(users);
+ Main.replyJSON(request, response, json);
+ return;
+ }
+ }
+ }
+ response.sendError(404);
+ }
+
+ public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ int uid = 0;
+ String uname = request.getParameter("uname");
+ if (uname == null) {
+ uid = vuid;
+ } else {
+ if (UserQueries.checkUserNameValid(uname)) {
+ com.juick.User u = UserQueries.getUserByName(sql, uname);
+ if (u != null && u.UID > 0) {
+ uid = u.UID;
+ }
+ }
+ }
+
+ if (uid > 0) {
+ ArrayList uids = UserQueries.getUserReaders(sql, uid);
+ if (uids.size() > 0) {
+ ArrayList users = UserQueries.getUsersByID(sql, uids);
+ if (users.size() > 0) {
+ String json = com.juick.json.Users.arrayToString(users);
+ Main.replyJSON(request, response, json);
+ return;
+ }
+ }
+ }
+ response.sendError(404);
+ }
+}
diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java
new file mode 100644
index 00000000..10e0cccb
--- /dev/null
+++ b/src/main/java/com/juick/api/Utils.java
@@ -0,0 +1,149 @@
+/*
+ * Juick
+ * Copyright (C) 2008-2011, Ugnich Anton
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+package com.juick.api;
+
+import com.juick.server.UserQueries;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import sun.misc.BASE64Decoder;
+
+/**
+ *
+ * @author Ugnich Anton
+ */
+public class Utils {
+
+ public static String getCookie(HttpServletRequest request, String name) {
+ Cookie cookies[] = request.getCookies();
+ if (cookies != null) {
+ for (int i = 0; i < cookies.length; i++) {
+ if (cookies[i].getName().equals(name)) {
+ return cookies[i].getValue();
+ }
+ }
+ }
+ return null;
+ }
+
+ public static com.juick.User getVisitorUser(Connection sql, HttpServletRequest request) {
+ String hash = getCookie(request, "hash");
+ if (hash != null) {
+ return com.juick.server.UserQueries.getUserByHash(sql, hash);
+ } else {
+ return null;
+ }
+ }
+
+ public static int getVisitorUID(Connection sql, HttpServletRequest request) {
+ Cookie cookies[] = request.getCookies();
+ if (cookies != null) {
+ for (int i = 0; i < cookies.length; i++) {
+ if (cookies[i].getName().equals("hash")) {
+ String hash = cookies[i].getValue();
+ return com.juick.server.UserQueries.getUIDbyHash(sql, hash);
+ }
+ }
+ }
+ return 0;
+ }
+
+ public static int getHttpAuthUID(Connection sql, HttpServletRequest request) {
+ String auth = request.getHeader("Authorization");
+ if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) {
+ try {
+ BASE64Decoder dec = new BASE64Decoder();
+ String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2);
+ if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) {
+ return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]);
+ }
+ } catch (IOException e) {
+ }
+ }
+ return 0;
+ }
+
+ public static int getVisitorQueryStringUID(Connection sql, HttpServletRequest request) {
+ String hash = request.getParameter("hash");
+ if (hash != null && hash.length() == 16) {
+ return com.juick.server.UserQueries.getUIDbyHash(sql, hash);
+ }
+ return 0;
+ }
+
+ public static void sendPermanentRedirect(HttpServletResponse response, String location) {
+ response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
+ response.setHeader("Location", location);
+ }
+
+ public static void finishSQL(ResultSet rs, Statement stmt) {
+ if (rs != null) {
+ try {
+ rs.close();
+ } catch (SQLException e) {
+ }
+ }
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (SQLException e) {
+ }
+ }
+ }
+
+ public static String convertArray2String(ArrayList mids) {
+ String q = "";
+ for (int i = 0; i < mids.size(); i++) {
+ if (i > 0) {
+ q += ",";
+ }
+ q += mids.get(i);
+ }
+ return q;
+ }
+
+ public static String encodeHTML(String str) {
+ String ret = str;
+ ret = ret.replaceAll("<", "<");
+ ret = ret.replaceAll(">", ">");
+ return str;
+ }
+
+ public static String encodeSphinx(String str) {
+ String ret = str;
+ ret = ret.replaceAll("@", "\\\\@");
+ return ret;
+ }
+
+ public static int parseInt(String str, int def) {
+ int ret = def;
+ if (str != null) {
+ try {
+ ret = Integer.parseInt(str);
+ } catch (Exception e) {
+ }
+ }
+ return ret;
+ }
+}
--
cgit v1.2.3
From 0acc3ca041434ca5486e7def8cb75729995106d5 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Tue, 3 Nov 2015 16:38:52 +0300
Subject: /messages/recommended
---
src/main/java/com/juick/api/Main.java | 6 ++++++
src/main/java/com/juick/api/Messages.java | 17 +++++++++++++++++
2 files changed, 23 insertions(+)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 5ee4027b..e10b9078 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -166,6 +166,12 @@ public class Main extends HttpServlet implements Stream.StreamListener {
} else {
response.sendError(401);
}
+ } else if (uri.equals("/messages/recommended")) {
+ if (vuid > 0) {
+ messages.doGetRecommended(request, response, vuid);
+ } else {
+ response.sendError(401);
+ }
} else if (uri.equals("/messages/set_popular") && vuid == 1) {
messages.doSetPopular(request, response, xmpp);
} else if (uri.equals("/messages/set_privacy") && vuid > 0) {
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index b5462258..76615e44 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -41,6 +41,23 @@ public class Messages {
}
}
+ public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+
+ ArrayList mids = MessagesQueries.getRecommended(sql, vuid, before_mid);
+ if (mids != null && !mids.isEmpty()) {
+ ArrayList msgs = MessagesQueries.getMessages(sql, mids);
+ if (msgs != null && !msgs.isEmpty()) {
+ String json = com.juick.json.Messages.arrayToString(msgs);
+ Main.replyJSON(request, response, json);
+ } else {
+ response.sendError(404);
+ }
+ } else {
+ response.sendError(404);
+ }
+ }
+
public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
int mid = Utils.parseInt(request.getParameter("mid"), 0);
com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid);
--
cgit v1.2.3
From 9d7b2473308fe841d84ce8af9efef164c61518e8 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Tue, 3 Nov 2015 16:52:58 +0300
Subject: recommended -> UserRecommendations
---
src/main/java/com/juick/api/Messages.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index 76615e44..b7a55361 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -44,7 +44,7 @@ public class Messages {
public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
- ArrayList mids = MessagesQueries.getRecommended(sql, vuid, before_mid);
+ ArrayList mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
if (mids != null && !mids.isEmpty()) {
ArrayList msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
--
cgit v1.2.3
From 63b14e7818a20d598e4634a0ee686376d7f687b2 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Wed, 4 Nov 2015 15:18:41 +0300
Subject: drop gson, refactoring
---
src/main/java/com/juick/api/Messages.java | 7 +++++--
src/main/java/com/juick/api/Others.java | 5 ++++-
src/main/java/com/juick/api/PM.java | 7 +++++--
src/main/java/com/juick/api/Users.java | 9 ++++++---
src/test/java/com/juick/tests/JsonTests.java | 12 ------------
5 files changed, 20 insertions(+), 20 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index b7a55361..548e816f 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -1,5 +1,6 @@
package com.juick.api;
+import com.juick.json.MessageSerializer;
import com.juick.server.MessagesQueries;
import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
@@ -19,6 +20,8 @@ import javax.servlet.http.HttpServletResponse;
public class Messages {
Connection sql;
+
+ MessageSerializer messageSerializer = new MessageSerializer();
public Messages(Connection sql) {
this.sql = sql;
@@ -31,7 +34,7 @@ public class Messages {
if (mids != null && !mids.isEmpty()) {
ArrayList msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
- String json = com.juick.json.Messages.arrayToString(msgs);
+ String json = messageSerializer.serializeList(msgs);
Main.replyJSON(request, response, json);
} else {
response.sendError(404);
@@ -48,7 +51,7 @@ public class Messages {
if (mids != null && !mids.isEmpty()) {
ArrayList msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
- String json = com.juick.json.Messages.arrayToString(msgs);
+ String json = messageSerializer.serializeList(msgs);
Main.replyJSON(request, response, json);
} else {
response.sendError(404);
diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java
index 25df5bf4..5e5c7475 100644
--- a/src/main/java/com/juick/api/Others.java
+++ b/src/main/java/com/juick/api/Others.java
@@ -1,5 +1,6 @@
package com.juick.api;
+import com.juick.json.UserSerializer;
import com.juick.server.PMQueries;
import java.io.IOException;
import java.sql.Connection;
@@ -15,6 +16,8 @@ import javax.servlet.http.HttpServletResponse;
public class Others {
Connection sql;
+
+ UserSerializer userSerializer = new UserSerializer();
public Others(Connection sql) {
this.sql = sql;
@@ -36,7 +39,7 @@ public class Others {
ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt);
if (lastconv != null && !lastconv.isEmpty()) {
- String json = "{\"pms\":" + com.juick.json.Users.arrayToString(lastconv) + "}";
+ String json = "{\"pms\":" + userSerializer.serializeList(lastconv) + "}";
Main.replyJSON(request, response, json);
} else {
response.sendError(404);
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
index 2722526d..ffcd155a 100644
--- a/src/main/java/com/juick/api/PM.java
+++ b/src/main/java/com/juick/api/PM.java
@@ -1,5 +1,6 @@
package com.juick.api;
+import com.juick.json.MessageSerializer;
import com.juick.server.PMQueries;
import com.juick.server.UserQueries;
import com.juick.xmpp.JID;
@@ -20,6 +21,8 @@ import javax.servlet.http.HttpServletResponse;
public class PM {
Connection sql;
+
+ MessageSerializer messageSerializer = new MessageSerializer();
public PM(Connection sql) {
this.sql = sql;
@@ -39,7 +42,7 @@ public class PM {
ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid);
if (msgs != null && !msgs.isEmpty()) {
- String json = com.juick.json.Messages.arrayToString(msgs);
+ String json = messageSerializer.serializeList(msgs);
Main.replyJSON(request, response, json);
} else {
response.sendError(404);
@@ -77,7 +80,7 @@ public class PM {
msg.to.Host = "ws.juick.com";
xmpp.send(msg);
- Main.replyJSON(request, response, com.juick.json.Message.toJSON(jmsg).toString());
+ Main.replyJSON(request, response, messageSerializer.serialize(jmsg).toString());
String jid = UserQueries.getJIDbyUID(sql, uid);
if (jid != null) {
diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java
index cdd48fd6..37c9ca49 100644
--- a/src/main/java/com/juick/api/Users.java
+++ b/src/main/java/com/juick/api/Users.java
@@ -1,6 +1,7 @@
package com.juick.api;
import com.juick.User;
+import com.juick.json.UserSerializer;
import com.juick.server.UserQueries;
import java.io.IOException;
import java.sql.Connection;
@@ -18,6 +19,8 @@ import javax.servlet.http.HttpServletResponse;
public class Users {
Connection sql;
+
+ UserSerializer userSerializer = new UserSerializer();
public Users(Connection sql) {
this.sql = sql;
@@ -55,7 +58,7 @@ public class Users {
}
if (!users.isEmpty()) {
- String json = com.juick.json.Users.arrayToString(users);
+ String json = userSerializer.serializeList(users);
Main.replyJSON(request, response, json);
} else {
response.sendError(404);
@@ -81,7 +84,7 @@ public class Users {
if (uids.size() > 0) {
ArrayList users = UserQueries.getUsersByID(sql, uids);
if (users.size() > 0) {
- String json = com.juick.json.Users.arrayToString(users);
+ String json = userSerializer.serializeList(users);
Main.replyJSON(request, response, json);
return;
}
@@ -109,7 +112,7 @@ public class Users {
if (uids.size() > 0) {
ArrayList users = UserQueries.getUsersByID(sql, uids);
if (users.size() > 0) {
- String json = com.juick.json.Users.arrayToString(users);
+ String json = userSerializer.serializeList(users);
Main.replyJSON(request, response, json);
return;
}
diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java
index 9a42dea5..f44fac20 100644
--- a/src/test/java/com/juick/tests/JsonTests.java
+++ b/src/test/java/com/juick/tests/JsonTests.java
@@ -1,23 +1,11 @@
package com.juick.tests;
-import com.google.gson.Gson;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-import com.juick.Message;
-
public class JsonTests {
@Test
public void CompareSerializers() {
- Message msg = new Message();
- msg.ReplyTo = 1;
- msg.MID = 234566;
- Gson gson = new Gson();
- String gsonResult = gson.toJson(msg);
- String ugnichResult = com.juick.json.Message.toJSON(msg).toString();
- System.out.println(gsonResult);
- System.out.println(ugnichResult);
- assertEquals("our result must equal to ugnich", ugnichResult, gsonResult);
}
}
\ No newline at end of file
--
cgit v1.2.3
From 36a01d90e0948435046abf0c40db48a60c525420 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 5 Nov 2015 16:02:04 +0300
Subject: set myself as top moderator
---
src/main/java/com/juick/api/Main.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index e10b9078..07504179 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -172,7 +172,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
} else {
response.sendError(401);
}
- } else if (uri.equals("/messages/set_popular") && vuid == 1) {
+ } else if (uri.equals("/messages/set_popular") && vuid == 3694) {
messages.doSetPopular(request, response, xmpp);
} else if (uri.equals("/messages/set_privacy") && vuid > 0) {
messages.doSetPrivacy(request, response, xmpp, vuid);
--
cgit v1.2.3
From ee86970fcae9878af0adcad00cf5333647b8babf Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Sun, 10 Jan 2016 18:54:05 +0300
Subject: refactoring
---
src/main/java/com/juick/api/Main.java | 23 ++++++++++-------------
src/main/java/com/juick/api/Messages.java | 15 ++++++++-------
src/main/java/com/juick/api/Others.java | 10 ++++++----
src/main/java/com/juick/api/PM.java | 3 ++-
src/main/java/com/juick/api/Users.java | 23 ++++++++++++-----------
src/test/java/com/juick/tests/JsonTests.java | 5 +++--
6 files changed, 41 insertions(+), 38 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 07504179..09dd4cbd 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -28,6 +28,7 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
+import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
@@ -75,18 +76,14 @@ public class Main extends HttpServlet implements Stream.StreamListener {
}
public void setupXmppComponent(final String password) {
- Thread thr = new Thread(new Runnable() {
-
- @Override
- public void run() {
- try {
- Socket socket = new Socket("localhost", 5347);
- xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password);
- xmpp.addListener(Main.this);
- xmpp.startParsing();
- } catch (IOException e) {
- System.err.println(e);
- }
+ Thread thr = new Thread(() -> {
+ try {
+ Socket socket = new Socket("localhost", 5347);
+ xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password);
+ xmpp.addListener(Main.this);
+ xmpp.startParsing();
+ } catch (IOException e) {
+ log("XMPP exception", e);
}
});
thr.start();
@@ -94,7 +91,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
@Override
public void onStreamFail(String msg) {
- System.err.println("XMPP STREAM FAIL: " + msg);
+ log("XMPP failed: " + msg);
}
@Override
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index 548e816f..cde3987f 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -6,12 +6,13 @@ import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
import com.juick.xmpp.extensions.JuickMessage;
-import java.io.IOException;
-import java.sql.Connection;
-import java.util.ArrayList;
+
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.List;
/**
*
@@ -30,9 +31,9 @@ public class Messages {
public void doGetHome(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
- ArrayList mids = MessagesQueries.getMyFeed(sql, vuid, before_mid);
+ List mids = MessagesQueries.getMyFeed(sql, vuid, before_mid);
if (mids != null && !mids.isEmpty()) {
- ArrayList msgs = MessagesQueries.getMessages(sql, mids);
+ List msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
String json = messageSerializer.serializeList(msgs);
Main.replyJSON(request, response, json);
@@ -47,9 +48,9 @@ public class Messages {
public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
- ArrayList mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
+ List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
if (mids != null && !mids.isEmpty()) {
- ArrayList msgs = MessagesQueries.getMessages(sql, mids);
+ List msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
String json = messageSerializer.serializeList(msgs);
Main.replyJSON(request, response, json);
diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java
index 5e5c7475..323ed41a 100644
--- a/src/main/java/com/juick/api/Others.java
+++ b/src/main/java/com/juick/api/Others.java
@@ -1,13 +1,15 @@
package com.juick.api;
+import com.juick.User;
import com.juick.json.UserSerializer;
import com.juick.server.PMQueries;
-import java.io.IOException;
-import java.sql.Connection;
-import java.util.ArrayList;
+
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.List;
/**
*
@@ -37,7 +39,7 @@ public class Others {
} catch (Exception e) {
}
- ArrayList lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt);
+ List lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt);
if (lastconv != null && !lastconv.isEmpty()) {
String json = "{\"pms\":" + userSerializer.serializeList(lastconv) + "}";
Main.replyJSON(request, response, json);
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
index ffcd155a..f22a4add 100644
--- a/src/main/java/com/juick/api/PM.java
+++ b/src/main/java/com/juick/api/PM.java
@@ -10,6 +10,7 @@ import com.juick.xmpp.extensions.JuickMessage;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
+import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -40,7 +41,7 @@ public class PM {
return;
}
- ArrayList msgs = PMQueries.getPMMessages(sql, vuid, uid);
+ List msgs = PMQueries.getPMMessages(sql, vuid, uid);
if (msgs != null && !msgs.isEmpty()) {
String json = messageSerializer.serializeList(msgs);
Main.replyJSON(request, response, json);
diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java
index 37c9ca49..5bae4028 100644
--- a/src/main/java/com/juick/api/Users.java
+++ b/src/main/java/com/juick/api/Users.java
@@ -1,16 +1,17 @@
package com.juick.api;
-import com.juick.User;
import com.juick.json.UserSerializer;
import com.juick.server.UserQueries;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import java.util.List;
/**
*
@@ -27,11 +28,11 @@ public class Users {
}
public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
- ArrayList users = new ArrayList();
+ List users = new ArrayList<>();
String punames[] = request.getParameterValues("uname");
if (punames != null) {
- ArrayList unames = new ArrayList(Arrays.asList(punames));
+ ArrayList unames = new ArrayList<>(Arrays.asList(punames));
Iterator i = unames.iterator();
while (i.hasNext()) {
if (!i.next().matches("^[a-zA-Z0-9\\-]{2,16}$")) {
@@ -45,7 +46,7 @@ public class Users {
String pjids[] = request.getParameterValues("jid");
if (pjids != null) {
- ArrayList jids = new ArrayList(Arrays.asList(pjids));
+ List jids = new ArrayList<>(Arrays.asList(pjids));
Iterator ii = jids.iterator();
while (ii.hasNext()) {
if (!ii.next().matches("^[a-zA-Z0-9\\-\\_\\@\\.]{6,64}$")) {
@@ -80,9 +81,9 @@ public class Users {
}
if (uid > 0) {
- ArrayList uids = UserQueries.getUserRead(sql, uid);
+ List uids = UserQueries.getUserRead(sql, uid);
if (uids.size() > 0) {
- ArrayList users = UserQueries.getUsersByID(sql, uids);
+ List users = UserQueries.getUsersByID(sql, uids);
if (users.size() > 0) {
String json = userSerializer.serializeList(users);
Main.replyJSON(request, response, json);
@@ -108,9 +109,9 @@ public class Users {
}
if (uid > 0) {
- ArrayList uids = UserQueries.getUserReaders(sql, uid);
+ List uids = UserQueries.getUserReaders(sql, uid);
if (uids.size() > 0) {
- ArrayList users = UserQueries.getUsersByID(sql, uids);
+ List users = UserQueries.getUsersByID(sql, uids);
if (users.size() > 0) {
String json = userSerializer.serializeList(users);
Main.replyJSON(request, response, json);
diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java
index c99432a6..35854171 100644
--- a/src/test/java/com/juick/tests/JsonTests.java
+++ b/src/test/java/com/juick/tests/JsonTests.java
@@ -14,6 +14,7 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
+import java.util.List;
import java.util.Properties;
public class JsonTests {
@@ -40,10 +41,10 @@ public class JsonTests {
@Test
public void CompareSerializers() {
- ArrayList mids = MessagesQueries.getMyFeed(sql, 3694, 2799786);
+ List mids = MessagesQueries.getMyFeed(sql, 3694, 2799786);
MessageSerializer messageSerializer = new MessageSerializer();
if (mids != null && !mids.isEmpty()) {
- ArrayList msgs = MessagesQueries.getMessages(sql, mids);
+ List msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
String json = messageSerializer.serializeList(msgs);
try {
--
cgit v1.2.3
From 690b3ea447a7a2434ecf1d210e5f5ef89ce27f04 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 15 Jan 2016 12:51:21 +0300
Subject: spring-jdbc WIP
---
build.gradle | 2 ++
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/Main.java | 47 ++++++++++++++-----------
src/main/java/com/juick/api/Messages.java | 54 ++++++++++++++++++++++++-----
src/main/java/com/juick/api/Others.java | 5 +--
src/main/java/com/juick/api/PM.java | 12 +++----
src/main/java/com/juick/api/Users.java | 6 ++--
src/main/java/com/juick/api/Utils.java | 7 ++--
src/test/java/com/juick/tests/ApiTests.java | 40 +++++++++++++++++++++
9 files changed, 131 insertions(+), 44 deletions(-)
create mode 100644 src/test/java/com/juick/tests/ApiTests.java
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index 14e74f02..c2ca747e 100644
--- a/build.gradle
+++ b/build.gradle
@@ -53,6 +53,8 @@ dependencies {
compile server
compile xmpp
compile json
+ compile "org.springframework:spring-jdbc:4.2.4.RELEASE"
+ compile "org.apache.commons:commons-dbcp2:2.1.1"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
def tomcatVersion = '7.0.+'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
diff --git a/deps/com.juick.server b/deps/com.juick.server
index c37ed56f..9bd8a41c 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit c37ed56f884661666b964e47efd23a36be9b24d4
+Subproject commit 9bd8a41c0db5a1027a184facfca8d0152945c078
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 09dd4cbd..71f7f2d7 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -20,6 +20,9 @@ package com.juick.api;
import com.juick.xmpp.JID;
import com.juick.xmpp.Stream;
import com.juick.xmpp.StreamComponent;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.springframework.jdbc.core.JdbcTemplate;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
@@ -28,7 +31,6 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
-import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
@@ -46,6 +48,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
Connection sql;
Connection sqlSearch;
+ JdbcTemplate jdbc;
Stream xmpp;
Messages messages;
Users users;
@@ -58,19 +61,22 @@ public class Main extends HttpServlet implements Stream.StreamListener {
try {
Properties conf = new Properties();
conf.load(new FileInputStream("/etc/juick/api.conf"));
-
- Class.forName("com.mysql.jdbc.Driver");
+ final String driverClassName = "com.mysql.jdbc.Driver";
+ Class.forName(driverClassName);
sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", ""));
sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password=");
-
- messages = new Messages(sql);
- users = new Users(sql);
- pm = new PM(sql);
- others = new Others(sql);
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setUrl(sql.getMetaData().getURL());
+ dataSource.setDriverClassName(driverClassName);
+ jdbc = new JdbcTemplate(dataSource);
+ messages = new Messages(jdbc);
+ users = new Users(jdbc);
+ pm = new PM(jdbc);
+ others = new Others(jdbc);
setupXmppComponent(conf.getProperty("xmpp_password"));
- } catch (Exception e) {
+ } catch (IOException | ClassNotFoundException | SQLException e) {
log(null, e);
}
}
@@ -135,7 +141,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
int vuid = Utils.getHttpAuthUID(sql, request);
if (vuid == 0) {
- vuid = Utils.getVisitorQueryStringUID(sql, request);
+ vuid = Utils.getVisitorQueryStringUID(jdbc, request);
}
String uri = request.getRequestURI();
@@ -193,7 +199,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
int vuid = Utils.getHttpAuthUID(sql, request);
if (vuid == 0) {
- vuid = Utils.getVisitorQueryStringUID(sql, request);
+ vuid = Utils.getVisitorQueryStringUID(jdbc, request);
}
if (vuid == 0) {
response.sendError(401);
@@ -201,11 +207,15 @@ public class Main extends HttpServlet implements Stream.StreamListener {
}
String uri = request.getRequestURI();
- if (uri.equals("/post")) {
- } else if (uri.equals("/pm")) {
- pm.doPostPM(request, response, xmpp, vuid);
- } else {
- response.sendError(405);
+ switch (uri) {
+ case "/post":
+ break;
+ case "/pm":
+ pm.doPostPM(request, response, xmpp, vuid);
+ break;
+ default:
+ response.sendError(405);
+ break;
}
}
@@ -218,8 +228,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
callback = null;
}
- PrintWriter out = response.getWriter();
- try {
+ try (PrintWriter out = response.getWriter()) {
if (callback != null) {
out.print(callback + "(");
out.print(json);
@@ -227,8 +236,6 @@ public class Main extends HttpServlet implements Stream.StreamListener {
} else {
out.print(json);
}
- } finally {
- out.close();
}
}
}
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index cde3987f..e3dcabfd 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -1,17 +1,21 @@
package com.juick.api;
+import com.juick.Tag;
+import com.juick.User;
import com.juick.json.MessageSerializer;
import com.juick.server.MessagesQueries;
+import com.juick.server.TagQueries;
+import com.juick.server.UserQueries;
import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
import com.juick.xmpp.extensions.JuickMessage;
+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.sql.Connection;
import java.util.List;
/**
@@ -20,11 +24,32 @@ import java.util.List;
*/
public class Messages {
- Connection sql;
+ JdbcTemplate sql;
MessageSerializer messageSerializer = new MessageSerializer();
- public Messages(Connection sql) {
+ enum MediaType {
+ ALL("all"),
+ PHOTO("photo"),
+ VIDEO("video"),
+ NONE("");
+
+ private final String value;
+
+ MediaType(final String value) {
+ this.value = value;
+ }
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return this.getValue();
+ }
+ }
+
+ public Messages(JdbcTemplate sql) {
this.sql = sql;
}
@@ -45,8 +70,19 @@ public class Messages {
}
}
- public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGet(HttpServletRequest request, HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
+ User user = UserQueries.getUserByName(sql, request.getParameter("uname"));
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+ int page = Utils.parseInt(request.getParameter("page"), 0);
+ MediaType media = MediaType.valueOf(request.getParameter("media"));
+ boolean popular = Boolean.valueOf(request.getParameter("popular"));
+ Tag tag = TagQueries.getTag(sql, request.getParameter("tag"), false);
+
+ }
+
+ public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ /*int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
if (mids != null && !mids.isEmpty()) {
@@ -59,21 +95,21 @@ public class Messages {
}
} else {
response.sendError(404);
- }
+ }*/
}
public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
- int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ /*int mid = Utils.parseInt(request.getParameter("mid"), 0);
com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid);
if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) {
Main.replyJSON(request, response, "{\"status\":\"ok\"}");
} else {
response.sendError(400);
- }
+ }*/
}
public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException {
- int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ /*int mid = Utils.parseInt(request.getParameter("mid"), 0);
int popular = Utils.parseInt(request.getParameter("popular"), 0);
if (mid > 0) {
@@ -105,6 +141,6 @@ public class Messages {
}
Main.replyJSON(request, response, "{\"status\":\"ok\"}");
- }
+ }*/
}
}
diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java
index 323ed41a..3c8d4a96 100644
--- a/src/main/java/com/juick/api/Others.java
+++ b/src/main/java/com/juick/api/Others.java
@@ -3,6 +3,7 @@ package com.juick.api;
import com.juick.User;
import com.juick.json.UserSerializer;
import com.juick.server.PMQueries;
+import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -17,11 +18,11 @@ import java.util.List;
*/
public class Others {
- Connection sql;
+ JdbcTemplate sql;
UserSerializer userSerializer = new UserSerializer();
- public Others(Connection sql) {
+ public Others(JdbcTemplate sql) {
this.sql = sql;
}
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
index f22a4add..01a5669a 100644
--- a/src/main/java/com/juick/api/PM.java
+++ b/src/main/java/com/juick/api/PM.java
@@ -7,9 +7,9 @@ import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
import com.juick.xmpp.extensions.JuickMessage;
+import org.springframework.jdbc.core.JdbcTemplate;
+
import java.io.IOException;
-import java.sql.Connection;
-import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -21,11 +21,11 @@ import javax.servlet.http.HttpServletResponse;
*/
public class PM {
- Connection sql;
-
- MessageSerializer messageSerializer = new MessageSerializer();
+ JdbcTemplate sql;
+
+ MessageSerializer messageSerializer = new MessageSerializer();
- public PM(Connection sql) {
+ public PM(JdbcTemplate sql) {
this.sql = sql;
}
diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java
index 5bae4028..d3818a5a 100644
--- a/src/main/java/com/juick/api/Users.java
+++ b/src/main/java/com/juick/api/Users.java
@@ -2,12 +2,12 @@ package com.juick.api;
import com.juick.json.UserSerializer;
import com.juick.server.UserQueries;
+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.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
@@ -19,11 +19,11 @@ import java.util.List;
*/
public class Users {
- Connection sql;
+ JdbcTemplate sql;
UserSerializer userSerializer = new UserSerializer();
- public Users(Connection sql) {
+ public Users(JdbcTemplate sql) {
this.sql = sql;
}
diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java
index 10e0cccb..db73fdaa 100644
--- a/src/main/java/com/juick/api/Utils.java
+++ b/src/main/java/com/juick/api/Utils.java
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.springframework.jdbc.core.JdbcTemplate;
import sun.misc.BASE64Decoder;
/**
@@ -47,7 +48,7 @@ public class Utils {
return null;
}
- public static com.juick.User getVisitorUser(Connection sql, HttpServletRequest request) {
+ public static com.juick.User getVisitorUser(JdbcTemplate sql, HttpServletRequest request) {
String hash = getCookie(request, "hash");
if (hash != null) {
return com.juick.server.UserQueries.getUserByHash(sql, hash);
@@ -56,7 +57,7 @@ public class Utils {
}
}
- public static int getVisitorUID(Connection sql, HttpServletRequest request) {
+ public static int getVisitorUID(JdbcTemplate sql, HttpServletRequest request) {
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
@@ -84,7 +85,7 @@ public class Utils {
return 0;
}
- public static int getVisitorQueryStringUID(Connection sql, HttpServletRequest request) {
+ public static int getVisitorQueryStringUID(JdbcTemplate sql, HttpServletRequest request) {
String hash = request.getParameter("hash");
if (hash != null && hash.length() == 16) {
return com.juick.server.UserQueries.getUIDbyHash(sql, hash);
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
new file mode 100644
index 00000000..01cdd4c5
--- /dev/null
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -0,0 +1,40 @@
+package com.juick.tests;
+
+import com.juick.User;
+import com.juick.server.UserQueries;
+import junit.framework.Assert;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Properties;
+
+/**
+ * Created by vt on 14.01.2016.
+ */
+public class ApiTests {
+ JdbcTemplate jdbc;
+ @Before
+ public void setupConnection() {
+ Properties conf = new Properties();
+ try {
+ conf.load(new FileInputStream("/etc/juick/api.conf"));
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName("com.mysql.jdbc.Driver");
+ dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user="
+ + conf.getProperty("mysql_username", "")
+ + "&password=" + conf.getProperty("mysql_password", ""));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void userTests() {
+ User user = UserQueries.getUserByUID(jdbc, 3694);
+ Assert.assertEquals("it should be me", "vt", user.UName);
+ }
+}
--
cgit v1.2.3
From f9d5099bf4be816aa267e02b5713a672fd4da562 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 15 Jan 2016 14:49:51 +0300
Subject: spring-jdbc WIP
---
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/Messages.java | 12 ++++++------
src/test/java/com/juick/tests/ApiTests.java | 9 +++++++++
3 files changed, 16 insertions(+), 7 deletions(-)
(limited to 'src/main/java/com')
diff --git a/deps/com.juick.server b/deps/com.juick.server
index 1ef890d2..2635d618 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit 1ef890d21db2ed9aeefc37b71ff82d0f59df8516
+Subproject commit 2635d6187ecd48c732d21e4f510f1df8451ce646
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index e3dcabfd..fb9be051 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -82,7 +82,7 @@ public class Messages {
}
public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
- /*int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+ int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
if (mids != null && !mids.isEmpty()) {
@@ -95,21 +95,21 @@ public class Messages {
}
} else {
response.sendError(404);
- }*/
+ }
}
public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
- /*int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid);
if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) {
Main.replyJSON(request, response, "{\"status\":\"ok\"}");
} else {
response.sendError(400);
- }*/
+ }
}
public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException {
- /*int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
int popular = Utils.parseInt(request.getParameter("popular"), 0);
if (mid > 0) {
@@ -141,6 +141,6 @@ public class Messages {
}
Main.replyJSON(request, response, "{\"status\":\"ok\"}");
- }*/
+ }
}
}
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
index f111ffc7..e67c23f2 100644
--- a/src/test/java/com/juick/tests/ApiTests.java
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -1,7 +1,9 @@
package com.juick.tests;
+import com.juick.Message;
import com.juick.User;
import com.juick.server.UserQueries;
+import com.juick.server.MessagesQueries;
import junit.framework.Assert;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Before;
@@ -38,4 +40,11 @@ public class ApiTests {
User user = UserQueries.getUserByUID(jdbc, 3694);
Assert.assertEquals("it should be me", "vt", user.UName);
}
+
+ @Test void messageTests() {
+ Message msg = MessagesQueries.getMessage(jdbc, 2817722);
+ User ugnich = msg.User;
+ Assert.assertEquals("ugnich", ugnich.UName);
+ Assert.assertEquals("Microsoft", msg.Tags.get(0));
+ }
}
--
cgit v1.2.3
From 30068e18a3d8ae37b509f5cd766515735a818692 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 15 Jan 2016 15:54:04 +0300
Subject: update core
---
deps/com.juick | 2 +-
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/Messages.java | 23 ++++++++++++++++-------
src/main/java/com/juick/api/Others.java | 4 +++-
src/main/java/com/juick/api/PM.java | 16 ++++++++++------
src/main/java/com/juick/api/Users.java | 20 +++++++++++++-------
src/test/java/com/juick/tests/ApiTests.java | 6 +++---
7 files changed, 47 insertions(+), 26 deletions(-)
(limited to 'src/main/java/com')
diff --git a/deps/com.juick b/deps/com.juick
index 5f08b8b1..1df19b47 160000
--- a/deps/com.juick
+++ b/deps/com.juick
@@ -1 +1 @@
-Subproject commit 5f08b8b1cfaacf1e78c56e7752277533eb84b02e
+Subproject commit 1df19b47f7f463e6cafa7dcf877cb42967fff166
diff --git a/deps/com.juick.server b/deps/com.juick.server
index 0ac9d76d..f14eea2c 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit 0ac9d76d6348f487ada697678395d15abee244c9
+Subproject commit f14eea2cfc80dac5e9b304a57457e7f82842a8ed
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index fb9be051..e242d05b 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -53,7 +53,9 @@ public class Messages {
this.sql = sql;
}
- public void doGetHome(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetHome(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
List mids = MessagesQueries.getMyFeed(sql, vuid, before_mid);
@@ -70,7 +72,8 @@ public class Messages {
}
}
- public void doGet(HttpServletRequest request, HttpServletResponse response, int vuid)
+ public void doGet(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
throws ServletException, IOException {
User user = UserQueries.getUserByName(sql, request.getParameter("uname"));
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
@@ -81,7 +84,9 @@ public class Messages {
}
- public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetRecommended(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
@@ -98,17 +103,21 @@ public class Messages {
}
}
- public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
+ public void doSetPrivacy(HttpServletRequest request,
+ HttpServletResponse response, Stream xmpp, int vuid)
+ throws ServletException, IOException {
int mid = Utils.parseInt(request.getParameter("mid"), 0);
com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid);
- if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) {
+ if (user != null && user.getUID() == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) {
Main.replyJSON(request, response, "{\"status\":\"ok\"}");
} else {
response.sendError(400);
}
}
- public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException {
+ public void doSetPopular(HttpServletRequest request,
+ HttpServletResponse response, Stream xmpp)
+ throws ServletException, IOException {
int mid = Utils.parseInt(request.getParameter("mid"), 0);
int popular = Utils.parseInt(request.getParameter("popular"), 0);
@@ -123,7 +132,7 @@ public class Messages {
msg.from = new JID("juick", "juick.com", null);
msg.to = new JID(null, "crosspost.juick.com", null);
JuickMessage jmsg = new JuickMessage(m);
- jmsg.User.UID = 11574;
+ jmsg.setUser(UserQueries.getUserByUID(sql, 11574));
msg.childs.add(jmsg);
msg.to.Username = "twitter";
diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java
index 3c8d4a96..12849f90 100644
--- a/src/main/java/com/juick/api/Others.java
+++ b/src/main/java/com/juick/api/Others.java
@@ -26,7 +26,9 @@ public class Others {
this.sql = sql;
}
- public void doGetGroupsPMs(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetGroupsPMs(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
int cnt = 5;
try {
String cntStr = request.getParameter("cnt");
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
index 01a5669a..3ca9eada 100644
--- a/src/main/java/com/juick/api/PM.java
+++ b/src/main/java/com/juick/api/PM.java
@@ -29,7 +29,9 @@ public class PM {
this.sql = sql;
}
- public void doGetPM(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetPM(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
String uname = request.getParameter("uname");
int uid = 0;
if (uname != null && uname.matches("^[a-zA-Z0-9\\-]{2,16}$")) {
@@ -50,7 +52,9 @@ public class PM {
}
}
- public void doPostPM(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException {
+ public void doPostPM(HttpServletRequest request,
+ HttpServletResponse response, Stream xmpp, int vuid)
+ throws ServletException, IOException {
String uname = request.getParameter("uname");
int uid = 0;
if (UserQueries.checkUserNameValid(uname)) {
@@ -73,8 +77,8 @@ public class PM {
msg.from = new JID("juick", "juick.com", null);
msg.to = new JID(Integer.toString(uid), "push.juick.com", null);
JuickMessage jmsg = new JuickMessage();
- jmsg.User = UserQueries.getUserByUID(sql, vuid);
- jmsg.Text = body;
+ jmsg.setUser(UserQueries.getUserByUID(sql, vuid));
+ jmsg.setText(body);
msg.childs.add(jmsg);
xmpp.send(msg);
@@ -89,11 +93,11 @@ public class PM {
mm.to = new JID(jid);
mm.type = Message.Type.chat;
if (PMQueries.havePMinRoster(sql, vuid, jid)) {
- mm.from = new JID(jmsg.User.UName, "juick.com", "Juick");
+ mm.from = new JID(jmsg.getUser().getUName(), "juick.com", "Juick");
mm.body = body;
} else {
mm.from = new JID("juick", "juick.com", "Juick");
- mm.body = "Private message from @" + jmsg.User.UName + ":\n" + body;
+ mm.body = "Private message from @" + jmsg.getUser().getUName() + ":\n" + body;
}
xmpp.send(mm);
}
diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java
index d3818a5a..57f8c4b9 100644
--- a/src/main/java/com/juick/api/Users.java
+++ b/src/main/java/com/juick/api/Users.java
@@ -27,7 +27,9 @@ public class Users {
this.sql = sql;
}
- public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetUsers(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
List users = new ArrayList<>();
String punames[] = request.getParameterValues("uname");
@@ -66,7 +68,9 @@ public class Users {
}
}
- public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetUserRead(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
int uid = 0;
String uname = request.getParameter("uname");
if (uname == null) {
@@ -74,8 +78,8 @@ public class Users {
} else {
if (UserQueries.checkUserNameValid(uname)) {
com.juick.User u = UserQueries.getUserByName(sql, uname);
- if (u != null && u.UID > 0) {
- uid = u.UID;
+ if (u != null && u.getUID() > 0) {
+ uid = u.getUID();
}
}
}
@@ -94,7 +98,9 @@ public class Users {
response.sendError(404);
}
- public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException {
+ public void doGetUserReaders(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
int uid = 0;
String uname = request.getParameter("uname");
if (uname == null) {
@@ -102,8 +108,8 @@ public class Users {
} else {
if (UserQueries.checkUserNameValid(uname)) {
com.juick.User u = UserQueries.getUserByName(sql, uname);
- if (u != null && u.UID > 0) {
- uid = u.UID;
+ if (u != null && u.getUID() > 0) {
+ uid = u.getUID();
}
}
}
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
index b679f528..046077ef 100644
--- a/src/test/java/com/juick/tests/ApiTests.java
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -38,14 +38,14 @@ public class ApiTests {
@Test
public void userTests() {
User user = UserQueries.getUserByUID(jdbc, 3694);
- Assert.assertEquals("it should be me", "vt", user.UName);
+ Assert.assertEquals("it should be me", "vt", user.getUName());
}
@Test
public void messageTests() {
Message msg = MessagesQueries.getMessage(jdbc, 2817722);
- User ugnich = msg.User;
- Assert.assertEquals("ugnich", ugnich.UName);
+ User ugnich = msg.getUser();
+ Assert.assertEquals("ugnich", ugnich.getUName());
Assert.assertEquals("Microsoft", msg.Tags.get(0));
}
}
--
cgit v1.2.3
From 093a022955d547e6f94a4204a193c0e7296c11b2 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Sat, 16 Jan 2016 14:13:11 +0300
Subject: drop unneeded dependency
---
build.gradle | 1 -
src/main/java/com/juick/api/Main.java | 16 ++++++++--------
src/test/java/com/juick/tests/JsonTests.java | 6 +++---
3 files changed, 11 insertions(+), 12 deletions(-)
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index c2ca747e..380f5b39 100644
--- a/build.gradle
+++ b/build.gradle
@@ -54,7 +54,6 @@ dependencies {
compile xmpp
compile json
compile "org.springframework:spring-jdbc:4.2.4.RELEASE"
- compile "org.apache.commons:commons-dbcp2:2.1.1"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
def tomcatVersion = '7.0.+'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 71f7f2d7..4233c45d 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -20,9 +20,15 @@ package com.juick.api;
import com.juick.xmpp.JID;
import com.juick.xmpp.Stream;
import com.juick.xmpp.StreamComponent;
-import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+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.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
@@ -31,12 +37,6 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
-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;
/**
*
@@ -65,7 +65,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
Class.forName(driverClassName);
sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", ""));
sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password=");
- BasicDataSource dataSource = new BasicDataSource();
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(sql.getMetaData().getURL());
dataSource.setDriverClassName(driverClassName);
jdbc = new JdbcTemplate(dataSource);
diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java
index 496dea24..795b3429 100644
--- a/src/test/java/com/juick/tests/JsonTests.java
+++ b/src/test/java/com/juick/tests/JsonTests.java
@@ -5,6 +5,8 @@ import com.juick.server.MessagesQueries;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.io.FileInputStream;
import java.io.IOException;
@@ -12,8 +14,6 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
-import org.apache.commons.dbcp2.BasicDataSource;
-import org.springframework.jdbc.core.JdbcTemplate;
public class JsonTests {
@@ -23,7 +23,7 @@ public class JsonTests {
Properties conf = new Properties();
try {
conf.load(new FileInputStream("/etc/juick/api.conf"));
- BasicDataSource dataSource = new BasicDataSource();
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user="
+ conf.getProperty("mysql_username", "")
--
cgit v1.2.3
From f0834c91bfcd8b5d6f658c946334ad6b89ad36a3 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Sat, 16 Jan 2016 18:33:36 +0300
Subject: almost working with spring-jdbc
---
build.gradle | 1 +
deps/com.juick | 2 +-
deps/com.juick.json | 2 +-
deps/com.juick.server | 2 +-
deps/com.juick.xmpp | 2 +-
src/main/java/com/juick/api/Main.java | 39 ++------
src/main/java/com/juick/api/Utils.java | 2 +-
src/test/java/com/juick/tests/ApiTests.java | 127 +++++++++++++++++++++------
src/test/java/com/juick/tests/JsonTests.java | 55 ------------
src/test/java/com/juick/tests/original.json | 1 -
10 files changed, 110 insertions(+), 123 deletions(-)
delete mode 100644 src/test/java/com/juick/tests/JsonTests.java
delete mode 100644 src/test/java/com/juick/tests/original.json
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index 380f5b39..ea705d8c 100644
--- a/build.gradle
+++ b/build.gradle
@@ -61,6 +61,7 @@ dependencies {
"org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
testCompile 'junit:junit:4.12'
runtime 'mysql:mysql-connector-java:5.1.37'
+ testRuntime 'com.h2database:h2:1.4.190'
}
compileJava.options.encoding = 'UTF-8'
diff --git a/deps/com.juick b/deps/com.juick
index 1df19b47..39ec74ab 160000
--- a/deps/com.juick
+++ b/deps/com.juick
@@ -1 +1 @@
-Subproject commit 1df19b47f7f463e6cafa7dcf877cb42967fff166
+Subproject commit 39ec74abe77cdab5aa8f50c2524e6f71c2dbbd01
diff --git a/deps/com.juick.json b/deps/com.juick.json
index ee0e13e7..9a50ad8d 160000
--- a/deps/com.juick.json
+++ b/deps/com.juick.json
@@ -1 +1 @@
-Subproject commit ee0e13e7243abecf242236c224551774195524a3
+Subproject commit 9a50ad8dea5e9ebc5eb1c5efb19aa7a784283e14
diff --git a/deps/com.juick.server b/deps/com.juick.server
index 09fd6b8e..714a267a 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit 09fd6b8ee40802eceff9746d3c23aa8446ccbd64
+Subproject commit 714a267ae35354e86512288e0ac91990937f95ab
diff --git a/deps/com.juick.xmpp b/deps/com.juick.xmpp
index c266eb31..a096ecc6 160000
--- a/deps/com.juick.xmpp
+++ b/deps/com.juick.xmpp
@@ -1 +1 @@
-Subproject commit c266eb31e454dc382caadf8efc19d688125ac287
+Subproject commit a096ecc6d011bf0f6c738b10d7d0a7319ffcf2dc
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 4233c45d..cdced593 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -33,9 +33,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
import java.util.Properties;
/**
@@ -46,8 +43,6 @@ import java.util.Properties;
@MultipartConfig
public class Main extends HttpServlet implements Stream.StreamListener {
- Connection sql;
- Connection sqlSearch;
JdbcTemplate jdbc;
Stream xmpp;
Messages messages;
@@ -62,11 +57,8 @@ public class Main extends HttpServlet implements Stream.StreamListener {
Properties conf = new Properties();
conf.load(new FileInputStream("/etc/juick/api.conf"));
final String driverClassName = "com.mysql.jdbc.Driver";
- Class.forName(driverClassName);
- sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", ""));
- sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password=");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setUrl(sql.getMetaData().getURL());
+ dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", ""));
dataSource.setDriverClassName(driverClassName);
jdbc = new JdbcTemplate(dataSource);
messages = new Messages(jdbc);
@@ -76,8 +68,8 @@ public class Main extends HttpServlet implements Stream.StreamListener {
setupXmppComponent(conf.getProperty("xmpp_password"));
- } catch (IOException | ClassNotFoundException | SQLException e) {
- log(null, e);
+ } catch (IOException e) {
+ log("API initialization error", e);
}
}
@@ -105,27 +97,6 @@ public class Main extends HttpServlet implements Stream.StreamListener {
System.err.println("XMPP STREAM READY");
}
- @Override
- public void destroy() {
- super.destroy();
- if (sql != null) {
- try {
- sql.close();
- sql = null;
- } catch (SQLException e) {
- log(null, e);
- }
- }
- if (sqlSearch != null) {
- try {
- sqlSearch.close();
- sqlSearch = null;
- } catch (SQLException e) {
- log(null, e);
- }
- }
- }
-
/**
* Handles the HTTP GET
method.
* @param request servlet request
@@ -139,7 +110,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
request.setCharacterEncoding("UTF-8");
}
- int vuid = Utils.getHttpAuthUID(sql, request);
+ int vuid = Utils.getHttpAuthUID(jdbc, request);
if (vuid == 0) {
vuid = Utils.getVisitorQueryStringUID(jdbc, request);
}
@@ -197,7 +168,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
request.setCharacterEncoding("UTF-8");
}
- int vuid = Utils.getHttpAuthUID(sql, request);
+ int vuid = Utils.getHttpAuthUID(jdbc, request);
if (vuid == 0) {
vuid = Utils.getVisitorQueryStringUID(jdbc, request);
}
diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java
index db73fdaa..ccb81f8e 100644
--- a/src/main/java/com/juick/api/Utils.java
+++ b/src/main/java/com/juick/api/Utils.java
@@ -70,7 +70,7 @@ public class Utils {
return 0;
}
- public static int getHttpAuthUID(Connection sql, HttpServletRequest request) {
+ public static int getHttpAuthUID(JdbcTemplate sql, HttpServletRequest request) {
String auth = request.getHeader("Authorization");
if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) {
try {
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
index f7d6d6ac..83afb62e 100644
--- a/src/test/java/com/juick/tests/ApiTests.java
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -1,18 +1,21 @@
package com.juick.tests;
import com.juick.Message;
+import com.juick.Tag;
import com.juick.User;
import com.juick.server.MessagesQueries;
+import com.juick.server.TagQueries;
import com.juick.server.UserQueries;
import junit.framework.Assert;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Properties;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
/**
* Created by vt on 14.01.2016.
@@ -21,35 +24,103 @@ public class ApiTests {
JdbcTemplate jdbc;
@Before
public void setupConnection() {
- Properties conf = new Properties();
- try {
- conf.load(new FileInputStream("/etc/juick/api.conf"));
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user="
- + conf.getProperty("mysql_username", "")
- + "&password=" + conf.getProperty("mysql_password", ""));
- jdbc = new JdbcTemplate(dataSource);
- } catch (IOException e) {
- e.printStackTrace();
- }
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName("org.h2.Driver");
+ dataSource.setUrl("jdbc:h2:~/test");
+ jdbc = new JdbcTemplate(dataSource);
+ jdbc.execute("CREATE TABLE bl_users (user_id int(10) unsigned NOT NULL, " +
+ "bl_user_id int(10) unsigned NOT NULL, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP )");
+ jdbc.execute("CREATE TABLE messages (" +
+ "message_id int(10) unsigned NOT NULL AUTO_INCREMENT," +
+ "user_id int(10) unsigned NOT NULL," +
+ "place_id int(10) unsigned DEFAULT NULL," +
+ "lat decimal(10,7) DEFAULT NULL," +
+ "lon decimal(10,7) DEFAULT NULL," +
+ "ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," +
+ "replies smallint(5) unsigned NOT NULL DEFAULT 0," +
+ "maxreplyid smallint(5) unsigned NOT NULL DEFAULT 0," +
+ "privacy tinyint(4) NOT NULL DEFAULT '1'," +
+ "attach nchar(3) check (attach in ('jpg', 'mp4', 'png'))," +
+ "readonly tinyint(1) NOT NULL DEFAULT 0," +
+ "likes smallint(6) NOT NULL DEFAULT 0," +
+ "hidden tinyint(3) unsigned NOT NULL DEFAULT 0" +
+ ")");
+ jdbc.execute("CREATE TABLE messages_tags (" +
+ "message_id int(10) unsigned NOT NULL," +
+ "tag_id int(10) unsigned NOT NULL" +
+ ")");
+ jdbc.execute("CREATE TABLE users (" +
+ "id int(10) unsigned NOT NULL AUTO_INCREMENT," +
+ "nick char(64) NOT NULL," +
+ "passw char(32) NOT NULL," +
+ "banned tinyint(3) unsigned NOT NULL DEFAULT 0)");
+ jdbc.execute("CREATE TABLE useroptions (" +
+ "user_id int(10) unsigned NOT NULL," +
+ "jnotify tinyint(1) NOT NULL DEFAULT 1," +
+ "subscr_active tinyint(1) NOT NULL DEFAULT 1)");
+ jdbc.execute("CREATE TABLE subscr_users (" +
+ "user_id int(10) unsigned NOT NULL," +
+ "suser_id int(10) unsigned NOT NULL," +
+ "jid char(64) DEFAULT NULL," +
+ "active tinyint(1) NOT NULL DEFAULT 1," +
+ "ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)");
+ jdbc.execute("CREATE TABLE messages_txt (" +
+ "message_id int(10) unsigned NOT NULL," +
+ "tags varchar(255)," +
+ "repliesby varchar(96)," +
+ "txt TEXT)");
+ jdbc.execute("CREATE TABLE tags(" +
+ "tag_id int(10) unsigned NOT NULL AUTO_INCREMENT," +
+ "synonym_id int(10) unsigned DEFAULT NULL," +
+ "name char(48) NOT NULL," +
+ "top tinyint(1) unsigned NOT NULL DEFAULT 0," +
+ "stat_messages int(10) unsigned NOT NULL DEFAULT 0," +
+ "stat_users smallint(5) unsigned NOT NULL DEFAULT 0)");
+ jdbc.execute("CREATE TABLE replies (" +
+ "message_id int(10) unsigned NOT NULL," +
+ "reply_id smallint(5) unsigned NOT NULL," +
+ "user_id int(10) unsigned NOT NULL," +
+ "replyto smallint(5) unsigned NOT NULL DEFAULT 0," +
+ "ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," +
+ "attach nchar(3) check (attach in ('jpg', 'mp4', 'png'))," +
+ "txt text)");
}
-
- @Test
- public void userTests() {
- User user = UserQueries.getUserByUID(jdbc, 3694);
- Assert.assertEquals("it should be me", "vt", user.getUName());
+ @After
+ public void tearDown() {
+ jdbc.execute("DROP ALL OBJECTS DELETE FILES");
}
+
@Test
public void messageTests() {
- Message msg = MessagesQueries.getMessage(jdbc, 2817722);
- User ugnich = msg.getUser();
- Assert.assertEquals("ugnich", ugnich.getUName());
- org.junit.Assert.assertEquals("ugnich", MessagesQueries.getMessageAuthor(jdbc, 2817722).getUName());
- Assert.assertEquals("Microsoft", msg.Tags.get(0));
- Message reply = MessagesQueries.getReply(jdbc, 2817722, 8);
- User linda = reply.getUser();
- Assert.assertEquals("Linda-chan", linda.getUName());
+ int user_id = UserQueries.createUser(jdbc, "me", "secret");
+ User user = UserQueries.getUserByUID(jdbc, user_id);
+ Assert.assertEquals("it should be me", "me", user.getUName());
+ int mid = MessagesQueries.createMessage(jdbc, user_id, "yo", null, new ArrayList<>());
+ Message msg = MessagesQueries.getMessage(jdbc, mid);
+ org.junit.Assert.assertEquals("yo", msg.getText());
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(msg.getDate());
+ org.junit.Assert.assertEquals(2016, calendar.get(Calendar.YEAR));
+ User me = msg.getUser();
+ Assert.assertEquals("me", me.getUName());
+ org.junit.Assert.assertEquals("me", MessagesQueries.getMessageAuthor(jdbc, mid).getUName());
+ int tagID = TagQueries.createTag(jdbc, "weather");
+ Tag tag = TagQueries.getTag(jdbc, tagID);
+ List tagList = new ArrayList<>();
+ tagList.add(tag);
+ int mid2 = MessagesQueries.createMessage(jdbc, user_id, "yo2", null, tagList);
+ Message msg2 = MessagesQueries.getMessage(jdbc, mid2);
+ org.junit.Assert.assertEquals(1, msg2.Tags.size());
+ int ugnich_id = UserQueries.createUser(jdbc, "ugnich", "x");
+ User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id);
+ int rid = MessagesQueries.createReply(jdbc, msg2.getMID(), 0, ugnich.getUID(), "bla-bla", null);
+ org.junit.Assert.assertEquals(1, rid);
+ Message msg3 = MessagesQueries.getMessage(jdbc, mid2);
+ org.junit.Assert.assertEquals(1, msg3.Replies);
+ org.junit.Assert.assertEquals("weather", msg3.Tags.get(0));
+ org.junit.Assert.assertEquals(ugnich.getUID(), UserQueries.checkPassword(jdbc, ugnich.getUName(), "x"));
+ org.junit.Assert.assertEquals(-1, UserQueries.checkPassword(jdbc, ugnich.getUName(), "xy"));
}
+
}
diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java
deleted file mode 100644
index 795b3429..00000000
--- a/src/test/java/com/juick/tests/JsonTests.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.juick.tests;
-
-import com.juick.json.MessageSerializer;
-import com.juick.server.MessagesQueries;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.datasource.DriverManagerDataSource;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Properties;
-
-public class JsonTests {
-
- JdbcTemplate jdbc;
- @Before
- public void setupConnection() {
- Properties conf = new Properties();
- try {
- conf.load(new FileInputStream("/etc/juick/api.conf"));
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user="
- + conf.getProperty("mysql_username", "")
- + "&password=" + conf.getProperty("mysql_password", ""));
- jdbc = new JdbcTemplate(dataSource);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void CompareSerializers() {
- List mids = MessagesQueries.getMyFeed(jdbc, 3694, 2799786);
- MessageSerializer messageSerializer = new MessageSerializer();
- if (mids != null && !mids.isEmpty()) {
- List msgs = MessagesQueries.getMessages(jdbc, mids);
- if (msgs != null && !msgs.isEmpty()) {
- String json = messageSerializer.serializeList(msgs);
- try {
- String data = new String(Files.readAllBytes(Paths.get("original.json")), "UTF-8");
- Assert.assertEquals("json should match", data, json);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
- }
- }
-}
diff --git a/src/test/java/com/juick/tests/original.json b/src/test/java/com/juick/tests/original.json
deleted file mode 100644
index 2f4e42a3..00000000
--- a/src/test/java/com/juick/tests/original.json
+++ /dev/null
@@ -1 +0,0 @@
-[{"mid":2799784,"user":{"uid":27928,"uname":"Rainbow-Spike"},"body":"это не стили, а ё-аный пиздец какой-то","tags":["докувики","MLP","CSS"],"timestamp":"2015-08-22 02:01:49"},{"mid":2799783,"user":{"uid":14276,"uname":"waterlaz"},"body":"Катались с Ляхом по грунтовым дорожкам Труханового острова на тандеме, заехали в песок и погнули вилку, а я сильно ударил себе тазобедренную кость. Успех.","tags":["велосипеды","тандем","L29Ah"],"timestamp":"2015-08-22 01:12:22","replies":1,"repliesby":"@failman"},{"mid":2799782,"user":{"uid":25625,"uname":"provaton"},"body":"Посмотрел отрывки из озеровского "направления главного удара", и вот никак не могу отделаться от навязчивой мысли. Каково было немецким актерам там играть? Гитлер и его генералы там выставлены немного в клоунском свете. А ведь в эту войну немецкий народ вложил почти все свои силы. Это ж не только мы в блокадном ленинграде умирали - неемцы там тоже не объедались, особенно к концу войны. И бомбили их в тылу союзнички нещадно, и на фронтах били превосходящие силы. Но немцы бились как звери, в условиях подавляющего превосходства врага. Бились искренне, за Родину. А тут бери и играй роль мудака, которого великие русские отымели как последнего дебила. Не понимаю.","tags":["тег"],"timestamp":"2015-08-22 00:58:20"},{"mid":2799781,"user":{"uid":14978,"uname":"ndtimofeev"},"body":"Моя женщина ткнула меня в Lindemann - Skills in Pills. Это целый альбом который выглядит как песни не вошедшие в Liebe ist für alle da потому что там и так до хрена всего^W^W^W^W^Wих нельзя крутить по радио исполненные в немного электронном варианте. Я рад.","tags":["rammstein","music"],"timestamp":"2015-08-22 00:56:06"},{"mid":2799780,"user":{"uid":14978,"uname":"ndtimofeev"},"body":"Одна из причин по которой haskell хреново заменяет python состоит в том что он работает как помешательство у малковиан: кинул кубик и всё сделал в 500 строк, кинул кубик ещё раз и добавил блэкджек и шлюх, кинул ещё и обнаружил что уже неделю сидишь и читаешь статьи по какой-то абстрактной фигне.","tags":["vtm","Haskell"],"timestamp":"2015-08-22 00:50:32","replies":1},{"mid":2799779,"user":{"uid":25625,"uname":"provaton"},"body":"http://jpgazeta.ru/priznayte-menya-russkoy/\n\nЕще одну романтичную душу долбануло российской бюрократией по самые помидоры.","tags":["тег"],"timestamp":"2015-08-21 23:51:10","replies":1,"repliesby":"@ig276"},{"mid":2799778,"user":{"uid":28473,"uname":"complemento"},"body":"[Курс доллара подскочил до 69 рублей][https://news.mail.ru/economics/23055957/]","tags":["3m"],"timestamp":"2015-08-21 23:48:28"},{"mid":2799777,"user":{"uid":16608,"uname":"lurker"},"body":"...","tags":["альтернатива"],"timestamp":"2015-08-21 23:40:34","replies":2,"photo":{"thumbnail":"http://i.juick.com/ps/2799777.jpg","small":"http://i.juick.com/photos-512/2799777.jpg","medium":"http://i.juick.com/photos-1024/2799777.jpg"}},{"mid":2799776,"user":{"uid":176,"uname":"bighouse"},"body":"Не долго музыка играла... Откатываюсь с 10 ки на 8.1.. Не впечатлила десятка. Минусов куча, а плюсов не обнаружил.","tags":["вин"],"timestamp":"2015-08-21 23:33:19","replies":1,"repliesby":"@SolderStain"},{"mid":2799775,"user":{"uid":17560,"uname":"iZevg"},"body":"Ребятки, посоветуйте хостинг с 5Гб HDD, CPanel и PHP до 200 руб/м","tags":["?","web"],"timestamp":"2015-08-21 22:48:37","replies":2},{"mid":2799774,"user":{"uid":23893,"uname":"Shizokl"},"body":"Мировая экономика, бессердечная ты сука, остановись, прекрати. Тебя уже не существует уже который месяц. Верни нефть-матушку в исконное стодолларовое равновесие, бо лепо было и любо!","tags":["."],"timestamp":"2015-08-21 22:39:31"},{"mid":2799773,"user":{"uid":6715,"uname":"O01eg"},"body":"http://blog.kittysanders.com/interviewmovie/\n"Посмотрела нашумевшее «Интервью», то самое, где убивают Ким Чен Ына, из-за чего оный Ын взбесился и начал нервно угрожать США.\nВ последнее время снимается много фильмов, «высмеивающих тоталитаризм», какие-то из них более удачные, какие-то — совершенно кривые, как вышедший недавно «Джеки в царстве женщин», о котором мы поговорим отдельно. Проблема в том, что США (и, если говорить шире, «Запад») умеют бороться только тогда, когда в Белом доме и в Голливуде доминируют правые параноики, которые понимают очарование тоталитаризма. Они понимают, что ощущают люди, ставшие частью единого коллективного тела, люди, утратившие «Я» и приобретшие «Мы». Они знают, как волнующе звучит старое доброе «война — это мир, свобода — это рабство, незнание — сила». И эти параноики используют верные ходы в борьбе с этой притягательностью зла. Потому что они его понимают, они говорят с ним на одном языке, их лица обожжены дыханием Бельфегора, они сталкивались с ним и смогли преодолеть соблазн.\nЕсли мне зачем-то нужно будет рассказать о том, что свобода — это рабство, я смогу без подготовки говорить минут 10-15. Если вы скажете мне, что в нижеприведенном стихе нет чего-то, цепляющего вашу глубокую, грязную, обычно тихо лежащую тихо, часть, которую вы со стыдом прячете от всех, потому что она плохая, вы это знаете, как ребенок, которого родители застали за плохими занятиями — вы либо соврете, либо вы не настолько носитель этого, скорее всего, выросший в какой-то благополучной стране. Но вообще, это задевает густую чёрную дрянь, которая залегает очень глубоко. Как нефть. Эта нефть есть в большинстве из нас, людей с высоким IQ и низкой усвоенностью социальных норм, родом из мест, достаточно развитых, чтобы дать нам возможность образоваться, но достаточно жестоких, чтобы периодически пытаться нас унитожить как личностей. Вопрос в том, чтобы держать ее под контролем. Потому что она — зло. Тот, кто писал эти стихи — «аулия эш-шайтан», «святой Сатаны». Надо это осознавать. Как надо осознавать, что героин в больших количествах отправит вас в ад бесконечной трансформации в собственный кошмар, и вы целую вечность будете маяться, не понимая, что умерли, куда там Тибецкой Книге Мёртвых. Но если ваше тело само производит героин, то с этим надо как-то жить и что-то предпринимать, иначе рано или поздно будет передоз.\nА век поджидает на мостовой,\nСосредоточен, как часовой.\nИди — и не бойся с ним рядом встать.\nТвое одиночество веку под стать.\nОглянешься — а вокруг враги;\nРуки протянешь — и нет друзей;\nНо если он скажет: «Солги»,- солги.\nНо если он скажет: «Убей»,- убей.\nЯ тоже почувствовал тяжкий груз\nОпущенной на плечо руки.\nПодстриженный по-солдатски ус\nКасался тоже моей щеки.\nИ стол мой раскидывался, как страна,\nВ крови, в чернилах квадрат сукна,\nРжавчина перьев, бумаги клок —\nВсё друга и недруга стерегло.\nВраги приходили — на тот же стул\nСадились и рушились в пустоту.\nИх нежные кости сосала грязь.\nНад ними захлопывались рвы.\nИ подпись на приговоре вилась\nСтруей из простреленной головы.\nВас встряхивает от этого стиха? Меня да. Я уже давно бросила притворяться. Подобно Адаму Чаплину, в лопатке которого жило существо без имени, я дала ему имя\nя буду звать тебя… Дерек\nи научилась жить с ним. А вы нет? Ну тогда у вас, наверное, много стресса в жизни, соболезную. Вы еще не поняли, что боль, страдание и вообще весь этот дискурс «подавления» — это бонус, если его держать под контролем, понимать, что он есть ваш внутренний «дьявол» и рационализировать его."","tags":["прекрасное"],"timestamp":"2015-08-21 22:35:51","replies":1},{"mid":2799772,"user":{"uid":16870,"uname":"AlexVK"},"body":"* MATE с 1 гиг занятым при загруденной IDE - неплохо, неплохо, впечатляет.","tags":["Linux","Fedora"],"timestamp":"2015-08-21 22:34:54","replies":3,"repliesby":"@AlexVK"},{"mid":2799771,"user":{"uid":6715,"uname":"O01eg"},"body":"https://2ch.hk/po/src/10469747/14401550234011.webm","tags":["прекрасное","говнорашка","humor"],"timestamp":"2015-08-21 22:31:39"},{"mid":2799770,"user":{"uid":8836,"uname":"OCTAGRAM"},"body":"Слушаю Аксёнова на [крымском госсовете](https://youtu.be/-nuoP7qI-dY?t=15m42s), и уши в трубочку сворачиваются от его предложений:\n– Предлагает ввести праздник: день виноградарства и виноделия\n– Пытается разделить «винный туризм» и «злоупотребление алкоголем», как если бы существовало употребление алкоголя, не являющееся злоупотреблением\n– Разрешить продавать в розницу вино на туристических, сельскохозяйственных и винных выставках, ярмарках и фестивалях\n– Рекомендовать врачам применять лечение вином\n\nНаверное, если бы Афганистан вырвался из–под управления США и вошёл в состав РФ, то его глава, понимая, как он впух, был бы тоже вынужден либо просить средства на то, чтобы переобучить чему–нибудь достойному всех этих бездельников, которые волею судеб ничего другого просто делать не умеют, либо вводить праздники, налаживать «опиумный туризм» с продажей опиума в розницу на выставках, ярмарках и фестивалях, рекомендовать врачам применять лечение опиумом, и даже нашёл бы таких учёных, которые подведут соответствующую базу","tags":["вещества","легалайз","Крым","алкоголь"],"timestamp":"2015-08-21 22:30:03"},{"mid":2799769,"user":{"uid":6715,"uname":"O01eg"},"body":"Жизнь эталонного пидороквадратника 30ых: сегодня ты дрочишь на Путина и лаешь на "пятую колонну", а завтра "пятая колонна" - ты: https://pbs.twimg.com/media/CM9EVRYWcAAzOdR.jpg:orig\n> В марте 1938 года был снят с поста начальника Московского управления НКВД и назначен начальником треста Камлесосплав. В апреле 1938 года снят с этого поста, уволен из НКВД, исключён из ВКП(б) и арестован 19 апреля 1938 года по обвинению в «создании латышской контрреволюционной организации в НКВД, а также шпионаже в пользу Германии, Польши, Англии». Расстрелян 29 августа 1938 года. После смерти Сталина реабилитирован не был.","tags":["прекрасное","говнорашка","сталирасты","history"],"timestamp":"2015-08-21 22:22:21","replies":2,"repliesby":"@Kim, @alv"},{"mid":2799768,"user":{"uid":6715,"uname":"O01eg"},"body":"https://i.imgur.com/nvoqXFY.jpg","tags":["прекрасное","говнорашка"],"timestamp":"2015-08-21 22:07:37","replies":6,"repliesby":"@Bounty, @O01eg, @Kim"},{"mid":2799767,"user":{"uid":16791,"uname":"alex0b"},"body":"Играем в некое подобие эрудита (скраблз). Мама вводит новое правило: нельзя одновременно две пустышки выставлять под видом разных букв. Детеныш сидит, мается в муках творчества, от недостатка гласных и избытка пустышек: "эх, жаль, что нельзя разногласие устроить". \nПодсказываю ему вариант: "синоним слова чёрт". Думает, пыхтит: "Не помню, но кажется /гадлёныш/".","tags":["слова","детеныш"],"timestamp":"2015-08-21 22:00:47","replies":1,"repliesby":"@Greederius"},{"mid":2799766,"user":{"uid":24531,"uname":"justonemore"},"body":"Прекрасная сценка из "The Chronicles of Riddick: Assault On Dark Athena": http://www.youtube.com/watch?v=Zizc3Dnf2fk&t=42m34s","tags":["games","riddick","видео"],"timestamp":"2015-08-21 21:32:02","replies":1},{"mid":2799765,"user":{"uid":6715,"uname":"O01eg"},"body":"https://pbs.twimg.com/media/CM7YQo1UkAAnLPZ.jpg:orig","tags":["прекрасное","humor","говнорашка"],"timestamp":"2015-08-21 21:26:33"}]
\ No newline at end of file
--
cgit v1.2.3
From d8f9f16d16f4e2f7133de464ba8d3f6cc704bd00 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Sun, 17 Jan 2016 00:18:33 +0300
Subject: almost working messages api
---
.gitignore | 26 ++++----
build.gradle | 1 +
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/Main.java | 31 +++++----
src/main/java/com/juick/api/Messages.java | 97 +++++++++++++++++++----------
src/main/java/com/juick/api/Utils.java | 5 ++
src/main/webapp/WEB-INF/juick.conf.example | 6 ++
src/test/java/com/juick/tests/ApiTests.java | 11 ++--
8 files changed, 118 insertions(+), 61 deletions(-)
create mode 100644 src/main/webapp/WEB-INF/juick.conf.example
(limited to 'src/main/java/com')
diff --git a/.gitignore b/.gitignore
index b25773e5..56340f6c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,14 @@
-build/*
-.gradle/*
-deps/*
-.idea/*
-**/*.iml
-**/juick.conf
-/build/
-/bin/
-/.nb-gradle/
-.settings/*
-.classpath
-.project
+build/*
+.gradle/*
+deps/*
+.idea/*
+**/*.iml
+**/juick.conf
+/build/
+/bin/
+/.nb-gradle/
+.settings/*
+.classpath
+.project
+**/*.properties
+**/*.conf
diff --git a/build.gradle b/build.gradle
index ea705d8c..b76df16a 100644
--- a/build.gradle
+++ b/build.gradle
@@ -53,6 +53,7 @@ dependencies {
compile server
compile xmpp
compile json
+ compile "org.apache.commons:commons-lang3:3.4"
compile "org.springframework:spring-jdbc:4.2.4.RELEASE"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
def tomcatVersion = '7.0.+'
diff --git a/deps/com.juick.server b/deps/com.juick.server
index 27976585..9232bdcb 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit 279765857724cf35addc0e3f5e7180a8724d23b9
+Subproject commit 9232bdcb144bc3b94f4b825b3a4cb588078bd72d
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index cdced593..cc068ccd 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -29,11 +29,13 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Properties;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.logging.LogManager;
/**
*
@@ -54,37 +56,38 @@ public class Main extends HttpServlet implements Stream.StreamListener {
public void init() throws ServletException {
super.init();
try {
+ LogManager.getLogManager().readConfiguration(getServletContext().getResourceAsStream("WEB-INF/logging.properties"));
Properties conf = new Properties();
- conf.load(new FileInputStream("/etc/juick/api.conf"));
- final String driverClassName = "com.mysql.jdbc.Driver";
+ conf.load(getServletContext().getResourceAsStream("WEB-INF/juick.conf"));
DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", ""));
- dataSource.setDriverClassName(driverClassName);
+ dataSource.setDriverClassName(conf.getProperty("datasource_driver"));
+ dataSource.setUrl(conf.getProperty("datasource_url"));
jdbc = new JdbcTemplate(dataSource);
messages = new Messages(jdbc);
users = new Users(jdbc);
pm = new PM(jdbc);
others = new Others(jdbc);
- setupXmppComponent(conf.getProperty("xmpp_password"));
+ setupXmppComponent(conf.getProperty("xmpp_host", "localhost"), Integer.parseInt(conf.getProperty("xmpp_port", "5347")),
+ conf.getProperty("xmpp_jid", "api.localhost"), conf.getProperty("xmpp_password"));
} catch (IOException e) {
log("API initialization error", e);
}
}
- public void setupXmppComponent(final String password) {
- Thread thr = new Thread(() -> {
+ public void setupXmppComponent(final String host, final int port, final String jid, final String password) {
+ ExecutorService executorService = Executors.newSingleThreadExecutor();
+ executorService.submit(() -> {
try {
- Socket socket = new Socket("localhost", 5347);
- xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password);
+ Socket socket = new Socket(host, port);
+ xmpp = new StreamComponent(new JID(jid), socket.getInputStream(), socket.getOutputStream(), password);
xmpp.addListener(Main.this);
xmpp.startParsing();
} catch (IOException e) {
log("XMPP exception", e);
}
});
- thr.start();
}
@Override
@@ -94,7 +97,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
@Override
public void onStreamReady() {
- System.err.println("XMPP STREAM READY");
+ log("XMPP STREAM READY");
}
/**
@@ -122,6 +125,10 @@ public class Main extends HttpServlet implements Stream.StreamListener {
} else {
response.sendError(401);
}
+ } else if (uri.equals("/messages")) {
+ messages.doGet(request, response, vuid);
+ } else if (uri.equals("/thread")) {
+ messages.doThreadGet(request, response, vuid);
} else if (uri.equals("/users")) {
users.doGetUsers(request, response, vuid);
} else if (uri.equals("/users/read")) {
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index e242d05b..d86193f1 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -11,6 +11,7 @@ import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
import com.juick.xmpp.extensions.JuickMessage;
import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.util.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -28,37 +29,11 @@ public class Messages {
MessageSerializer messageSerializer = new MessageSerializer();
- enum MediaType {
- ALL("all"),
- PHOTO("photo"),
- VIDEO("video"),
- NONE("");
-
- private final String value;
-
- MediaType(final String value) {
- this.value = value;
- }
- public String getValue() {
- return value;
- }
-
- @Override
- public String toString() {
- return this.getValue();
- }
- }
-
public Messages(JdbcTemplate sql) {
this.sql = sql;
}
- public void doGetHome(HttpServletRequest request,
- HttpServletResponse response, int vuid)
- throws ServletException, IOException {
- int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
-
- List mids = MessagesQueries.getMyFeed(sql, vuid, before_mid);
+ void feedMessages(HttpServletRequest request, HttpServletResponse response, List mids) throws IOException {
if (mids != null && !mids.isEmpty()) {
List msgs = MessagesQueries.getMessages(sql, mids);
if (msgs != null && !msgs.isEmpty()) {
@@ -72,16 +47,74 @@ public class Messages {
}
}
+ public void doGetHome(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
+ int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+
+ feedMessages(request, response, MessagesQueries.getMyFeed(sql, vuid, before_mid));
+
+ }
+
public void doGet(HttpServletRequest request,
HttpServletResponse response, int vuid)
throws ServletException, IOException {
- User user = UserQueries.getUserByName(sql, request.getParameter("uname"));
int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
- int page = Utils.parseInt(request.getParameter("page"), 0);
- MediaType media = MediaType.valueOf(request.getParameter("media"));
- boolean popular = Boolean.valueOf(request.getParameter("popular"));
- Tag tag = TagQueries.getTag(sql, request.getParameter("tag"), false);
+ String uname = request.getParameter("uname");
+ String popular = request.getParameter("popular");
+ String media = request.getParameter("media");
+ String tag = request.getParameter("tag");
+ if (!StringUtils.isEmpty(uname)) {
+ User user = UserQueries.getUserByName(sql, uname);
+ if (user != null) {
+ if (!StringUtils.isEmpty(media)) {
+ feedMessages(request, response, MessagesQueries.getUserPhotos(sql, user.getUID(), 0, before_mid));
+ } else if (!StringUtils.isEmpty(tag)) {
+ Tag tagObject = TagQueries.getTag(sql, tag, false);
+ if (tagObject != null) {
+ feedMessages(request, response, MessagesQueries.getUserTag(sql, user.getUID(), tagObject.TID, 0, before_mid));
+ } else {
+ response.sendError(404);
+ }
+ } else {
+ feedMessages(request, response, MessagesQueries.getUserBlog(sql, user.getUID(), 0, before_mid));
+ }
+ } else {
+ response.sendError(404);
+ }
+ } else {
+ if (!StringUtils.isEmpty(popular)) {
+ feedMessages(request, response, MessagesQueries.getPopular(sql, before_mid));
+ } else if (!StringUtils.isEmpty(media)) {
+ feedMessages(request, response, MessagesQueries.getPhotos(sql, vuid, before_mid));
+ } else if (!StringUtils.isEmpty(tag)) {
+ Tag tagObject = TagQueries.getTag(sql, tag, false);
+ if (tagObject != null) {
+ feedMessages(request, response, MessagesQueries.getTag(sql, tagObject.TID, vuid, before_mid, 20));
+ } else {
+ response.sendError(404);
+ }
+ } else {
+ feedMessages(request, response, MessagesQueries.getAll(sql, vuid, before_mid));
+ }
+ }
+ }
+ public void doThreadGet(HttpServletRequest request, HttpServletResponse response, int vuid) throws IOException {
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ com.juick.Message msg = MessagesQueries.getMessage(sql, mid);
+ if (msg != null) {
+ if (!MessagesQueries.canViewThread(sql, mid, vuid)) {
+ response.sendError(403);
+ } else {
+ List replies = MessagesQueries.getReplies(sql, mid);
+ replies.add(0, msg);
+ String json = messageSerializer.serializeList(replies);
+ Main.replyJSON(request, response, json);
+ }
+ } else {
+ response.sendError(404);
+ }
}
public void doGetRecommended(HttpServletRequest request,
diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java
index ccb81f8e..6383fec0 100644
--- a/src/main/java/com/juick/api/Utils.java
+++ b/src/main/java/com/juick/api/Utils.java
@@ -24,6 +24,8 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -36,6 +38,8 @@ import sun.misc.BASE64Decoder;
*/
public class Utils {
+ private static final Logger LOGGER = Logger.getLogger(Utils.class.getName());
+
public static String getCookie(HttpServletRequest request, String name) {
Cookie cookies[] = request.getCookies();
if (cookies != null) {
@@ -80,6 +84,7 @@ public class Utils {
return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]);
}
} catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Auth", e);
}
}
return 0;
diff --git a/src/main/webapp/WEB-INF/juick.conf.example b/src/main/webapp/WEB-INF/juick.conf.example
new file mode 100644
index 00000000..61ebbc29
--- /dev/null
+++ b/src/main/webapp/WEB-INF/juick.conf.example
@@ -0,0 +1,6 @@
+datasource_driver=org.h2.Driver
+datasource_url=jdbc:h2:~/test
+xmpp_host=localhost
+xmpp_port=5347
+xmpp_jid=api.localhost
+xmpp_password=secret
\ No newline at end of file
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
index 83afb62e..7b0264c0 100644
--- a/src/test/java/com/juick/tests/ApiTests.java
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -4,6 +4,7 @@ import com.juick.Message;
import com.juick.Tag;
import com.juick.User;
import com.juick.server.MessagesQueries;
+import com.juick.server.SubscriptionsQueries;
import com.juick.server.TagQueries;
import com.juick.server.UserQueries;
import junit.framework.Assert;
@@ -28,6 +29,7 @@ public class ApiTests {
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:~/test");
jdbc = new JdbcTemplate(dataSource);
+ jdbc.execute("DROP ALL OBJECTS DELETE FILES");
jdbc.execute("CREATE TABLE bl_users (user_id int(10) unsigned NOT NULL, " +
"bl_user_id int(10) unsigned NOT NULL, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP )");
jdbc.execute("CREATE TABLE messages (" +
@@ -64,6 +66,9 @@ public class ApiTests {
"jid char(64) DEFAULT NULL," +
"active tinyint(1) NOT NULL DEFAULT 1," +
"ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)");
+ jdbc.execute("CREATE TABLE subscr_messages (" +
+ "message_id int(10) unsigned NOT NULL," +
+ "suser_id int(10) unsigned NOT NULL)");
jdbc.execute("CREATE TABLE messages_txt (" +
"message_id int(10) unsigned NOT NULL," +
"tags varchar(255)," +
@@ -85,10 +90,6 @@ public class ApiTests {
"attach nchar(3) check (attach in ('jpg', 'mp4', 'png'))," +
"txt text)");
}
- @After
- public void tearDown() {
- jdbc.execute("DROP ALL OBJECTS DELETE FILES");
- }
@Test
@@ -121,6 +122,8 @@ public class ApiTests {
org.junit.Assert.assertEquals("weather", msg3.Tags.get(0));
org.junit.Assert.assertEquals(ugnich.getUID(), UserQueries.checkPassword(jdbc, ugnich.getUName(), "x"));
org.junit.Assert.assertEquals(-1, UserQueries.checkPassword(jdbc, ugnich.getUName(), "xy"));
+ SubscriptionsQueries.subscribeMessage(jdbc, msg.getMID(), ugnich.getUID());
+ Assert.assertEquals(1, SubscriptionsQueries.getUsersSubscribedToComments(jdbc, msg.getMID(), user.getUID()).size());
}
}
--
cgit v1.2.3
From ca45d2216ccef8231860aa349a5e745ab17dc43c Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Sun, 17 Jan 2016 01:08:24 +0300
Subject: POST
---
build.gradle | 2 +-
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/Main.java | 233 +++++++++++++++++++++++++++++++++
src/main/java/com/juick/api/Utils.java | 87 ++++++++++++
4 files changed, 322 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index b76df16a..e82e7e96 100644
--- a/build.gradle
+++ b/build.gradle
@@ -62,7 +62,7 @@ dependencies {
"org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
testCompile 'junit:junit:4.12'
runtime 'mysql:mysql-connector-java:5.1.37'
- testRuntime 'com.h2database:h2:1.4.190'
+ testTuntime 'com.h2database:h2:1.4.190'
}
compileJava.options.encoding = 'UTF-8'
diff --git a/deps/com.juick.server b/deps/com.juick.server
index 9232bdcb..27e4beeb 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit 9232bdcb144bc3b94f4b825b3a4cb588078bd72d
+Subproject commit 27e4beeb2ed195985942262f3f94a8c5b069ba66
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index cc068ccd..c43804d7 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -17,9 +17,16 @@
*/
package com.juick.api;
+import com.juick.Tag;
+import com.juick.json.MessageSerializer;
+import com.juick.server.*;
import com.juick.xmpp.JID;
+import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
import com.juick.xmpp.StreamComponent;
+import com.juick.xmpp.extensions.JuickMessage;
+import com.juick.xmpp.extensions.Nickname;
+import com.juick.xmpp.extensions.XOOB;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@@ -32,6 +39,11 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -187,6 +199,12 @@ public class Main extends HttpServlet implements Stream.StreamListener {
String uri = request.getRequestURI();
switch (uri) {
case "/post":
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ if (mid == 0) {
+ doPostMessage(jdbc, request, response, xmpp, vuid);
+ } else {
+ doPostComment(jdbc, request, response, xmpp, vuid);
+ }
break;
case "/pm":
pm.doPostPM(request, response, xmpp, vuid);
@@ -197,6 +215,221 @@ public class Main extends HttpServlet implements Stream.StreamListener {
}
}
+ public void doPostMessage(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid)
+ throws ServletException, IOException {
+ String body = request.getParameter("body");
+ if (body == null || body.length() < 1 || body.length() > 4096) {
+ response.sendError(400);
+ return;
+ }
+ body = body.replace("\r", "");
+
+ String tagsStr = request.getParameter("tags");
+ List tags = new ArrayList<>();
+ String tagsArr[] = new String[1];
+ 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);
+ }
+ }
+
+ String attachmentFName = null;
+ try {
+ attachmentFName = Utils.receiveMultiPartFile(request, "attach");
+ } catch (Exception e) {
+ System.out.println("MULTIPART ERROR: " + e.toString());
+ response.sendError(400);
+ return;
+ }
+
+ String paramImg = request.getParameter("img");
+ if (attachmentFName == null && paramImg != null && paramImg.length() > 10 ) {
+ try {
+ URL imgUrl = new URL(paramImg);
+ attachmentFName = Utils.downloadImage(imgUrl);
+ } catch (Exception e) {
+ System.out.println("DOWNLOAD ERROR: " + e.toString());
+ response.sendError(500);
+ return;
+ }
+ }
+
+ String attachmentType = attachmentFName != null ? attachmentFName.substring(attachmentFName.length() - 3) : null;
+ int mid = MessagesQueries.createMessage(sql, vuid, body, attachmentType, tags);
+ SubscriptionsQueries.subscribeMessage(sql, mid, vuid);
+ JuickMessage jmsg = new JuickMessage(MessagesQueries.getMessage(sql, mid));
+ if (xmpp != null) {
+ Message xmsg = new Message();
+ xmsg.from = new JID("juick", "juick.com", null);
+ xmsg.type = Message.Type.chat;
+ xmsg.thread = "juick-" + mid;
+
+ xmsg.addChild(jmsg);
+
+ Nickname nick = new Nickname();
+ nick.Nickname = "@" + jmsg.getUser().getUName();
+ xmsg.addChild(nick);
+
+ if (attachmentFName != null) {
+ String fname = mid + "." + attachmentType;
+ String attachmentURL = "http://i.juick.com/photos-1024/" + fname;
+
+ Runtime.getRuntime().exec("/var/www/juick.com/cgi/p-convert.sh /var/www/juick.com/i/tmp/" + attachmentFName + " " + fname);
+
+ body = attachmentURL + "\n" + body;
+ XOOB xoob = new XOOB();
+ xoob.URL = attachmentURL;
+ xmsg.addChild(xoob);
+ }
+
+ String tagsStr2 = "";
+ for (String tag : tagsArr) {
+ tagsStr2 += " *" + tag;
+ }
+ xmsg.body = "@" + jmsg.getUser().getUName() + ":" + tagsStr2 + "\n" + body + "\n\n#" + mid + " http://juick.com/" + mid;
+
+ xmsg.to = new JID("juick", "s2s.juick.com", null);
+ xmpp.send(xmsg);
+
+ xmsg.to.Host = "ws.juick.com";
+ xmpp.send(xmsg);
+
+ xmsg.to.Host = "push.juick.com";
+ xmpp.send(xmsg);
+
+ xmsg.to.Host = "crosspost.juick.com";
+ xmsg.to.Username = "twitter";
+ xmpp.send(xmsg);
+ xmsg.to.Username = "fb";
+ xmpp.send(xmsg);
+
+ xmsg.to.Host = "nologin.ru";
+ xmsg.to.Username = "jubo";
+ xmpp.send(xmsg);
+ } else {
+ log("XMPP unavailable");
+ }
+ MessageSerializer serializer = new MessageSerializer();
+ Main.replyJSON(request, response, serializer.serialize(jmsg).toString());
+ }
+
+ public void doPostComment(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid)
+ throws ServletException, IOException {
+ int mid = Utils.parseInt(request.getParameter("mid"), 0);
+ if (mid == 0) {
+ response.sendError(400);
+ return;
+ }
+ com.juick.Message msg = MessagesQueries.getMessage(sql, mid);
+ if (msg == null) {
+ response.sendError(404);
+ return;
+ }
+
+ int rid = Utils.parseInt(request.getParameter("rid"), 0);
+ com.juick.Message reply = null;
+ if (rid > 0) {
+ reply = MessagesQueries.getReply(sql, mid, rid);
+ if (reply == null) {
+ response.sendError(404);
+ return;
+ }
+ }
+
+ String body = request.getParameter("body");
+ if (body == null || body.length() < 1 || body.length() > 4096) {
+ response.sendError(400);
+ return;
+ }
+ body = body.replace("\r", "");
+
+ if ((msg.ReadOnly && msg.getUser().getUID() != vuid) || UserQueries.isInBLAny(sql, msg.getUser().getUID(), vuid)
+ || (reply != null && UserQueries.isInBLAny(sql, reply.getUser().getUID(), vuid))) {
+ response.sendError(403);
+ return;
+ }
+
+ String attachmentFName = null;
+ try {
+ attachmentFName = Utils.receiveMultiPartFile(request, "attach");
+ } catch (Exception e) {
+ System.out.println("MULTIPART ERROR: " + e.toString());
+ response.sendError(400);
+ return;
+ }
+
+ String paramImg = request.getParameter("img");
+ if (attachmentFName == null && paramImg != null && paramImg.length() > 10) {
+ try {
+ attachmentFName = Utils.downloadImage(new URL(paramImg));
+ } catch (Exception e) {
+ System.out.println("DOWNLOAD ERROR: " + e.toString());
+ response.sendError(500);
+ return;
+ }
+ }
+
+ String attachmentType = attachmentFName != null ? attachmentFName.substring(attachmentFName.length() - 3) : null;
+ int ridnew = MessagesQueries.createReply(sql, mid, rid, vuid, body, attachmentType);
+ SubscriptionsQueries.subscribeMessage(sql, mid, vuid);
+
+ JuickMessage jmsg = new JuickMessage(MessagesQueries.getReply(sql, mid, ridnew));
+
+ if (xmpp != null) {
+ Message xmsg = new Message();
+ xmsg.from = new JID("juick", "juick.com", null);
+ xmsg.type = Message.Type.chat;
+ xmsg.thread = "juick-" + mid;
+ xmsg.addChild(jmsg);
+
+ String quote = reply != null ? reply.getText() : msg.getText();
+ if (quote.length() >= 50) {
+ quote = quote.substring(0, 47) + "...";
+ }
+
+ Nickname nick = new Nickname();
+ nick.Nickname = "@" + jmsg.getUser().getUName();
+ xmsg.addChild(nick);
+
+ if (attachmentFName != null) {
+ String fname = mid + "-" + ridnew + "." + attachmentType;
+ String attachmentURL = "http://i.juick.com/photos-1024/" + fname;
+
+ Runtime.getRuntime().exec("/var/www/juick.com/cgi/p-convert.sh /var/www/juick.com/i/tmp/" + attachmentFName + " " + fname);
+
+ body = attachmentURL + "\n" + body;
+ XOOB xoob = new XOOB();
+ xoob.URL = attachmentURL;
+ xmsg.addChild(xoob);
+ }
+
+ xmsg.body = "Reply by @" + jmsg.getUser().getUName() + ":\n>" + quote + "\n" + body + "\n\n#" + mid + "/" + ridnew + " http://juick.com/" + mid + "#" + ridnew;
+
+ xmsg.to = new JID("juick", "s2s.juick.com", null);
+ xmpp.send(xmsg);
+
+ xmsg.to.Host = "ws.juick.com";
+ xmpp.send(xmsg);
+
+ xmsg.to.Host = "push.juick.com";
+ xmpp.send(xmsg);
+ } else {
+ log("XMPP unavailable");
+ }
+ MessageSerializer serializer = new MessageSerializer();
+ Main.replyJSON(request, response, serializer.serialize(jmsg).toString());
+ }
+
public static void replyJSON(HttpServletRequest request, HttpServletResponse response, String json) throws IOException {
response.setContentType("application/json; charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java
index 6383fec0..7a498a10 100644
--- a/src/main/java/com/juick/api/Utils.java
+++ b/src/main/java/com/juick/api/Utils.java
@@ -18,17 +18,25 @@
package com.juick.api;
import com.juick.server.UserQueries;
+
+import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
+import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.Part;
+
import org.springframework.jdbc.core.JdbcTemplate;
import sun.misc.BASE64Decoder;
@@ -152,4 +160,83 @@ public class Utils {
}
return ret;
}
+ public static String getPartFilename(Part part) {
+ for (String cd : part.getHeader("content-disposition").split(";")) {
+ if (cd.trim().startsWith("filename")) {
+ String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
+ return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
+ }
+ }
+ return null;
+ }
+ public static String receiveMultiPartFile(HttpServletRequest request, String name) throws Exception {
+ String attachmentFName = null;
+
+ Part filePart = request.getPart("attach");
+ 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 = UUID.randomUUID().toString() + "." + attachmentType;
+ filePart.write("/var/www/juick.com/i/tmp/" + attachmentFName);
+ } else {
+ throw new Exception("Wrong file type");
+ }
+ }
+ }
+
+ return attachmentFName;
+ }
+ 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 = 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;
+ }
+ }
}
--
cgit v1.2.3
From 846d0b67d11ba9444a8a32ee173bb431683fa572 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 10:01:43 +0300
Subject: fix base64 usage
---
src/main/java/com/juick/api/Utils.java | 31 ++++++++++---------------------
1 file changed, 10 insertions(+), 21 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java
index 7a498a10..ca0518e1 100644
--- a/src/main/java/com/juick/api/Utils.java
+++ b/src/main/java/com/juick/api/Utils.java
@@ -18,27 +18,22 @@
package com.juick.api;
import com.juick.server.UserQueries;
+import org.springframework.jdbc.core.JdbcTemplate;
+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.net.URL;
import java.net.URLConnection;
-import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.UUID;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.Part;
-
-import org.springframework.jdbc.core.JdbcTemplate;
-import sun.misc.BASE64Decoder;
/**
*
@@ -46,8 +41,6 @@ import sun.misc.BASE64Decoder;
*/
public class Utils {
- private static final Logger LOGGER = Logger.getLogger(Utils.class.getName());
-
public static String getCookie(HttpServletRequest request, String name) {
Cookie cookies[] = request.getCookies();
if (cookies != null) {
@@ -85,14 +78,10 @@ public class Utils {
public static int getHttpAuthUID(JdbcTemplate sql, HttpServletRequest request) {
String auth = request.getHeader("Authorization");
if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) {
- try {
- BASE64Decoder dec = new BASE64Decoder();
- String loginpassw[] = new String(dec.decodeBuffer(auth.substring(6))).split(":", 2);
- if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) {
- return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]);
- }
- } catch (IOException e) {
- LOGGER.log(Level.WARNING, "Auth", e);
+ Base64.Decoder dec = Base64.getDecoder();
+ String loginpassw[] = new String(dec.decode(auth.substring(6))).split(":", 2);
+ if (loginpassw.length == 2 && loginpassw[0].length() > 1 && loginpassw[0].length() < 16 && loginpassw[0].matches("[a-zA-Z0-9\\-]+") && !loginpassw[1].isEmpty()) {
+ return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]);
}
}
return 0;
--
cgit v1.2.3
From 70a6b6c49ee6e220942a43ae4328ce9dcd24232b Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 19:25:26 +0300
Subject: initial telegram bot
---
build.gradle | 2 +-
src/main/java/com/juick/api/Main.java | 13 +++++++----
src/main/java/com/juick/api/TelegramBotHook.java | 29 ++++++++++++++++++++++++
3 files changed, 39 insertions(+), 5 deletions(-)
create mode 100644 src/main/java/com/juick/api/TelegramBotHook.java
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index b76df16a..f6b37262 100644
--- a/build.gradle
+++ b/build.gradle
@@ -54,7 +54,7 @@ dependencies {
compile xmpp
compile json
compile "org.apache.commons:commons-lang3:3.4"
- compile "org.springframework:spring-jdbc:4.2.4.RELEASE"
+ compile 'com.github.pengrad:java-telegram-bot-api:2.0.1'
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
def tomcatVersion = '7.0.+'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index c43804d7..003b9aa3 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -19,7 +19,10 @@ package com.juick.api;
import com.juick.Tag;
import com.juick.json.MessageSerializer;
-import com.juick.server.*;
+import com.juick.server.MessagesQueries;
+import com.juick.server.SubscriptionsQueries;
+import com.juick.server.TagQueries;
+import com.juick.server.UserQueries;
import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
@@ -40,8 +43,6 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
-import java.net.URLEncoder;
-import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@@ -63,6 +64,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
Users users;
PM pm;
Others others;
+ TelegramBotHook tgb;
@Override
public void init() throws ServletException {
@@ -79,7 +81,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
users = new Users(jdbc);
pm = new PM(jdbc);
others = new Others(jdbc);
-
+ tgb = new TelegramBotHook(conf.getProperty("telegram_token", ""));
setupXmppComponent(conf.getProperty("xmpp_host", "localhost"), Integer.parseInt(conf.getProperty("xmpp_port", "5347")),
conf.getProperty("xmpp_jid", "api.localhost"), conf.getProperty("xmpp_password"));
@@ -209,6 +211,9 @@ public class Main extends HttpServlet implements Stream.StreamListener {
case "/pm":
pm.doPostPM(request, response, xmpp, vuid);
break;
+ case "/tlgmbtwbhk":
+ tgb.doPost(request, response);
+ break;
default:
response.sendError(405);
break;
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
new file mode 100644
index 00000000..6d73fbfb
--- /dev/null
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -0,0 +1,29 @@
+package com.juick.api;
+
+import com.pengrad.telegrambot.TelegramBot;
+import com.pengrad.telegrambot.TelegramBotAdapter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.logging.Logger;
+
+/**
+ * Created by vt on 12/05/16.
+ */
+public class TelegramBotHook {
+ private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName());
+
+ private String token;
+ TelegramBot bot;
+
+
+ public TelegramBotHook(String token) {
+ this.token = token;
+ bot = TelegramBotAdapter.build(token);
+ bot.setWebhook("https://api.juick.com/tlgmbtwbhk");
+ }
+
+ public void doPost(HttpServletRequest request, HttpServletResponse response) {
+ logger.info("got telegram msg: " + request);
+ }
+}
--
cgit v1.2.3
From c58e021d8631fd8e1dd1d40546a4aabce27e2cdf Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 22:27:41 +0300
Subject: parse update
---
src/main/java/com/juick/api/Main.java | 6 +++++-
src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++++++--
2 files changed, 15 insertions(+), 3 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 003b9aa3..7d5c8f1b 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -127,12 +127,16 @@ public class Main extends HttpServlet implements Stream.StreamListener {
request.setCharacterEncoding("UTF-8");
}
+ String uri = request.getRequestURI();
+ if (uri.equals("/tlgmbtwbhk")) {
+ tgb.doPost(request, response);
+ return;
+ }
int vuid = Utils.getHttpAuthUID(jdbc, request);
if (vuid == 0) {
vuid = Utils.getVisitorQueryStringUID(jdbc, request);
}
- String uri = request.getRequestURI();
if (uri.equals("/home")) {
if (vuid > 0) {
messages.doGetHome(request, response, vuid);
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 6d73fbfb..a502e846 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -1,10 +1,14 @@
package com.juick.api;
+import com.pengrad.telegrambot.BotUtils;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.TelegramBotAdapter;
+import com.pengrad.telegrambot.model.Update;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
+import java.io.IOException;
import java.util.logging.Logger;
/**
@@ -23,7 +27,11 @@ public class TelegramBotHook {
bot.setWebhook("https://api.juick.com/tlgmbtwbhk");
}
- public void doPost(HttpServletRequest request, HttpServletResponse response) {
- logger.info("got telegram msg: " + request);
+ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ try (BufferedReader reader = request.getReader()) {
+ Update update = BotUtils.parseUpdate(reader);
+ logger.info("got telegram msg: " + update.message().toString());
+ }
}
}
--
cgit v1.2.3
From 01cf5ebb4e9db6458bdda762454b699593f796f5 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 22:30:23 +0300
Subject: use post not get
---
src/main/java/com/juick/api/Main.java | 15 ++++++---------
1 file changed, 6 insertions(+), 9 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 7d5c8f1b..7a571fe0 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -128,10 +128,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
}
String uri = request.getRequestURI();
- if (uri.equals("/tlgmbtwbhk")) {
- tgb.doPost(request, response);
- return;
- }
+
int vuid = Utils.getHttpAuthUID(jdbc, request);
if (vuid == 0) {
vuid = Utils.getVisitorQueryStringUID(jdbc, request);
@@ -192,6 +189,11 @@ public class Main extends HttpServlet implements Stream.StreamListener {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
+ String uri = request.getRequestURI();
+ if (uri.equals("/tlgmbtwbhk")) {
+ tgb.doPost(request, response);
+ return;
+ }
int vuid = Utils.getHttpAuthUID(jdbc, request);
if (vuid == 0) {
@@ -201,8 +203,6 @@ public class Main extends HttpServlet implements Stream.StreamListener {
response.sendError(401);
return;
}
-
- String uri = request.getRequestURI();
switch (uri) {
case "/post":
int mid = Utils.parseInt(request.getParameter("mid"), 0);
@@ -215,9 +215,6 @@ public class Main extends HttpServlet implements Stream.StreamListener {
case "/pm":
pm.doPostPM(request, response, xmpp, vuid);
break;
- case "/tlgmbtwbhk":
- tgb.doPost(request, response);
- break;
default:
response.sendError(405);
break;
--
cgit v1.2.3
From a24822ad17cc4be9ccaa01badfd17f193867e457 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 22:53:12 +0300
Subject: forward all juick messages
---
build.gradle | 1 +
src/main/java/com/juick/api/Main.java | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 57 ++++++++++++++++++++----
3 files changed, 51 insertions(+), 9 deletions(-)
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index f6b37262..d9317928 100644
--- a/build.gradle
+++ b/build.gradle
@@ -55,6 +55,7 @@ dependencies {
compile json
compile "org.apache.commons:commons-lang3:3.4"
compile 'com.github.pengrad:java-telegram-bot-api:2.0.1'
+ compile 'com.neovisionaries:nv-websocket-client:1.27'
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
def tomcatVersion = '7.0.+'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 7a571fe0..6adef22a 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -191,7 +191,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
}
String uri = request.getRequestURI();
if (uri.equals("/tlgmbtwbhk")) {
- tgb.doPost(request, response);
+ tgb.doPost(request);
return;
}
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index a502e846..b6cd16ab 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -1,14 +1,25 @@
package com.juick.api;
+import com.juick.json.MessageSerializer;
+import com.neovisionaries.ws.client.WebSocket;
+import com.neovisionaries.ws.client.WebSocketAdapter;
+import com.neovisionaries.ws.client.WebSocketFactory;
+import com.neovisionaries.ws.client.WebSocketListener;
import com.pengrad.telegrambot.BotUtils;
+import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.TelegramBotAdapter;
-import com.pengrad.telegrambot.model.Update;
+import com.pengrad.telegrambot.model.Message;
+import com.pengrad.telegrambot.request.SendMessage;
+import com.pengrad.telegrambot.response.SendResponse;
+import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -17,21 +28,51 @@ import java.util.logging.Logger;
public class TelegramBotHook {
private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName());
- private String token;
TelegramBot bot;
+ List chats = new ArrayList<>();
+ WebSocket ws;
+ MessageSerializer ms = new MessageSerializer();
public TelegramBotHook(String token) {
- this.token = token;
bot = TelegramBotAdapter.build(token);
bot.setWebhook("https://api.juick.com/tlgmbtwbhk");
+ try {
+ ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all");
+ ws.addListener(new WebSocketAdapter() {
+ @Override
+ public void onTextMessage(WebSocket websocket, String text) throws Exception {
+ super.onTextMessage(websocket, text);
+ com.juick.Message jmsg = ms.deserialize(new JSONObject(text));
+ logger.info("got jmsg: " + jmsg.toString());
+ chats.stream().forEach(c -> {
+ bot.execute(new SendMessage(c, jmsg.getText()), new Callback() {
+ @Override
+ public void onResponse(SendMessage request, SendResponse response) {
+ logger.info("got response: " + response.message().toString());
+ }
+
+ @Override
+ public void onFailure(SendMessage request, IOException e) {
+ logger.log(Level.WARNING, "telegram failure", e);
+ }
+ });
+ });
+ }
+ });
+ } catch (IOException e) {
+ logger.log(Level.SEVERE, "couldn't create ws connection", e);
+ }
}
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
- StringBuilder sb = new StringBuilder();
+ public void doPost(HttpServletRequest request) throws IOException {
try (BufferedReader reader = request.getReader()) {
- Update update = BotUtils.parseUpdate(reader);
- logger.info("got telegram msg: " + update.message().toString());
+ Message message = BotUtils.parseUpdate(reader).message();
+ logger.info("got telegram msg: " + message.toString());
+ if (!chats.contains(message.chat().id())) {
+ chats.add(message.chat().id());
+ logger.info("added chat with " + message.from().firstName());
+ }
}
}
}
--
cgit v1.2.3
From 2c7fb63528ee2544d2c9f6f32047c9178618331b Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 22:58:07 +0300
Subject: forgot to connect
---
src/main/java/com/juick/api/TelegramBotHook.java | 13 ++++++++-----
1 file changed, 8 insertions(+), 5 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index b6cd16ab..83eea314 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -1,10 +1,7 @@
package com.juick.api;
import com.juick.json.MessageSerializer;
-import com.neovisionaries.ws.client.WebSocket;
-import com.neovisionaries.ws.client.WebSocketAdapter;
-import com.neovisionaries.ws.client.WebSocketFactory;
-import com.neovisionaries.ws.client.WebSocketListener;
+import com.neovisionaries.ws.client.*;
import com.pengrad.telegrambot.BotUtils;
import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.TelegramBot;
@@ -19,6 +16,7 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -40,6 +38,10 @@ public class TelegramBotHook {
try {
ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all");
ws.addListener(new WebSocketAdapter() {
+ @Override
+ public void onConnected(WebSocket websocket, Map> headers) {
+ logger.info("ws connected");
+ }
@Override
public void onTextMessage(WebSocket websocket, String text) throws Exception {
super.onTextMessage(websocket, text);
@@ -60,7 +62,8 @@ public class TelegramBotHook {
});
}
});
- } catch (IOException e) {
+ ws.connect();
+ } catch (IOException | WebSocketException e) {
logger.log(Level.SEVERE, "couldn't create ws connection", e);
}
}
--
cgit v1.2.3
From d77b21dcf62c3e8d63615d5ef5acaaaf2614736d Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 23:32:50 +0300
Subject: add ping
---
src/main/java/com/juick/api/TelegramBotHook.java | 8 ++++++++
1 file changed, 8 insertions(+)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 83eea314..2d64b83e 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -37,7 +37,15 @@ public class TelegramBotHook {
bot.setWebhook("https://api.juick.com/tlgmbtwbhk");
try {
ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all");
+ ws.addHeader("Origin", "ws.juick.com");
+ ws.addHeader("Host", "ws.juick.com"); //TODO: remove from server
+ ws.setPingInterval(60 * 1000);
ws.addListener(new WebSocketAdapter() {
+ @Override
+ public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
+ logger.info("ws disconnected");
+ }
+
@Override
public void onConnected(WebSocket websocket, Map> headers) {
logger.info("ws connected");
--
cgit v1.2.3
From 0879730b19ac8d5ea2250c320a17de0ed7361bb3 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 12 May 2016 23:37:48 +0300
Subject: notify subscribed users
---
src/main/java/com/juick/api/TelegramBotHook.java | 11 +++++++++++
1 file changed, 11 insertions(+)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 2d64b83e..7ee759eb 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -83,6 +83,17 @@ public class TelegramBotHook {
if (!chats.contains(message.chat().id())) {
chats.add(message.chat().id());
logger.info("added chat with " + message.from().firstName());
+ bot.execute(new SendMessage(message.chat().id(), "Subscribed!"), new Callback() {
+ @Override
+ public void onResponse(SendMessage request, SendResponse response) {
+ logger.info("got response: " + response.message().toString());
+ }
+
+ @Override
+ public void onFailure(SendMessage request, IOException e) {
+ logger.log(Level.WARNING, "telegram failure", e);
+ }
+ });
}
}
}
--
cgit v1.2.3
From daab143efa277ca42e60dcd29daeddbfa5179ace Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 09:32:46 +0300
Subject: gretty
---
build.gradle | 26 ++++++++++----------------
src/main/java/com/juick/api/Main.java | 13 +++++++------
2 files changed, 17 insertions(+), 22 deletions(-)
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index b76df16a..84617e95 100644
--- a/build.gradle
+++ b/build.gradle
@@ -4,21 +4,20 @@ subprojects {
mavenCentral()
}
}
-
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
- classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.+'
+ classpath 'org.akhikhl.gretty:gretty:+'
classpath 'com.tkruse.gradle:gradle-groovysh-plugin:1.0.7'
}
}
apply plugin: 'java'
apply plugin: 'war'
-apply plugin: 'com.bmuschko.tomcat'
+apply plugin: 'org.akhikhl.gretty'
apply plugin: 'com.github.tkruse.groovysh'
repositories {
@@ -35,39 +34,34 @@ project(':deps:com.juick.server') {
compile core
}
}
-
project(':deps:com.juick.xmpp') {
dependencies {
compile core
}
}
-
project(':deps:com.juick.json') {
dependencies {
compile core
}
}
-
+configurations.all {
+ exclude group: "commons-logging", module: "commons-logging"
+}
dependencies {
compile core
compile server
compile xmpp
compile json
compile "org.apache.commons:commons-lang3:3.4"
- compile "org.springframework:spring-jdbc:4.2.4.RELEASE"
+ compile "org.springframework:spring-jdbc:4.2.6.RELEASE"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
- def tomcatVersion = '7.0.+'
- tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
- "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}",
- "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
- testCompile 'junit:junit:4.12'
- runtime 'mysql:mysql-connector-java:5.1.37'
+ compile 'javax.inject:javax.inject:1'
+ runtime 'mysql:mysql-connector-java:5.1.39'
testRuntime 'com.h2database:h2:1.4.190'
}
-
compileJava.options.encoding = 'UTF-8'
-
-tomcat {
+gretty {
httpPort = 8080
contextPath = '/'
+ servletContainer = 'tomcat8'
}
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index c43804d7..09fb51ec 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -19,7 +19,10 @@ package com.juick.api;
import com.juick.Tag;
import com.juick.json.MessageSerializer;
-import com.juick.server.*;
+import com.juick.server.MessagesQueries;
+import com.juick.server.SubscriptionsQueries;
+import com.juick.server.TagQueries;
+import com.juick.server.UserQueries;
import com.juick.xmpp.JID;
import com.juick.xmpp.Message;
import com.juick.xmpp.Stream;
@@ -40,8 +43,6 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
-import java.net.URLEncoder;
-import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@@ -68,11 +69,11 @@ public class Main extends HttpServlet implements Stream.StreamListener {
public void init() throws ServletException {
super.init();
try {
- LogManager.getLogManager().readConfiguration(getServletContext().getResourceAsStream("WEB-INF/logging.properties"));
+ LogManager.getLogManager().readConfiguration(getServletContext().getResourceAsStream("/WEB-INF/logging.properties"));
Properties conf = new Properties();
- conf.load(getServletContext().getResourceAsStream("WEB-INF/juick.conf"));
+ conf.load(getServletContext().getResourceAsStream("/WEB-INF/juick.conf"));
DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName(conf.getProperty("datasource_driver"));
+ dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver"));
dataSource.setUrl(conf.getProperty("datasource_url"));
jdbc = new JdbcTemplate(dataSource);
messages = new Messages(jdbc);
--
cgit v1.2.3
From c0115554aac7106974e12fd5b66ceaf69cee6e84 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 11:26:34 +0300
Subject: full message format
---
src/main/java/com/juick/api/TelegramBotHook.java | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 7ee759eb..6a6404de 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -54,9 +54,15 @@ public class TelegramBotHook {
public void onTextMessage(WebSocket websocket, String text) throws Exception {
super.onTextMessage(websocket, text);
com.juick.Message jmsg = ms.deserialize(new JSONObject(text));
- logger.info("got jmsg: " + jmsg.toString());
+ logger.info("got jmsg: " + ms.serialize(jmsg).toString());
+ StringBuilder sb = new StringBuilder();
+ sb.append(jmsg.getUser()).append("\n").append(jmsg.getText()).append("\n");
+ if (jmsg.getAttachmentURL() != null) {
+ sb.append(jmsg.getAttachmentURL());
+ }
+ sb.append("https://juick.com/" + jmsg.getMID());
chats.stream().forEach(c -> {
- bot.execute(new SendMessage(c, jmsg.getText()), new Callback() {
+ bot.execute(new SendMessage(c, sb.toString()), new Callback() {
@Override
public void onResponse(SendMessage request, SendResponse response) {
logger.info("got response: " + response.message().toString());
--
cgit v1.2.3
From e9202d13bca4894efb7e365d42eb9b703a0dc7eb Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 11:33:17 +0300
Subject: full message format, take 2
---
build.gradle | 3 ---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
2 files changed, 1 insertion(+), 4 deletions(-)
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index 1cffaf68..d11187c4 100644
--- a/build.gradle
+++ b/build.gradle
@@ -44,9 +44,6 @@ project(':deps:com.juick.json') {
compile core
}
}
-configurations.all {
- exclude group: "commons-logging", module: "commons-logging"
-}
dependencies {
compile core
compile server
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 6a6404de..90c644af 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -56,7 +56,7 @@ public class TelegramBotHook {
com.juick.Message jmsg = ms.deserialize(new JSONObject(text));
logger.info("got jmsg: " + ms.serialize(jmsg).toString());
StringBuilder sb = new StringBuilder();
- sb.append(jmsg.getUser()).append("\n").append(jmsg.getText()).append("\n");
+ sb.append("@").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n");
if (jmsg.getAttachmentURL() != null) {
sb.append(jmsg.getAttachmentURL());
}
--
cgit v1.2.3
From 324391a3b775f6508b316f72268d776e50aff2cc Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 11:48:19 +0300
Subject: full message format, take 3
---
src/main/java/com/juick/api/TelegramBotHook.java | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 90c644af..ed3e8942 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -60,9 +60,10 @@ public class TelegramBotHook {
if (jmsg.getAttachmentURL() != null) {
sb.append(jmsg.getAttachmentURL());
}
- sb.append("https://juick.com/" + jmsg.getMID());
+ sb.append("https://juick.com/").append(jmsg.getMID());
+ String msg = sb.toString();
chats.stream().forEach(c -> {
- bot.execute(new SendMessage(c, sb.toString()), new Callback() {
+ bot.execute(new SendMessage(c, msg), new Callback() {
@Override
public void onResponse(SendMessage request, SendResponse response) {
logger.info("got response: " + response.message().toString());
--
cgit v1.2.3
From 950177ab7959590cfd9c8678b6dbe563fcc964e0 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 12:11:52 +0300
Subject: store chats in db
---
src/main/java/com/juick/api/Main.java | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 17 ++++++++++++++---
2 files changed, 15 insertions(+), 4 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java
index 9b327e83..c632d8fc 100644
--- a/src/main/java/com/juick/api/Main.java
+++ b/src/main/java/com/juick/api/Main.java
@@ -81,7 +81,7 @@ public class Main extends HttpServlet implements Stream.StreamListener {
users = new Users(jdbc);
pm = new PM(jdbc);
others = new Others(jdbc);
- tgb = new TelegramBotHook(conf.getProperty("telegram_token", ""));
+ tgb = new TelegramBotHook(jdbc, conf.getProperty("telegram_token", ""));
setupXmppComponent(conf.getProperty("xmpp_host", "localhost"), Integer.parseInt(conf.getProperty("xmpp_port", "5347")),
conf.getProperty("xmpp_jid", "api.localhost"), conf.getProperty("xmpp_password"));
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index ed3e8942..d06473a3 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -10,6 +10,7 @@ import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import org.json.JSONObject;
+import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
@@ -27,12 +28,13 @@ public class TelegramBotHook {
private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName());
TelegramBot bot;
- List chats = new ArrayList<>();
WebSocket ws;
MessageSerializer ms = new MessageSerializer();
+ JdbcTemplate jdbc;
- public TelegramBotHook(String token) {
+ public TelegramBotHook(JdbcTemplate jdbc, String token) {
+ this.jdbc = jdbc;
bot = TelegramBotAdapter.build(token);
bot.setWebhook("https://api.juick.com/tlgmbtwbhk");
try {
@@ -62,6 +64,7 @@ public class TelegramBotHook {
}
sb.append("https://juick.com/").append(jmsg.getMID());
String msg = sb.toString();
+ List chats = getChats();
chats.stream().forEach(c -> {
bot.execute(new SendMessage(c, msg), new Callback() {
@Override
@@ -83,12 +86,20 @@ public class TelegramBotHook {
}
}
+ List getChats() {
+ return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class);
+ }
+ void addChat(Long id) {
+ jdbc.update("INSERT IGNORE TO telegram_chats(chat_id) VALUES(?)", id);
+ }
+
public void doPost(HttpServletRequest request) throws IOException {
try (BufferedReader reader = request.getReader()) {
Message message = BotUtils.parseUpdate(reader).message();
logger.info("got telegram msg: " + message.toString());
+ List chats = getChats();
if (!chats.contains(message.chat().id())) {
- chats.add(message.chat().id());
+ addChat(message.chat().id());
logger.info("added chat with " + message.from().firstName());
bot.execute(new SendMessage(message.chat().id(), "Subscribed!"), new Callback() {
@Override
--
cgit v1.2.3
From 2a595eb7e7f0c220f38b1501b75d97f7b8a234a3 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 12:33:52 +0300
Subject: store chats in db, fix
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index d06473a3..880be5e2 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -90,7 +90,7 @@ public class TelegramBotHook {
return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class);
}
void addChat(Long id) {
- jdbc.update("INSERT IGNORE TO telegram_chats(chat_id) VALUES(?)", id);
+ jdbc.update("INSERT IGNORE INTO telegram_chats(chat_id) VALUES(?)", id);
}
public void doPost(HttpServletRequest request) throws IOException {
--
cgit v1.2.3
From d7b8c7307b09a0dad102c37863bd03d551b5c8a9 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 14:47:14 +0300
Subject: url as button
---
src/main/java/com/juick/api/TelegramBotHook.java | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 880be5e2..cf0979cd 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -7,6 +7,8 @@ import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.TelegramBotAdapter;
import com.pengrad.telegrambot.model.Message;
+import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
+import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import org.json.JSONObject;
@@ -15,7 +17,6 @@ import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
@@ -62,11 +63,15 @@ public class TelegramBotHook {
if (jmsg.getAttachmentURL() != null) {
sb.append(jmsg.getAttachmentURL());
}
- sb.append("https://juick.com/").append(jmsg.getMID());
String msg = sb.toString();
List chats = getChats();
chats.stream().forEach(c -> {
- bot.execute(new SendMessage(c, msg), new Callback() {
+ bot.execute(new SendMessage(c, msg).replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[] {
+ new InlineKeyboardButton("See on Juick").url("https://juick.com/" + jmsg.getMID())
+ }
+ )), new Callback() {
@Override
public void onResponse(SendMessage request, SendResponse response) {
logger.info("got response: " + response.message().toString());
--
cgit v1.2.3
From c8156fc1361b7467306d731cd57f5a4f2a9b2006 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 16:13:08 +0300
Subject: telegram login
---
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 17 ++++++++++++++++-
2 files changed, 17 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/deps/com.juick.server b/deps/com.juick.server
index c95b63af..ea43e78c 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit c95b63af82ed58c68876563692340d74ced156f2
+Subproject commit ea43e78cb8dc20c2f54a15e37dba638b963f65ec
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index cf0979cd..9b75a4ae 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -1,6 +1,7 @@
package com.juick.api;
import com.juick.json.MessageSerializer;
+import com.juick.server.UserQueries;
import com.neovisionaries.ws.client.*;
import com.pengrad.telegrambot.BotUtils;
import com.pengrad.telegrambot.Callback;
@@ -19,6 +20,7 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -106,7 +108,16 @@ public class TelegramBotHook {
if (!chats.contains(message.chat().id())) {
addChat(message.chat().id());
logger.info("added chat with " + message.from().firstName());
- bot.execute(new SendMessage(message.chat().id(), "Subscribed!"), new Callback() {
+ createTelegramUser(message.from().id(), message.from().username());
+ bot.execute(new SendMessage(message.chat().id(),
+ "You are subscribed to all Juick messages. " +
+ "Create or link an existing Juick account to control " +
+ "what do you want to receive").replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[]{
+ new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=d&hash=" +
+ UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()))
+ })), new Callback() {
@Override
public void onResponse(SendMessage request, SendResponse response) {
logger.info("got response: " + response.message().toString());
@@ -120,4 +131,8 @@ public class TelegramBotHook {
}
}
}
+ private boolean createTelegramUser(long tgID, String tgName) {
+ return jdbc.update("INSERT INTO telegram(tg_ig, tg_name, loginhash) VALUES(?,?,?)",
+ tgID, tgName, UUID.randomUUID().toString()) > 0;
+ }
}
--
cgit v1.2.3
From 9cd79ef58a443289aa6756e8fbfabf5fe9ac8630 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 16:15:13 +0300
Subject: fix login type
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 9b75a4ae..05b99b02 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -115,7 +115,7 @@ public class TelegramBotHook {
"what do you want to receive").replyMarkup(
new InlineKeyboardMarkup(
new InlineKeyboardButton[]{
- new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=d&hash=" +
+ new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=durov&hash=" +
UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()))
})), new Callback() {
@Override
--
cgit v1.2.3
From 0400e141715d44e6cb8f25a3709e86a2d1ac7a1a Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 13 May 2016 16:32:24 +0300
Subject: fix typo
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 05b99b02..c68d829a 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -132,7 +132,7 @@ public class TelegramBotHook {
}
}
private boolean createTelegramUser(long tgID, String tgName) {
- return jdbc.update("INSERT INTO telegram(tg_ig, tg_name, loginhash) VALUES(?,?,?)",
+ return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)",
tgID, tgName, UUID.randomUUID().toString()) > 0;
}
}
--
cgit v1.2.3
From cc0a29650d3ba9b848a86cce73fbe6e3ff5d8693 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 19:46:31 +0300
Subject: telegram: notify subcribed users
---
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 57 ++++++++++++++++--------
2 files changed, 40 insertions(+), 19 deletions(-)
(limited to 'src/main/java/com')
diff --git a/deps/com.juick.server b/deps/com.juick.server
index ea43e78c..3fe5180f 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit ea43e78cb8dc20c2f54a15e37dba638b963f65ec
+Subproject commit 3fe5180ff7f2488966d3c940629ddefcfc84467f
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index c68d829a..907898f2 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -1,5 +1,6 @@
package com.juick.api;
+import com.juick.User;
import com.juick.json.MessageSerializer;
import com.juick.server.UserQueries;
import com.neovisionaries.ws.client.*;
@@ -13,6 +14,7 @@ import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import org.json.JSONObject;
+import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.http.HttpServletRequest;
@@ -20,6 +22,7 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -66,25 +69,12 @@ public class TelegramBotHook {
sb.append(jmsg.getAttachmentURL());
}
String msg = sb.toString();
+ List users = getSubscribers(jmsg.getUser().getUID());
List chats = getChats();
- chats.stream().forEach(c -> {
- bot.execute(new SendMessage(c, msg).replyMarkup(
- new InlineKeyboardMarkup(
- new InlineKeyboardButton[] {
- new InlineKeyboardButton("See on Juick").url("https://juick.com/" + jmsg.getMID())
- }
- )), new Callback() {
- @Override
- public void onResponse(SendMessage request, SendResponse response) {
- logger.info("got response: " + response.message().toString());
- }
-
- @Override
- public void onFailure(SendMessage request, IOException e) {
- logger.log(Level.WARNING, "telegram failure", e);
- }
- });
- });
+ // registered subscribed users
+ users.stream().forEach(c -> telegramNotify(c, msg, jmsg.getMID()));
+ // anonymous
+ chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, jmsg.getMID()));
}
});
ws.connect();
@@ -93,6 +83,25 @@ public class TelegramBotHook {
}
}
+ private void telegramNotify(Long c, String msg, int mid) {
+ bot.execute(new SendMessage(c, msg).replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[] {
+ new InlineKeyboardButton("See on Juick").url("https://juick.com/" + mid)
+ }
+ )), new Callback() {
+ @Override
+ public void onResponse(SendMessage request, SendResponse response) {
+ logger.info("got response: " + response.message().toString());
+ }
+
+ @Override
+ public void onFailure(SendMessage request, IOException e) {
+ logger.log(Level.WARNING, "telegram failure", e);
+ }
+ });
+ }
+
List getChats() {
return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class);
}
@@ -135,4 +144,16 @@ public class TelegramBotHook {
return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)",
tgID, tgName, UUID.randomUUID().toString()) > 0;
}
+ private Optional getUser(long tgId) {
+ try {
+ return Optional.of(jdbc.queryForObject("SELECT id, name, banned FROM users INNER JOIN telegram" +
+ "ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId));
+ } catch (EmptyResultDataAccessException e) {
+ return Optional.empty();
+ }
+ }
+ private List getSubscribers(int uid) {
+ return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " +
+ "ON (subscr_users.user_id=? AND telegram.tg_id=subscr_users.suser_id)", Long.class, uid, uid);
+ }
}
--
cgit v1.2.3
From 15f02eb428584970a95ce5787299f32b432b9a80 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 19:57:24 +0300
Subject: telegram: fix user query
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 907898f2..0cc3aa84 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -146,7 +146,7 @@ public class TelegramBotHook {
}
private Optional getUser(long tgId) {
try {
- return Optional.of(jdbc.queryForObject("SELECT id, name, banned FROM users INNER JOIN telegram" +
+ return Optional.of(jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram" +
"ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
--
cgit v1.2.3
From 2b49c5d7215aa5bd75b14101ca48c872b232bc79 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 20:14:21 +0300
Subject: comment notifications
---
src/main/java/com/juick/api/TelegramBotHook.java | 46 +++++++++++++++++++++---
1 file changed, 41 insertions(+), 5 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 907898f2..40ff5411 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -34,7 +34,7 @@ public class TelegramBotHook {
private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName());
TelegramBot bot;
- WebSocket ws;
+ WebSocket ws, wsReply;
MessageSerializer ms = new MessageSerializer();
JdbcTemplate jdbc;
@@ -72,22 +72,54 @@ public class TelegramBotHook {
List users = getSubscribers(jmsg.getUser().getUID());
List chats = getChats();
// registered subscribed users
- users.stream().forEach(c -> telegramNotify(c, msg, jmsg.getMID()));
+ String msgUrl = "https://juick.com/" + jmsg.getMID();
+ users.stream().forEach(c -> telegramNotify(c, msg, msgUrl));
// anonymous
- chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, jmsg.getMID()));
+ chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, msgUrl));
}
});
ws.connect();
+ wsReply = new WebSocketFactory().createSocket("wss://ws.juick.com/_replies");
+ wsReply.addHeader("Origin", "ws.juick.com");
+ wsReply.addHeader("Host", "ws.juick.com");
+ wsReply.setPingInterval(60 * 1000);
+ wsReply.addListener(new WebSocketAdapter() {
+ @Override
+ public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
+ logger.info("ws replies disconnected");
+ }
+
+ @Override
+ public void onConnected(WebSocket websocket, Map> headers) throws Exception {
+ logger.info("ws replies connected");
+ }
+
+ @Override
+ public void onTextMessage(WebSocket websocket, String text) throws Exception {
+ com.juick.Message jmsg = ms.deserialize(new JSONObject(text));
+ logger.info(String.format("got jmsg: %s", ms.serialize(jmsg).toString()));
+ StringBuilder sb = new StringBuilder();
+ sb.append("Reply from @").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n");
+ if (jmsg.getAttachmentURL() != null) {
+ sb.append(jmsg.getAttachmentURL());
+ }
+ String msg = sb.toString();
+ String msgUrl = String.format("https://juick.com/%d#%d", jmsg.getMID(), jmsg.getRID());
+ getSubscribersToComments(jmsg.getMID(), jmsg.getUser().getUID()).stream()
+ .forEach(c -> telegramNotify(c, msg, msgUrl));
+ }
+ });
+ wsReply.connect();
} catch (IOException | WebSocketException e) {
logger.log(Level.SEVERE, "couldn't create ws connection", e);
}
}
- private void telegramNotify(Long c, String msg, int mid) {
+ private void telegramNotify(Long c, String msg, String msgUrl) {
bot.execute(new SendMessage(c, msg).replyMarkup(
new InlineKeyboardMarkup(
new InlineKeyboardButton[] {
- new InlineKeyboardButton("See on Juick").url("https://juick.com/" + mid)
+ new InlineKeyboardButton("See on Juick").url(msgUrl)
}
)), new Callback() {
@Override
@@ -156,4 +188,8 @@ public class TelegramBotHook {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " +
"ON (subscr_users.user_id=? AND telegram.tg_id=subscr_users.suser_id)", Long.class, uid, uid);
}
+ private List getSubscribersToComments(int mid, int ignore_uid) {
+ return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " +
+ "ON (telegram.user_id=subscr_messages.suser_id) WHERE message_id=? AND suser_id!=?", Long.class, mid, ignore_uid);
+ }
}
--
cgit v1.2.3
From 9be74d0e4b5c62e54685483b132c0311bc8aed2a Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 20:42:48 +0300
Subject: fix subscribers query
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 97418418..9a743bc1 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -186,7 +186,7 @@ public class TelegramBotHook {
}
private List getSubscribers(int uid) {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " +
- "ON (subscr_users.user_id=? AND telegram.tg_id=subscr_users.suser_id)", Long.class, uid, uid);
+ "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid, uid);
}
private List getSubscribersToComments(int mid, int ignore_uid) {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " +
--
cgit v1.2.3
From b4e6e2092606afb2a321fd07f5bdb687ef03356e Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 20:50:09 +0300
Subject: telegram reply quote
---
src/main/java/com/juick/api/TelegramBotHook.java | 26 ++++++++++++++++++++++--
1 file changed, 24 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 9a743bc1..a9a35683 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -2,6 +2,7 @@ package com.juick.api;
import com.juick.User;
import com.juick.json.MessageSerializer;
+import com.juick.server.MessagesQueries;
import com.juick.server.UserQueries;
import com.neovisionaries.ws.client.*;
import com.pengrad.telegrambot.BotUtils;
@@ -99,9 +100,10 @@ public class TelegramBotHook {
com.juick.Message jmsg = ms.deserialize(new JSONObject(text));
logger.info(String.format("got jmsg: %s", ms.serialize(jmsg).toString()));
StringBuilder sb = new StringBuilder();
- sb.append("Reply from @").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n");
+ sb.append("Reply by @").append(jmsg.getUser().getUName()).append(":\n")
+ .append(getReplyQuote(jmsg.getMID(), jmsg.ReplyTo)).append("\n").append(jmsg.getText());
if (jmsg.getAttachmentURL() != null) {
- sb.append(jmsg.getAttachmentURL());
+ sb.append("\n").append(jmsg.getAttachmentURL());
}
String msg = sb.toString();
String msgUrl = String.format("https://juick.com/%d#%d", jmsg.getMID(), jmsg.getRID());
@@ -192,4 +194,24 @@ public class TelegramBotHook {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " +
"ON (telegram.user_id=subscr_messages.suser_id) WHERE message_id=? AND suser_id!=?", Long.class, mid, ignore_uid);
}
+ private String getReplyQuote(int MID, int ReplyTo) {
+ String quote = "";
+ if (ReplyTo > 0) {
+ com.juick.Message q = MessagesQueries.getReply(jdbc, MID, ReplyTo);
+ if (q != null) {
+ quote = q.getText();
+ }
+ } else {
+ com.juick.Message q = MessagesQueries.getMessage(jdbc, MID);
+ if (q != null) {
+ quote = q.getText();
+ }
+ }
+ if (quote.length() > 50) {
+ quote = ">" + quote.substring(0, 47).replace('\n', ' ') + "...\n";
+ } else if (quote.length() > 0) {
+ quote = ">" + quote.replace('\n', ' ') + "\n";
+ }
+ return quote;
+ }
}
--
cgit v1.2.3
From 7c7d4de2f68a22b63920dd4662ab530cc1b6ecfe Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 21:06:28 +0300
Subject: improve login flow
---
src/main/java/com/juick/api/TelegramBotHook.java | 54 +++++++++++++++---------
1 file changed, 34 insertions(+), 20 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index a9a35683..80ae0649 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -146,34 +146,48 @@ public class TelegramBotHook {
public void doPost(HttpServletRequest request) throws IOException {
try (BufferedReader reader = request.getReader()) {
Message message = BotUtils.parseUpdate(reader).message();
- logger.info("got telegram msg: " + message.toString());
+ User user_from = getUser(message.chat().id()).orElse(new User());
+ logger.info(String.format("got telegram msg %s from juick user %d", message.toString(), user_from.getUID()));
List chats = getChats();
if (!chats.contains(message.chat().id())) {
addChat(message.chat().id());
logger.info("added chat with " + message.from().firstName());
createTelegramUser(message.from().id(), message.from().username());
- bot.execute(new SendMessage(message.chat().id(),
- "You are subscribed to all Juick messages. " +
- "Create or link an existing Juick account to control " +
- "what do you want to receive").replyMarkup(
- new InlineKeyboardMarkup(
- new InlineKeyboardButton[]{
- new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=durov&hash=" +
- UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()))
- })), new Callback() {
- @Override
- public void onResponse(SendMessage request, SendResponse response) {
- logger.info("got response: " + response.message().toString());
- }
-
- @Override
- public void onFailure(SendMessage request, IOException e) {
- logger.log(Level.WARNING, "telegram failure", e);
- }
- });
+ telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()));
+ } else {
+ if (user_from.getUID() == 0) {
+ telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()));
+ } else if (message.text().equalsIgnoreCase("/login")) {
+ String msg = String.format("Hi, %s!\nTap to log in", user_from.getUName());
+ String msgUrl = "http://juick.com/login?" + UserQueries.getHashByUID(jdbc, user_from.getUID());
+ telegramNotify(message.from().id().longValue(), msg, msgUrl);
+ }
}
}
}
+
+ private void telegramSignupNotify(Long telegramId, String hash) {
+ bot.execute(new SendMessage(telegramId,
+ "You are subscribed to all Juick messages. " +
+ "Create or link an existing Juick account to control " +
+ "what do you want to receive").replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[]{
+ new InlineKeyboardButton("SIGNUP").url("http://juick.com/signup?type=durov&hash=" +
+ hash)
+ })), new Callback() {
+ @Override
+ public void onResponse(SendMessage request, SendResponse response) {
+ logger.info("got response: " + response.message().toString());
+ }
+
+ @Override
+ public void onFailure(SendMessage request, IOException e) {
+ logger.log(Level.WARNING, "telegram failure", e);
+ }
+ });
+ }
+
private boolean createTelegramUser(long tgID, String tgName) {
return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)",
tgID, tgName, UUID.randomUUID().toString()) > 0;
--
cgit v1.2.3
From 2dd33510e9b82174605bc0f19514cf04d194fe52 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 21:09:38 +0300
Subject: fix user query
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 80ae0649..6b1f946c 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -194,7 +194,7 @@ public class TelegramBotHook {
}
private Optional getUser(long tgId) {
try {
- return Optional.of(jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram" +
+ return Optional.of(jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " +
"ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
--
cgit v1.2.3
From 7fb8cdfb02c24c265a081499c858f3aca1efbb2b Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Thu, 19 May 2016 23:24:22 +0300
Subject: update server api and try to fix anonymous chats
---
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/Messages.java | 2 +-
src/main/java/com/juick/api/PM.java | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++------
src/test/java/com/juick/tests/ApiTests.java | 4 ++--
5 files changed, 11 insertions(+), 11 deletions(-)
(limited to 'src/main/java/com')
diff --git a/deps/com.juick.server b/deps/com.juick.server
index a4110979..b633724c 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit a41109795f6f6a3803d52606df9bd1a0da641f43
+Subproject commit b633724c75081eb05b70ceee74636f19576a4483
diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java
index d86193f1..18c868f4 100644
--- a/src/main/java/com/juick/api/Messages.java
+++ b/src/main/java/com/juick/api/Messages.java
@@ -165,7 +165,7 @@ public class Messages {
msg.from = new JID("juick", "juick.com", null);
msg.to = new JID(null, "crosspost.juick.com", null);
JuickMessage jmsg = new JuickMessage(m);
- jmsg.setUser(UserQueries.getUserByUID(sql, 11574));
+ jmsg.setUser(UserQueries.getUserByUID(sql, 11574).get());
msg.childs.add(jmsg);
msg.to.Username = "twitter";
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
index 3ca9eada..c7123d0a 100644
--- a/src/main/java/com/juick/api/PM.java
+++ b/src/main/java/com/juick/api/PM.java
@@ -77,7 +77,7 @@ public class PM {
msg.from = new JID("juick", "juick.com", null);
msg.to = new JID(Integer.toString(uid), "push.juick.com", null);
JuickMessage jmsg = new JuickMessage();
- jmsg.setUser(UserQueries.getUserByUID(sql, vuid));
+ jmsg.setUser(UserQueries.getUserByUID(sql, vuid).get());
jmsg.setText(body);
msg.childs.add(jmsg);
xmpp.send(msg);
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 6b1f946c..8bbf0e33 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -76,7 +76,7 @@ public class TelegramBotHook {
String msgUrl = "https://juick.com/" + jmsg.getMID();
users.stream().forEach(c -> telegramNotify(c, msg, msgUrl));
// anonymous
- chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, msgUrl));
+ chats.stream().filter(u -> getUser(u) == 0).forEach(c -> telegramNotify(c, msg, msgUrl));
}
});
ws.connect();
@@ -146,7 +146,7 @@ public class TelegramBotHook {
public void doPost(HttpServletRequest request) throws IOException {
try (BufferedReader reader = request.getReader()) {
Message message = BotUtils.parseUpdate(reader).message();
- User user_from = getUser(message.chat().id()).orElse(new User());
+ User user_from = UserQueries.getUserByUID(jdbc, getUser(message.chat().id())).orElse(new User());
logger.info(String.format("got telegram msg %s from juick user %d", message.toString(), user_from.getUID()));
List chats = getChats();
if (!chats.contains(message.chat().id())) {
@@ -192,12 +192,12 @@ public class TelegramBotHook {
return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)",
tgID, tgName, UUID.randomUUID().toString()) > 0;
}
- private Optional getUser(long tgId) {
+ private int getUser(long tgId) {
try {
- return Optional.of(jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " +
- "ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId));
+ return jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " +
+ "ON telegram.user_id = users.id WHERE telegram.tg_id=?", Integer.class, tgId);
} catch (EmptyResultDataAccessException e) {
- return Optional.empty();
+ return 0;
}
}
private List getSubscribers(int uid) {
diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java
index 5bd90509..2bae183d 100644
--- a/src/test/java/com/juick/tests/ApiTests.java
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -94,7 +94,7 @@ public class ApiTests {
@Test
public void messageTests() {
int user_id = UserQueries.createUser(jdbc, "me", "secret");
- User user = UserQueries.getUserByUID(jdbc, user_id);
+ User user = UserQueries.getUserByUID(jdbc, user_id).orElse(new User());
Assert.assertEquals("it should be me", "me", user.getUName());
int mid = MessagesQueries.createMessage(jdbc, user_id, "yo", null, new ArrayList<>());
Message msg = MessagesQueries.getMessage(jdbc, mid);
@@ -113,7 +113,7 @@ public class ApiTests {
Message msg2 = MessagesQueries.getMessage(jdbc, mid2);
org.junit.Assert.assertEquals(1, msg2.Tags.size());
int ugnich_id = UserQueries.createUser(jdbc, "ugnich", "x");
- User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id);
+ User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id).orElse(new User());
int rid = MessagesQueries.createReply(jdbc, msg2.getMID(), 0, ugnich.getUID(), "bla-bla", null);
org.junit.Assert.assertEquals(1, rid);
Message msg3 = MessagesQueries.getMessage(jdbc, mid2);
--
cgit v1.2.3
From c622ff7f5a99277c0c27da1eba527c1257471ae0 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 20 May 2016 00:03:04 +0300
Subject: fix sql
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 8bbf0e33..48e6bccb 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -202,7 +202,7 @@ public class TelegramBotHook {
}
private List getSubscribers(int uid) {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " +
- "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid, uid);
+ "ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid);
}
private List getSubscribersToComments(int mid, int ignore_uid) {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " +
--
cgit v1.2.3
From 3c47c5763ad624ac525cd8d2c19b08b61a55fcda Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 20 May 2016 00:13:11 +0300
Subject: fix query
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 48e6bccb..fa05c2f0 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -194,7 +194,7 @@ public class TelegramBotHook {
}
private int getUser(long tgId) {
try {
- return jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " +
+ return jdbc.queryForObject("SELECT id FROM users INNER JOIN telegram " +
"ON telegram.user_id = users.id WHERE telegram.tg_id=?", Integer.class, tgId);
} catch (EmptyResultDataAccessException e) {
return 0;
--
cgit v1.2.3
From 740fa16a06f9aeae839ffda6344c663a258d8e85 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Tue, 24 May 2016 14:44:11 +0300
Subject: fix telegram signup
---
deps/com.juick.server | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)
(limited to 'src/main/java/com')
diff --git a/deps/com.juick.server b/deps/com.juick.server
index b633724c..1ce6bc55 160000
--- a/deps/com.juick.server
+++ b/deps/com.juick.server
@@ -1 +1 @@
-Subproject commit b633724c75081eb05b70ceee74636f19576a4483
+Subproject commit 1ce6bc55817129159b1cda5076d039e9c3bc8508
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index fa05c2f0..8c23973e 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -153,10 +153,10 @@ public class TelegramBotHook {
addChat(message.chat().id());
logger.info("added chat with " + message.from().firstName());
createTelegramUser(message.from().id(), message.from().username());
- telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()));
+ telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username()));
} else {
if (user_from.getUID() == 0) {
- telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue()));
+ telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username()));
} else if (message.text().equalsIgnoreCase("/login")) {
String msg = String.format("Hi, %s!\nTap to log in", user_from.getUName());
String msgUrl = "http://juick.com/login?" + UserQueries.getHashByUID(jdbc, user_from.getUID());
--
cgit v1.2.3
From f2d66113d764f81d58905256a0f74e4f2ebd19f0 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Tue, 7 Jun 2016 18:56:02 +0300
Subject: telegram: use first name when username is not set
---
src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 8c23973e..ccfa2c11 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -149,14 +149,18 @@ public class TelegramBotHook {
User user_from = UserQueries.getUserByUID(jdbc, getUser(message.chat().id())).orElse(new User());
logger.info(String.format("got telegram msg %s from juick user %d", message.toString(), user_from.getUID()));
List chats = getChats();
+ String username = message.from().username();
+ if (username == null) {
+ username = message.from().firstName();
+ }
if (!chats.contains(message.chat().id())) {
addChat(message.chat().id());
- logger.info("added chat with " + message.from().firstName());
- createTelegramUser(message.from().id(), message.from().username());
- telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username()));
+ logger.info("added chat with " + username);
+ createTelegramUser(message.from().id(), username);
+ telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), username));
} else {
if (user_from.getUID() == 0) {
- telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username()));
+ telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), username));
} else if (message.text().equalsIgnoreCase("/login")) {
String msg = String.format("Hi, %s!\nTap to log in", user_from.getUName());
String msgUrl = "http://juick.com/login?" + UserQueries.getHashByUID(jdbc, user_from.getUID());
--
cgit v1.2.3
From 904a06d013f999e98724b222e6a4b48f68ddf32f Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Tue, 7 Jun 2016 19:01:40 +0300
Subject: fix indentation and update telegram library
---
build.gradle | 2 +-
src/main/java/com/juick/api/TelegramBotHook.java | 18 ++++++++++++------
2 files changed, 13 insertions(+), 7 deletions(-)
(limited to 'src/main/java/com')
diff --git a/build.gradle b/build.gradle
index d11187c4..0d69481d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -53,7 +53,7 @@ dependencies {
compile "org.springframework:spring-jdbc:4.2.6.RELEASE"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'javax.inject:javax.inject:1'
- compile 'com.github.pengrad:java-telegram-bot-api:2.0.1'
+ compile 'com.github.pengrad:java-telegram-bot-api:2.1.1'
compile 'com.neovisionaries:nv-websocket-client:1.27'
runtime 'mysql:mysql-connector-java:5.1.39'
testCompile 'junit:junit:4.12'
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index ccfa2c11..2e1ac20c 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -42,7 +42,7 @@ public class TelegramBotHook {
public TelegramBotHook(JdbcTemplate jdbc, String token) {
this.jdbc = jdbc;
- bot = TelegramBotAdapter.build(token);
+ bot = TelegramBotAdapter.build(token);
bot.setWebhook("https://api.juick.com/tlgmbtwbhk");
try {
ws = new WebSocketFactory().createSocket("wss://ws.juick.com/_all");
@@ -59,6 +59,7 @@ public class TelegramBotHook {
public void onConnected(WebSocket websocket, Map> headers) {
logger.info("ws connected");
}
+
@Override
public void onTextMessage(WebSocket websocket, String text) throws Exception {
super.onTextMessage(websocket, text);
@@ -120,7 +121,7 @@ public class TelegramBotHook {
private void telegramNotify(Long c, String msg, String msgUrl) {
bot.execute(new SendMessage(c, msg).replyMarkup(
new InlineKeyboardMarkup(
- new InlineKeyboardButton[] {
+ new InlineKeyboardButton[]{
new InlineKeyboardButton("See on Juick").url(msgUrl)
}
)), new Callback() {
@@ -139,6 +140,7 @@ public class TelegramBotHook {
List getChats() {
return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class);
}
+
void addChat(Long id) {
jdbc.update("INSERT IGNORE INTO telegram_chats(chat_id) VALUES(?)", id);
}
@@ -149,10 +151,10 @@ public class TelegramBotHook {
User user_from = UserQueries.getUserByUID(jdbc, getUser(message.chat().id())).orElse(new User());
logger.info(String.format("got telegram msg %s from juick user %d", message.toString(), user_from.getUID()));
List chats = getChats();
- String username = message.from().username();
- if (username == null) {
- username = message.from().firstName();
- }
+ String username = message.from().username();
+ if (username == null) {
+ username = message.from().firstName();
+ }
if (!chats.contains(message.chat().id())) {
addChat(message.chat().id());
logger.info("added chat with " + username);
@@ -196,6 +198,7 @@ public class TelegramBotHook {
return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)",
tgID, tgName, UUID.randomUUID().toString()) > 0;
}
+
private int getUser(long tgId) {
try {
return jdbc.queryForObject("SELECT id FROM users INNER JOIN telegram " +
@@ -204,14 +207,17 @@ public class TelegramBotHook {
return 0;
}
}
+
private List getSubscribers(int uid) {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " +
"ON (subscr_users.user_id=? AND telegram.user_id=subscr_users.suser_id)", Long.class, uid);
}
+
private List getSubscribersToComments(int mid, int ignore_uid) {
return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_messages " +
"ON (telegram.user_id=subscr_messages.suser_id) WHERE message_id=? AND suser_id!=?", Long.class, mid, ignore_uid);
}
+
private String getReplyQuote(int MID, int ReplyTo) {
String quote = "";
if (ReplyTo > 0) {
--
cgit v1.2.3
From 0a2d8c6b44acc8f9e4ca3a70bcd891ff903f1708 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Tue, 7 Jun 2016 19:35:57 +0300
Subject: telegram: show tags
---
src/main/java/com/juick/api/TelegramBotHook.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 2e1ac20c..e3afdd51 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -23,7 +23,6 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -66,7 +65,8 @@ public class TelegramBotHook {
com.juick.Message jmsg = ms.deserialize(new JSONObject(text));
logger.info("got jmsg: " + ms.serialize(jmsg).toString());
StringBuilder sb = new StringBuilder();
- sb.append("@").append(jmsg.getUser().getUName()).append(":\n").append(jmsg.getText()).append("\n");
+ sb.append("@").append(jmsg.getUser().getUName()).append(":\n")
+ .append(jmsg.getTagsString()).append("\n").append(jmsg.getText()).append("\n");
if (jmsg.getAttachmentURL() != null) {
sb.append(jmsg.getAttachmentURL());
}
--
cgit v1.2.3
From 5df4a0d2631e31e4c035aaedec1d6d50e3bdb098 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Mon, 27 Jun 2016 16:02:40 +0300
Subject: telegram: try to add photo
---
src/main/java/com/juick/api/TelegramBotHook.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index e3afdd51..429b55f3 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -67,8 +67,8 @@ public class TelegramBotHook {
StringBuilder sb = new StringBuilder();
sb.append("@").append(jmsg.getUser().getUName()).append(":\n")
.append(jmsg.getTagsString()).append("\n").append(jmsg.getText()).append("\n");
- if (jmsg.getAttachmentURL() != null) {
- sb.append(jmsg.getAttachmentURL());
+ if (jmsg.Photo != null) {
+ sb.append(jmsg.Photo);
}
String msg = sb.toString();
List users = getSubscribers(jmsg.getUser().getUID());
--
cgit v1.2.3
From 1f631483bbed66a5afee88eb8341880a40075a7c Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Mon, 27 Jun 2016 16:38:56 +0300
Subject: fix compilation
---
src/main/java/com/juick/api/PM.java | 4 ++--
src/main/java/com/juick/api/Users.java | 14 +++++---------
2 files changed, 7 insertions(+), 11 deletions(-)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java
index c7123d0a..631ae978 100644
--- a/src/main/java/com/juick/api/PM.java
+++ b/src/main/java/com/juick/api/PM.java
@@ -87,8 +87,8 @@ public class PM {
Main.replyJSON(request, response, messageSerializer.serialize(jmsg).toString());
- String jid = UserQueries.getJIDbyUID(sql, uid);
- if (jid != null) {
+ List jids = UserQueries.getJIDsbyUID(sql, uid);
+ for (String jid: jids) {
Message mm = new Message();
mm.to = new JID(jid);
mm.type = Message.Type.chat;
diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java
index 57f8c4b9..e85c517a 100644
--- a/src/main/java/com/juick/api/Users.java
+++ b/src/main/java/com/juick/api/Users.java
@@ -1,5 +1,6 @@
package com.juick.api;
+import com.juick.User;
import com.juick.json.UserSerializer;
import com.juick.server.UserQueries;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -115,15 +116,10 @@ public class Users {
}
if (uid > 0) {
- List uids = UserQueries.getUserReaders(sql, uid);
- if (uids.size() > 0) {
- List users = UserQueries.getUsersByID(sql, uids);
- if (users.size() > 0) {
- String json = userSerializer.serializeList(users);
- Main.replyJSON(request, response, json);
- return;
- }
- }
+ List users = UserQueries.getUserReaders(sql, uid);
+ String json = userSerializer.serializeList(users);
+ Main.replyJSON(request, response, json);
+ return;
}
response.sendError(404);
}
--
cgit v1.2.3
From 5fc121e7dc0c5c61dda58f4e4a73d7e43848e1e4 Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Mon, 27 Jun 2016 16:56:13 +0300
Subject: telegram: reconnect websockets
---
src/main/java/com/juick/api/TelegramBotHook.java | 2 ++
1 file changed, 2 insertions(+)
(limited to 'src/main/java/com')
diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java
index 429b55f3..e1094ff6 100644
--- a/src/main/java/com/juick/api/TelegramBotHook.java
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -52,6 +52,7 @@ public class TelegramBotHook {
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
logger.info("ws disconnected");
+ ws.connect();
}
@Override
@@ -89,6 +90,7 @@ public class TelegramBotHook {
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
logger.info("ws replies disconnected");
+ ws.connect();
}
@Override
--
cgit v1.2.3