Add unit test for get sone command, fix some bugs
[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 + "Name", sone.getName());
241                 soneBuilder.put(prefix + "NiceName", SoneAccessor.getNiceName(sone));
242                 soneBuilder.put(prefix + "LastUpdated", sone.getTime());
243                 if (localSone.isPresent()) {
244                         soneBuilder.put(prefix + "Followed", String.valueOf(localSone.get().hasFriend(sone.getId())));
245                 }
246                 Profile profile = sone.getProfile();
247                 soneBuilder.put(prefix + "Field.Count", profile.getFields().size());
248                 int fieldIndex = 0;
249                 for (Field field : profile.getFields()) {
250                         soneBuilder.put(prefix + "Field." + fieldIndex + ".Name", field.getName());
251                         soneBuilder.put(prefix + "Field." + fieldIndex + ".Value", field.getValue());
252                         ++fieldIndex;
253                 }
254
255                 return soneBuilder.get();
256         }
257
258         /**
259          * Creates a simple field set from the given collection of Sones.
260          *
261          * @param sones
262          *            The Sones to encode
263          * @param prefix
264          *            The prefix for the field names (may be empty but not
265          *            {@code null})
266          * @return The simple field set containing the given Sones
267          */
268         protected static SimpleFieldSet encodeSones(Collection<? extends Sone> sones, String prefix) {
269                 SimpleFieldSetBuilder soneBuilder = new SimpleFieldSetBuilder();
270
271                 int soneIndex = 0;
272                 soneBuilder.put(prefix + "Count", sones.size());
273                 for (Sone sone : sones) {
274                         String sonePrefix = prefix + soneIndex++ + ".";
275                         soneBuilder.put(sonePrefix + "ID", sone.getId());
276                         soneBuilder.put(sonePrefix + "Name", sone.getName());
277                         soneBuilder.put(sonePrefix + "NiceName", SoneAccessor.getNiceName(sone));
278                         soneBuilder.put(sonePrefix + "Time", sone.getTime());
279                 }
280
281                 return soneBuilder.get();
282         }
283
284         /**
285          * Creates a simple field set from the given post.
286          *
287          * @param post
288          *            The post to encode
289          * @param prefix
290          *            The prefix for the field names (may be empty but not
291          *            {@code null})
292          * @param includeReplies
293          *            {@code true} to include replies, {@code false} to not include
294          *            replies
295          * @return The simple field set containing the post
296          */
297         protected SimpleFieldSet encodePost(Post post, String prefix, boolean includeReplies) {
298                 SimpleFieldSetBuilder postBuilder = new SimpleFieldSetBuilder();
299
300                 postBuilder.put(prefix + "ID", post.getId());
301                 postBuilder.put(prefix + "Sone", post.getSone().getId());
302                 if (post.getRecipientId().isPresent()) {
303                         postBuilder.put(prefix + "Recipient", post.getRecipientId().get());
304                 }
305                 postBuilder.put(prefix + "Time", post.getTime());
306                 postBuilder.put(prefix + "Text", encodeString(post.getText()));
307                 postBuilder.put(encodeLikes(core.getLikes(post), prefix + "Likes."));
308
309                 if (includeReplies) {
310                         List<PostReply> replies = core.getReplies(post.getId());
311                         postBuilder.put(encodeReplies(replies, prefix));
312                 }
313
314                 return postBuilder.get();
315         }
316
317         /**
318          * Creates a simple field set from the given collection of posts.
319          *
320          * @param posts
321          *            The posts to encode
322          * @param prefix
323          *            The prefix for the field names (may be empty but not
324          *            {@code null})
325          * @param includeReplies
326          *            {@code true} to include the replies, {@code false} to not
327          *            include the replies
328          * @return The simple field set containing the posts
329          */
330         protected SimpleFieldSet encodePosts(Collection<? extends Post> posts, String prefix, boolean includeReplies) {
331                 SimpleFieldSetBuilder postBuilder = new SimpleFieldSetBuilder();
332
333                 int postIndex = 0;
334                 postBuilder.put(prefix + "Count", posts.size());
335                 for (Post post : posts) {
336                         String postPrefix = prefix + postIndex++;
337                         postBuilder.put(encodePost(post, postPrefix + ".", includeReplies));
338                 }
339
340                 return postBuilder.get();
341         }
342
343         /**
344          * Creates a simple field set from the given collection of replies.
345          *
346          * @param replies
347          *            The replies to encode
348          * @param prefix
349          *            The prefix for the field names (may be empty, but not
350          *            {@code null})
351          * @return The simple field set containing the replies
352          */
353         protected SimpleFieldSet encodeReplies(Collection<? extends PostReply> replies, String prefix) {
354                 SimpleFieldSetBuilder replyBuilder = new SimpleFieldSetBuilder();
355
356                 int replyIndex = 0;
357                 replyBuilder.put(prefix + "Replies.Count", replies.size());
358                 for (PostReply reply : replies) {
359                         String replyPrefix = prefix + "Replies." + replyIndex++ + ".";
360                         replyBuilder.put(replyPrefix + "ID", reply.getId());
361                         replyBuilder.put(replyPrefix + "Sone", reply.getSone().getId());
362                         replyBuilder.put(replyPrefix + "Time", reply.getTime());
363                         replyBuilder.put(replyPrefix + "Text", encodeString(reply.getText()));
364                         replyBuilder.put(encodeLikes(core.getLikes(reply), replyPrefix + "Likes."));
365                 }
366
367                 return replyBuilder.get();
368         }
369
370         /**
371          * Creates a simple field set from the given collection of Sones that like
372          * an element.
373          *
374          * @param likes
375          *            The liking Sones
376          * @param prefix
377          *            The prefix for the field names (may be empty but not
378          *            {@code null})
379          * @return The simple field set containing the likes
380          */
381         protected static SimpleFieldSet encodeLikes(Collection<? extends Sone> likes, String prefix) {
382                 SimpleFieldSetBuilder likesBuilder = new SimpleFieldSetBuilder();
383
384                 int likeIndex = 0;
385                 likesBuilder.put(prefix + "Count", likes.size());
386                 for (Sone sone : likes) {
387                         String sonePrefix = prefix + likeIndex++ + ".";
388                         likesBuilder.put(sonePrefix + "ID", sone.getId());
389                 }
390
391                 return likesBuilder.get();
392         }
393
394         //
395         // OBJECT METHODS
396         //
397
398         /**
399          * {@inheritDoc}
400          */
401         @Override
402         public String toString() {
403                 return getClass().getName() + "[writeAccess=" + writeAccess + "]";
404         }
405
406 }