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