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