From 7a2f89266c8f6337e4e81a2fd8488e0f80f4f9bd Mon Sep 17 00:00:00 2001
From: Vitaly Takmazov
Date: Fri, 3 Apr 2020 23:53:23 +0300
Subject: Reorganize layout and code cleanup
---
src/main/java/com/juick/www/HelpService.java | 69 ---
src/main/java/com/juick/www/ad/SapeService.java | 4 +-
.../java/com/juick/www/api/ApiSocialLogin.java | 322 +++++++++++
src/main/java/com/juick/www/api/Index.java | 42 ++
src/main/java/com/juick/www/api/Messages.java | 217 ++++++++
src/main/java/com/juick/www/api/Notifications.java | 213 ++++++++
src/main/java/com/juick/www/api/PM.java | 120 +++++
src/main/java/com/juick/www/api/Post.java | 238 +++++++++
src/main/java/com/juick/www/api/Service.java | 223 ++++++++
.../java/com/juick/www/api/SystemActivity.java | 108 ++++
src/main/java/com/juick/www/api/Tags.java | 54 ++
src/main/java/com/juick/www/api/Users.java | 279 ++++++++++
.../java/com/juick/www/api/activity/Profile.java | 410 ++++++++++++++
.../activity/helpers/ActivityIdDeserializer.java | 38 ++
.../activity/helpers/LinkValueDeserializer.java | 38 ++
.../com/juick/www/api/activity/model/Activity.java | 50 ++
.../com/juick/www/api/activity/model/Context.java | 144 +++++
.../www/api/activity/model/activities/Accept.java | 23 +
.../api/activity/model/activities/Announce.java | 23 +
.../www/api/activity/model/activities/Block.java | 23 +
.../www/api/activity/model/activities/Create.java | 23 +
.../www/api/activity/model/activities/Delete.java | 23 +
.../www/api/activity/model/activities/Follow.java | 23 +
.../www/api/activity/model/activities/Like.java | 23 +
.../www/api/activity/model/activities/Undo.java | 23 +
.../www/api/activity/model/activities/Update.java | 23 +
.../www/api/activity/model/objects/Emoji.java | 23 +
.../www/api/activity/model/objects/Hashtag.java | 28 +
.../www/api/activity/model/objects/Image.java | 32 ++
.../juick/www/api/activity/model/objects/Key.java | 41 ++
.../juick/www/api/activity/model/objects/Link.java | 32 ++
.../www/api/activity/model/objects/Mention.java | 29 +
.../juick/www/api/activity/model/objects/Note.java | 81 +++
.../activity/model/objects/OrderedCollection.java | 42 ++
.../model/objects/OrderedCollectionPage.java | 75 +++
.../www/api/activity/model/objects/Person.java | 104 ++++
.../juick/www/api/apple/AppSiteAssociation.java | 66 +++
.../java/com/juick/www/api/hostmeta/HostMeta.java | 42 ++
.../java/com/juick/www/api/webfinger/Resource.java | 68 +++
.../com/juick/www/api/webfinger/model/Account.java | 41 ++
.../com/juick/www/api/webfinger/model/Link.java | 48 ++
.../juick/www/api/webhooks/TelegramWebhook.java | 58 ++
.../java/com/juick/www/api/xnodeinfo2/Info.java | 103 ++++
.../juick/www/api/xnodeinfo2/model/NodeInfo.java | 104 ++++
.../com/juick/www/api/xnodeinfo2/model/Server.java | 63 +++
.../www/api/xnodeinfo2/model/ServiceInfo.java | 44 ++
.../com/juick/www/api/xnodeinfo2/model/Usage.java | 51 ++
.../juick/www/api/xnodeinfo2/model/UserStats.java | 51 ++
src/main/java/com/juick/www/controllers/Help.java | 7 +-
.../com/juick/www/controllers/MessagesWWW.java | 590 ---------------------
src/main/java/com/juick/www/controllers/Site.java | 590 +++++++++++++++++++++
src/main/java/com/juick/www/rss/Feeds.java | 76 +++
src/main/java/com/juick/www/rss/MessagesView.java | 158 ++++++
src/main/java/com/juick/www/rss/RepliesView.java | 111 ++++
.../com/juick/www/rss/extension/JuickModule.java | 33 ++
.../www/rss/extension/JuickModuleGenerator.java | 66 +++
.../juick/www/rss/extension/JuickModuleImpl.java | 54 ++
.../juick/www/rss/extension/JuickModuleParser.java | 42 ++
58 files changed, 5063 insertions(+), 666 deletions(-)
delete mode 100644 src/main/java/com/juick/www/HelpService.java
create mode 100644 src/main/java/com/juick/www/api/ApiSocialLogin.java
create mode 100644 src/main/java/com/juick/www/api/Index.java
create mode 100644 src/main/java/com/juick/www/api/Messages.java
create mode 100644 src/main/java/com/juick/www/api/Notifications.java
create mode 100644 src/main/java/com/juick/www/api/PM.java
create mode 100644 src/main/java/com/juick/www/api/Post.java
create mode 100644 src/main/java/com/juick/www/api/Service.java
create mode 100644 src/main/java/com/juick/www/api/SystemActivity.java
create mode 100644 src/main/java/com/juick/www/api/Tags.java
create mode 100644 src/main/java/com/juick/www/api/Users.java
create mode 100644 src/main/java/com/juick/www/api/activity/Profile.java
create mode 100644 src/main/java/com/juick/www/api/activity/helpers/ActivityIdDeserializer.java
create mode 100644 src/main/java/com/juick/www/api/activity/helpers/LinkValueDeserializer.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/Activity.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/Context.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Accept.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Announce.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Block.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Create.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Delete.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Follow.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Like.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Undo.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/activities/Update.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Emoji.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Hashtag.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Image.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Key.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Link.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Mention.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Note.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/OrderedCollection.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/OrderedCollectionPage.java
create mode 100644 src/main/java/com/juick/www/api/activity/model/objects/Person.java
create mode 100644 src/main/java/com/juick/www/api/apple/AppSiteAssociation.java
create mode 100644 src/main/java/com/juick/www/api/hostmeta/HostMeta.java
create mode 100644 src/main/java/com/juick/www/api/webfinger/Resource.java
create mode 100644 src/main/java/com/juick/www/api/webfinger/model/Account.java
create mode 100644 src/main/java/com/juick/www/api/webfinger/model/Link.java
create mode 100644 src/main/java/com/juick/www/api/webhooks/TelegramWebhook.java
create mode 100644 src/main/java/com/juick/www/api/xnodeinfo2/Info.java
create mode 100644 src/main/java/com/juick/www/api/xnodeinfo2/model/NodeInfo.java
create mode 100644 src/main/java/com/juick/www/api/xnodeinfo2/model/Server.java
create mode 100644 src/main/java/com/juick/www/api/xnodeinfo2/model/ServiceInfo.java
create mode 100644 src/main/java/com/juick/www/api/xnodeinfo2/model/Usage.java
create mode 100644 src/main/java/com/juick/www/api/xnodeinfo2/model/UserStats.java
delete mode 100644 src/main/java/com/juick/www/controllers/MessagesWWW.java
create mode 100644 src/main/java/com/juick/www/controllers/Site.java
create mode 100644 src/main/java/com/juick/www/rss/Feeds.java
create mode 100644 src/main/java/com/juick/www/rss/MessagesView.java
create mode 100644 src/main/java/com/juick/www/rss/RepliesView.java
create mode 100644 src/main/java/com/juick/www/rss/extension/JuickModule.java
create mode 100644 src/main/java/com/juick/www/rss/extension/JuickModuleGenerator.java
create mode 100644 src/main/java/com/juick/www/rss/extension/JuickModuleImpl.java
create mode 100644 src/main/java/com/juick/www/rss/extension/JuickModuleParser.java
(limited to 'src/main/java/com/juick/www')
diff --git a/src/main/java/com/juick/www/HelpService.java b/src/main/java/com/juick/www/HelpService.java
deleted file mode 100644
index 9d3c3f16..00000000
--- a/src/main/java/com/juick/www/HelpService.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2008-2019, Juick
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see .
- */
-
-package com.juick.www;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.cache.annotation.Cacheable;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.util.regex.Pattern;
-
-/**
- * Created by aalexeev on 12/11/16.
- */
-public class HelpService {
- private static final Pattern LANG_PATTERN = Pattern.compile("[a-z]{2}");
-
- private static final Pattern PAGE_PATTERN = Pattern.compile("[a-zA-Z0-9\\-_]+");
-
- private final String helpPath;
-
-
- public HelpService(String helpPath) {
- this.helpPath = helpPath;
- }
-
- @Cacheable("help")
- public String getHelp(final String page, final String lang) {
- if (canBePage(page) && canBeLang(lang)) {
- String path = StringUtils.joinWith("/", helpPath, lang, page + ".md");
-
- try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
- if (is != null)
- return IOUtils.toString(is, StandardCharsets.UTF_8);
- } catch (IOException e) {
- }
- }
- return null;
- }
-
- public boolean canBePage(final String anything) {
- return anything != null && PAGE_PATTERN.matcher(anything).matches();
- }
-
- public boolean canBeLang(final String anything) {
- return anything != null && LANG_PATTERN.matcher(anything).matches();
- }
-
- public String getHelpPath() {
- return helpPath;
- }
-}
diff --git a/src/main/java/com/juick/www/ad/SapeService.java b/src/main/java/com/juick/www/ad/SapeService.java
index 9d58f8b4..4ef4a213 100644
--- a/src/main/java/com/juick/www/ad/SapeService.java
+++ b/src/main/java/com/juick/www/ad/SapeService.java
@@ -19,7 +19,7 @@ package com.juick.www.ad;
import com.juick.model.User;
import com.juick.service.security.annotation.Visitor;
-import com.juick.www.controllers.MessagesWWW;
+import com.juick.www.controllers.Site;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.ui.ModelMap;
@@ -34,7 +34,7 @@ import ru.sape.Sape;
import javax.inject.Inject;
import java.net.URI;
-@ControllerAdvice(assignableTypes = MessagesWWW.class)
+@ControllerAdvice(assignableTypes = Site.class)
@ConditionalOnProperty("sape_user")
public class SapeService {
diff --git a/src/main/java/com/juick/www/api/ApiSocialLogin.java b/src/main/java/com/juick/www/api/ApiSocialLogin.java
new file mode 100644
index 00000000..6499b507
--- /dev/null
+++ b/src/main/java/com/juick/www/api/ApiSocialLogin.java
@@ -0,0 +1,322 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+package com.juick.www.api;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.scribejava.apis.AppleClientSecretGenerator;
+import com.github.scribejava.apis.AppleSignInApi;
+import com.github.scribejava.apis.FacebookApi;
+import com.github.scribejava.apis.VkontakteApi;
+import com.github.scribejava.core.builder.ServiceBuilder;
+import com.github.scribejava.core.model.OAuth2AccessToken;
+import com.github.scribejava.core.model.OAuthRequest;
+import com.github.scribejava.core.model.Verb;
+import com.github.scribejava.core.oauth.OAuth20Service;
+import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
+import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
+import com.google.api.client.http.HttpTransport;
+import com.google.api.client.http.javanet.NetHttpTransport;
+import com.google.api.client.json.JsonFactory;
+import com.google.api.client.json.jackson2.JacksonFactory;
+import com.juick.model.AuthResponse;
+import com.juick.model.ext.facebook.User;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.service.CrosspostService;
+import com.juick.service.EmailService;
+import com.juick.service.UserService;
+import com.juick.model.ext.vk.UsersResponse;
+import com.nimbusds.jose.JOSEException;
+import com.nimbusds.jose.proc.BadJOSEException;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.text.ParseException;
+import java.util.Collections;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+/**
+ *
+ * @author Ugnich Anton
+ */
+@Controller
+public class ApiSocialLogin {
+
+ private static final Logger logger = LoggerFactory.getLogger(ApiSocialLogin.class);
+
+ @Value("${facebook_appid:appid}")
+ private String FACEBOOK_APPID;
+ @Value("${facebook_secret:secret}")
+ private String FACEBOOK_SECRET;
+ private static final String FACEBOOK_REDIRECT = "https://api.juick.com/_fblogin";
+ private static final String VK_REDIRECT = "https://api.juick.com/_vklogin";
+ private static final String TWITTER_VERIFY_URL = "https://api.twitter.com/1.1/account/verify_credentials.json";
+ @Inject
+ private ObjectMapper jsonMapper;
+ private OAuth20Service facebookAuthService, vkAuthService, appleSignInService;
+
+ @Value("${twitter_consumer_key:appid}")
+ private String twitterConsumerKey;
+ @Value("${twitter_consumer_secret:secret}")
+ private String twitterConsumerSecret;
+ @Value("${vk_appid:appid}")
+ private String VK_APPID;
+ @Value("${vk_secret:secret}")
+ private String VK_SECRET;
+ @Value("${google_client_id:}")
+ private String googleClientId;
+ @Value("${apple_app_id:appid}")
+ private String appleApplicationId;
+ @Value("${ap_base_uri:http://localhost:8080/}")
+ private String baseUri;
+
+ @Inject
+ private CrosspostService crosspostService;
+ @Inject
+ private UserService userService;
+ @Inject
+ private EmailService emailService;
+ @Inject
+ private AppleClientSecretGenerator clientSecretGenerator;
+ @Inject
+ private Users users;
+
+ private final HttpTransport transport = new NetHttpTransport();
+ private final JsonFactory jsonFactory = new JacksonFactory();
+ private GoogleIdTokenVerifier verifier;
+
+ @PostConstruct
+ public void init() {
+ ServiceBuilder facebookBuilder = new ServiceBuilder(FACEBOOK_APPID);
+ ServiceBuilder twitterBuilder = new ServiceBuilder(twitterConsumerKey);
+ ServiceBuilder vkBuilder = new ServiceBuilder(VK_APPID);
+ verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
+ .setAudience(Collections.singletonList(googleClientId))
+ .build();
+ facebookAuthService = facebookBuilder
+ .apiSecret(FACEBOOK_SECRET)
+ .callback(FACEBOOK_REDIRECT)
+ .defaultScope("email")
+ .build(FacebookApi.instance());
+ vkAuthService = vkBuilder
+ .apiSecret(VK_SECRET)
+ .defaultScope("friends,wall,offline")
+ .callback(VK_REDIRECT)
+ .build(VkontakteApi.instance());
+ ServiceBuilder appleSignInBuilder = new ServiceBuilder(appleApplicationId);
+ UriComponentsBuilder redirectBuilder = UriComponentsBuilder.fromUriString(baseUri);
+ String appleSignInRedirectUri = redirectBuilder.replacePath("/api/_applelogin").build().toUriString();
+ appleSignInService = appleSignInBuilder
+ .callback(appleSignInRedirectUri)
+ .defaultScope("email")
+ .build(new AppleSignInApi(clientSecretGenerator));
+ }
+
+ @GetMapping("/api/_fblogin")
+ protected String doFacebookLogin(@RequestParam(required = false) String code,
+ @RequestParam(required = false) String state) throws IOException, ExecutionException, InterruptedException {
+ if (StringUtils.isBlank(code)) {
+ String fbstate = UUID.randomUUID().toString();
+ crosspostService.addFacebookState(fbstate, state);
+ return "redirect:" + facebookAuthService.getAuthorizationUrl(fbstate);
+ }
+
+ String redirectUrl = crosspostService.verifyFacebookState(state);
+
+ if (StringUtils.isEmpty(redirectUrl)) {
+ logger.error("state is missing");
+ throw new HttpBadRequestException();
+ }
+ OAuth2AccessToken token = facebookAuthService.getAccessToken(code);
+ final OAuthRequest meRequest = new OAuthRequest(Verb.GET, "https://graph.facebook.com/v3.2/me?fields=id,name,email");
+ facebookAuthService.signRequest(token, meRequest);
+ String graph = facebookAuthService.execute(meRequest).getBody();
+ if (StringUtils.isBlank(graph)) {
+ logger.error("FACEBOOK GRAPH ERROR");
+ throw new HttpBadRequestException();
+ }
+ User fb = jsonMapper.readValue(graph, User.class);
+ long fbID = NumberUtils.toLong(fb.getId(), 0);
+ if (fbID == 0 || StringUtils.isBlank(fb.getName())) {
+ logger.error("Missing required fields, id: {}, name: {}", fbID, fb.getName());
+ throw new HttpBadRequestException();
+ }
+
+ int uid = crosspostService.getUIDbyFBID(fbID);
+ if (uid > 0) {
+ if (!crosspostService.updateFacebookUser(fbID, token.getAccessToken(), fb.getName())) {
+ logger.error("error updating facebook user, id: {}, token: {}", fbID, token.getAccessToken());
+ throw new HttpBadRequestException();
+ }
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl);
+ uriComponentsBuilder.queryParam("hash", userService.getHashByUID(uid));
+ uriComponentsBuilder.queryParam("retpath", redirectUrl);
+ return "redirect:" + uriComponentsBuilder.build().toUriString();
+ } else {
+ if (!crosspostService.createFacebookUser(fbID, state, token.getAccessToken(), fb.getName())) {
+ if (StringUtils.isNotEmpty(fb.getEmail())) {
+ logger.info("found {} for facebook user {}", fb.getEmail(), fb.getName());
+ Integer userId = crosspostService.getUIDbyFBID(fbID);
+ if (!emailService.getEmails(userId, false).contains(fb.getEmail())) {
+ emailService.addEmail(userId, fb.getEmail());
+ }
+ }
+ logger.info("email not found for facebook user {}", fb.getName());
+ throw new HttpBadRequestException();
+ }
+ return "redirect:/signup?type=fb&hash=" + state;
+ }
+ }
+ @GetMapping("/api/_vklogin")
+ protected String doVKLogin(@RequestParam(required = false) String code,
+ @RequestParam String state) throws IOException, ExecutionException, InterruptedException {
+ if (StringUtils.isBlank(code)) {
+ String vkstate = UUID.randomUUID().toString();
+ crosspostService.addVKState(vkstate, state);
+ return "redirect:" + vkAuthService.getAuthorizationUrl(vkstate);
+ }
+
+ String redirectUrl = crosspostService.verifyVKState(state);
+ if (StringUtils.isBlank(redirectUrl)) {
+ logger.error("state is missing");
+ throw new HttpBadRequestException();
+ }
+ OAuth2AccessToken token = vkAuthService.getAccessToken(code);
+
+ OAuthRequest meRequest = new OAuthRequest(Verb.GET, "https://api.vk.com/method/users.get?fields=screen_name&v=5.73");
+ vkAuthService.signRequest(token, meRequest);
+ String graph = vkAuthService.execute(meRequest).getBody();
+
+ com.juick.model.ext.vk.User jsonUser = jsonMapper.readValue(graph, UsersResponse.class).getUsers().get(0);
+ String vkName = jsonUser.getFirstName() + " " + jsonUser.getLastName();
+ String vkLink = jsonUser.getScreenName();
+
+ if (vkName.length() == 1 || StringUtils.isBlank(vkLink)) {
+ logger.error("vk user error");
+ throw new HttpBadRequestException();
+ }
+
+ long vkID = NumberUtils.toLong(jsonUser.getId(), 0);
+ int uid = crosspostService.getUIDbyVKID(vkID);
+ if (uid > 0) {
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl);
+ uriComponentsBuilder.queryParam("hash", userService.getHashByUID(uid));
+ uriComponentsBuilder.queryParam("retpath", redirectUrl);
+ return "redirect:" + uriComponentsBuilder.build().toUriString();
+ } else {
+ String loginhash = UUID.randomUUID().toString();
+ if (!crosspostService.createVKUser(vkID, loginhash, token.getAccessToken(), vkName, vkLink)) {
+ logger.error("create vk user error");
+ throw new HttpBadRequestException();
+ }
+ return "redirect:/signup?type=vk&hash=" + loginhash;
+ }
+ }
+ @ResponseBody
+ @PostMapping("/api/_google")
+ public ResponseEntity googleSignIn(@RequestParam(name = "idToken") String idTokenString)
+ throws GeneralSecurityException, IOException {
+ logger.info("Token: {}", idTokenString);
+ logger.info("Client: {}", googleClientId);
+ GoogleIdToken idToken = verifier.verify(idTokenString);
+ if (idToken != null) {
+ String email = idToken.getPayload().getEmail();
+ com.juick.model.User visitor = userService.getUserByEmail(email);
+ if (visitor.isAnonymous()) {
+ String verificationCode = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
+ emailService.addVerificationCode(null, email, verificationCode);
+ return ResponseEntity.ok(new AuthResponse(null, email, verificationCode));
+ } else {
+ return ResponseEntity.ok(new AuthResponse(users.getMe(visitor), null, null));
+ }
+ }
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
+ }
+ @ResponseBody
+ @PostMapping("/api/signup")
+ public ResponseEntity signupWithEmail(String username, String password, String verificationCode) {
+ if (username.length() < 2 || username.length() > 16 || !username.matches("^[a-zA-Z0-9\\-]+$")
+ || password.length() < 6 || password.length() > 32) {
+ throw new HttpBadRequestException();
+ }
+
+ String verifiedEmail = emailService.getEmailByAuthCode(verificationCode);
+ if (StringUtils.isNotEmpty(verifiedEmail)) {
+ com.juick.model.User newUser = userService.createUser(username, password).orElseThrow(HttpBadRequestException::new);
+ emailService.addEmail(newUser.getUid(), verifiedEmail);
+ emailService.deleteAuthCode(verificationCode);
+ return ResponseEntity.ok(newUser);
+ } else {
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
+ }
+ }
+ @GetMapping("/api/_applelogin")
+ public String doAppleLogin(@RequestParam(required = false) String code, @RequestParam String state) {
+ if (StringUtils.isBlank(code)) {
+ String astate = UUID.randomUUID().toString();
+ crosspostService.addVKState(astate, state);
+ return "redirect:" + appleSignInService.getAuthorizationUrl(astate);
+ }
+ throw new HttpBadRequestException();
+ }
+ @PostMapping("/api/_applelogin")
+ public String doVerifyAppleResponse(@RequestParam Map body) throws InterruptedException, ExecutionException, IOException, ParseException, JOSEException, BadJOSEException {
+ OAuth2AccessToken token = appleSignInService.getAccessToken(body.get("code"));
+ var jsonNode = jsonMapper.readTree(token.getRawResponse());
+ var idToken = jsonNode.get("id_token").textValue();
+
+ AppleSignInApi api = (AppleSignInApi) appleSignInService.getApi();
+ var email = api.validateToken(idToken);
+
+ if (email.isPresent()) {
+ com.juick.model.User user = userService.getUserByEmail(email.get());
+ if (!user.isAnonymous()) {
+ String redirectUrl = crosspostService.verifyVKState(body.get("state"));
+ if (StringUtils.isBlank(redirectUrl)) {
+ logger.error("state is missing");
+ throw new HttpBadRequestException();
+ }
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl);
+ uriComponentsBuilder.queryParam("hash", userService.getHashByUID(user.getUid()));
+ uriComponentsBuilder.queryParam("retpath", redirectUrl);
+ return "redirect:" + uriComponentsBuilder.build().toUriString();
+ } else {
+ String verificationCode = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
+ emailService.addVerificationCode(null, email.get(), verificationCode);
+ return "redirect:/signup?type=email&hash=" + verificationCode;
+ }
+ }
+ throw new HttpBadRequestException();
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Index.java b/src/main/java/com/juick/www/api/Index.java
new file mode 100644
index 00000000..5b771efd
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Index.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+import springfox.documentation.annotations.ApiIgnore;
+
+import java.net.URI;
+
+/**
+ * Created by vitalyster on 25.07.2016.
+ */
+@RestController
+public class Index {
+
+ @ApiIgnore
+ @RequestMapping(value = { "/api/", "/ws/" }, method = RequestMethod.GET)
+ public ResponseEntity description() {
+ URI redirectUri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/swagger-ui.html").build().toUri();
+ return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).location(redirectUri).build();
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Messages.java b/src/main/java/com/juick/www/api/Messages.java
new file mode 100644
index 00000000..59ed7c8f
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Messages.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.Message;
+import com.juick.model.Tag;
+import com.juick.model.User;
+import com.juick.server.Utils;
+import com.juick.www.WebApp;
+import com.juick.model.CommandResult;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.service.MessagesService;
+import com.juick.service.TagService;
+import com.juick.service.UserService;
+import com.juick.service.component.SystemEvent;
+import com.juick.service.security.annotation.Visitor;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.tuple.Pair;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.*;
+
+import javax.inject.Inject;
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * @author ugnich
+ */
+@RestController
+@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
+public class Messages {
+
+ private static final ResponseEntity> NOT_FOUND = ResponseEntity
+ .status(HttpStatus.NOT_FOUND)
+ .body(Collections.emptyList());
+
+ private static final ResponseEntity> FORBIDDEN = ResponseEntity
+ .status(HttpStatus.FORBIDDEN)
+ .body(Collections.emptyList());
+
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private UserService userService;
+ @Inject
+ private TagService tagService;
+ @Inject
+ private ApplicationEventPublisher applicationEventPublisher;
+ @Inject
+ private WebApp webApp;
+ @Value("classpath:Transparent.gif")
+ private Resource invisiblePixel;
+
+ // TODO: serialize image urls
+
+ @GetMapping("/api/home")
+ public ResponseEntity> getHome(
+ @Visitor User visitor,
+ @RequestParam(defaultValue = "0") int before_mid) {
+ if (!visitor.isAnonymous()) {
+ int vuid = visitor.getUid();
+ List mids = messagesService.getMyFeed(vuid, before_mid, true);
+ List msgs = messagesService.getMessages(visitor, mids);
+ msgs.forEach(m -> m.getUser().setAvatar(webApp.getAvatarUrl(m.getUser())));
+ return ResponseEntity.ok(msgs);
+ }
+ return FORBIDDEN;
+ }
+
+ @GetMapping("/api/messages")
+ public ResponseEntity> getMessages(
+ @Visitor User visitor,
+ @RequestParam(required = false) String uname,
+ @RequestParam(name = "before_mid", defaultValue = "0") Integer before,
+ @RequestParam(required = false, defaultValue = "0") Integer daysback,
+ @RequestParam(required = false) String withrecommended,
+ @RequestParam(required = false) String popular,
+ @RequestParam(required = false) String search,
+ @RequestParam(required = false, defaultValue = "0") Integer page,
+ @RequestParam(required = false) String media,
+ @RequestParam(required = false) String tag) {
+ List mids;
+ if (!StringUtils.isEmpty(uname)) {
+ User user = userService.getUserByName(uname);
+ if (!user.isAnonymous() && !user.isBanned()) {
+ if (!StringUtils.isEmpty(media)) {
+ mids = messagesService.getUserPhotos(user.getUid(), 0, before);
+ } else if (!StringUtils.isEmpty(tag)) {
+ Tag tagObject = tagService.getTag(tag, false);
+ if (tagObject != null) {
+ mids = messagesService.getUserTag(user.getUid(), tagObject.TID, 0, before);
+ } else {
+ return NOT_FOUND;
+ }
+ } else if (!StringUtils.isEmpty(withrecommended)) {
+ mids = messagesService.getUserBlogWithRecommendations(user.getUid(), 0, before);
+ } else if (daysback > 0) {
+ mids = messagesService.getUserBlogAtDay(user.getUid(), 0, daysback);
+ } else if (!StringUtils.isEmpty(search)) {
+ mids = messagesService.getUserSearch(visitor, user.getUid(), Utils.encodeSphinx(search), 0, page);
+ } else {
+ mids = messagesService.getUserBlog(user.getUid(), 0, before);
+ }
+ } else {
+ return NOT_FOUND;
+ }
+ } else {
+ if (!StringUtils.isEmpty(popular)) {
+ mids = messagesService.getPopular(visitor.getUid(), before);
+ } else if (!StringUtils.isEmpty(media)) {
+ mids = messagesService.getPhotos(visitor.getUid(), before);
+ } else if (!StringUtils.isEmpty(tag)) {
+ Tag tagObject = tagService.getTag(tag, false);
+ if (tagObject != null) {
+ mids = messagesService.getTag(tagObject.TID, visitor.getUid(), before, 20);
+ } else {
+ return NOT_FOUND;
+ }
+ } else if (!StringUtils.isEmpty(search)) {
+ mids = messagesService.getSearch(visitor, Utils.encodeSphinx(search), page);
+ } else {
+ mids = messagesService.getAll(visitor.getUid(), before);
+ }
+ }
+ List msgs = messagesService.getMessages(visitor, mids);
+ msgs.forEach(m -> m.getUser().setAvatar(webApp.getAvatarUrl(m.getUser())));
+ return ResponseEntity.ok(msgs);
+ }
+ @DeleteMapping("/api/messages")
+ public CommandResult deleteMessage(
+ @Visitor User visitor,
+ @RequestParam int mid, @RequestParam(required = false, defaultValue = "0") int rid) {
+ if (rid > 0) {
+ if (messagesService.deleteReply(visitor.getUid(), mid, rid)) {
+ return CommandResult.fromString("Reply deleted");
+ }
+ }
+ if (messagesService.deleteMessage(visitor.getUid(), mid)) {
+ return CommandResult.fromString("Message deleted");
+ }
+ throw new HttpBadRequestException();
+ }
+
+ @GetMapping("/api/messages/discussions")
+ public List getDiscussions(
+ @Visitor User visitor,
+ @RequestParam(required = false, defaultValue = "0") Long to) {
+ List msgs = messagesService.getMessages(visitor,
+ messagesService.getDiscussions(visitor.getUid(), to));
+ msgs.forEach(m -> m.getUser().setAvatar(webApp.getAvatarUrl(m.getUser())));
+ return msgs;
+ }
+ @GetMapping("/api/thread")
+ public ResponseEntity> getThread(
+ @Visitor User visitor,
+ @RequestParam(defaultValue = "0") int mid) {
+ Optional message = messagesService.getMessage(mid);
+ if (message.isPresent()) {
+ Message msg = message.get();
+ if (!messagesService.canViewThread(mid, visitor.getUid())) {
+ return FORBIDDEN;
+ } else {
+ msg.getUser().setAvatar(webApp.getAvatarUrl(msg.getUser()));
+ msg.setRecommendations(new HashSet<>(messagesService.getMessagesRecommendations(
+ Collections.singletonList(msg.getMid()))
+ .stream().map(Pair::getRight).collect(Collectors.toList())));
+ msg.getRecommendations().forEach(r -> r.setAvatar(webApp.getAvatarUrl(r)));
+ List replies = messagesService.getReplies(visitor, mid);
+ replies.forEach(m -> m.getUser().setAvatar(webApp.getAvatarUrl(m.getUser())));
+ if (!visitor.isAnonymous()) {
+ userService.updateLastSeen(visitor);
+ applicationEventPublisher.publishEvent(
+ new SystemEvent(this, SystemActivity.read(visitor, msg)));
+ }
+ replies.add(0, msg);
+ return ResponseEntity.ok(replies);
+ }
+ }
+ return NOT_FOUND;
+ }
+ @GetMapping(value = "/api/thread/mark_read/{mid}-{rid}.gif", produces = MediaType.IMAGE_GIF_VALUE)
+ public byte[] markThreadRead(
+ @Visitor User visitor,
+ @PathVariable int mid, @PathVariable int rid) throws IOException {
+ if (!visitor.isAnonymous()) {
+ messagesService.setLastReadComment(visitor, mid, rid);
+ Message msg = messagesService.getMessage(mid).orElseThrow(IllegalStateException::new);
+ userService.updateLastSeen(visitor);
+ applicationEventPublisher.publishEvent(
+ new SystemEvent(this, SystemActivity.read(visitor, msg)));
+ return IOUtils.toByteArray(invisiblePixel.getInputStream());
+ }
+ throw new HttpBadRequestException();
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Notifications.java b/src/main/java/com/juick/www/api/Notifications.java
new file mode 100644
index 00000000..ca382246
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Notifications.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.ExternalToken;
+import com.juick.model.Message;
+import com.juick.model.Status;
+import com.juick.model.User;
+import com.juick.model.AnonymousUser;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.service.MessagesService;
+import com.juick.service.PushQueriesService;
+import com.juick.service.SubscriptionService;
+import com.juick.service.TelegramService;
+import com.juick.service.UserService;
+import com.juick.service.security.annotation.Visitor;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import springfox.documentation.annotations.ApiIgnore;
+
+import javax.inject.Inject;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Created by vitalyster on 24.10.2016.
+ */
+@RestController
+public class Notifications {
+
+ @Inject
+ private PushQueriesService pushQueriesService;
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private SubscriptionService subscriptionService;
+ @Inject
+ private UserService userService;
+ @Inject
+ private TelegramService telegramService;
+ @Value("${api_user:juick}")
+ private String serviceUser;
+
+
+ private User collectTokens(Integer uid) {
+ User user = userService.getUserByUID(uid).orElse(AnonymousUser.INSTANCE);
+ user.setUnreadCount(messagesService.getUnread(user).size());
+ pushQueriesService.getGCMRegID(uid).forEach(t -> user.getTokens().add(new ExternalToken(null, "gcm", t, null)));
+ pushQueriesService.getAPNSToken(uid).forEach(t -> user.getTokens().add(new ExternalToken(null, "apns", t, null)));
+ pushQueriesService.getMPNSURL(uid).forEach(t -> user.getTokens().add(new ExternalToken(null, "mpns", t, null)));
+ List xmppJids = userService.getJIDsbyUID(uid).stream()
+ .map(jid -> new ExternalToken(null, "xmpp", jid, null))
+ .collect(Collectors.toList());
+ user.getTokens().addAll(xmppJids);
+ List tgIds = telegramService.getTelegramIdentifiers(Collections.singletonList(user)).stream()
+ .map(tgId -> new ExternalToken(null, "durov", String.valueOf(tgId), null))
+ .collect(Collectors.toList());
+ user.getTokens().addAll(tgIds);
+ return user;
+ }
+
+ @ApiIgnore
+ @RequestMapping(value = "/api/notifications", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity> doGet(
+ @Visitor User visitor,
+ @RequestParam(required = false, defaultValue = "0") int uid,
+ @RequestParam(required = false, defaultValue = "0") int mid,
+ @RequestParam(required = false, defaultValue = "0") int rid) {
+ if (!(visitor.getName().equals(serviceUser))) {
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
+ }
+ if (uid > 0 && mid == 0) {
+ // PM
+ return ResponseEntity.ok(Collections.singletonList(collectTokens(uid)));
+ } else {
+ if (mid > 0) {
+ // reply
+ Message msg = messagesService.getMessage(mid).orElseThrow(IllegalStateException::new);
+ List users;
+ if (rid > 0) {
+ Message op = messagesService.getMessage(mid).orElseThrow(IllegalStateException::new);
+ Message reply = messagesService.getReply(mid, rid);
+ users = subscriptionService.getUsersSubscribedToComments(op, reply);
+ } else {
+ users = subscriptionService.getSubscribedUsers(msg.getUser().getUid(), msg);
+ }
+
+ return ResponseEntity.ok(users.stream().map(User::getUid)
+ .map(this::collectTokens).collect(Collectors.toList()));
+ } else {
+ // read
+ return ResponseEntity.ok(Collections.singletonList(collectTokens(uid)));
+ }
+ }
+ }
+
+ @ApiIgnore
+ @RequestMapping(value = "/api/notifications", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity doDelete(
+ @Visitor User visitor,
+ @RequestBody List list) {
+ if (!visitor.getName().equals(serviceUser)) {
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
+ }
+ list.forEach(t -> {
+ switch (t.getType()) {
+ case "gcm":
+ pushQueriesService.deleteGCMToken(t.getToken());
+ break;
+ case "apns":
+ pushQueriesService.deleteAPNSToken(t.getToken());
+ break;
+ case "mpns":
+ pushQueriesService.deleteMPNSToken(t.getToken());
+ break;
+ default:
+ throw new HttpBadRequestException();
+ }
+ });
+
+ return ResponseEntity.ok(Status.OK);
+ }
+ @ApiIgnore
+ @RequestMapping(value = "/api/notifications/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity doDeleteTokens(
+ @Visitor User visitor,
+ @RequestBody List list) {
+ if (!visitor.getName().equals(serviceUser)) {
+ return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);
+ }
+ list.forEach(t -> {
+ switch (t.getType()) {
+ case "gcm":
+ pushQueriesService.deleteGCMToken(t.getToken());
+ break;
+ case "apns":
+ pushQueriesService.deleteAPNSToken(t.getToken());
+ break;
+ case "mpns":
+ pushQueriesService.deleteMPNSToken(t.getToken());
+ break;
+ default:
+ throw new HttpBadRequestException();
+ }
+ });
+
+ return ResponseEntity.ok(Status.OK);
+ }
+
+ @ApiIgnore
+ @RequestMapping(value = "/api/notifications", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
+ public Status doPut(
+ @Visitor User visitor,
+ @RequestBody List list) {
+ list.forEach(t -> {
+ switch (t.getType()) {
+ case "gcm":
+ pushQueriesService.addGCMToken(visitor.getUid(), t.getToken());
+ break;
+ case "apns":
+ pushQueriesService.addAPNSToken(visitor.getUid(), t.getToken());
+ break;
+ case "mpns":
+ pushQueriesService.addMPNSToken(visitor.getUid(), t.getToken());
+ break;
+ default:
+ throw new HttpBadRequestException();
+ }
+ });
+ return Status.OK;
+ }
+
+ @Deprecated
+ @RequestMapping(value = "/api/android/register", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public Status doAndroidRegister(
+ @Visitor User visitor,
+ @RequestParam(name = "regid") String regId) {
+ pushQueriesService.addGCMToken(visitor.getUid(), regId);
+ return Status.OK;
+ }
+
+ @Deprecated
+ @RequestMapping(value = "/api/winphone/register", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public Status doWinphoneRegister(
+ @Visitor User visitor,
+ @RequestParam(name = "url") String regId) {
+ pushQueriesService.addMPNSToken(visitor.getUid(), regId);
+ return Status.OK;
+ }
+}
diff --git a/src/main/java/com/juick/www/api/PM.java b/src/main/java/com/juick/www/api/PM.java
new file mode 100644
index 00000000..b81dcc78
--- /dev/null
+++ b/src/main/java/com/juick/www/api/PM.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.Chat;
+import com.juick.model.Message;
+import com.juick.model.User;
+import com.juick.model.AnonymousUser;
+import com.juick.model.PrivateChats;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.server.util.HttpForbiddenException;
+import com.juick.server.util.WebUtils;
+import com.juick.www.WebApp;
+import com.juick.service.PMQueriesService;
+import com.juick.service.UserService;
+import com.juick.service.component.SystemEvent;
+import com.juick.service.security.annotation.Visitor;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.inject.Inject;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author ugnich
+ */
+@RestController
+public class PM {
+ @Inject
+ private UserService userService;
+ @Inject
+ private PMQueriesService pmQueriesService;
+ @Inject
+ private ApplicationEventPublisher applicationEventPublisher;
+ @Inject
+ private WebApp webApp;
+
+ @RequestMapping(value = "/api/pm", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public List doGetPM(
+ @Visitor User visitor,
+ @RequestParam(required = false) String uname) {
+ int uid = 0;
+ if (uname != null && uname.matches("^[a-zA-Z0-9\\-]{2,16}$")) {
+ uid = userService.getUIDbyName(uname);
+ }
+
+ if (uid == 0) {
+ throw new HttpBadRequestException();
+ }
+
+ List msgs = pmQueriesService.getPMMessages(visitor.getUid(), uid);
+ msgs.forEach(m -> m.getUser().setAvatar(webApp.getAvatarUrl(m.getUser())));
+ return msgs;
+ }
+
+ @RequestMapping(value = "/api/pm", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
+ public Message doPostPM(
+ @Visitor User visitor,
+ @RequestParam String uname,
+ @RequestParam String body) {
+ User userTo = AnonymousUser.INSTANCE;
+ if (WebUtils.isUserName(uname)) {
+ userTo = userService.getUserByName(uname);
+ }
+
+ if (userTo.getUid() == 0 || body == null || body.length() < 1 || body.length() > 10240) {
+ throw new HttpBadRequestException();
+ }
+
+ if (userService.isInBLAny(userTo.getUid(), visitor.getUid())) {
+ throw new HttpForbiddenException();
+ }
+
+ if (pmQueriesService.createPM(visitor.getUid(), userTo.getUid(), body)) {
+ Message jmsg = new Message();
+ jmsg.setUser(visitor);
+ jmsg.setText(body);
+ jmsg.setTo(userTo);
+ jmsg.getUser().setAvatar(webApp.getAvatarUrl(jmsg.getUser()));
+ applicationEventPublisher.publishEvent(
+ new SystemEvent(this,
+ SystemActivity.message(jmsg.getUser(), jmsg, Collections.singletonList(jmsg.getTo()))));
+ return jmsg;
+
+ }
+ throw new HttpBadRequestException();
+ }
+ @RequestMapping(value = "/api/groups_pms", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public PrivateChats doGetGroupsPMs(
+ @Visitor User visitor,
+ @RequestParam(defaultValue = "5") int cnt) {
+ // TODO: ignore cnt param for now but make sure paging param will not be cnt
+
+ List lastconv = pmQueriesService.getLastChats(visitor);
+ lastconv.forEach(c -> c.setAvatar(webApp.getAvatarUrl(c)));
+ PrivateChats pms = new PrivateChats();
+ pms.setUsers(lastconv);
+ return pms;
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Post.java b/src/main/java/com/juick/www/api/Post.java
new file mode 100644
index 00000000..3c1fbf6b
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Post.java
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.Message;
+import com.juick.model.Reaction;
+import com.juick.model.Status;
+import com.juick.model.User;
+import com.juick.model.CommandResult;
+import com.juick.server.ActivityPubManager;
+import com.juick.server.CommandsManager;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.server.util.HttpForbiddenException;
+import com.juick.server.util.HttpNotFoundException;
+import com.juick.server.util.HttpUtils;
+import com.juick.service.MessagesService;
+import com.juick.service.UserService;
+import com.juick.service.activities.UpdateEvent;
+import com.juick.service.security.annotation.Visitor;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.inject.Inject;
+import javax.validation.constraints.NotNull;
+import java.net.URI;
+import java.net.URL;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Created by vt on 24/11/2016.
+ */
+@RestController
+public class Post {
+ private final static Logger logger = LoggerFactory.getLogger("API");
+
+ @Inject
+ private UserService userService;
+ @Inject
+ private MessagesService messagesService;
+ @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}")
+ private String tmpDir;
+ @Inject
+ CommandsManager commandsManager;
+ @Inject
+ ApplicationEventPublisher applicationEventPublisher;
+ @Inject
+ ActivityPubManager activityPubManager;
+
+ @RequestMapping(value = "/api/post", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
+ @ResponseStatus(value = HttpStatus.OK)
+ public CommandResult doPostMessage(
+ @Visitor User visitor,
+ @RequestParam(required = false, defaultValue = StringUtils.EMPTY) String body,
+ @RequestParam(required = false) String img,
+ @RequestParam(required = false) MultipartFile attach) throws Exception {
+ body = body.replace("\r", StringUtils.EMPTY);
+
+ URI attachmentFName = HttpUtils.receiveMultiPartFile(attach, tmpDir);
+
+ if (StringUtils.isBlank(attachmentFName.toString()) && img != null && img.length() > 10) {
+ URI juickUri = URI.create(img);
+ if (juickUri.getScheme().equals("juick")) {
+ attachmentFName = juickUri;
+ } else {
+ try {
+ URL imgUrl = new URL(img);
+ attachmentFName = HttpUtils.downloadImage(imgUrl, tmpDir);
+ } catch (Exception e) {
+ logger.error("DOWNLOAD ERROR", e);
+ throw new HttpBadRequestException();
+ }
+ }
+ }
+ if (StringUtils.isBlank(body) && StringUtils.isBlank(attachmentFName.toString())) {
+ // Should be there for compatibility
+ throw new HttpBadRequestException();
+ }
+ return commandsManager.processCommand(visitor, body, attachmentFName);
+ }
+
+ @RequestMapping(value = "/api/comment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
+ public CommandResult doPostComment(
+ @Visitor User visitor,
+ @RequestParam(defaultValue = "0") int mid,
+ @RequestParam(defaultValue = "0") int rid,
+ @RequestParam(required = false, defaultValue = StringUtils.EMPTY) final String body,
+ @RequestParam(required = false) String img,
+ @RequestParam(required = false) MultipartFile attach)
+ throws Exception {
+ if (mid == 0) {
+ throw new HttpBadRequestException();
+ }
+ Optional message = messagesService.getMessage(mid);
+ if (message.isEmpty()) {
+ throw new HttpNotFoundException();
+ }
+
+ Message msg = message.get();
+
+ Message reply = null;
+ if (rid > 0) {
+ reply = messagesService.getReply(mid, rid);
+ if (reply == null) {
+ throw new HttpNotFoundException();
+ }
+ }
+
+ if ((msg.ReadOnly && msg.getUser().getUid() != visitor.getUid())
+ || userService.isInBLAny(msg.getUser().getUid(), visitor.getUid())
+ || (reply != null && userService.isInBLAny(reply.getUser().getUid(), visitor.getUid()))) {
+ // TODO: validator
+ throw new HttpForbiddenException();
+ }
+
+ URI attachmentFName = HttpUtils.receiveMultiPartFile(attach, tmpDir);
+
+ if (StringUtils.isBlank(attachmentFName.toString()) && img != null && img.length() > 10) {
+ try {
+ attachmentFName = HttpUtils.downloadImage(new URL(img), tmpDir);
+ } catch (Exception e) {
+ logger.error("DOWNLOAD ERROR", e);
+ throw new HttpBadRequestException();
+ }
+ }
+ if (StringUtils.isBlank(body) && StringUtils.isBlank(attachmentFName.toString())) {
+ // Should be there for compatibility
+ throw new HttpBadRequestException();
+ }
+ return commandsManager.processCommand(visitor, String.format("#%d/%d %s", mid, rid, body),
+ attachmentFName);
+ }
+
+ @PostMapping("/api/like")
+ @ResponseStatus(value = HttpStatus.OK)
+ public Status doPostRecomm(@Visitor User visitor, @RequestParam Integer mid) throws Exception {
+ Optional message = messagesService.getMessage(mid);
+ if (message.isEmpty()) {
+ throw new HttpNotFoundException();
+ }
+ Message msg = message.get();
+ if (msg.getUser().getUid() == visitor.getUid()) {
+ throw new HttpForbiddenException();
+ }
+ CommandResult status = commandsManager.processCommand(visitor, String.format("! #%d", mid),
+ URI.create(StringUtils.EMPTY));
+ return Status.getStatus(status.getText());
+ }
+
+ @PostMapping("/api/subscribe")
+ @ResponseStatus(value = HttpStatus.OK)
+ public Status doPostSubscribe(@Visitor User visitor,
+ @RequestParam Integer mid) throws Exception {
+ Optional message = messagesService.getMessage(mid);
+ if (message.isEmpty()) {
+ throw new HttpNotFoundException();
+ }
+ Message msg = message.get();
+ if (msg.getUser().getUid() == visitor.getUid()) {
+ throw new HttpForbiddenException();
+ }
+ CommandResult status = commandsManager.processCommand(visitor, String.format("S #%d", mid),
+ URI.create(StringUtils.EMPTY));
+ return Status.getStatus(status.getText());
+ }
+
+ @GetMapping("/api/reactions")
+ @ResponseStatus(value = HttpStatus.OK)
+ public List reactionsList() {
+ return messagesService.listReactions();
+ }
+
+ @PostMapping("/api/react")
+ @ResponseStatus(value = HttpStatus.OK)
+ public Status doPostReact(
+ @Visitor User visitor,
+ @RequestParam Integer mid, @RequestParam @NotNull int reactionId,
+ @RequestParam(required = false, defaultValue = "1") int count) {
+
+ logger.info("got reaction with type: {}", reactionId);
+ Optional message = messagesService.getMessage(mid);
+ if (message.isEmpty()) {
+ throw new HttpNotFoundException();
+ }
+ Message msg = message.get();
+ if (msg.getUser().getUid() == visitor.getUid()) {
+ throw new HttpForbiddenException();
+ }
+ MessagesService.RecommendStatus recommendStatus = MessagesService.RecommendStatus.Error;
+ for (int i = 0; i < count; i++)
+ recommendStatus = messagesService.likeMessage(mid, visitor.getUid(),
+ reactionId);
+
+ return recommendStatus == MessagesService.RecommendStatus.Error ? Status.ERROR :Status.OK;
+ }
+
+ @PostMapping("/api/update")
+ public CommandResult updateMessage(@Visitor User visitor,
+ @RequestParam Integer mid,
+ @RequestParam(required = false, defaultValue = "0") Integer rid,
+ @RequestParam String body) {
+ User author = rid == 0 ? messagesService.getMessageAuthor(mid) : messagesService.getReply(mid, rid).getUser();
+ if (visitor.equals(author)) {
+ if (messagesService.updateMessage(mid, rid, body)) {
+ Message result = rid == 0 ?
+ messagesService.getMessage(mid).orElseThrow(IllegalStateException::new)
+ : messagesService.getReply(mid, rid);
+ applicationEventPublisher.publishEvent(
+ new UpdateEvent(this, author, activityPubManager.messageUri(mid, rid)));
+ return CommandResult.build(result, "Message updated", StringUtils.EMPTY);
+ }
+ throw new HttpBadRequestException();
+ }
+ throw new HttpForbiddenException();
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Service.java b/src/main/java/com/juick/www/api/Service.java
new file mode 100644
index 00000000..cb918682
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Service.java
@@ -0,0 +1,223 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.Message;
+import com.juick.model.User;
+import com.juick.model.CommandResult;
+import com.juick.server.CommandsManager;
+import com.juick.server.EmailManager;
+import com.juick.server.ServerManager;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.server.util.HttpForbiddenException;
+import com.juick.service.EmailService;
+import com.juick.service.MessagesService;
+import com.juick.service.UserService;
+import com.juick.service.component.AccountVerificationEvent;
+import com.juick.service.security.annotation.Visitor;
+import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.mail.util.MimeMessageParser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+import springfox.documentation.annotations.ApiIgnore;
+
+import javax.inject.Inject;
+import javax.mail.Session;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Paths;
+import java.util.*;
+
+@Controller
+public class Service {
+ private static Logger logger = LoggerFactory.getLogger("Session");
+ @Inject
+ private UserService userService;
+ @Inject
+ private EmailService emailService;
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private CommandsManager commandsManager;
+ @Inject
+ private ApplicationEventPublisher applicationEventPublisher;
+ @Value("${api_user:juick}")
+ private String serviceUser;
+ @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}")
+ private String tmpDir;
+ @Value("${banned_emails:}")
+ private String[] ignoredEmails;
+ @Inject
+ private ServerManager serverManager;
+
+ private Session session = Session.getDefaultInstance(new Properties());
+
+ @ApiIgnore
+ @PostMapping("/api/mail")
+ @ResponseStatus(value = HttpStatus.OK)
+ public void processMail(@Visitor User current, InputStream data) throws Exception {
+ if (current.getName().equals(serviceUser)) {
+ MimeMessage msg = new MimeMessage(session, data);
+ String[] returnPaths = msg.getHeader("Return-Path");
+ if (returnPaths != null) {
+ logger.info("got msg with return path {}", returnPaths[0]);
+ if (returnPaths[0].equals("<>")) {
+ return;
+ }
+ }
+ String from = msg.getFrom() == null || msg.getFrom().length > 1 ? ((InternetAddress) msg.getSender()).getAddress()
+ : ((InternetAddress) msg.getFrom()[0]).getAddress();
+
+ User visitor = userService.getUserByEmail(from);
+ if (!visitor.isAnonymous()) {
+ MimeMessageParser parser = new MimeMessageParser(msg);
+ parser.parse();
+ final String[] body = {parser.getPlainContent()};
+ if (body[0] == null) {
+ parser.getAttachmentList().stream()
+ .filter(a -> a.getContentType().equals("text/plain")).findFirst()
+ .ifPresent(a -> {
+ try {
+ body[0] = IOUtils.toString(a.getInputStream(), StandardCharsets.UTF_8);
+ logger.info("got text: {}", body[0]);
+ } catch (IOException e) {
+ logger.info("attachment error", e);
+ }
+ });
+ }
+ final String[] attachmentFName = new String[1];
+ parser.getAttachmentList().stream().filter(a ->
+ a.getContentType().equals("image/jpeg") || a.getContentType().equals("image/png"))
+ .findFirst().ifPresent(a -> {
+ logger.info("got attachment: {}", a.getContentType());
+ String attachmentType;
+ if (a.getContentType().equals("image/jpeg")) {
+ attachmentType = "jpg";
+ } else {
+ attachmentType = "png";
+ }
+ attachmentFName[0] = DigestUtils.md5Hex(UUID.randomUUID().toString()) + "." + attachmentType;
+ try {
+ logger.info("got inputstream: {}", a.getInputStream());
+ FileOutputStream fos = new FileOutputStream(Paths.get(tmpDir, attachmentFName[0]).toString());
+ IOUtils.copy(a.getInputStream(), fos);
+ fos.close();
+ } catch (IOException e) {
+ logger.info("attachment error", e);
+ }
+ });
+ String[] inReplyToHeaders = msg.getHeader("In-Reply-To");
+ if (inReplyToHeaders != null && inReplyToHeaders.length > 0) {
+ int mid, rid;
+ var originalMessage = messagesService.findMessageByProperty("messageId", inReplyToHeaders[0]);
+ if (originalMessage.isPresent()) {
+ mid = originalMessage.get().getLeft();
+ rid = originalMessage.get().getRight();
+ } else {
+ Scanner inReplyToScanner = new Scanner(inReplyToHeaders[0].trim()).useDelimiter(EmailManager.MSGID_PATTERN);
+ mid = Integer.parseInt(inReplyToScanner.next());
+ rid = Integer.parseInt(inReplyToScanner.next());
+ }
+ logger.info("Message is reply to #{}/{}", mid, rid);
+ body[0] = rid > 0 ? String.format("#%d/%d %s", mid, rid, body[0])
+ : String.format("#%d %s", mid, body[0]);
+ }
+ URI attachmentUri = StringUtils.isNotEmpty(attachmentFName[0]) ? URI.create(String.format("juick://%s", attachmentFName[0]))
+ : URI.create(StringUtils.EMPTY);
+ CommandResult result = commandsManager.processCommand(visitor, body[0], attachmentUri);
+ if (result.getNewMessage().isPresent()) {
+ String[] messageIds = msg.getHeader("Message-Id");
+ if (messageIds.length == 1) {
+ Message message = result.getNewMessage().get();
+ messagesService.setMessageProperty(message.getMid(), message.getRid(), "messageId", messageIds[0]);
+ } else {
+ logger.warn("Wrong number of Message-Id headers");
+ }
+ }
+ } else {
+ if (!Arrays.asList(ignoredEmails).contains(from)) {
+ String verificationCode = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
+ emailService.addVerificationCode(null, from, verificationCode);
+ applicationEventPublisher.publishEvent(new AccountVerificationEvent(this, from, verificationCode));
+ }
+ }
+ } else {
+ throw new HttpForbiddenException();
+ }
+ }
+ @ApiIgnore
+ @PostMapping("/api/mail/unsubscribe")
+ @ResponseStatus(value = HttpStatus.OK)
+ public void processMailUnsubscribe(@Visitor User current, InputStream data) throws Exception {
+ if (current.getName().equals(serviceUser)) {
+ MimeMessage msg = new MimeMessage(session, data);
+ String from = msg.getFrom() == null || msg.getFrom().length > 1 ? ((InternetAddress) msg.getSender()).getAddress()
+ : ((InternetAddress) msg.getFrom()[0]).getAddress();
+
+ User visitor = userService.getUserByEmail(from);
+ if (!visitor.isAnonymous()) {
+ if (!emailService.disableEmail(visitor, from)) {
+ throw new HttpBadRequestException();
+ }
+ }
+ } else {
+ throw new HttpForbiddenException();
+ }
+ }
+ private void endSession(SseEmitter emitter) {
+ serverManager.getSessions().stream()
+ .filter(s -> s.getEmitter().equals(emitter))
+ .forEach(session -> serverManager.getSessions().remove(session));
+ }
+ @GetMapping("/api/events")
+ public SseEmitter handle(@Visitor User visitor) throws IOException {
+ logger.info("{} connected", visitor.getName());
+ if (!visitor.isAnonymous()) {
+ userService.updateLastSeen(visitor);
+ }
+ SseEmitter emitter = new SseEmitter(600000L);
+ serverManager.getSessions().add(new ServerManager.EventSession(visitor, emitter));
+
+ emitter.onCompletion(() -> endSession(emitter));
+ emitter.onTimeout(() -> endSession(emitter));
+
+ return emitter;
+ }
+ @ExceptionHandler(AsyncRequestTimeoutException.class)
+ public void eventErrorHandler(Exception ex) {
+ logger.debug("SSE timeout", ex);
+ }
+}
diff --git a/src/main/java/com/juick/www/api/SystemActivity.java b/src/main/java/com/juick/www/api/SystemActivity.java
new file mode 100644
index 00000000..0827537a
--- /dev/null
+++ b/src/main/java/com/juick/www/api/SystemActivity.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.Message;
+import com.juick.model.User;
+
+import java.util.Collections;
+import java.util.List;
+
+public class SystemActivity {
+ public static SystemActivity like(User from, Message message, List subscribers) {
+ var like = new SystemActivity();
+ like.setType(ActivityType.like);
+ like.setFrom(from);
+ like.setMessage(message);
+ like.setTo(subscribers);
+ return like;
+ }
+
+ public static SystemActivity message(User from, Message message, List subscribers) {
+ var msg = new SystemActivity();
+ msg.setType(ActivityType.message);
+ msg.setFrom(from);
+ msg.setMessage(message);
+ msg.setTo(subscribers);
+ return msg;
+ }
+
+ public static SystemActivity read(User from, Message message) {
+ var read = new SystemActivity();
+ read.setType(ActivityType.message);
+ read.setFrom(from);
+ read.setTo(Collections.emptyList());
+ var msg = new Message();
+ msg.setMid(message.getMid());
+ msg.setUser(from);
+ msg.setService(true);
+ msg.setUnread(false);
+ read.setMessage(msg);
+ return read;
+ }
+
+ public static SystemActivity follow(User from, List to) {
+ var follow = new SystemActivity();
+ follow.setFrom(from);
+ follow.setTo(to);
+ return follow;
+ }
+
+ public enum ActivityType {
+ message,
+ like,
+ follow
+ }
+
+ private ActivityType type;
+ private User from;
+ private List to;
+ private Message message;
+
+ public ActivityType getType() {
+ return type;
+ }
+
+ public void setType(ActivityType type) {
+ this.type = type;
+ }
+
+ public User getFrom() {
+ return from;
+ }
+
+ public void setFrom(User from) {
+ this.from = from;
+ }
+
+ public List getTo() {
+ return to;
+ }
+
+ public void setTo(List to) {
+ this.to = to;
+ }
+
+ public Message getMessage() {
+ return message;
+ }
+
+ public void setMessage(Message message) {
+ this.message = message;
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Tags.java b/src/main/java/com/juick/www/api/Tags.java
new file mode 100644
index 00000000..b50e9bd5
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Tags.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.User;
+import com.juick.model.TagStats;
+import com.juick.service.TagService;
+import com.juick.service.security.annotation.Visitor;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.inject.Inject;
+import java.util.List;
+
+/**
+ * Created by vitalyster on 29.11.2016.
+ */
+@RestController
+public class Tags {
+ @Inject
+ private TagService tagService;
+
+ @RequestMapping(value = "/api/tags", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public List tags(
+ @Visitor User visitor,
+ @RequestParam(required = false, defaultValue = "0") int user_id
+ ) {
+ if (user_id == 0) {
+ user_id = visitor.getUid();
+ }
+ if (user_id > 0) {
+ return tagService.getUserTagStats(user_id);
+ }
+ return tagService.getTagStats();
+ }
+}
diff --git a/src/main/java/com/juick/www/api/Users.java b/src/main/java/com/juick/www/api/Users.java
new file mode 100644
index 00000000..06467b7d
--- /dev/null
+++ b/src/main/java/com/juick/www/api/Users.java
@@ -0,0 +1,279 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api;
+
+import com.juick.model.User;
+import com.juick.model.AnonymousUser;
+import com.juick.model.ApplicationStatus;
+import com.juick.server.util.HttpBadRequestException;
+import com.juick.server.util.HttpNotFoundException;
+import com.juick.server.util.HttpUtils;
+import com.juick.server.util.WebUtils;
+import com.juick.www.WebApp;
+import com.juick.service.*;
+import com.juick.service.component.MailVerificationEvent;
+import com.juick.service.security.annotation.Visitor;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.inject.Inject;
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author ugnich
+ */
+@RestController
+public class Users {
+ @Inject
+ private UserService userService;
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private CrosspostService crosspostService;
+ @Inject
+ private TelegramService telegramService;
+ @Inject
+ private EmailService emailService;
+ @Inject
+ private TagService tagService;
+ @Inject
+ private WebApp webApp;
+ @Inject
+ private ImagesService imagesService;
+ @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}")
+ private String tmpDir;
+ @Inject
+ private ApplicationEventPublisher applicationEventPublisher;
+
+ @RequestMapping(value = "/api/auth", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public String getAuthToken(@Visitor User visitor) {
+ return userService.getHashByUID(visitor.getUid());
+ }
+
+ @RequestMapping(value = "/api/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public List doGetUsers(
+ @Visitor User visitor,
+ @RequestParam(value = "uname", required = false) List unames) {
+ List users = new ArrayList<>();
+
+ if (unames != null) {
+ unames.removeIf(WebUtils::isNotUserName);
+
+ if (!unames.isEmpty() && unames.size() < 20)
+ users.addAll(userService.getUsersByName(unames));
+ }
+ users.forEach(u -> u.setAvatar(webApp.getAvatarUrl(u)));
+ if (!users.isEmpty())
+ return users;
+ if (!visitor.isAnonymous()) {
+ visitor.setAvatar(webApp.getAvatarUrl(visitor));
+ return Collections.singletonList(visitor);
+ }
+
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping("/api/me")
+ public SecureUser getMe(@Visitor User visitor) {
+ SecureUser me = new SecureUser();
+ me.setUid(visitor.getUid());
+ me.setName(visitor.getName());
+ me.setAuthHash(getAuthToken(visitor));
+ List unread = messagesService.getUnread(visitor);
+ me.setUnread(unread);
+ me.setUnreadCount(unread.size());
+ var friends = userService.getUserFriends(visitor.getUid());
+ friends.forEach(r -> r.setAvatar(webApp.getAvatarUrl(r)));
+ me.setRead(friends);
+ var readers = userService.getUserReaders(visitor.getUid());
+ readers.forEach(r -> r.setAvatar(webApp.getAvatarUrl(r)));
+ me.setReaders(readers);
+ me.setAvatar(webApp.getAvatarUrl(visitor));
+ me.getTagStats().addAll(tagService.getUserTagStats(me.getUid()));
+ return (SecureUser)userService.getUserInfo(me);
+ }
+ @PostMapping("/api/me")
+ public ResponseEntity updateMe(@Visitor User visitor,
+ @RequestParam(required = false) String password,
+ @RequestParam(value = "jid-del", required = false) String jidForDeletion,
+ @RequestParam(value = "email-add", required = false) String newEmail,
+ @RequestParam(value = "email-del", required = false) String emailForDeletion,
+ @RequestParam(value = "account-del", required = false) String accountToDelete) {
+ if (StringUtils.isNotEmpty(password)) {
+ if (!userService.updatePassword(visitor, password)) {
+ throw new HttpBadRequestException();
+ }
+ }
+ if (StringUtils.isNotEmpty(jidForDeletion)) {
+ if (!userService.deleteJID(visitor.getUid(), jidForDeletion)) {
+ throw new HttpBadRequestException();
+ }
+ }
+ if (StringUtils.isNotEmpty(newEmail)) {
+ if (!emailService.verifyAddressByCode(visitor.getUid(), newEmail)) {
+ String authCode = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
+ if (emailService.addVerificationCode(visitor.getUid(), newEmail, authCode)) {
+ applicationEventPublisher.publishEvent(new MailVerificationEvent(this, newEmail , authCode));
+ }
+ }
+ }
+ if (StringUtils.isNotEmpty(emailForDeletion)) {
+ if (!emailService.deleteEmail(visitor.getUid(), emailForDeletion)) {
+ throw new HttpBadRequestException();
+ }
+ }
+ if (StringUtils.isNotEmpty(accountToDelete)) {
+ switch (accountToDelete) {
+ case "twitter":
+ crosspostService.deleteTwitterToken(visitor.getUid());
+ break;
+ case "vk":
+ crosspostService.deleteVKUser(visitor.getUid());
+ break;
+ case "durov":
+ telegramService.deleteTelegramUser(visitor.getUid());
+ break;
+ }
+ }
+ return ResponseEntity.ok().build();
+ }
+ @PostMapping("/api/me/subscribe")
+ public ResponseEntity subscribeMe(@Visitor User visitor, String email) {
+ // TODO: check status
+ emailService.setNotificationsEmail(visitor.getUid(), email);
+ return ResponseEntity.ok().build();
+ }
+ @PostMapping("/api/me/upload")
+ public void updateInfo(@Visitor User visitor,
+ @RequestParam MultipartFile avatar) throws IOException {
+ String avatarTmpPath = HttpUtils.receiveMultiPartFile(avatar, tmpDir).getHost();
+ if (StringUtils.isNotEmpty(avatarTmpPath)) {
+ imagesService.saveAvatar(avatarTmpPath, visitor.getUid());
+ }
+ }
+
+ @RequestMapping(value = "/api/users/read", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public List doGetUserRead(
+ @Visitor User visitor,
+ @RequestParam String uname) {
+ int uid = 0;
+ if (uname == null) {
+ uid = visitor.getUid();
+ } else {
+ if (WebUtils.isUserName(uname)) {
+ User u = userService.getUserByName(uname);
+ if (!u.isAnonymous()) {
+ uid = u.getUid();
+ }
+ }
+ }
+
+ if (uid > 0) {
+ List friends = userService.getUserFriends(uid);
+ friends.forEach(f -> f.setAvatar(webApp.getAvatarUrl(f)));
+ return friends;
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @RequestMapping(value = "/api/users/readers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public List doGetUserReaders(
+ @Visitor User visitor,
+ @RequestParam String uname) {
+ int uid = 0;
+ if (uname == null) {
+ uid = visitor.getUid();
+ } else {
+ if (WebUtils.isUserName(uname)) {
+ User u = userService.getUserByName(uname);
+ if (!u.isAnonymous()) {
+ uid = u.getUid();
+ }
+ }
+ }
+
+ if (uid > 0) {
+ List readers = userService.getUserReaders(uid);
+ readers.forEach(r -> r.setAvatar(webApp.getAvatarUrl(r)));
+ return readers;
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping("/api/info/{uname}")
+ public User getUserInfo(@Visitor User visitor, @PathVariable String uname) {
+ User user = userService.getUserByName(uname);
+ if (!user.isBanned()) {
+ user.setRead(doGetUserRead(visitor, uname));
+ user.setReaders(doGetUserReaders(visitor, uname));
+ user.setAvatar(webApp.getAvatarUrl(user));
+ return userService.getUserInfo(user);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @Deprecated
+ @GetMapping(value = "/api/avatar", produces = MediaType.IMAGE_PNG_VALUE)
+ public byte[] getAvatarUrl(
+ @RequestParam(required = false) String uname,
+ @RequestParam(required = false) String jid)
+ throws IOException {
+ User user = AnonymousUser.INSTANCE;
+ if (StringUtils.isNotEmpty(uname)) {
+ user = userService.getUserByName(uname);
+ }
+ if (user.isAnonymous() && StringUtils.isNotEmpty(jid)) {
+ user = userService.getUserByJID(jid);
+ }
+ return IOUtils.toByteArray(URI.create(webApp.getAvatarUrl(user)));
+ }
+ public class SecureUser extends User {
+ public String getHash() {
+ return getAuthHash();
+ }
+ public List getJIDs() {
+ return userService.getAllJIDs(this);
+ }
+ public List getEmails() {
+ return userService.getEmails(this);
+ }
+ public String getActiveEmail() {
+ return emailService.getNotificationsEmail(this.getUid());
+ }
+ public String getTwitterName() {
+ return crosspostService.getTwitterName(this.getUid());
+ }
+ public String getTelegramName() {
+ return crosspostService.getTelegramName(this.getUid());
+ }
+ public ApplicationStatus getFacebookStatus() {
+ return crosspostService.getFbCrossPostStatus(this.getUid());
+ }
+ }
+}
diff --git a/src/main/java/com/juick/www/api/activity/Profile.java b/src/main/java/com/juick/www/api/activity/Profile.java
new file mode 100644
index 00000000..bdd7cab2
--- /dev/null
+++ b/src/main/java/com/juick/www/api/activity/Profile.java
@@ -0,0 +1,410 @@
+/*
+ * Copyright (C) 2008-2019, Juick
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ */
+
+package com.juick.www.api.activity;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.juick.model.Message;
+import com.juick.model.User;
+import com.juick.formatters.PlainTextFormatter;
+import com.juick.model.CommandResult;
+import com.juick.server.ActivityPubManager;
+import com.juick.server.CommandsManager;
+import com.juick.server.KeystoreManager;
+import com.juick.server.SignatureManager;
+import com.juick.www.api.activity.model.Activity;
+import com.juick.www.api.activity.model.Context;
+import com.juick.www.api.activity.model.activities.Announce;
+import com.juick.www.api.activity.model.activities.Create;
+import com.juick.www.api.activity.model.activities.Delete;
+import com.juick.www.api.activity.model.activities.Follow;
+import com.juick.www.api.activity.model.activities.Like;
+import com.juick.www.api.activity.model.activities.Undo;
+import com.juick.www.api.activity.model.objects.Image;
+import com.juick.www.api.activity.model.objects.Key;
+import com.juick.www.api.activity.model.objects.Note;
+import com.juick.www.api.activity.model.objects.OrderedCollection;
+import com.juick.www.api.activity.model.objects.OrderedCollectionPage;
+import com.juick.www.api.activity.model.objects.Person;
+import com.juick.server.util.HttpNotFoundException;
+import com.juick.www.WebApp;
+import com.juick.service.MessagesService;
+import com.juick.service.UserService;
+import com.juick.service.activities.AnnounceEvent;
+import com.juick.service.activities.FollowEvent;
+import com.juick.service.activities.UndoAnnounceEvent;
+import com.juick.service.activities.UndoFollowEvent;
+import com.juick.service.security.annotation.Visitor;
+import com.overzealous.remark.Remark;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import javax.inject.Inject;
+import java.io.InputStream;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+@RestController
+public class Profile {
+ private static final Logger logger = LoggerFactory.getLogger("ActivityPub");
+ @Inject
+ private UserService userService;
+ @Inject
+ private MessagesService messagesService;
+ @Inject
+ private KeystoreManager keystoreManager;
+ @Inject
+ private SignatureManager signatureManager;
+ @Inject
+ private ActivityPubManager activityPubManager;
+ @Inject
+ private ApplicationEventPublisher applicationEventPublisher;
+ @Inject
+ private CommandsManager commandsManager;
+ @Value("${web_domain:localhost}")
+ private String domain;
+ @Value("${ap_base_uri:http://localhost:8080/}")
+ private String baseUri;
+ @Inject
+ private ObjectMapper jsonMapper;
+ @Inject
+ private WebApp webApp;
+ @Inject
+ private Remark remarkConverter;
+
+ @GetMapping(value = "/u/{userName}", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public Person getUser(@PathVariable String userName) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous()) {
+ Person person = new Person();
+ person.setId(activityPubManager.personUri(user));
+ person.setUrl(activityPubManager.personWebUri(user));
+ person.setName(userName);
+ person.setPreferredUsername(userName);
+ Key publicKey = new Key();
+ publicKey.setId(person.getId() + "#main-key");
+ publicKey.setOwner(person.getId());
+ publicKey.setPublicKeyPem(keystoreManager.getPublicKeyPem());
+ person.setPublicKey(publicKey);
+ person.setInbox(activityPubManager.inboxUri());
+ person.setOutbox(activityPubManager.outboxUri(user));
+ person.setFollowers(activityPubManager.followersUri(user));
+ person.setFollowing(activityPubManager.followingUri(user));
+ Image avatar = new Image();
+ avatar.setUrl(webApp.getAvatarUrl(user));
+ avatar.setMediaType("image/png");
+ person.setIcon(avatar);
+ return (Person) Context.build(person);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/u/{userName}/blog/toc", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public OrderedCollection getOutbox(@PathVariable String userName) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous()) {
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
+ OrderedCollection blog = new OrderedCollection();
+ blog.setId(ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString());
+ blog.setTotalItems(userService.getStatsMessages(user.getUid()));
+ blog.setFirst(uriComponentsBuilder.path(String.format("/u/%s/blog", userName)).toUriString());
+ return (OrderedCollection) Context.build(blog);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/u/{userName}/blog", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public OrderedCollectionPage getOutboxPage(@Visitor User visitor, @PathVariable String userName,
+ @RequestParam(required = false, defaultValue = "0") int before) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous() && !user.isBanned()) {
+ UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
+ String personUri = uri.path(String.format("/u/%s", userName)).toUriString();
+ List mids = messagesService.getUserBlog(user.getUid(), 0, before);
+ List notes = messagesService.getMessages(visitor, mids)
+ .stream().map(activityPubManager::makeNote).collect(Collectors.toList());
+ OrderedCollectionPage page = new OrderedCollectionPage();
+ page.setPartOf(uri.replacePath(String.format("/u/%s/blog/toc", userName)).toUriString());
+ page.setFirst(uri.replacePath(String.format("/u/%s/blog", userName)).toUriString());
+ page.setId(ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString());
+ page.setOrderedItems(notes.stream().map(a -> {
+ Create create = new Create();
+ create.setId(a.getId() + "#Create");
+ create.setTo(a.getTo());
+ create.setActor(personUri);
+ create.setObject(a);
+ create.setPublished(a.getPublished());
+ return create;
+ }).collect(Collectors.toList()));
+ int beforeNext = mids.stream().reduce((fst, second) -> second).orElse(0);
+ if (beforeNext > 0) {
+ page.setNext(uri.queryParam("before", beforeNext).toUriString());
+ }
+ page.setLast(uri.replaceQueryParam("before", "1").toUriString());
+ return (OrderedCollectionPage) Context.build(page);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/u/{userName}/followers/toc", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public OrderedCollection getFollowers(@PathVariable String userName) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous()) {
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
+ OrderedCollection followers = new OrderedCollection();
+ followers.setId(ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString());
+ followers.setTotalItems(userService.getStatsMyReaders(user.getUid()));
+ followers.setFirst(uriComponentsBuilder.path(String.format("/u/%s/followers", userName)).toUriString());
+ return (OrderedCollection) Context.build(followers);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/u/{userName}/followers", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public OrderedCollectionPage getFollowersPage(@PathVariable String userName,
+ @RequestParam(required = false, defaultValue = "0") int page) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous()) {
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
+ uriComponentsBuilder.path(String.format("/u/%s/followers", userName));
+ List followers = userService.getUserReaders(user.getUid());
+ Stream followersPage = followers.stream().skip(20 * page).limit(20);
+
+ OrderedCollectionPage result = new OrderedCollectionPage();
+ result.setId(ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString());
+ result.setOrderedItems(followersPage.map(a -> {
+ Person follower = new Person();
+ follower.setName(a.getName());
+ follower.setPreferredUsername(a.getName());
+ follower.setUrl(activityPubManager.personWebUri(a));
+ return follower;
+ }).collect(Collectors.toList()));
+ boolean hasNext = followers.size() <= 20 * page;
+ if (hasNext) {
+ result.setNext(uriComponentsBuilder.queryParam("page", page + 1).toUriString());
+ }
+ return (OrderedCollectionPage) Context.build(result);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/u/{userName}/following/toc", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public OrderedCollection getFollowing(@PathVariable String userName) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous()) {
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
+ OrderedCollection following = new OrderedCollection();
+ following.setId(ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString());
+ following.setTotalItems(userService.getUserFriends(user.getUid()).size());
+ following.setFirst(uriComponentsBuilder.path(String.format("/u/%s/followers", userName)).toUriString());
+ return (OrderedCollection) Context.build(following);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/u/{userName}/following", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public OrderedCollectionPage getFollowingPage(@PathVariable String userName,
+ @RequestParam(required = false, defaultValue = "0") int page) {
+ User user = userService.getUserByName(userName);
+ if (!user.isAnonymous()) {
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
+ uriComponentsBuilder.path(String.format("/u/%s/following", userName));
+ List following = userService.getUserFriends(user.getUid());
+ Stream followingPage = following.stream().skip(20 * page).limit(20);
+
+ OrderedCollectionPage result = new OrderedCollectionPage();
+ result.setId(ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString());
+ result.setOrderedItems(followingPage.map(a -> {
+ Person follower = new Person();
+ follower.setName(a.getName());
+ follower.setPreferredUsername(a.getName());
+ follower.setUrl(activityPubManager.personWebUri(a));
+ return follower;
+ }).collect(Collectors.toList()));
+ boolean hasNext = following.size() <= 20 * page;
+ if (hasNext) {
+ result.setNext(uriComponentsBuilder.queryParam("page", page + 1).toUriString());
+ }
+ return (OrderedCollectionPage) Context.build(result);
+ }
+ throw new HttpNotFoundException();
+ }
+
+ @GetMapping(value = "/n/{mid}-{rid}", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public Context showNote(@PathVariable int mid, @PathVariable int rid) {
+ if (rid > 0) {
+ // reply
+ return Context.build(activityPubManager.makeNote(
+ messagesService.getReply(mid, rid)));
+ }
+ return Context.build(activityPubManager.makeNote(
+ messagesService.getMessage(mid).orElseThrow(IllegalStateException::new)));
+ }
+
+ @PostMapping(value = "/api/inbox", consumes = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE})
+ public ResponseEntity processInbox(
+ @Visitor User visitor,
+ InputStream inboxData) throws Exception {
+ String inbox = IOUtils.toString(inboxData, StandardCharsets.UTF_8);
+ logger.info("Inbox: {}", inbox);
+ Activity activity = jsonMapper.readValue(inbox, Activity.class);
+ if ((StringUtils.isNotEmpty(visitor.getUri().toString())
+ && visitor.getUri().equals(URI.create(activity.getActor())))
+ || !visitor.isAnonymous()) {
+ if (activity instanceof Follow) {
+ Follow followRequest = (Follow) activity;
+ applicationEventPublisher.publishEvent(
+ new FollowEvent(this, followRequest));
+ return new ResponseEntity<>(CommandResult.fromString("Follow request accepted"), HttpStatus.ACCEPTED);
+
+ }
+ if (activity instanceof Undo) {
+ Map object = (Map) activity.getObject();
+ String objectType = (String) object.get("type");
+ String objectObject = (String) object.get("object");
+ if (objectType.equals("Follow")) {
+ applicationEventPublisher.publishEvent(new UndoFollowEvent(this, activity.getActor(), objectObject));
+ return new ResponseEntity<>(CommandResult.fromString("Undo follow request accepted"), HttpStatus.OK);
+ } else if (objectType.equals("Like") || objectType.equals("Announce")) {
+ applicationEventPublisher.publishEvent(new UndoAnnounceEvent(this, activity.getActor(), objectObject));
+ return new ResponseEntity<>(CommandResult.fromString("Undo like/announce request accepted"), HttpStatus.OK);
+ }
+ }
+ if (activity instanceof Create) {
+ if (activity.getObject() instanceof Map) {
+ Map note = (Map) activity.getObject();
+ if (note.get("type").equals("Note")) {
+ URI noteId = URI.create((String) note.get("id"));
+ if (messagesService.replyExists(noteId)) {
+ return new ResponseEntity<>(CommandResult.fromString("Reply already exists"), HttpStatus.OK);
+ } else {
+ String inReplyTo = (String) note.get("inReplyTo");
+ if (StringUtils.isNotBlank(inReplyTo)) {
+ if (inReplyTo.startsWith(baseUri)) {
+ String postId = activityPubManager.postId(inReplyTo);
+ User user = new User();
+ user.setUri(URI.create(activity.getActor()));
+ String markdown = remarkConverter.convertFragment((String) note.get("content"));
+ String commandBody = note.get("attachment") == null ? markdown :
+ ((List