Add method to get all replies for a post.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * FreenetSone - Core.java - Copyright © 2010 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.core;
19
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.UUID;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32
33 import net.pterodactylus.sone.core.SoneException.Type;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.Profile;
36 import net.pterodactylus.sone.data.Reply;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.util.config.Configuration;
39 import net.pterodactylus.util.config.ConfigurationException;
40 import net.pterodactylus.util.logging.Logging;
41 import net.pterodactylus.util.service.AbstractService;
42 import freenet.keys.FreenetURI;
43
44 /**
45  * The Sone core.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class Core extends AbstractService {
50
51         /** The logger. */
52         private static final Logger logger = Logging.getLogger(Core.class);
53
54         /** The configuration. */
55         private Configuration configuration;
56
57         /** Interface to freenet. */
58         private FreenetInterface freenetInterface;
59
60         /** The Sone downloader. */
61         private SoneDownloader soneDownloader;
62
63         /** The local Sones. */
64         private final Set<Sone> localSones = new HashSet<Sone>();
65
66         /** Sone inserters. */
67         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
68
69         /* various caches follow here. */
70
71         /** Cache for all known Sones. */
72         private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
73
74         /** Cache for all known posts. */
75         private final Map<String, Post> postCache = new HashMap<String, Post>();
76
77         /** Cache for all known replies. */
78         private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
79
80         /**
81          * Creates a new core.
82          */
83         public Core() {
84                 super("Sone Core");
85         }
86
87         //
88         // ACCESSORS
89         //
90
91         /**
92          * Sets the configuration of the core.
93          *
94          * @param configuration
95          *            The configuration of the core
96          * @return This core (for method chaining)
97          */
98         public Core configuration(Configuration configuration) {
99                 this.configuration = configuration;
100                 return this;
101         }
102
103         /**
104          * Sets the Freenet interface to use.
105          *
106          * @param freenetInterface
107          *            The Freenet interface to use
108          * @return This core (for method chaining)
109          */
110         public Core freenetInterface(FreenetInterface freenetInterface) {
111                 this.freenetInterface = freenetInterface;
112                 soneDownloader = new SoneDownloader(this, freenetInterface);
113                 soneDownloader.start();
114                 return this;
115         }
116
117         /**
118          * Returns the local Sones.
119          *
120          * @return The local Sones
121          */
122         public Set<Sone> getSones() {
123                 return Collections.unmodifiableSet(localSones);
124         }
125
126         /**
127          * Returns the Sone with the given ID, or an empty Sone that has been
128          * initialized with the given ID.
129          *
130          * @param soneId
131          *            The ID of the Sone
132          * @return The Sone
133          */
134         public Sone getSone(String soneId) {
135                 if (!soneCache.containsKey(soneId)) {
136                         Sone sone = new Sone(soneId);
137                         soneCache.put(soneId, sone);
138                 }
139                 return soneCache.get(soneId);
140         }
141
142         /**
143          * Creates a new post.
144          *
145          * @param sone
146          *            The sone that creates the post
147          * @param text
148          *            The text of the post
149          * @return The created post
150          */
151         public Post createPost(Sone sone, String text) {
152                 return createPost(sone, System.currentTimeMillis(), text);
153         }
154
155         /**
156          * Creates a new post.
157          *
158          * @param sone
159          *            The Sone that creates the post
160          * @param time
161          *            The time of the post
162          * @param text
163          *            The text of the post
164          * @return The created post
165          */
166         public Post createPost(Sone sone, long time, String text) {
167                 return getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
168         }
169
170         //
171         // ACTIONS
172         //
173
174         /**
175          * Adds the given Sone.
176          *
177          * @param sone
178          *            The Sone to add
179          */
180         public void addLocalSone(Sone sone) {
181                 if (localSones.add(sone)) {
182                         soneCache.put(sone.getId(), sone);
183                         SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
184                         soneInserter.start();
185                         soneDownloader.addSone(sone);
186                         soneInserters.put(sone, soneInserter);
187                 }
188         }
189
190         /**
191          * Adds a remote Sone so that it is watched for updates.
192          *
193          * @param sone
194          *            The sone to watch
195          */
196         public void addSone(Sone sone) {
197                 if (!soneCache.containsKey(sone.getId())) {
198                         soneCache.put(sone.getId(), sone);
199                 }
200                 soneDownloader.addSone(sone);
201         }
202
203         /**
204          * Creates a new Sone at a random location.
205          *
206          * @param name
207          *            The name of the Sone
208          * @return The created Sone
209          * @throws SoneException
210          *             if a Sone error occurs
211          */
212         public Sone createSone(String name) throws SoneException {
213                 return createSone(name, null, null);
214         }
215
216         /**
217          * Creates a new Sone at the given location. If one of {@code requestUri} or
218          * {@code insertUrI} is {@code null}, the Sone is created at a random
219          * location.
220          *
221          * @param name
222          *            The name of the Sone
223          * @param requestUri
224          *            The request URI of the Sone, or {@link NullPointerException}
225          *            to create a Sone at a random location
226          * @param insertUri
227          *            The insert URI of the Sone, or {@code null} to create a Sone
228          *            at a random location
229          * @return The created Sone
230          * @throws SoneException
231          *             if a Sone error occurs
232          */
233         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
234                 if ((name == null) || (name.trim().length() == 0)) {
235                         throw new SoneException(Type.INVALID_SONE_NAME);
236                 }
237                 String finalRequestUri;
238                 String finalInsertUri;
239                 if ((requestUri == null) || (insertUri == null)) {
240                         String[] keyPair = freenetInterface.generateKeyPair();
241                         finalRequestUri = keyPair[0];
242                         finalInsertUri = keyPair[1];
243                 } else {
244                         finalRequestUri = requestUri;
245                         finalInsertUri = insertUri;
246                 }
247                 Sone sone;
248                 try {
249                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
250                         sone = new Sone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName("Sone-" + name)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName("Sone-" + name));
251                         sone.setProfile(new Profile());
252                         /* set modification counter to 1 so it is inserted immediately. */
253                         sone.setModificationCounter(1);
254                         addLocalSone(sone);
255                 } catch (MalformedURLException mue1) {
256                         throw new SoneException(Type.INVALID_URI);
257                 }
258                 return sone;
259         }
260
261         /**
262          * Deletes the given Sone from this plugin instance.
263          *
264          * @param sone
265          *            The sone to delete
266          */
267         public void deleteSone(Sone sone) {
268                 SoneInserter soneInserter = soneInserters.remove(sone);
269                 soneInserter.stop();
270                 localSones.remove(sone);
271         }
272
273         /**
274          * Returns the post with the given ID. If no post exists yet with the given
275          * ID, a new post is returned.
276          *
277          * @param postId
278          *            The ID of the post
279          * @return The post
280          */
281         public Post getPost(String postId) {
282                 if (!postCache.containsKey(postId)) {
283                         postCache.put(postId, new Post(postId));
284                 }
285                 return postCache.get(postId);
286         }
287
288         /**
289          * Returns the reply with the given ID. If no reply exists yet with the
290          * given ID, a new reply is returned.
291          *
292          * @param replyId
293          *            The ID of the reply
294          * @return The reply
295          */
296         public Reply getReply(String replyId) {
297                 if (!replyCache.containsKey(replyId)) {
298                         replyCache.put(replyId, new Reply(replyId));
299                 }
300                 return replyCache.get(replyId);
301         }
302
303         /**
304          * Gets all replies to the given post, sorted by date, oldest first.
305          *
306          * @param post
307          *            The post the replies refer to
308          * @return The sorted list of replies for the post
309          */
310         public List<Reply> getReplies(Post post) {
311                 List<Reply> replies = new ArrayList<Reply>();
312                 for (Reply reply : replyCache.values()) {
313                         if (reply.getPost().equals(post)) {
314                                 replies.add(reply);
315                         }
316                 }
317                 Collections.sort(replies, new Comparator<Reply>() {
318
319                         /**
320                          * {@inheritDoc}
321                          */
322                         @Override
323                         public int compare(Reply leftReply, Reply rightReply) {
324                                 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
325                         }
326                 });
327                 return replies;
328         }
329
330         //
331         // SERVICE METHODS
332         //
333
334         /**
335          * {@inheritDoc}
336          */
337         @Override
338         protected void serviceStart() {
339                 loadConfiguration();
340         }
341
342         /**
343          * {@inheritDoc}
344          */
345         @Override
346         protected void serviceStop() {
347                 soneDownloader.stop();
348                 /* stop all Sone inserters. */
349                 for (SoneInserter soneInserter : soneInserters.values()) {
350                         soneInserter.stop();
351                 }
352                 saveConfiguration();
353         }
354
355         //
356         // PRIVATE METHODS
357         //
358
359         /**
360          * Loads the configuration.
361          */
362         private void loadConfiguration() {
363                 logger.entering(Core.class.getName(), "loadConfiguration()");
364
365                 /* parse local Sones. */
366                 logger.log(Level.INFO, "Loading Sones…");
367                 int soneId = 0;
368                 do {
369                         String sonePrefix = "Sone/Sone." + soneId++;
370                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
371                         if (id == null) {
372                                 break;
373                         }
374                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
375                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
376                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
377                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
378                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
379                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
380                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
381                         try {
382                                 Profile profile = new Profile();
383                                 profile.setFirstName(firstName);
384                                 profile.setMiddleName(middleName);
385                                 profile.setLastName(lastName);
386                                 Sone sone = new Sone(id).setName(name).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
387                                 soneCache.put(id, sone);
388                                 sone.setProfile(profile);
389                                 int postId = 0;
390                                 do {
391                                         String postPrefix = sonePrefix + "/Post." + postId++;
392                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
393                                         if (id == null) {
394                                                 break;
395                                         }
396                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
397                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
398                                         Post post = getPost(id).setSone(sone).setTime(time).setText(text);
399                                         sone.addPost(post);
400                                 } while (true);
401                                 int replyCounter = 0;
402                                 do {
403                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
404                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
405                                         if (replyId == null) {
406                                                 break;
407                                         }
408                                         Sone replySone = getSone(configuration.getStringValue(replyPrefix + "/Sone/ID").getValue(null));
409                                         String replySoneKey = configuration.getStringValue(replyPrefix + "/Sone/Key").getValue(null);
410                                         String replySoneName = configuration.getStringValue(replyPrefix + "/Sone/Name").getValue(null);
411                                         replySone.setRequestUri(new FreenetURI(replySoneKey)).setName(replySoneName);
412                                         Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
413                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
414                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
415                                         Reply reply = getReply(replyId).setSone(replySone).setPost(replyPost).setTime(replyTime).setText(replyText);
416                                         replyCache.put(replyId, reply);
417                                 } while (true);
418
419                                 /* load friends. */
420                                 int friendCounter = 0;
421                                 while (true) {
422                                         String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
423                                         String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
424                                         if (friendId == null) {
425                                                 break;
426                                         }
427                                         Sone friendSone = getSone(friendId);
428                                         String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
429                                         String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
430                                         friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
431                                         addSone(friendSone);
432                                         sone.addFriend(sone);
433                                 }
434
435                                 sone.setModificationCounter(modificationCounter);
436                                 addLocalSone(sone);
437                         } catch (MalformedURLException mue1) {
438                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
439                         }
440                 } while (true);
441                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
442
443                 logger.exiting(Core.class.getName(), "loadConfiguration()");
444         }
445
446         /**
447          * Saves the configuraiton.
448          */
449         private void saveConfiguration() {
450                 Set<Sone> sones = getSones();
451                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
452                 try {
453                         /* store all Sones. */
454                         int soneId = 0;
455                         for (Sone sone : localSones) {
456                                 String sonePrefix = "Sone/Sone." + soneId++;
457                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
458                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
459                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
460                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
461                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
462                                 Profile profile = sone.getProfile();
463                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
464                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
465                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
466                                 int postId = 0;
467                                 for (Post post : sone.getPosts()) {
468                                         String postPrefix = sonePrefix + "/Post." + postId++;
469                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
470                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
471                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
472                                 }
473                                 /* write null ID as terminator. */
474                                 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
475
476                                 int replyId = 0;
477                                 for (Reply reply : sone.getReplies()) {
478                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
479                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
480                                         configuration.getStringValue(replyPrefix + "/Sone/ID").setValue(reply.getSone().getId());
481                                         configuration.getStringValue(replyPrefix + "/Sone/Key").setValue(reply.getSone().getRequestUri().toString());
482                                         configuration.getStringValue(replyPrefix + "/Sone/Name").setValue(reply.getSone().getName());
483                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
484                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
485                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
486                                 }
487                                 /* write null ID as terminator. */
488                                 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
489
490                                 int friendId = 0;
491                                 for (Sone friend : sone.getFriends()) {
492                                         String friendPrefix = sonePrefix + "/Friend." + friendId++;
493                                         configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
494                                         configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
495                                         configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
496                                 }
497                                 /* write null ID as terminator. */
498                                 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
499
500                         }
501                         /* write null ID as terminator. */
502                         configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
503
504                 } catch (ConfigurationException ce1) {
505                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
506                 }
507         }
508
509 }