Merge branch 'release-0.9.7'
[Sone.git] / src / main / java / net / pterodactylus / sone / fcp / AbstractSoneCommand.java
1 /*
2  * Sone - AbstractSoneCommand.java - Copyright © 2011–2016 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.fcp;
19
20 import java.util.Collection;
21 import java.util.List;
22
23 import net.pterodactylus.sone.core.Core;
24 import net.pterodactylus.sone.data.Post;
25 import net.pterodactylus.sone.data.PostReply;
26 import net.pterodactylus.sone.data.Profile;
27 import net.pterodactylus.sone.data.Profile.Field;
28 import net.pterodactylus.sone.data.Sone;
29 import net.pterodactylus.sone.freenet.SimpleFieldSetBuilder;
30 import net.pterodactylus.sone.freenet.fcp.AbstractCommand;
31 import net.pterodactylus.sone.freenet.fcp.Command;
32 import net.pterodactylus.sone.freenet.fcp.FcpException;
33 import net.pterodactylus.sone.template.SoneAccessor;
34
35 import freenet.node.FSParseException;
36 import freenet.support.SimpleFieldSet;
37
38 import com.google.common.base.Optional;
39
40 /**
41  * Abstract base implementation of a {@link Command} with Sone-related helper
42  * methods.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public abstract class AbstractSoneCommand extends AbstractCommand {
47
48         /** The Sone core. */
49         private final Core core;
50
51         /** Whether this command needs write access. */
52         private final boolean writeAccess;
53
54         /**
55          * Creates a new abstract Sone FCP command.
56          *
57          * @param core
58          *            The Sone core
59          */
60         protected AbstractSoneCommand(Core core) {
61                 this(core, false);
62         }
63
64         /**
65          * Creates a new abstract Sone FCP command.
66          *
67          * @param core
68          *            The Sone core
69          * @param writeAccess
70          *            {@code true} if this command requires write access,
71          *            {@code false} otherwise
72          */
73         protected AbstractSoneCommand(Core core, boolean writeAccess) {
74                 this.core = core;
75                 this.writeAccess = writeAccess;
76         }
77
78         //
79         // ACCESSORS
80         //
81
82         /**
83          * Returns the Sone core.
84          *
85          * @return The Sone core
86          */
87         protected Core getCore() {
88                 return core;
89         }
90
91         /**
92          * Returns whether this command requires write access.
93          *
94          * @return {@code true} if this command require write access, {@code false}
95          *         otherwise
96          */
97         public boolean requiresWriteAccess() {
98                 return writeAccess;
99         }
100
101         //
102         // PROTECTED METHODS
103         //
104
105         /**
106          * Encodes text in a way that makes it possible for the text to be stored in
107          * a {@link SimpleFieldSet}. Backslashes, CR, and LF are prepended with a
108          * backslash.
109          *
110          * @param text
111          *            The text to encode
112          * @return The encoded text
113          */
114         protected static String encodeString(String text) {
115                 return text.replaceAll("\\\\", "\\\\\\\\").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
116         }
117
118         /**
119          * Returns a Sone whose ID is a parameter in the given simple field set.
120          *
121          * @param simpleFieldSet
122          *            The simple field set containing the ID of the Sone
123          * @param parameterName
124          *            The name under which the Sone ID is stored in the simple field
125          *            set
126          * @param localOnly
127          *            {@code true} to only return local Sones, {@code false} to
128          *            return any Sones
129          * @return The Sone
130          * @throws FcpException
131          *             if there is no Sone ID stored under the given parameter name,
132          *             or if the Sone ID is invalid
133          */
134         protected Sone getSone(SimpleFieldSet simpleFieldSet, String parameterName, boolean localOnly) throws FcpException {
135                 return getSone(simpleFieldSet, parameterName, localOnly, true).get();
136         }
137
138         /**
139          * Returns a Sone whose ID is a parameter in the given simple field set.
140          *
141          * @param simpleFieldSet
142          *            The simple field set containing the ID of the Sone
143          * @param parameterName
144          *            The name under which the Sone ID is stored in the simple field
145          *            set
146          * @param localOnly
147          *            {@code true} to only return local Sones, {@code false} to
148          *            return any Sones
149          * @param mandatory
150          *            {@code true} if a valid Sone ID is required, {@code false}
151          *            otherwise
152          * @return The Sone, or {@code null} if {@code mandatory} is {@code false}
153          *         and the Sone ID is invalid
154          * @throws FcpException
155          *             if there is no Sone ID stored under the given parameter name,
156          *             or if {@code mandatory} is {@code true} and the Sone ID is
157          *             invalid
158          */
159         protected Optional<Sone> getSone(SimpleFieldSet simpleFieldSet, String parameterName, boolean localOnly, boolean mandatory) throws FcpException {
160                 String soneId = simpleFieldSet.get(parameterName);
161                 if (mandatory && (soneId == null)) {
162                         throw new FcpException("Could not load Sone ID from “" + parameterName + "”.");
163                 }
164                 Optional<Sone> sone = core.getSone(soneId);
165                 if ((mandatory && !sone.isPresent()) || (sone.isPresent() && localOnly && !sone.get().isLocal())) {
166                         throw new FcpException("Could not load Sone from “" + soneId + "”.");
167                 }
168                 return sone;
169         }
170
171         /**
172          * Returns a post whose ID is a parameter in the given simple field set.
173          *
174          * @param simpleFieldSet
175          *            The simple field set containing the ID of the post
176          * @param parameterName
177          *            The name under which the post ID is stored in the simple field
178          *            set
179          * @return The post
180          * @throws FcpException
181          *             if there is no post ID stored under the given parameter name,
182          *             or if the post ID is invalid
183          */
184         protected Post getPost(SimpleFieldSet simpleFieldSet, String parameterName) throws FcpException {
185                 try {
186                         String postId = simpleFieldSet.getString(parameterName);
187                         Optional<Post> post = core.getPost(postId);
188                         if (!post.isPresent()) {
189                                 throw new FcpException("Could not load post from “" + postId + "”.");
190                         }
191                         return post.get();
192                 } catch (FSParseException fspe1) {
193                         throw new FcpException("Could not post ID from “" + parameterName + "”.", fspe1);
194                 }
195         }
196
197         /**
198          * Returns a reply whose ID is a parameter in the given simple field set.
199          *
200          * @param simpleFieldSet
201          *            The simple field set containing the ID of the reply
202          * @param parameterName
203          *            The name under which the reply ID is stored in the simple
204          *            field set
205          * @return The reply
206          * @throws FcpException
207          *             if there is no reply ID stored under the given parameter
208          *             name, or if the reply ID is invalid
209          */
210         protected PostReply getReply(SimpleFieldSet simpleFieldSet, String parameterName) throws FcpException {
211                 try {
212                         String replyId = simpleFieldSet.getString(parameterName);
213                         Optional<PostReply> reply = core.getPostReply(replyId);
214                         if (!reply.isPresent()) {
215                                 throw new FcpException("Could not load reply from “" + replyId + "”.");
216                         }
217                         return reply.get();
218                 } catch (FSParseException fspe1) {
219                         throw new FcpException("Could not reply ID from “" + parameterName + "”.", fspe1);
220                 }
221         }
222
223         /**
224          * Creates a simple field set from the given Sone, including {@link Profile}
225          * information.
226          *
227          * @param sone
228          *            The Sone to encode
229          * @param prefix
230          *            The prefix for the field names (may be empty but not {@code
231          *            null})
232          * @param localSone
233          *            An optional local Sone that is used for Sone-specific data,
234          *            such as if the Sone is followed by the local Sone
235          * @return The simple field set containing the given Sone
236          */
237         protected static SimpleFieldSet encodeSone(Sone sone, String prefix, Optional<Sone> localSone) {
238                 SimpleFieldSetBuilder soneBuilder = new SimpleFieldSetBuilder();
239
240                 soneBuilder.put(prefix + "ID", sone.getId());
241                 soneBuilder.put(prefix + "Name", sone.getName());
242                 soneBuilder.put(prefix + "NiceName", SoneAccessor.getNiceName(sone));
243                 soneBuilder.put(prefix + "LastUpdated", sone.getTime());
244                 if (localSone.isPresent()) {
245                         soneBuilder.put(prefix + "Followed", String.valueOf(localSone.get().hasFriend(sone.getId())));
246                 }
247                 Profile profile = sone.getProfile();
248                 soneBuilder.put(prefix + "Field.Count", profile.getFields().size());
249                 int fieldIndex = 0;
250                 for (Field field : profile.getFields()) {
251                         soneBuilder.put(prefix + "Field." + fieldIndex + ".Name", field.getName());
252                         soneBuilder.put(prefix + "Field." + fieldIndex + ".Value", field.getValue());
253                         ++fieldIndex;
254                 }
255
256                 return soneBuilder.get();
257         }
258
259         /**
260          * Creates a simple field set from the given collection of Sones.
261          *
262          * @param sones
263          *            The Sones to encode
264          * @param prefix
265          *            The prefix for the field names (may be empty but not
266          *            {@code null})
267          * @return The simple field set containing the given Sones
268          */
269         protected static SimpleFieldSet encodeSones(Collection<? extends Sone> sones, String prefix) {
270                 SimpleFieldSetBuilder soneBuilder = new SimpleFieldSetBuilder();
271
272                 int soneIndex = 0;
273                 soneBuilder.put(prefix + "Count", sones.size());
274                 for (Sone sone : sones) {
275                         String sonePrefix = prefix + soneIndex++ + ".";
276                         soneBuilder.put(encodeSone(sone, sonePrefix, Optional.<Sone>absent()));
277                 }
278
279                 return soneBuilder.get();
280         }
281
282         /**
283          * Creates a simple field set from the given post.
284          *
285          * @param post
286          *            The post to encode
287          * @param prefix
288          *            The prefix for the field names (may be empty but not
289          *            {@code null})
290          * @param includeReplies
291          *            {@code true} to include replies, {@code false} to not include
292          *            replies
293          * @return The simple field set containing the post
294          */
295         protected SimpleFieldSet encodePost(Post post, String prefix, boolean includeReplies) {
296                 SimpleFieldSetBuilder postBuilder = new SimpleFieldSetBuilder();
297
298                 postBuilder.put(prefix + "ID", post.getId());
299                 postBuilder.put(prefix + "Sone", post.getSone().getId());
300                 if (post.getRecipientId().isPresent()) {
301                         postBuilder.put(prefix + "Recipient", post.getRecipientId().get());
302                 }
303                 postBuilder.put(prefix + "Time", post.getTime());
304                 postBuilder.put(prefix + "Text", encodeString(post.getText()));
305                 postBuilder.put(encodeLikes(core.getLikes(post), prefix + "Likes."));
306
307                 if (includeReplies) {
308                         List<PostReply> replies = core.getReplies(post.getId());
309                         postBuilder.put(encodeReplies(replies, prefix));
310                 }
311
312                 return postBuilder.get();
313         }
314
315         /**
316          * Creates a simple field set from the given collection of posts.
317          *
318          * @param posts
319          *            The posts to encode
320          * @param prefix
321          *            The prefix for the field names (may be empty but not
322          *            {@code null})
323          * @param includeReplies
324          *            {@code true} to include the replies, {@code false} to not
325          *            include the replies
326          * @return The simple field set containing the posts
327          */
328         protected SimpleFieldSet encodePosts(Collection<? extends Post> posts, String prefix, boolean includeReplies) {
329                 SimpleFieldSetBuilder postBuilder = new SimpleFieldSetBuilder();
330
331                 int postIndex = 0;
332                 postBuilder.put(prefix + "Count", posts.size());
333                 for (Post post : posts) {
334                         String postPrefix = prefix + postIndex++;
335                         postBuilder.put(encodePost(post, postPrefix + ".", includeReplies));
336                 }
337
338                 return postBuilder.get();
339         }
340
341         /**
342          * Creates a simple field set from the given collection of replies.
343          *
344          * @param replies
345          *            The replies to encode
346          * @param prefix
347          *            The prefix for the field names (may be empty, but not
348          *            {@code null})
349          * @return The simple field set containing the replies
350          */
351         protected SimpleFieldSet encodeReplies(Collection<? extends PostReply> replies, String prefix) {
352                 SimpleFieldSetBuilder replyBuilder = new SimpleFieldSetBuilder();
353
354                 int replyIndex = 0;
355                 replyBuilder.put(prefix + "Replies.Count", replies.size());
356                 for (PostReply reply : replies) {
357                         String replyPrefix = prefix + "Replies." + replyIndex++ + ".";
358                         replyBuilder.put(replyPrefix + "ID", reply.getId());
359                         replyBuilder.put(replyPrefix + "Sone", reply.getSone().getId());
360                         replyBuilder.put(replyPrefix + "Time", reply.getTime());
361                         replyBuilder.put(replyPrefix + "Text", encodeString(reply.getText()));
362                         replyBuilder.put(encodeLikes(core.getLikes(reply), replyPrefix + "Likes."));
363                 }
364
365                 return replyBuilder.get();
366         }
367
368         /**
369          * Creates a simple field set from the given collection of Sones that like
370          * an element.
371          *
372          * @param likes
373          *            The liking Sones
374          * @param prefix
375          *            The prefix for the field names (may be empty but not
376          *            {@code null})
377          * @return The simple field set containing the likes
378          */
379         protected static SimpleFieldSet encodeLikes(Collection<? extends Sone> likes, String prefix) {
380                 SimpleFieldSetBuilder likesBuilder = new SimpleFieldSetBuilder();
381
382                 int likeIndex = 0;
383                 likesBuilder.put(prefix + "Count", likes.size());
384                 for (Sone sone : likes) {
385                         String sonePrefix = prefix + likeIndex++ + ".";
386                         likesBuilder.put(sonePrefix + "ID", sone.getId());
387                 }
388
389                 return likesBuilder.get();
390         }
391
392         //
393         // OBJECT METHODS
394         //
395
396         /**
397          * {@inheritDoc}
398          */
399         @Override
400         public String toString() {
401                 return getClass().getName() + "[writeAccess=" + writeAccess + "]";
402         }
403
404 }