aboutsummaryrefslogtreecommitdiff
path: root/juick-www/src/main/java/com/juick/www/Main.java
blob: d8096ff4633e755f5d498c79482a647b2f1b68af (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
 * Juick
 * Copyright (C) 2008-2011, Ugnich Anton
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.juick.www;

import com.juick.server.UserQueries;
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 ru.sape.Sape;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author Ugnich Anton
 */
@WebServlet(name = "Main", urlPatterns = {"/"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxRequestSize = 1024 * 1024 * 10)
public class Main extends HttpServlet implements Stream.StreamListener {

    JdbcTemplate sql;
    JdbcTemplate sqlSearch;
    String sqlSearchConnStr = "jdbc:mysql://127.0.0.1:9306?autoReconnect=true&useUnicode=yes&characterEncoding=utf8&maxAllowedPacket=512000";
    Stream xmpp;
    Home home = new Home();
    Discover discover = new Discover();
    PM pm = new PM();
    Login login = new Login();
    Help help = new Help();
    User pagesUser = new User();
    UserThread pagesUserThread = new UserThread();
    NewMessage pagesNewMessage;
    FacebookLogin loginFacebook = new FacebookLogin();
    VKontakteLogin loginVK = new VKontakteLogin();
    TwitterAuth twitterAuth;
    SignUp signup = new SignUp();
    Settings settings = new Settings();
    RSS rss = new RSS();
    ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Override
    public void init() throws ServletException {

        super.init();
        try {
            Properties conf = new Properties();
            conf.load(getServletContext().getResourceAsStream("/WEB-INF/juick.conf"));

            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver"));
            dataSource.setUrl(conf.getProperty("datasource_url"));
            BasicDataSource dataSourceSearch = new BasicDataSource();
            dataSourceSearch.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver"));
            dataSourceSearch.setUrl(sqlSearchConnStr);
            sql = new JdbcTemplate(dataSource);
            sqlSearch = new JdbcTemplate(dataSourceSearch);

            setupXmppComponent(new JID(conf.getProperty("www_xmpp_jid", "www.juick.local")), conf.getProperty("xmpp_password"));
            twitterAuth = new TwitterAuth(conf.getProperty("twitter_consumer_key"),
                    conf.getProperty("twitter_consumer_secret"));
            pagesNewMessage = new NewMessage(conf.getProperty("upload_tmp_dir", "/var/www/juick.com/i/tmp/"),
                    conf.getProperty("img_path", "/var/www/juick.com/i/"));
            String sapeUser = conf.getProperty("sape_user", "");
            if (!Objects.equals(sapeUser, "")) {
                PageTemplates.sape = new Sape(sapeUser, "juick.com", 2000, 3600);
            } else {
                log("Sape is not initialized");
            }
        } catch (Exception e) {
            log(null, e);
        }
    }

    @Override
    public void destroy() {
        executorService.shutdownNow();
        super.destroy();
    }

    public void setupXmppComponent(final JID componentJid, final String password) {
        executorService.submit(() -> {
            try {
                Socket socket = new Socket("localhost", 5347);
                xmpp = new StreamComponent(componentJid, socket.getInputStream(), socket.getOutputStream(), password);
                xmpp.addListener(Main.this);
                xmpp.startParsing();
            } catch (IOException e) {
                log("XMPP is not initialized");
            }
        });
    }

    @Override
    public void onStreamFail(Exception e) {log("XMPP STREAM FAIL:" + e);}

    @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();

        if (uri.equals("/")) {
            String tag = request.getParameter("tag");
            if (tag != null) {
                Utils.sendPermanentRedirect(response, "/tag/" + URLEncoder.encode(tag, "UTF-8"));
            } else {
                com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
                home.doGet(sql, sqlSearch, request, response, visitor);
            }
        } else if (uri.equals("/post")) {
            com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
            if (visitor.getUID() > 0) {
                pagesNewMessage.doGetNewMessage(sql, request, response, visitor);
            } else {
                Utils.sendTemporaryRedirect(response, "/login");
            }
        } else if (uri.equals("/login")) {
            if (request.getQueryString() == null) {
                login.doGetLoginForm(sql, request, response);
            } else {
                login.doGetLogin(sql, request, response);
            }
        } else if (uri.startsWith("/pm/")) {
            com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
            if (visitor.getUID() == 0) {
                Utils.sendTemporaryRedirect(response, "/login");
            } else {
                switch (uri) {
                    case "/pm/inbox":
                        pm.doGetInbox(sql, request, response, visitor);
                        break;
                    case "/pm/sent":
                        pm.doGetSent(sql, request, response, visitor);
                        break;
                    default:
                        Errors.doGet404(sql, request, response);
                        break;
                }
            }
        } else if (uri.startsWith("/rss/")) {
            String uname = uri.substring(5);
            int uid = UserQueries.getUIDbyName(sql, uname);
            if (uid > 0) {
                rss.doGet(sql, request, response, uid, uname);
            } else {
                response.sendError(404);
            }
        } else if (uri.equals("/logout")) {
            login.doGetLogout(sql, request, response);
        } else if (uri.equals("/settings")) {
            settings.doGet(sql, request, response);
        } else if (uri.equals("/_fblogin")) {
            loginFacebook.doGet(sql, request, response);
        } else if (uri.equals("/_vklogin")) {
            loginVK.doGet(sql, request, response);
        } else if (uri.startsWith("/_twitter")) {
            twitterAuth.doGet(sql, request, response);
        } else if (uri.equals("/signup")) {
            signup.doGet(sql, request, response);
        } else if (uri.equals("/help") || uri.equals("/help/")) {
            help.doRedirectToHelpIndex(response);
        } else if (uri.startsWith("/help/")) {
            help.doGetHelp(sql, request, response);
        } else if (uri.startsWith("/tag/")) {
            discover.doGet(sql, sqlSearch, request, response);
        } else if (uri.matches("^/\\d+$")) {
            String strID = request.getRequestURI().substring(1);
            int mid = 0;
            try {
                mid = Integer.parseInt(strID);
            } catch (NumberFormatException e) {
            }
            if (mid > 0) {
                com.juick.User author = com.juick.server.MessagesQueries.getMessageAuthor(sql, mid);
                if (author != null) {
                    Utils.sendPermanentRedirect(response, "/" + author.getUName() + "/" + mid);
                    return;
                }
            }
            Errors.doGet404(sql, request, response);
        } else if (uri.matches("^/[^/]+$")) {
            com.juick.User user = com.juick.server.UserQueries.getUserByName(sql, request.getRequestURI().substring(1));
            if (user != null) {
                Utils.sendPermanentRedirect(response, "/" + user.getUName() + "/");
            } else {
                Errors.doGet404(sql, request, response);
            }
        } else if (uri.matches("^/.+/.*")) {
            String uriparts[] = uri.split("/");
            com.juick.User user = com.juick.server.UserQueries.getUserByName(sql, uriparts[1]);
            if (user != null && user.getUName().equals(uriparts[1]) && !user.Banned) {
                if (uriparts.length == 2) { // http://juick.com/username/
                    pagesUser.doGetBlog(sql, sqlSearch, request, response, user);
                } else if (uriparts[2].equals("tags")) {
                    pagesUser.doGetTags(sql, request, response, user);
                } else if (uriparts[2].equals("friends")) {
                    pagesUser.doGetFriends(sql, request, response, user);
                } else if (uriparts[2].equals("readers")) {
                    pagesUser.doGetReaders(sql, request, response, user);
                } else {
                    int mid = 0;
                    try {
                        mid = Integer.parseInt(uriparts[2]);
                    } catch (NumberFormatException e) {
                    }
                    if (mid > 0) {
                        com.juick.User author = com.juick.server.MessagesQueries.getMessageAuthor(sql, mid);
                        if (author != null) {
                            if (!author.getUName().equals(user.getUName())) {
                                Utils.sendPermanentRedirect(response, "/" + author.getUName() + "/" + mid);
                            } else {
                                pagesUserThread.doGetThread(sql, request, response, mid);
                            }
                        } else {
                            Errors.doGet404(sql, request, response);
                        }
                    } else {
                        Errors.doGet404(sql, request, response);
                    }
                }
            } else if (user != null && !user.Banned) {
                Utils.sendPermanentRedirect(response, "/" + user.getUName() + "/" + (uriparts.length > 2 ? uriparts[2] : ""));
            } else {
                Errors.doGet404(sql, request, response);
            }
        } else {
            Errors.doGet404(sql, request, response);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }

        String uri = request.getRequestURI();
        switch (uri) {
            case "/post": {
                com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
                if (visitor.getUID() > 0 && !visitor.Banned) {
                    pagesNewMessage.doPostMessage(sql, request, response, xmpp, visitor);
                } else {
                    response.sendError(403);
                }
                break;
            }
            case "/comment": {
                com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
                if (visitor.getUID() > 0 && !visitor.Banned) {
                    pagesNewMessage.doPostComment(sql, request, response, xmpp, visitor);
                } else {
                    response.sendError(403);
                }
                break;
            }
            case "/like": {
                com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
                if (visitor.getUID() > 0 && !visitor.Banned) {
                    pagesNewMessage.doPostRecomm(sql, request, response, xmpp, visitor);
                } else {
                    response.sendError(403);
                }
                break;
            }
            case "/pm/send": {
                com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
                if (visitor.getUID() > 0 && !visitor.Banned) {
                    pm.doPostPM(sql, request, response, xmpp, visitor);
                } else {
                    response.sendError(403);
                }
                break;
            }
            case "/login":
                login.doPostLogin(sql, request, response);
                break;
            case "/signup":
                signup.doPost(sql, request, response);
                break;
            case "/settings":
                settings.doPost(sql, request, response);
                break;
            default:
                response.sendError(405);
                break;
        }
    }
}