aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2016-07-07 15:16:21 +0300
committerGravatar Vitaly Takmazov2016-07-07 15:16:21 +0300
commite5c286017b59a0862f2ccc4d9f905d8a3b0008ac (patch)
tree6522c6c00f64491fb1c9aca7cc8f36ad3c581954
parente5c8298beee5dde90ca98cc4707faac4bf0e2f0c (diff)
parenta2d11294adca359bb6f7021a9b5db13647b5f504 (diff)
merge api
-rw-r--r--build.gradle69
m---------deps/com.juick6
m---------deps/com.juick.json6
m---------deps/com.juick.server6
-rw-r--r--src/main/java/com/juick/api/Main.java458
-rw-r--r--src/main/java/com/juick/api/Messages.java188
-rw-r--r--src/main/java/com/juick/api/Others.java53
-rw-r--r--src/main/java/com/juick/api/PM.java109
-rw-r--r--src/main/java/com/juick/api/TelegramBotHook.java243
-rw-r--r--src/main/java/com/juick/api/Users.java126
-rw-r--r--src/main/java/com/juick/api/Utils.java231
-rw-r--r--src/main/resources/schema.sql838
-rw-r--r--src/main/webapp/WEB-INF/juick.conf.example6
-rw-r--r--src/main/webapp/WEB-INF/web.xml16
-rw-r--r--src/test/java/com/juick/tests/ApiTests.java74
15 files changed, 2429 insertions, 0 deletions
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 00000000..5a62cfd2
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,69 @@
+subprojects {
+ apply plugin: 'java'
+ repositories {
+ mavenCentral()
+ }
+}
+buildscript {
+ repositories {
+ mavenCentral()
+ jcenter()
+ }
+ dependencies {
+ classpath 'org.akhikhl.gretty:gretty:+'
+ classpath 'com.tkruse.gradle:gradle-groovysh-plugin:1.0.7'
+ }
+}
+
+apply plugin: 'java'
+apply plugin: 'war'
+apply plugin: 'org.akhikhl.gretty'
+apply plugin: 'com.github.tkruse.groovysh'
+
+repositories {
+ mavenCentral()
+ jcenter()
+}
+
+def core = project(':deps:com.juick')
+def server = project(':deps:com.juick.server')
+def xmpp = project(':deps:com.juick.xmpp')
+def json = project(':deps:com.juick.json')
+
+project(':deps:com.juick.server') {
+ dependencies {
+ compile core
+ }
+}
+project(':deps:com.juick.xmpp') {
+ dependencies {
+ compile core
+ }
+}
+project(':deps:com.juick.json') {
+ dependencies {
+ compile core
+ }
+}
+dependencies {
+ compile core
+ compile server
+ compile xmpp
+ compile json
+ compile "org.apache.commons:commons-lang3:3.4"
+ 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.1.1'
+ compile 'com.neovisionaries:nv-websocket-client:1.27'
+ testCompile 'ch.vorburger.mariaDB4j:mariaDB4j:2.1.3'
+ testCompile 'org.slf4j:slf4j-jdk14:1.7.13'
+ providedRuntime 'mysql:mysql-connector-java:5.1.39'
+ testCompile 'junit:junit:4.12'
+}
+compileJava.options.encoding = 'UTF-8'
+gretty {
+ httpPort = 8080
+ contextPath = '/'
+ servletContainer = 'tomcat8'
+}
diff --git a/deps/com.juick b/deps/com.juick
new file mode 160000
+Subproject 39ec74abe77cdab5aa8f50c2524e6f71c2dbbd0
diff --git a/deps/com.juick.json b/deps/com.juick.json
new file mode 160000
+Subproject 9dfad84fa487960fde4cc4b0ac6760c8dd5f4ac
diff --git a/deps/com.juick.server b/deps/com.juick.server
new file mode 160000
+Subproject 53a4aaacf585e70aadd3b1133319a5bb1e08f0c
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..c632d8fc
--- /dev/null
+++ b/src/main/java/com/juick/api/Main.java
@@ -0,0 +1,458 @@
+/*
+ * Juick
+ * Copyright (C) 2008-2013, Ugnich Anton
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.juick.api;
+
+import com.juick.Tag;
+import com.juick.json.MessageSerializer;
+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;
+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;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.MultipartConfig;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.Socket;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.logging.LogManager;
+
+/**
+ *
+ * @author Ugnich Anton
+ */
+@WebServlet(name = "Main", urlPatterns = {"/"})
+@MultipartConfig
+public class Main extends HttpServlet implements Stream.StreamListener {
+
+ JdbcTemplate jdbc;
+ Stream xmpp;
+ Messages messages;
+ Users users;
+ PM pm;
+ Others others;
+ TelegramBotHook tgb;
+
+ @Override
+ public void init() throws ServletException {
+ super.init();
+ try {
+ LogManager.getLogManager().readConfiguration(getServletContext().getResourceAsStream("/WEB-INF/logging.properties"));
+ Properties conf = new Properties();
+ conf.load(getServletContext().getResourceAsStream("/WEB-INF/juick.conf"));
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.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);
+ 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"));
+
+ } catch (IOException e) {
+ log("API initialization error", e);
+ }
+ }
+
+ 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(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);
+ }
+ });
+ }
+
+ @Override
+ public void onStreamFail(String msg) {
+ log("XMPP failed: " + msg);
+ }
+
+ @Override
+ public void onStreamReady() {
+ log("XMPP STREAM READY");
+ }
+
+ /**
+ * Handles the HTTP <code>GET</code> method.
+ * @param request servlet request
+ * @param response servlet response
+ * @throws ServletException if a servlet-specific error occurs
+ * @throws IOException if an I/O error occurs
+ */
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ if (request.getCharacterEncoding() == null) {
+ request.setCharacterEncoding("UTF-8");
+ }
+
+ String uri = request.getRequestURI();
+
+ int vuid = Utils.getHttpAuthUID(jdbc, request);
+ if (vuid == 0) {
+ vuid = Utils.getVisitorQueryStringUID(jdbc, request);
+ }
+
+ if (uri.equals("/home")) {
+ if (vuid > 0) {
+ messages.doGetHome(request, response, vuid);
+ } 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")) {
+ 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/recommended")) {
+ if (vuid > 0) {
+ messages.doGetRecommended(request, response, vuid);
+ } else {
+ response.sendError(401);
+ }
+ } 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);
+ } else {
+ response.sendError(404);
+ }
+ }
+
+ /**
+ * Handles the HTTP <code>POST</code> method.
+ * @param request servlet request
+ * @param response servlet response
+ * @throws ServletException if a servlet-specific error occurs
+ * @throws IOException if an I/O error occurs
+ */
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ if (request.getCharacterEncoding() == null) {
+ request.setCharacterEncoding("UTF-8");
+ }
+ String uri = request.getRequestURI();
+ if (uri.equals("/tlgmbtwbhk")) {
+ tgb.doPost(request);
+ return;
+ }
+
+ int vuid = Utils.getHttpAuthUID(jdbc, request);
+ if (vuid == 0) {
+ vuid = Utils.getVisitorQueryStringUID(jdbc, request);
+ }
+ if (vuid == 0) {
+ response.sendError(401);
+ return;
+ }
+ 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);
+ break;
+ default:
+ response.sendError(405);
+ break;
+ }
+ }
+
+ 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<Tag> 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", "*");
+
+ String callback = request.getParameter("callback");
+ if (callback != null && (callback.length() > 64 || !callback.matches("[a-zA-Z0-9\\-\\_]+"))) {
+ callback = null;
+ }
+
+ try (PrintWriter out = response.getWriter()) {
+ if (callback != null) {
+ out.print(callback + "(");
+ out.print(json);
+ out.print(")");
+ } else {
+ out.print(json);
+ }
+ }
+ }
+}
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..18c868f4
--- /dev/null
+++ b/src/main/java/com/juick/api/Messages.java
@@ -0,0 +1,188 @@
+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 org.springframework.util.StringUtils;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ *
+ * @author ugnich
+ */
+public class Messages {
+
+ JdbcTemplate sql;
+
+ MessageSerializer messageSerializer = new MessageSerializer();
+
+ public Messages(JdbcTemplate sql) {
+ this.sql = sql;
+ }
+
+ void feedMessages(HttpServletRequest request, HttpServletResponse response, List<Integer> mids) throws IOException {
+ if (mids != null && !mids.isEmpty()) {
+ List<com.juick.Message> msgs = MessagesQueries.getMessages(sql, mids);
+ if (msgs != null && !msgs.isEmpty()) {
+ String json = messageSerializer.serializeList(msgs);
+ Main.replyJSON(request, response, json);
+ } else {
+ response.sendError(404);
+ }
+ } else {
+ response.sendError(404);
+ }
+ }
+
+ 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 {
+ int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+ 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<com.juick.Message> 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,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
+ int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0);
+
+ List<Integer> mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid);
+ if (mids != null && !mids.isEmpty()) {
+ List<com.juick.Message> msgs = MessagesQueries.getMessages(sql, mids);
+ if (msgs != null && !msgs.isEmpty()) {
+ String json = messageSerializer.serializeList(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.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 {
+ 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.setUser(UserQueries.getUserByUID(sql, 11574).get());
+ 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..12849f90
--- /dev/null
+++ b/src/main/java/com/juick/api/Others.java
@@ -0,0 +1,53 @@
+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;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.List;
+
+/**
+ *
+ * @author ugnich
+ */
+public class Others {
+
+ JdbcTemplate sql;
+
+ UserSerializer userSerializer = new UserSerializer();
+
+ public Others(JdbcTemplate 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) {
+ }
+
+ List<User> lastconv = PMQueries.getPMLastConversationsUsers(sql, vuid, cnt);
+ if (lastconv != null && !lastconv.isEmpty()) {
+ 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
new file mode 100644
index 00000000..631ae978
--- /dev/null
+++ b/src/main/java/com/juick/api/PM.java
@@ -0,0 +1,109 @@
+package com.juick.api;
+
+import com.juick.json.MessageSerializer;
+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 org.springframework.jdbc.core.JdbcTemplate;
+
+import java.io.IOException;
+import java.util.List;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ *
+ * @author ugnich
+ */
+public class PM {
+
+ JdbcTemplate sql;
+
+ MessageSerializer messageSerializer = new MessageSerializer();
+
+ public PM(JdbcTemplate 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;
+ }
+
+ List<com.juick.Message> msgs = PMQueries.getPMMessages(sql, vuid, uid);
+ if (msgs != null && !msgs.isEmpty()) {
+ String json = messageSerializer.serializeList(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.setUser(UserQueries.getUserByUID(sql, vuid).get());
+ jmsg.setText(body);
+ msg.childs.add(jmsg);
+ xmpp.send(msg);
+
+ msg.to.Host = "ws.juick.com";
+ xmpp.send(msg);
+
+ Main.replyJSON(request, response, messageSerializer.serialize(jmsg).toString());
+
+ List<String> jids = UserQueries.getJIDsbyUID(sql, uid);
+ for (String jid: jids) {
+ 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.getUser().getUName(), "juick.com", "Juick");
+ mm.body = body;
+ } else {
+ mm.from = new JID("juick", "juick.com", "Juick");
+ mm.body = "Private message from @" + jmsg.getUser().getUName() + ":\n" + body;
+ }
+ xmpp.send(mm);
+ }
+
+ } else {
+ response.sendError(500);
+ }
+ }
+}
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..e1094ff6
--- /dev/null
+++ b/src/main/java/com/juick/api/TelegramBotHook.java
@@ -0,0 +1,243 @@
+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;
+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;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import javax.servlet.http.HttpServletRequest;
+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;
+
+/**
+ * Created by vt on 12/05/16.
+ */
+public class TelegramBotHook {
+ private static final Logger logger = Logger.getLogger(TelegramBotHook.class.getName());
+
+ TelegramBot bot;
+ WebSocket ws, wsReply;
+ MessageSerializer ms = new MessageSerializer();
+ JdbcTemplate jdbc;
+
+
+ public TelegramBotHook(JdbcTemplate jdbc, String token) {
+ this.jdbc = jdbc;
+ bot = TelegramBotAdapter.build(token);
+ 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");
+ ws.connect();
+ }
+
+ @Override
+ public void onConnected(WebSocket websocket, Map<String, List<String>> headers) {
+ logger.info("ws connected");
+ }
+
+ @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: " + ms.serialize(jmsg).toString());
+ StringBuilder sb = new StringBuilder();
+ sb.append("@").append(jmsg.getUser().getUName()).append(":\n")
+ .append(jmsg.getTagsString()).append("\n").append(jmsg.getText()).append("\n");
+ if (jmsg.Photo != null) {
+ sb.append(jmsg.Photo);
+ }
+ String msg = sb.toString();
+ List<Long> users = getSubscribers(jmsg.getUser().getUID());
+ List<Long> chats = getChats();
+ // registered subscribed users
+ String msgUrl = "https://juick.com/" + jmsg.getMID();
+ users.stream().forEach(c -> telegramNotify(c, msg, msgUrl));
+ // anonymous
+ chats.stream().filter(u -> getUser(u) == 0).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");
+ ws.connect();
+ }
+
+ @Override
+ public void onConnected(WebSocket websocket, Map<String, List<String>> 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 by @").append(jmsg.getUser().getUName()).append(":\n")
+ .append(getReplyQuote(jmsg.getMID(), jmsg.ReplyTo)).append("\n").append(jmsg.getText());
+ if (jmsg.getAttachmentURL() != null) {
+ sb.append("\n").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, String msgUrl) {
+ bot.execute(new SendMessage(c, msg).replyMarkup(
+ new InlineKeyboardMarkup(
+ new InlineKeyboardButton[]{
+ new InlineKeyboardButton("See on Juick").url(msgUrl)
+ }
+ )), new Callback<SendMessage, SendResponse>() {
+ @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<Long> 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);
+ }
+
+ public void doPost(HttpServletRequest request) throws IOException {
+ try (BufferedReader reader = request.getReader()) {
+ Message message = BotUtils.parseUpdate(reader).message();
+ 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<Long> 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 " + 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(), 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());
+ 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<SendMessage, SendResponse>() {
+ @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;
+ }
+
+ private int getUser(long tgId) {
+ try {
+ 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;
+ }
+ }
+
+ private List<Long> 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<Long> 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) {
+ 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;
+ }
+}
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..e85c517a
--- /dev/null
+++ b/src/main/java/com/juick/api/Users.java
@@ -0,0 +1,126 @@
+package com.juick.api;
+
+import com.juick.User;
+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.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ *
+ * @author ugnich
+ */
+public class Users {
+
+ JdbcTemplate sql;
+
+ UserSerializer userSerializer = new UserSerializer();
+
+ public Users(JdbcTemplate sql) {
+ this.sql = sql;
+ }
+
+ public void doGetUsers(HttpServletRequest request,
+ HttpServletResponse response, int vuid)
+ throws ServletException, IOException {
+ List<com.juick.User> users = new ArrayList<>();
+
+ String punames[] = request.getParameterValues("uname");
+ if (punames != null) {
+ ArrayList<String> unames = new ArrayList<>(Arrays.asList(punames));
+ Iterator<String> 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) {
+ List<String> jids = new ArrayList<>(Arrays.asList(pjids));
+ Iterator<String> 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 = userSerializer.serializeList(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.getUID() > 0) {
+ uid = u.getUID();
+ }
+ }
+ }
+
+ if (uid > 0) {
+ List<Integer> uids = UserQueries.getUserRead(sql, uid);
+ if (uids.size() > 0) {
+ List<com.juick.User> users = UserQueries.getUsersByID(sql, uids);
+ if (users.size() > 0) {
+ String json = userSerializer.serializeList(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.getUID() > 0) {
+ uid = u.getUID();
+ }
+ }
+ }
+
+ if (uid > 0) {
+ List<User> users = UserQueries.getUserReaders(sql, uid);
+ String json = userSerializer.serializeList(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..ca0518e1
--- /dev/null
+++ b/src/main/java/com/juick/api/Utils.java
@@ -0,0 +1,231 @@
+/*
+ * Juick
+ * Copyright (C) 2008-2011, Ugnich Anton
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.juick.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.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.UUID;
+
+/**
+ *
+ * @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(JdbcTemplate 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(JdbcTemplate 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(JdbcTemplate sql, HttpServletRequest request) {
+ String auth = request.getHeader("Authorization");
+ if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) {
+ 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;
+ }
+
+ 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);
+ }
+ 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<Integer> 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("<", "&lt;");
+ ret = ret.replaceAll(">", "&gt;");
+ 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;
+ }
+ 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;
+ }
+ }
+}
diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql
new file mode 100644
index 00000000..cdc97b86
--- /dev/null
+++ b/src/main/resources/schema.sql
@@ -0,0 +1,838 @@
+-- MySQL dump 10.13 Distrib 5.5.44, for debian-linux-gnu (x86_64)
+--
+-- Host: localhost Database: juick
+-- ------------------------------------------------------
+-- Server version 5.5.44-0+deb8u1
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!40101 SET NAMES utf8mb4 */;
+/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
+/*!40103 SET TIME_ZONE='+00:00' */;
+/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
+/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
+/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
+/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
+
+use juick;
+--
+-- Table structure for table `ads_messages`
+--
+
+DROP TABLE IF EXISTS `ads_messages`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ads_messages` (
+ `message_id` int(10) unsigned NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `ads_messages_log`
+--
+
+DROP TABLE IF EXISTS `ads_messages_log`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ads_messages_log` (
+ `user_id` int(10) unsigned NOT NULL,
+ `message_id` int(10) unsigned NOT NULL,
+ `ts` int(10) unsigned NOT NULL DEFAULT '0'
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `android`
+--
+
+DROP TABLE IF EXISTS `android`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `android` (
+ `user_id` int(10) unsigned NOT NULL,
+ `regid` char(255) NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE KEY `regid` (`regid`),
+ KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `auth`
+--
+
+DROP TABLE IF EXISTS `auth`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `auth` (
+ `user_id` int(10) unsigned NOT NULL,
+ `protocol` enum('xmpp','email','sms') NOT NULL,
+ `account` char(64) NOT NULL,
+ `authcode` char(8) NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `bl_tags`
+--
+
+DROP TABLE IF EXISTS `bl_tags`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bl_tags` (
+ `user_id` int(10) unsigned NOT NULL,
+ `tag_id` int(10) unsigned NOT NULL,
+ KEY `tag_id` (`tag_id`),
+ KEY `user_id` (`user_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `bl_users`
+--
+
+DROP TABLE IF EXISTS `bl_users`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `bl_users` (
+ `user_id` int(10) unsigned NOT NULL,
+ `bl_user_id` int(10) unsigned NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`user_id`,`bl_user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `captcha`
+--
+
+DROP TABLE IF EXISTS `captcha`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `captcha` (
+ `jid` char(64) NOT NULL,
+ `hash` char(16) NOT NULL,
+ `confirmed` tinyint(4) NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `captchaimg`
+--
+
+DROP TABLE IF EXISTS `captchaimg`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `captchaimg` (
+ `id` char(16) NOT NULL,
+ `txt` char(6) NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `ip` char(16) NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `emails`
+--
+
+DROP TABLE IF EXISTS `emails`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `emails` (
+ `user_id` int(10) unsigned NOT NULL,
+ `email` char(64) NOT NULL,
+ `subscr_hour` tinyint(4) DEFAULT NULL,
+ KEY `email` (`email`) USING HASH
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `facebook`
+--
+
+DROP TABLE IF EXISTS `facebook`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `facebook` (
+ `user_id` int(10) unsigned DEFAULT NULL,
+ `fb_id` bigint(20) unsigned NOT NULL,
+ `loginhash` char(36) DEFAULT NULL,
+ `access_token` char(255) DEFAULT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `fb_name` char(64) NOT NULL,
+ `fb_link` char(64) NOT NULL,
+ `crosspost` tinyint(1) unsigned NOT NULL DEFAULT '1',
+ KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `favorites`
+--
+
+DROP TABLE IF EXISTS `favorites`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `favorites` (
+ `user_id` int(10) unsigned NOT NULL,
+ `message_id` int(10) unsigned NOT NULL,
+ `ts` datetime NOT NULL,
+ UNIQUE KEY `user_id_2` (`user_id`,`message_id`),
+ KEY `user_id` (`user_id`),
+ KEY `message_id` (`message_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `friends_facebook`
+--
+
+DROP TABLE IF EXISTS `friends_facebook`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `friends_facebook` (
+ `user_id` int(10) unsigned NOT NULL,
+ `friend_id` bigint(20) unsigned NOT NULL,
+ UNIQUE KEY `user_id` (`user_id`,`friend_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `ios`
+--
+
+DROP TABLE IF EXISTS `ios`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `ios` (
+ `user_id` int(10) unsigned NOT NULL,
+ `token` char(64) COLLATE utf8mb4_unicode_ci NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE KEY `token` (`token`),
+ KEY `user_id` (`user_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `jids`
+--
+
+DROP TABLE IF EXISTS `jids`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `jids` (
+ `user_id` int(10) unsigned DEFAULT NULL,
+ `jid` char(64) NOT NULL,
+ `active` tinyint(1) NOT NULL DEFAULT '1',
+ `loginhash` char(36) DEFAULT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE KEY `jid` (`jid`),
+ KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `logins`
+--
+
+DROP TABLE IF EXISTS `logins`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `logins` (
+ `user_id` int(10) unsigned NOT NULL,
+ `hash` char(16) NOT NULL,
+ UNIQUE KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `mail`
+--
+
+DROP TABLE IF EXISTS `mail`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `mail` (
+ `user_id` int(10) unsigned NOT NULL,
+ `hash` char(16) NOT NULL,
+ PRIMARY KEY (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `meon`
+--
+
+DROP TABLE IF EXISTS `meon`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `meon` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `user_id` int(10) unsigned NOT NULL,
+ `link` char(255) NOT NULL,
+ `name` char(32) NOT NULL,
+ `ico` smallint(5) unsigned DEFAULT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=MyISAM AUTO_INCREMENT=10850 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `messages`
+--
+
+DROP TABLE IF EXISTS `messages`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `messages` (
+ `message_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `user_id` int(10) unsigned NOT NULL,
+ `lang` enum('en','ru','fr','fa','__') NOT NULL DEFAULT '__',
+ `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',
+ `readonly` tinyint(1) NOT NULL DEFAULT '0',
+ `attach` enum('jpg','mp4','png') DEFAULT NULL,
+ `place_id` int(10) unsigned DEFAULT NULL,
+ `lat` decimal(10,7) DEFAULT NULL,
+ `lon` decimal(10,7) DEFAULT NULL,
+ `popular` tinyint(4) NOT NULL DEFAULT '0',
+ `hidden` tinyint(3) unsigned NOT NULL DEFAULT '0',
+ `likes` smallint(6) NOT NULL DEFAULT '0',
+ PRIMARY KEY (`message_id`),
+ KEY `user_id` (`user_id`),
+ KEY `ts` (`ts`),
+ KEY `attach` (`attach`),
+ KEY `place_id` (`place_id`),
+ KEY `popular` (`popular`),
+ KEY `hidden` (`hidden`)
+) ENGINE=InnoDB AUTO_INCREMENT=2814769 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `messages_access`
+--
+
+DROP TABLE IF EXISTS `messages_access`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `messages_access` (
+ `message_id` int(10) unsigned NOT NULL,
+ `user_id` int(10) unsigned NOT NULL,
+ KEY `message_id` (`message_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `messages_tags`
+--
+
+DROP TABLE IF EXISTS `messages_tags`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `messages_tags` (
+ `message_id` int(10) unsigned NOT NULL,
+ `tag_id` int(10) unsigned NOT NULL,
+ UNIQUE KEY `message_id_2` (`message_id`,`tag_id`),
+ KEY `message_id` (`message_id`),
+ KEY `tag_id` (`tag_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `messages_txt`
+--
+
+DROP TABLE IF EXISTS `messages_txt`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `messages_txt` (
+ `message_id` int(10) unsigned NOT NULL,
+ `tags` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ `repliesby` varchar(96) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ `txt` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
+ PRIMARY KEY (`message_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `messages_votes`
+--
+
+DROP TABLE IF EXISTS `messages_votes`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `messages_votes` (
+ `message_id` int(10) unsigned NOT NULL,
+ `user_id` int(10) unsigned NOT NULL,
+ `vote` tinyint(4) NOT NULL DEFAULT '1',
+ UNIQUE KEY `message_id` (`message_id`,`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `places`
+--
+
+DROP TABLE IF EXISTS `places`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `places` (
+ `place_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `lat` decimal(10,7) NOT NULL,
+ `lon` decimal(10,7) NOT NULL,
+ `name` char(64) NOT NULL,
+ `descr` char(255) DEFAULT NULL,
+ `url` char(128) DEFAULT NULL,
+ `user_id` int(10) unsigned NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`place_id`)
+) ENGINE=MyISAM AUTO_INCREMENT=2697 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `places_tags`
+--
+
+DROP TABLE IF EXISTS `places_tags`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `places_tags` (
+ `place_id` int(10) unsigned NOT NULL,
+ `tag_id` int(10) unsigned NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `pm`
+--
+
+DROP TABLE IF EXISTS `pm`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `pm` (
+ `user_id` int(10) unsigned NOT NULL,
+ `user_id_to` int(10) unsigned NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ `txt` text NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `pm_inroster`
+--
+
+DROP TABLE IF EXISTS `pm_inroster`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `pm_inroster` (
+ `user_id` int(10) unsigned NOT NULL,
+ `jid` char(64) NOT NULL,
+ UNIQUE KEY `user_id_2` (`user_id`,`jid`),
+ KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `pm_streams`
+--
+
+DROP TABLE IF EXISTS `pm_streams`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `pm_streams` (
+ `user_id` int(10) unsigned NOT NULL,
+ `user_id_to` int(10) unsigned NOT NULL,
+ `lastmessage` datetime NOT NULL,
+ `lastview` datetime DEFAULT NULL,
+ `unread` smallint(5) unsigned NOT NULL DEFAULT '0',
+ UNIQUE KEY `user_id` (`user_id`,`user_id_to`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `presence`
+--
+
+DROP TABLE IF EXISTS `presence`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `presence` (
+ `user_id` int(10) unsigned NOT NULL,
+ `jid` char(64) DEFAULT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ UNIQUE KEY `jid` (`jid`)
+) ENGINE=MEMORY DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `reader_links`
+--
+
+DROP TABLE IF EXISTS `reader_links`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `reader_links` (
+ `link_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `rss_id` int(10) unsigned NOT NULL,
+ `url` char(255) NOT NULL,
+ `title` char(255) NOT NULL,
+ `ts` datetime NOT NULL,
+ PRIMARY KEY (`link_id`)
+) ENGINE=MyISAM AUTO_INCREMENT=29932 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `reader_rss`
+--
+
+DROP TABLE IF EXISTS `reader_rss`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `reader_rss` (
+ `rss_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `url` char(255) NOT NULL,
+ `lastcheck` datetime NOT NULL,
+ PRIMARY KEY (`rss_id`)
+) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `replies`
+--
+
+DROP TABLE IF EXISTS `replies`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+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` enum('jpg','mp4','png') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ `txt` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
+ KEY `message_id` (`message_id`),
+ KEY `user_id` (`user_id`),
+ KEY `ts` (`ts`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `sphinx`
+--
+
+DROP TABLE IF EXISTS `sphinx`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `sphinx` (
+ `counter_id` tinyint(3) unsigned NOT NULL,
+ `max_id` int(10) unsigned NOT NULL,
+ PRIMARY KEY (`counter_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `subscr_messages`
+--
+
+DROP TABLE IF EXISTS `subscr_messages`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `subscr_messages` (
+ `message_id` int(10) unsigned NOT NULL,
+ `suser_id` int(10) unsigned NOT NULL,
+ UNIQUE KEY `message_id` (`message_id`,`suser_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `subscr_tags`
+--
+
+DROP TABLE IF EXISTS `subscr_tags`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `subscr_tags` (
+ `tag_id` int(10) unsigned NOT NULL,
+ `suser_id` int(10) unsigned NOT NULL,
+ `jid` char(64) NOT NULL,
+ `active` bit(1) NOT NULL DEFAULT b'1',
+ UNIQUE KEY `tag_id` (`tag_id`,`suser_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `subscr_users`
+--
+
+DROP TABLE IF EXISTS `subscr_users`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `subscr_users` (
+ `user_id` int(10) unsigned NOT NULL,
+ `suser_id` int(10) unsigned NOT NULL,
+ `jid` char(64) DEFAULT NULL,
+ `active` bit(1) NOT NULL DEFAULT b'1',
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE KEY `user_id` (`user_id`,`suser_id`),
+ KEY `suser_id` (`suser_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `tags`
+--
+
+DROP TABLE IF EXISTS `tags`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+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',
+ `noindex` 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',
+ PRIMARY KEY (`tag_id`),
+ KEY `synonym_id` (`synonym_id`)
+) ENGINE=MyISAM AUTO_INCREMENT=115285 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `tags_ignore`
+--
+
+DROP TABLE IF EXISTS `tags_ignore`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `tags_ignore` (
+ `tag_id` int(10) unsigned NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `tags_synonyms`
+--
+
+DROP TABLE IF EXISTS `tags_synonyms`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `tags_synonyms` (
+ `name` char(64) NOT NULL,
+ `changeto` char(64) NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `top_ignore_messages`
+--
+
+DROP TABLE IF EXISTS `top_ignore_messages`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `top_ignore_messages` (
+ `message_id` int(10) unsigned NOT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `top_ignore_tags`
+--
+
+DROP TABLE IF EXISTS `top_ignore_tags`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `top_ignore_tags` (
+ `tag_id` int(10) unsigned NOT NULL,
+ PRIMARY KEY (`tag_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `top_ignore_users`
+--
+
+DROP TABLE IF EXISTS `top_ignore_users`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `top_ignore_users` (
+ `user_id` int(10) unsigned NOT NULL,
+ PRIMARY KEY (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `twitter`
+--
+
+DROP TABLE IF EXISTS `twitter`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `twitter` (
+ `user_id` int(10) unsigned NOT NULL,
+ `access_token` char(64) NOT NULL,
+ `access_token_secret` char(64) NOT NULL,
+ `uname` char(64) NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `crosspost` tinyint(1) unsigned NOT NULL DEFAULT '1',
+ PRIMARY KEY (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `useroptions`
+--
+
+DROP TABLE IF EXISTS `useroptions`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+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',
+ `off_ts` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `xmppxhtml` tinyint(1) NOT NULL DEFAULT '0',
+ `subscr_notify` tinyint(1) NOT NULL DEFAULT '1',
+ `recommendations` tinyint(1) NOT NULL DEFAULT '1',
+ `privacy_view` tinyint(1) NOT NULL DEFAULT '1',
+ `privacy_reply` tinyint(1) NOT NULL DEFAULT '1',
+ `privacy_pm` tinyint(1) NOT NULL DEFAULT '1',
+ `repliesview` tinyint(1) NOT NULL DEFAULT '0',
+ PRIMARY KEY (`user_id`),
+ KEY `recommendations` (`recommendations`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `users`
+--
+
+DROP TABLE IF EXISTS `users`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `users` (
+ `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `nick` char(64) NOT NULL,
+ `passw` char(32) NOT NULL,
+ `lang` enum('en','ru','fr','fa','__') NOT NULL DEFAULT '__',
+ `banned` tinyint(3) unsigned NOT NULL DEFAULT '0',
+ `lastmessage` int(11) NOT NULL DEFAULT '0',
+ `lastpm` int(11) NOT NULL DEFAULT '0',
+ `lastphoto` int(11) NOT NULL DEFAULT '0',
+ `karma` smallint(6) NOT NULL DEFAULT '0',
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `nick` (`nick`)
+) ENGINE=InnoDB AUTO_INCREMENT=29642 DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `users_refs`
+--
+
+DROP TABLE IF EXISTS `users_refs`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `users_refs` (
+ `user_id` int(10) unsigned NOT NULL,
+ `ref` int(10) unsigned NOT NULL,
+ KEY `ref` (`ref`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `users_subscr`
+--
+
+DROP TABLE IF EXISTS `users_subscr`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `users_subscr` (
+ `user_id` int(10) unsigned NOT NULL,
+ `cnt` smallint(5) unsigned NOT NULL DEFAULT '0',
+ PRIMARY KEY (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `usersinfo`
+--
+
+DROP TABLE IF EXISTS `usersinfo`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `usersinfo` (
+ `user_id` int(10) unsigned NOT NULL,
+ `jid` char(32) DEFAULT NULL,
+ `fullname` char(32) DEFAULT NULL,
+ `country` char(32) DEFAULT NULL,
+ `url` char(64) DEFAULT NULL,
+ `gender` char(32) DEFAULT NULL,
+ `bday` char(10) DEFAULT NULL,
+ `descr` varchar(255) DEFAULT NULL,
+ PRIMARY KEY (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `vk`
+--
+
+DROP TABLE IF EXISTS `vk`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `vk` (
+ `user_id` int(10) unsigned DEFAULT NULL,
+ `vk_id` bigint(20) NOT NULL,
+ `loginhash` char(36) DEFAULT NULL,
+ `access_token` char(128) NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `vk_name` char(64) NOT NULL,
+ `vk_link` char(64) NOT NULL,
+ `crosspost` tinyint(3) unsigned NOT NULL DEFAULT '1',
+ KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `winphone`
+--
+
+DROP TABLE IF EXISTS `winphone`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `winphone` (
+ `user_id` int(10) unsigned NOT NULL,
+ `url` char(255) NOT NULL,
+ `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE KEY `url` (`url`),
+ KEY `user_id` (`user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `wl_users`
+--
+
+DROP TABLE IF EXISTS `wl_users`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8 */;
+CREATE TABLE `wl_users` (
+ `user_id` int(10) unsigned NOT NULL,
+ `wl_user_id` int(10) unsigned NOT NULL,
+ PRIMARY KEY (`user_id`,`wl_user_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+/*!40101 SET character_set_client = @saved_cs_client */;
+/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
+/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
+/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
+/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+-- Dump completed on 2015-12-17 10:49:43
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/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 00000000..533a6882
--- /dev/null
+++ b/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
+ <servlet>
+ <servlet-name>Main</servlet-name>
+ <servlet-class>com.juick.api.Main</servlet-class>
+ </servlet>
+ <servlet-mapping>
+ <servlet-name>Main</servlet-name>
+ <url-pattern>/</url-pattern>
+ </servlet-mapping>
+ <session-config>
+ <session-timeout>
+ 30
+ </session-timeout>
+ </session-config>
+</web-app>
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..7ab04708
--- /dev/null
+++ b/src/test/java/com/juick/tests/ApiTests.java
@@ -0,0 +1,74 @@
+package com.juick.tests;
+
+import ch.vorburger.exec.ManagedProcessException;
+import ch.vorburger.mariadb4j.DB;
+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 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.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+
+/**
+ * Created by vt on 14.01.2016.
+ */
+public class ApiTests {
+ JdbcTemplate jdbc;
+ @Before
+ public void setupConnection() throws ManagedProcessException {
+ DB db = DB.newEmbeddedDB(3306);
+ db.start();
+ db.createDB("juick");
+ db.source("schema.sql");
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName("com.mysql.jdbc.Driver");
+ dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=root");
+ jdbc = new JdbcTemplate(dataSource);
+ }
+
+
+ @Test
+ public void messageTests() {
+ int user_id = UserQueries.createUser(jdbc, "me", "secret");
+ 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);
+ 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<Tag> 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).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);
+ 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"));
+ SubscriptionsQueries.subscribeMessage(jdbc, msg.getMID(), ugnich.getUID());
+ Assert.assertEquals(1, SubscriptionsQueries.getUsersSubscribedToComments(jdbc, msg.getMID(), user.getUID()).size());
+ }
+
+}