aboutsummaryrefslogtreecommitdiff
path: root/juick-server/src/main/java/com/juick/server/ActivityPubManager.java
blob: 41dd52eb4fe5f350314f117341cb4839ac049226 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package com.juick.server;

import com.juick.Message;
import com.juick.User;
import com.juick.formatters.PlainTextFormatter;
import com.juick.server.api.activity.model.Context;
import com.juick.server.api.activity.model.objects.*;
import com.juick.server.api.activity.model.activities.Accept;
import com.juick.server.api.activity.model.activities.Announce;
import com.juick.server.api.activity.model.activities.Create;
import com.juick.server.api.activity.model.activities.Delete;
import com.juick.server.util.HttpUtils;
import com.juick.service.SocialService;
import com.juick.service.UserService;
import com.juick.service.activities.*;
import com.juick.service.component.*;
import com.juick.util.MessageUtils;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class ActivityPubManager implements ActivityListener, NotificationListener {
    private static final Logger logger = LoggerFactory.getLogger(ActivityPubManager.class);
    @Inject
    private SignatureManager signatureManager;
    @Inject
    private SocialService socialService;
    @Inject
    private UserService userService;
    @Inject
    private PebbleEngine pebbleEngine;
    @Value("${ap_base_uri:http://localhost:8080/}")
    private String baseUri;
    @Value("${service_user:juick}")
    private String serviceUsername;

    private User serviceUser;

    @PostConstruct
    public void init() {
        serviceUser = userService.getUserByName(serviceUsername);
    }

    @Override
    public void processFollowEvent(@Nonnull FollowEvent followEvent) {
        String acct = (String)followEvent.getRequest().getObject();
        logger.info("received follower request to {}", acct);
        User followedUser = socialService.getUserByAccountUri(acct);
        if (!followedUser.isAnonymous()) {
            // automatically accept follower requests
            Person me = (Person) signatureManager.getContext(URI.create(acct)).get();
            Person follower = (Person) signatureManager.getContext(URI.create(followEvent.getRequest().getActor())).get();
            Accept accept = new Accept();
            accept.setActor(me.getId());
            accept.setObject(followEvent.getRequest());
            try {
                signatureManager.post(me, follower, accept);
                socialService.addFollower(followedUser, follower.getId());
                logger.info("Follower added for {}", followedUser.getName());
            } catch (IOException e) {
                logger.info("activitypub exception", e);
            }
        }
    }

    @Override
    public void undoFollowEvent(UndoFollowEvent event) {
        String actor = event.getActor();
        String me = event.getObject();
        logger.info("{} stopping to follow {}", actor, me);
        User followedUser = socialService.getUserByAccountUri(me);
        if (!followedUser.isAnonymous()) {
            socialService.removeFollower(followedUser, actor);
        }
    }

    @Override
    public void deleteUserEvent(DeleteUserEvent event) {
        String acct = event.getUserUri();
        logger.info("Deleting {} from followers", acct);
        socialService.removeAccount(acct);
    }

    @Override
    public void deleteMessageEvent(DeleteMessageEvent event) {
        Message msg = event.getMessage();
        User user = msg.getUser();
        String userUri = personUri(user);
        Note note = makeNote(msg);
        Person me = (Person) signatureManager.getContext(URI.create(userUri)).get();
        socialService.getFollowers(user).forEach(acct -> {
            Person follower = (Person) signatureManager.getContext(URI.create(acct)).get();
            Delete delete = new Delete();
            delete.setId(note.getId());
            delete.setActor(me.getId());
            delete.setPublished(note.getPublished());
            delete.setObject(note);
            try {
                logger.info("Deletion to follower {}", follower.getId());
                signatureManager.post(me, follower, delete);
            } catch (IOException e) {
                logger.warn("activitypub exception", e);
            }
        });
    }

    @Override
    public void processMessageEvent(MessageEvent messageEvent) {
        Message msg = messageEvent.getMessage();
        if (MessageUtils.isPM(msg)) {
            return;
        }
        User user = msg.getUser();
        String userUri = personUri(user);
        Note note = makeNote(msg);
        Person me = (Person) signatureManager.getContext(URI.create(userUri)).get();
        Set<String> subscribers = new HashSet<>(socialService.getFollowers(user));
        if (MessageUtils.isReply(msg) && msg.getTo().getUri().toASCIIString().length() > 0) {
            String replier = msg.getTo().getUri().toASCIIString();
            subscribers.add(replier);
            List<String> cc = new ArrayList<>(note.getCc());
            cc.add(replier);
            note.setCc(cc);
        }
        subscribers.forEach(acct -> {
            Optional<Context> context = signatureManager.getContext(URI.create(acct));
            if (context.isPresent()) {
                Person follower = (Person)context.get();
                Create create = new Create();
                create.setId(note.getId());
                create.setActor(me.getId());
                create.setPublished(note.getPublished());
                create.setObject(note);
                try {
                    logger.info("Posting to subscriber {}", follower.getId());
                    signatureManager.post(me, follower, create);
                } catch (IOException e) {
                    logger.warn("activitypub exception", e);
                }
            }
        });
    }

    public String inboxUri() {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath("/api/inbox").toUriString();
    }

    public String outboxUri(User user) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath(String.format("/u/%s/blog/toc", user.getName())).toUriString();
    }

    public String personUri(User user) {
        if (user.getUri().toString().length() > 0) {
            return user.getUri().toASCIIString();
        }
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath(String.format("/u/%s", user.getName())).toUriString();
    }
    public String personWebUri(User user) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath(String.format("/%s/", user.getName())).toUriString();
    }

    public String followersUri(User user) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath(String.format("/u/%s/followers/toc", user.getName())).toUriString();
    }

    public String followingUri(User user) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath(String.format("/u/%s/following/toc", user.getName())).toUriString();
    }
    public String messageUri(Message msg) {
        return messageUri(msg.getMid(), msg.getRid());
    }
    public String messageUri(int mid, int rid) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        uri.replacePath(String.format("/n/%d-%d", mid, rid));
        return uri.toUriString();
    }
    public String tagUri(com.juick.Tag tag) {
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri);
        return uri.replacePath(String.format("/t/%s", tag.getName())).toUriString();
    }

    public Note makeNote(Message msg) {
        Note note = new Note();
        note.setId(messageUri(msg));
        note.setUrl(PlainTextFormatter.formatUrl(msg));
        note.setAttributedTo(personUri(msg.getUser()));
        if (MessageUtils.isReply(msg)) {
            if (msg.getReplyToUri().toASCIIString().length() > 0) {
                note.setInReplyTo(msg.getReplyToUri().toASCIIString());
            } else {
                note.setInReplyTo(messageUri(msg.getMid(), msg.getReplyto()));
            }
        }
        if (MessageUtils.isPM(msg)) {
            note.setTo(Collections.singletonList(personUri(msg.getTo())));
        } else {
            note.setTo(Collections.singletonList("https://www.w3.org/ns/activitystreams#Public"));
            note.setCc(Collections.singletonList(followersUri(msg.getUser())));
        }
        note.setPublished(msg.getTimestamp());
        if (StringUtils.isNotBlank(msg.getAttachmentType())) {
            Image attachment = new Image();
            attachment.setId(msg.getAttachment().getMedium().getUrl());
            attachment.setUrl(msg.getAttachment().getMedium().getUrl());
            attachment.setMediaType(HttpUtils.mediaType(msg.getAttachmentType()));
            note.setAttachment(Collections.singletonList(attachment));
        }
        note.setTags(msg.getTags().stream().map(t -> {
            Hashtag hashtag = new Hashtag();
            hashtag.setId(tagUri(t));
            hashtag.setName(t.getName());
            return hashtag;
        }).collect(Collectors.toList()));
        if (msg.getReplyToUri() != null && msg.getReplyToUri().toASCIIString().length() > 0) {
            Optional<Context> noteContext = signatureManager.getContext(msg.getReplyToUri());
            if (noteContext.isPresent()) {
                Note activity = (Note) noteContext.get();
                Optional<Context> personContext = signatureManager.getContext(URI.create(activity.getAttributedTo()));
                if (personContext.isPresent()) {
                    Person person = (Person) personContext.get();
                    note.getTags().add(new Mention(person.getUrl(), person.getPreferredUsername()));
                    msg.getTo().setName(person.getPreferredUsername());
                    note.setInReplyTo(activity.getInReplyTo());
                }
            }
        } else if (MessageUtils.isReply(msg)) {
            note.getTags().add(new Mention(personWebUri(msg.getTo()), msg.getTo().getName()));
        }
        if (msg.isHtml()) {
            note.setContent(msg.getText());
        } else {
            PebbleTemplate noteTemplate = pebbleEngine.getTemplate("layouts/note");
            Map<String, Object> context = new HashMap<>();
            context.put("msg", msg);
            context.put("baseUri", baseUri);
            try {
                Writer writer = new StringWriter();
                noteTemplate.evaluate(writer, context);
                note.setContent(writer.toString());
            } catch (IOException e) {
                logger.warn("template not rendered, falling back");
                note.setContent(MessageUtils.formatMessage(StringUtils.defaultString(msg.getText())));
            }
        }
        return note;
    }

    @Override
    public void processSubscribeEvent(SubscribeEvent subscribeEvent) {

    }

    @Override
    public void processLikeEvent(LikeEvent likeEvent) {

    }

    @Override
    public void processPingEvent(PingEvent pingEvent) {

    }

    @Override
    public void processMessageReadEvent(MessageReadEvent messageReadEvent) {

    }

    @Override
    public void processTopEvent(TopEvent topEvent) {
        Message message = topEvent.getMessage();
        Note note = makeNote(message);
        Announce announce = new Announce();
        announce.setId(note.getId() + "#top");
        announce.setActor(personUri(serviceUser));
        announce.setObject(note);
        Person me = (Person) signatureManager.getContext(URI.create(announce.getActor())).get();
        socialService.getFollowers(serviceUser).forEach(acct -> {
            Person follower = (Person) signatureManager.getContext(URI.create(acct)).get();
            try {
                logger.info("Announcing top: {}", message.getMid());
                signatureManager.post(me, follower, announce);
            } catch (IOException e) {
                logger.warn("activitypub exception", e);
            }
        });
    }
}