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