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