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