Remove possibility to create new replies from core interface.
[Sone.git] / src / main / java / net / pterodactylus / sone / fcp / AbstractSoneCommand.java
1 /*
2  * Sone - AbstractSoneCommand.java - Copyright © 2011–2013 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.Reply;
29 import net.pterodactylus.sone.data.Sone;
30 import net.pterodactylus.sone.freenet.SimpleFieldSetBuilder;
31 import net.pterodactylus.sone.freenet.fcp.AbstractCommand;
32 import net.pterodactylus.sone.freenet.fcp.Command;
33 import net.pterodactylus.sone.freenet.fcp.FcpException;
34 import net.pterodactylus.sone.template.SoneAccessor;
35
36 import com.google.common.collect.Collections2;
37
38 import freenet.node.FSParseException;
39 import freenet.support.SimpleFieldSet;
40
41 /**
42  * Abstract base implementation of a {@link Command} with Sone-related helper
43  * methods.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public abstract class AbstractSoneCommand extends AbstractCommand {
48
49         /** The Sone core. */
50         private final Core core;
51
52         /** Whether this command needs write access. */
53         private final boolean writeAccess;
54
55         /**
56          * Creates a new abstract Sone FCP command.
57          *
58          * @param core
59          *            The Sone core
60          */
61         protected AbstractSoneCommand(Core core) {
62                 this(core, false);
63         }
64
65         /**
66          * Creates a new abstract Sone FCP command.
67          *
68          * @param core
69          *            The Sone core
70          * @param writeAccess
71          *            {@code true} if this command requires write access,
72          *            {@code false} otherwise
73          */
74         protected AbstractSoneCommand(Core core, boolean writeAccess) {
75                 this.core = core;
76                 this.writeAccess = writeAccess;
77         }
78
79         //
80         // ACCESSORS
81         //
82
83         /**
84          * Returns the Sone core.
85          *
86          * @return The Sone core
87          */
88         protected Core getCore() {
89                 return core;
90         }
91
92         /**
93          * Returns whether this command requires write access.
94          *
95          * @return {@code true} if this command require write access, {@code false}
96          *         otherwise
97          */
98         public boolean requiresWriteAccess() {
99                 return writeAccess;
100         }
101
102         //
103         // PROTECTED METHODS
104         //
105
106         /**
107          * Encodes text in a way that makes it possible for the text to be stored in
108          * a {@link SimpleFieldSet}. Backslashes, CR, and LF are prepended with a
109          * backslash.
110          *
111          * @param text
112          *            The text to encode
113          * @return The encoded text
114          */
115         protected static String encodeString(String text) {
116                 return text.replaceAll("\\\\", "\\\\").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
117         }
118
119         /**
120          * Returns a Sone whose ID is a parameter in the given simple field set.
121          *
122          * @param simpleFieldSet
123          *            The simple field set containing the ID of the Sone
124          * @param parameterName
125          *            The name under which the Sone ID is stored in the simple field
126          *            set
127          * @param localOnly
128          *            {@code true} to only return local Sones, {@code false} to
129          *            return any Sones
130          * @return The Sone
131          * @throws FcpException
132          *             if there is no Sone ID stored under the given parameter name,
133          *             or if the Sone ID is invalid
134          */
135         protected Sone getSone(SimpleFieldSet simpleFieldSet, String parameterName, boolean localOnly) throws FcpException {
136                 return getSone(simpleFieldSet, parameterName, localOnly, true);
137         }
138
139         /**
140          * Returns a Sone whose ID is a parameter in the given simple field set.
141          *
142          * @param simpleFieldSet
143          *            The simple field set containing the ID of the Sone
144          * @param parameterName
145          *            The name under which the Sone ID is stored in the simple field
146          *            set
147          * @param localOnly
148          *            {@code true} to only return local Sones, {@code false} to
149          *            return any Sones
150          * @param mandatory
151          *            {@code true} if a valid Sone ID is required, {@code false}
152          *            otherwise
153          * @return The Sone, or {@code null} if {@code mandatory} is {@code false}
154          *         and the Sone ID is invalid
155          * @throws FcpException
156          *             if there is no Sone ID stored under the given parameter name,
157          *             or if {@code mandatory} is {@code true} and the Sone ID is
158          *             invalid
159          */
160         protected Sone getSone(SimpleFieldSet simpleFieldSet, String parameterName, boolean localOnly, boolean mandatory) throws FcpException {
161                 String soneId = simpleFieldSet.get(parameterName);
162                 if (mandatory && (soneId == null)) {
163                         throw new FcpException("Could not load Sone ID from “" + parameterName + "”.");
164                 }
165                 Sone sone = localOnly ? core.getLocalSone(soneId, false) : core.getSone(soneId, false);
166                 if (mandatory && (sone == null)) {
167                         throw new FcpException("Could not load Sone from “" + soneId + "”.");
168                 }
169                 return sone;
170         }
171
172         /**
173          * Returns a post whose ID is a parameter in the given simple field set.
174          *
175          * @param simpleFieldSet
176          *            The simple field set containing the ID of the post
177          * @param parameterName
178          *            The name under which the post ID is stored in the simple field
179          *            set
180          * @return The post
181          * @throws FcpException
182          *             if there is no post ID stored under the given parameter name,
183          *             or if the post ID is invalid
184          */
185         protected Post getPost(SimpleFieldSet simpleFieldSet, String parameterName) throws FcpException {
186                 try {
187                         String postId = simpleFieldSet.getString(parameterName);
188                         Post post = core.getPost(postId);
189                         if (post == null) {
190                                 throw new FcpException("Could not load post from “" + postId + "”.");
191                         }
192                         return post;
193                 } catch (FSParseException fspe1) {
194                         throw new FcpException("Could not post ID from “" + parameterName + "”.", fspe1);
195                 }
196         }
197
198         /**
199          * Returns a reply whose ID is a parameter in the given simple field set.
200          *
201          * @param simpleFieldSet
202          *            The simple field set containing the ID of the reply
203          * @param parameterName
204          *            The name under which the reply ID is stored in the simple
205          *            field set
206          * @return The reply
207          * @throws FcpException
208          *             if there is no reply ID stored under the given parameter
209          *             name, or if the reply ID is invalid
210          */
211         protected PostReply getReply(SimpleFieldSet simpleFieldSet, String parameterName) throws FcpException {
212                 try {
213                         String replyId = simpleFieldSet.getString(parameterName);
214                         PostReply reply = core.getPostReply(replyId);
215                         if (reply == null) {
216                                 throw new FcpException("Could not load reply from “" + replyId + "”.");
217                         }
218                         return reply;
219                 } catch (FSParseException fspe1) {
220                         throw new FcpException("Could not reply ID from “" + parameterName + "”.", fspe1);
221                 }
222         }
223
224         /**
225          * Creates a simple field set from the given Sone, including {@link Profile}
226          * information.
227          *
228          * @param sone
229          *            The Sone to encode
230          * @param prefix
231          *            The prefix for the field names (may be empty but not {@code
232          *            null})
233          * @param localSone
234          *            An optional local Sone that is used for Sone-specific data,
235          *            such as if the Sone is followed by the local Sone
236          * @return The simple field set containing the given Sone
237          */
238         protected static SimpleFieldSet encodeSone(Sone sone, String prefix, Sone localSone) {
239                 SimpleFieldSetBuilder soneBuilder = new SimpleFieldSetBuilder();
240
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 != null) {
245                         soneBuilder.put(prefix + "Followed", String.valueOf(localSone.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(sonePrefix + "ID", sone.getId());
277                         soneBuilder.put(sonePrefix + "Name", sone.getName());
278                         soneBuilder.put(sonePrefix + "NiceName", SoneAccessor.getNiceName(sone));
279                         soneBuilder.put(sonePrefix + "Time", sone.getTime());
280                 }
281
282                 return soneBuilder.get();
283         }
284
285         /**
286          * Creates a simple field set from the given post.
287          *
288          * @param post
289          *            The post to encode
290          * @param prefix
291          *            The prefix for the field names (may be empty but not
292          *            {@code null})
293          * @param includeReplies
294          *            {@code true} to include replies, {@code false} to not include
295          *            replies
296          * @return The simple field set containing the post
297          */
298         protected SimpleFieldSet encodePost(Post post, String prefix, boolean includeReplies) {
299                 SimpleFieldSetBuilder postBuilder = new SimpleFieldSetBuilder();
300
301                 postBuilder.put(prefix + "ID", post.getId());
302                 postBuilder.put(prefix + "Sone", post.getSone().getId());
303                 if (post.getRecipient() != null) {
304                         postBuilder.put(prefix + "Recipient", post.getRecipient().getId());
305                 }
306                 postBuilder.put(prefix + "Time", post.getTime());
307                 postBuilder.put(prefix + "Text", encodeString(post.getText()));
308                 postBuilder.put(encodeLikes(core.getLikes(post), prefix + "Likes."));
309
310                 if (includeReplies) {
311                         List<PostReply> replies = core.getReplies(post);
312                         postBuilder.put(encodeReplies(replies, prefix));
313                 }
314
315                 return postBuilder.get();
316         }
317
318         /**
319          * Creates a simple field set from the given collection of posts.
320          *
321          * @param posts
322          *            The posts to encode
323          * @param prefix
324          *            The prefix for the field names (may be empty but not
325          *            {@code null})
326          * @param includeReplies
327          *            {@code true} to include the replies, {@code false} to not
328          *            include the replies
329          * @return The simple field set containing the posts
330          */
331         protected SimpleFieldSet encodePosts(Collection<? extends Post> posts, String prefix, boolean includeReplies) {
332                 SimpleFieldSetBuilder postBuilder = new SimpleFieldSetBuilder();
333
334                 int postIndex = 0;
335                 postBuilder.put(prefix + "Count", posts.size());
336                 for (Post post : posts) {
337                         String postPrefix = prefix + postIndex++;
338                         postBuilder.put(encodePost(post, postPrefix + ".", includeReplies));
339                         if (includeReplies) {
340                                 postBuilder.put(encodeReplies(Collections2.filter(core.getReplies(post), Reply.FUTURE_REPLY_FILTER), postPrefix + "."));
341                         }
342                 }
343
344                 return postBuilder.get();
345         }
346
347         /**
348          * Creates a simple field set from the given collection of replies.
349          *
350          * @param replies
351          *            The replies to encode
352          * @param prefix
353          *            The prefix for the field names (may be empty, but not
354          *            {@code null})
355          * @return The simple field set containing the replies
356          */
357         protected static SimpleFieldSet encodeReplies(Collection<? extends PostReply> replies, String prefix) {
358                 SimpleFieldSetBuilder replyBuilder = new SimpleFieldSetBuilder();
359
360                 int replyIndex = 0;
361                 replyBuilder.put(prefix + "Replies.Count", replies.size());
362                 for (PostReply reply : replies) {
363                         String replyPrefix = prefix + "Replies." + replyIndex++ + ".";
364                         replyBuilder.put(replyPrefix + "ID", reply.getId());
365                         replyBuilder.put(replyPrefix + "Sone", reply.getSone().getId());
366                         replyBuilder.put(replyPrefix + "Time", reply.getTime());
367                         replyBuilder.put(replyPrefix + "Text", encodeString(reply.getText()));
368                 }
369
370                 return replyBuilder.get();
371         }
372
373         /**
374          * Creates a simple field set from the given collection of Sones that like
375          * an element.
376          *
377          * @param likes
378          *            The liking Sones
379          * @param prefix
380          *            The prefix for the field names (may be empty but not
381          *            {@code null})
382          * @return The simple field set containing the likes
383          */
384         protected static SimpleFieldSet encodeLikes(Collection<? extends Sone> likes, String prefix) {
385                 SimpleFieldSetBuilder likesBuilder = new SimpleFieldSetBuilder();
386
387                 int likeIndex = 0;
388                 likesBuilder.put(prefix + "Count", likes.size());
389                 for (Sone sone : likes) {
390                         String sonePrefix = prefix + likeIndex++ + ".";
391                         likesBuilder.put(sonePrefix + "ID", sone.getId());
392                 }
393
394                 return likesBuilder.get();
395         }
396
397         //
398         // OBJECT METHODS
399         //
400
401         /**
402          * {@inheritDoc}
403          */
404         @Override
405         public String toString() {
406                 return getClass().getName() + "[writeAccess=" + writeAccess + "]";
407         }
408
409 }