8ce908b700aa8b4eb86a0bc81c1a645676200895
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2013 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 static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import net.pterodactylus.sone.core.Options.DefaultOption;
40 import net.pterodactylus.sone.core.Options.Option;
41 import net.pterodactylus.sone.core.Options.OptionWatcher;
42 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
43 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
46 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
47 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
48 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
49 import net.pterodactylus.sone.core.event.PostRemovedEvent;
50 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneLockedEvent;
52 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.AlbumImpl;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.data.TemporaryImage;
67 import net.pterodactylus.sone.database.Database;
68 import net.pterodactylus.sone.database.DatabaseException;
69 import net.pterodactylus.sone.database.PostBuilder;
70 import net.pterodactylus.sone.database.PostProvider;
71 import net.pterodactylus.sone.database.PostReplyBuilder;
72 import net.pterodactylus.sone.database.PostReplyProvider;
73 import net.pterodactylus.sone.database.SoneProvider;
74 import net.pterodactylus.sone.fcp.FcpInterface;
75 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
76 import net.pterodactylus.sone.freenet.wot.Identity;
77 import net.pterodactylus.sone.freenet.wot.IdentityManager;
78 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
84 import net.pterodactylus.sone.main.SonePlugin;
85 import net.pterodactylus.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
92
93 import com.google.common.base.Optional;
94 import com.google.common.base.Predicate;
95 import com.google.common.base.Predicates;
96 import com.google.common.collect.FluentIterable;
97 import com.google.common.collect.HashMultimap;
98 import com.google.common.collect.ImmutableSet;
99 import com.google.common.collect.Multimap;
100 import com.google.common.collect.Multimaps;
101 import com.google.common.eventbus.EventBus;
102 import com.google.common.eventbus.Subscribe;
103 import com.google.inject.Inject;
104
105 import freenet.keys.FreenetURI;
106
107 /**
108  * The Sone core.
109  *
110  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
111  */
112 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
113
114         /** The logger. */
115         private static final Logger logger = Logging.getLogger(Core.class);
116
117         /** The start time. */
118         private final long startupTime = System.currentTimeMillis();
119
120         /** The options. */
121         private final Options options = new Options();
122
123         /** The preferences. */
124         private final Preferences preferences = new Preferences(options);
125
126         /** The event bus. */
127         private final EventBus eventBus;
128
129         /** The configuration. */
130         private Configuration configuration;
131
132         /** Whether we’re currently saving the configuration. */
133         private boolean storingConfiguration = false;
134
135         /** The identity manager. */
136         private final IdentityManager identityManager;
137
138         /** Interface to freenet. */
139         private final FreenetInterface freenetInterface;
140
141         /** The Sone downloader. */
142         private final SoneDownloader soneDownloader;
143
144         /** The image inserter. */
145         private final ImageInserter imageInserter;
146
147         /** Sone downloader thread-pool. */
148         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
149
150         /** The update checker. */
151         private final UpdateChecker updateChecker;
152
153         /** The trust updater. */
154         private final WebOfTrustUpdater webOfTrustUpdater;
155
156         /** The FCP interface. */
157         private volatile FcpInterface fcpInterface;
158
159         /** The times Sones were followed. */
160         private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
161
162         /** Locked local Sones. */
163         /* synchronize on itself. */
164         private final Set<Sone> lockedSones = new HashSet<Sone>();
165
166         /** Sone inserters. */
167         /* synchronize access on this on sones. */
168         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
169
170         /** Sone rescuers. */
171         /* synchronize access on this on sones. */
172         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
173
174         /** All Sones. */
175         /* synchronize access on this on itself. */
176         private final Map<String, Sone> sones = new HashMap<String, Sone>();
177
178         /** All known Sones. */
179         private final Set<String> knownSones = new HashSet<String>();
180
181         /** The post database. */
182         private final Database database;
183
184         /** All bookmarked posts. */
185         /* synchronize access on itself. */
186         private final Set<String> bookmarkedPosts = new HashSet<String>();
187
188         /** Trusted identities, sorted by own identities. */
189         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
190
191         /** All known images. */
192         private final Map<String, Image> images = new HashMap<String, Image>();
193
194         /** All temporary images. */
195         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
196
197         /** Ticker for threads that mark own elements as known. */
198         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
199
200         /** The time the configuration was last touched. */
201         private volatile long lastConfigurationUpdate;
202
203         /**
204          * Creates a new core.
205          *
206          * @param configuration
207          *            The configuration of the core
208          * @param freenetInterface
209          *            The freenet interface
210          * @param identityManager
211          *            The identity manager
212          * @param webOfTrustUpdater
213          *            The WebOfTrust updater
214          * @param eventBus
215          *            The event bus
216          * @param database
217          *            The database
218          */
219         @Inject
220         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
221                 super("Sone Core");
222                 this.configuration = configuration;
223                 this.freenetInterface = freenetInterface;
224                 this.identityManager = identityManager;
225                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226                 this.imageInserter = new ImageInserter(freenetInterface);
227                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
228                 this.webOfTrustUpdater = webOfTrustUpdater;
229                 this.eventBus = eventBus;
230                 this.database = database;
231         }
232
233         //
234         // ACCESSORS
235         //
236
237         /**
238          * Returns the time Sone was started.
239          *
240          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
241          */
242         public long getStartupTime() {
243                 return startupTime;
244         }
245
246         /**
247          * Sets the configuration to use. This will automatically save the current
248          * configuration to the given configuration.
249          *
250          * @param configuration
251          *            The new configuration to use
252          */
253         public void setConfiguration(Configuration configuration) {
254                 this.configuration = configuration;
255                 touchConfiguration();
256         }
257
258         /**
259          * Returns the options used by the core.
260          *
261          * @return The options of the core
262          */
263         public Preferences getPreferences() {
264                 return preferences;
265         }
266
267         /**
268          * Returns the identity manager used by the core.
269          *
270          * @return The identity manager
271          */
272         public IdentityManager getIdentityManager() {
273                 return identityManager;
274         }
275
276         /**
277          * Returns the update checker.
278          *
279          * @return The update checker
280          */
281         public UpdateChecker getUpdateChecker() {
282                 return updateChecker;
283         }
284
285         /**
286          * Sets the FCP interface to use.
287          *
288          * @param fcpInterface
289          *            The FCP interface to use
290          */
291         public void setFcpInterface(FcpInterface fcpInterface) {
292                 this.fcpInterface = fcpInterface;
293         }
294
295         /**
296          * Returns the Sone rescuer for the given local Sone.
297          *
298          * @param sone
299          *            The local Sone to get the rescuer for
300          * @return The Sone rescuer for the given Sone
301          */
302         public SoneRescuer getSoneRescuer(Sone sone) {
303                 checkNotNull(sone, "sone must not be null");
304                 checkArgument(sone.isLocal(), "sone must be local");
305                 synchronized (sones) {
306                         SoneRescuer soneRescuer = soneRescuers.get(sone);
307                         if (soneRescuer == null) {
308                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
309                                 soneRescuers.put(sone, soneRescuer);
310                                 soneRescuer.start();
311                         }
312                         return soneRescuer;
313                 }
314         }
315
316         /**
317          * Returns whether the given Sone is currently locked.
318          *
319          * @param sone
320          *            The sone to check
321          * @return {@code true} if the Sone is locked, {@code false} if it is not
322          */
323         public boolean isLocked(Sone sone) {
324                 synchronized (lockedSones) {
325                         return lockedSones.contains(sone);
326                 }
327         }
328
329         /**
330          * {@inheritDocs}
331          */
332         @Override
333         public Collection<Sone> getSones() {
334                 synchronized (sones) {
335                         return ImmutableSet.copyOf(sones.values());
336                 }
337         }
338
339         /**
340          * Returns the Sone with the given ID, regardless whether it’s local or
341          * remote.
342          *
343          * @param id
344          *            The ID of the Sone to get
345          * @return The Sone with the given ID, or {@code null} if there is no such
346          *         Sone
347          */
348         @Override
349         public Optional<Sone> getSone(String id) {
350                 synchronized (sones) {
351                         return Optional.fromNullable(sones.get(id));
352                 }
353         }
354
355         /**
356          * {@inheritDocs}
357          */
358         @Override
359         public Collection<Sone> getLocalSones() {
360                 synchronized (sones) {
361                         return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
362
363                                 @Override
364                                 public boolean apply(Sone sone) {
365                                         return sone.isLocal();
366                                 }
367                         }).toSet();
368                 }
369         }
370
371         /**
372          * Returns the local Sone with the given ID, optionally creating a new Sone.
373          *
374          * @param id
375          *            The ID of the Sone
376          * @param create
377          *            {@code true} to create a new Sone if none exists,
378          *            {@code false} to return null if none exists
379          * @return The Sone with the given ID, or {@code null}
380          */
381         public Sone getLocalSone(String id, boolean create) {
382                 synchronized (sones) {
383                         Sone sone = sones.get(id);
384                         if ((sone == null) && create) {
385                                 sone = new Sone(id, true);
386                                 sones.put(id, sone);
387                         }
388                         if ((sone != null) && !sone.isLocal()) {
389                                 sone = new Sone(id, true);
390                                 sones.put(id, sone);
391                         }
392                         return sone;
393                 }
394         }
395
396         /**
397          * {@inheritDocs}
398          */
399         @Override
400         public Collection<Sone> getRemoteSones() {
401                 synchronized (sones) {
402                         return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
403
404                                 @Override
405                                 public boolean apply(Sone sone) {
406                                         return !sone.isLocal();
407                                 }
408                         }).toSet();
409                 }
410         }
411
412         /**
413          * Returns the remote Sone with the given ID.
414          *
415          * @param id
416          *            The ID of the remote Sone to get
417          * @param create
418          *            {@code true} to always create a Sone, {@code false} to return
419          *            {@code null} if no Sone with the given ID exists
420          * @return The Sone with the given ID
421          */
422         public Sone getRemoteSone(String id, boolean create) {
423                 synchronized (sones) {
424                         Sone sone = sones.get(id);
425                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
426                                 sone = new Sone(id, false);
427                                 sones.put(id, sone);
428                         }
429                         return sone;
430                 }
431         }
432
433         /**
434          * Returns whether the given Sone has been modified.
435          *
436          * @param sone
437          *            The Sone to check for modifications
438          * @return {@code true} if a modification has been detected in the Sone,
439          *         {@code false} otherwise
440          */
441         public boolean isModifiedSone(Sone sone) {
442                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
443         }
444
445         /**
446          * Returns the time when the given was first followed by any local Sone.
447          *
448          * @param sone
449          *            The Sone to get the time for
450          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
451          *         been followed, or {@link Long#MAX_VALUE}
452          */
453         public long getSoneFollowingTime(Sone sone) {
454                 synchronized (soneFollowingTimes) {
455                         return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
456                 }
457         }
458
459         /**
460          * Returns whether the target Sone is trusted by the origin Sone.
461          *
462          * @param origin
463          *            The origin Sone
464          * @param target
465          *            The target Sone
466          * @return {@code true} if the target Sone is trusted by the origin Sone
467          */
468         public boolean isSoneTrusted(Sone origin, Sone target) {
469                 checkNotNull(origin, "origin must not be null");
470                 checkNotNull(target, "target must not be null");
471                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
472                 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
473         }
474
475         /**
476          * Returns a post builder.
477          *
478          * @return A new post builder
479          */
480         public PostBuilder postBuilder() {
481                 return database.newPostBuilder();
482         }
483
484         /**
485          * {@inheritDoc}
486          */
487         @Override
488         public Optional<Post> getPost(String postId) {
489                 return database.getPost(postId);
490         }
491
492         /**
493          * {@inheritDocs}
494          */
495         @Override
496         public Collection<Post> getPosts(String soneId) {
497                 return database.getPosts(soneId);
498         }
499
500         /**
501          * {@inheritDoc}
502          */
503         @Override
504         public Collection<Post> getDirectedPosts(final String recipientId) {
505                 checkNotNull(recipientId, "recipient must not be null");
506                 return database.getDirectedPosts(recipientId);
507         }
508
509         /**
510          * Returns a post reply builder.
511          *
512          * @return A new post reply builder
513          */
514         public PostReplyBuilder postReplyBuilder() {
515                 return database.newPostReplyBuilder();
516         }
517
518         /**
519          * {@inheritDoc}
520          */
521         @Override
522         public Optional<PostReply> getPostReply(String replyId) {
523                 return database.getPostReply(replyId);
524         }
525
526         /**
527          * {@inheritDoc}
528          */
529         @Override
530         public List<PostReply> getReplies(final String postId) {
531                 return database.getReplies(postId);
532         }
533
534         /**
535          * Returns all Sones that have liked the given post.
536          *
537          * @param post
538          *            The post to get the liking Sones for
539          * @return The Sones that like the given post
540          */
541         public Set<Sone> getLikes(Post post) {
542                 Set<Sone> sones = new HashSet<Sone>();
543                 for (Sone sone : getSones()) {
544                         if (sone.getLikedPostIds().contains(post.getId())) {
545                                 sones.add(sone);
546                         }
547                 }
548                 return sones;
549         }
550
551         /**
552          * Returns all Sones that have liked the given reply.
553          *
554          * @param reply
555          *            The reply to get the liking Sones for
556          * @return The Sones that like the given reply
557          */
558         public Set<Sone> getLikes(PostReply reply) {
559                 Set<Sone> sones = new HashSet<Sone>();
560                 for (Sone sone : getSones()) {
561                         if (sone.getLikedReplyIds().contains(reply.getId())) {
562                                 sones.add(sone);
563                         }
564                 }
565                 return sones;
566         }
567
568         /**
569          * Returns whether the given post is bookmarked.
570          *
571          * @param post
572          *            The post to check
573          * @return {@code true} if the given post is bookmarked, {@code false}
574          *         otherwise
575          */
576         public boolean isBookmarked(Post post) {
577                 return isPostBookmarked(post.getId());
578         }
579
580         /**
581          * Returns whether the post with the given ID is bookmarked.
582          *
583          * @param id
584          *            The ID of the post to check
585          * @return {@code true} if the post with the given ID is bookmarked,
586          *         {@code false} otherwise
587          */
588         public boolean isPostBookmarked(String id) {
589                 synchronized (bookmarkedPosts) {
590                         return bookmarkedPosts.contains(id);
591                 }
592         }
593
594         /**
595          * Returns all currently known bookmarked posts.
596          *
597          * @return All bookmarked posts
598          */
599         public Set<Post> getBookmarkedPosts() {
600                 Set<Post> posts = new HashSet<Post>();
601                 synchronized (bookmarkedPosts) {
602                         for (String bookmarkedPostId : bookmarkedPosts) {
603                                 Optional<Post> post = getPost(bookmarkedPostId);
604                                 if (post.isPresent()) {
605                                         posts.add(post.get());
606                                 }
607                         }
608                 }
609                 return posts;
610         }
611
612         /**
613          * Returns the album with the given ID, creating a new album if no album
614          * with the given ID can be found.
615          *
616          * @param albumId
617          *            The ID of the album
618          * @return The album with the given ID
619          */
620         public Album getAlbum(String albumId) {
621                 return getAlbum(albumId, true);
622         }
623
624         /**
625          * Returns the album with the given ID, optionally creating a new album if
626          * an album with the given ID can not be found.
627          *
628          * @param albumId
629          *            The ID of the album
630          * @param create
631          *            {@code true} to create a new album if none exists for the
632          *            given ID
633          * @return The album with the given ID, or {@code null} if no album with the
634          *         given ID exists and {@code create} is {@code false}
635          */
636         public Album getAlbum(String albumId, boolean create) {
637                 Optional<Album> album = database.getAlbum(albumId);
638                 if (album.isPresent()) {
639                         return album.get();
640                 }
641                 if (!create) {
642                         return null;
643                 }
644                 Album newAlbum = new AlbumImpl(albumId);
645                 database.storeAlbum(newAlbum);
646                 return newAlbum;
647         }
648
649         /**
650          * Returns the image with the given ID, creating it if necessary.
651          *
652          * @param imageId
653          *            The ID of the image
654          * @return The image with the given ID
655          */
656         public Image getImage(String imageId) {
657                 return getImage(imageId, true);
658         }
659
660         /**
661          * Returns the image with the given ID, optionally creating it if it does
662          * not exist.
663          *
664          * @param imageId
665          *            The ID of the image
666          * @param create
667          *            {@code true} to create an image if none exists with the given
668          *            ID
669          * @return The image with the given ID, or {@code null} if none exists and
670          *         none was created
671          */
672         public Image getImage(String imageId, boolean create) {
673                 synchronized (images) {
674                         Image image = images.get(imageId);
675                         if (create && (image == null)) {
676                                 image = new Image(imageId);
677                                 images.put(imageId, image);
678                         }
679                         return image;
680                 }
681         }
682
683         /**
684          * Returns the temporary image with the given ID.
685          *
686          * @param imageId
687          *            The ID of the temporary image
688          * @return The temporary image, or {@code null} if there is no temporary
689          *         image with the given ID
690          */
691         public TemporaryImage getTemporaryImage(String imageId) {
692                 synchronized (temporaryImages) {
693                         return temporaryImages.get(imageId);
694                 }
695         }
696
697         //
698         // ACTIONS
699         //
700
701         /**
702          * Locks the given Sone. A locked Sone will not be inserted by
703          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
704          * again.
705          *
706          * @param sone
707          *            The sone to lock
708          */
709         public void lockSone(Sone sone) {
710                 synchronized (lockedSones) {
711                         if (lockedSones.add(sone)) {
712                                 eventBus.post(new SoneLockedEvent(sone));
713                         }
714                 }
715         }
716
717         /**
718          * Unlocks the given Sone.
719          *
720          * @see #lockSone(Sone)
721          * @param sone
722          *            The sone to unlock
723          */
724         public void unlockSone(Sone sone) {
725                 synchronized (lockedSones) {
726                         if (lockedSones.remove(sone)) {
727                                 eventBus.post(new SoneUnlockedEvent(sone));
728                         }
729                 }
730         }
731
732         /**
733          * Adds a local Sone from the given own identity.
734          *
735          * @param ownIdentity
736          *            The own identity to create a Sone from
737          * @return The added (or already existing) Sone
738          */
739         public Sone addLocalSone(OwnIdentity ownIdentity) {
740                 if (ownIdentity == null) {
741                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
742                         return null;
743                 }
744                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
745                 synchronized (sones) {
746                         final Sone sone;
747                         try {
748                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
749                         } catch (MalformedURLException mue1) {
750                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
751                                 return null;
752                         }
753                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
754                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
755                         sone.setKnown(true);
756                         /* TODO - load posts ’n stuff */
757                         sones.put(ownIdentity.getId(), sone);
758                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
759                         soneInserters.put(sone, soneInserter);
760                         sone.setStatus(SoneStatus.idle);
761                         loadSone(sone);
762                         soneInserter.start();
763                         return sone;
764                 }
765         }
766
767         /**
768          * Creates a new Sone for the given own identity.
769          *
770          * @param ownIdentity
771          *            The own identity to create a Sone for
772          * @return The created Sone
773          */
774         public Sone createSone(OwnIdentity ownIdentity) {
775                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
776                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
777                         return null;
778                 }
779                 Sone sone = addLocalSone(ownIdentity);
780                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
781                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
782                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
783                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
784                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
785                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
786
787                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
788                 touchConfiguration();
789                 return sone;
790         }
791
792         /**
793          * Adds the Sone of the given identity.
794          *
795          * @param identity
796          *            The identity whose Sone to add
797          * @return The added or already existing Sone
798          */
799         public Sone addRemoteSone(Identity identity) {
800                 if (identity == null) {
801                         logger.log(Level.WARNING, "Given Identity is null!");
802                         return null;
803                 }
804                 synchronized (sones) {
805                         final Sone sone = getRemoteSone(identity.getId(), true);
806                         if (sone.isLocal()) {
807                                 return sone;
808                         }
809                         sone.setIdentity(identity);
810                         boolean newSone = sone.getRequestUri() == null;
811                         sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
812                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
813                         if (newSone) {
814                                 synchronized (knownSones) {
815                                         newSone = !knownSones.contains(sone.getId());
816                                 }
817                                 sone.setKnown(!newSone);
818                                 if (newSone) {
819                                         eventBus.post(new NewSoneFoundEvent(sone));
820                                         for (Sone localSone : getLocalSones()) {
821                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
822                                                         followSone(localSone, sone.getId());
823                                                 }
824                                         }
825                                 }
826                         }
827                         soneDownloader.addSone(sone);
828                         soneDownloaders.execute(new Runnable() {
829
830                                 @Override
831                                 @SuppressWarnings("synthetic-access")
832                                 public void run() {
833                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
834                                 }
835
836                         });
837                         return sone;
838                 }
839         }
840
841         /**
842          * Lets the given local Sone follow the Sone with the given ID.
843          *
844          * @param sone
845          *            The local Sone that should follow another Sone
846          * @param soneId
847          *            The ID of the Sone to follow
848          */
849         public void followSone(Sone sone, String soneId) {
850                 checkNotNull(sone, "sone must not be null");
851                 checkNotNull(soneId, "soneId must not be null");
852                 sone.addFriend(soneId);
853                 synchronized (soneFollowingTimes) {
854                         if (!soneFollowingTimes.containsKey(soneId)) {
855                                 long now = System.currentTimeMillis();
856                                 soneFollowingTimes.put(soneId, now);
857                                 Optional<Sone> followedSone = getSone(soneId);
858                                 if (!followedSone.isPresent()) {
859                                         return;
860                                 }
861                                 for (Post post : followedSone.get().getPosts()) {
862                                         if (post.getTime() < now) {
863                                                 markPostKnown(post);
864                                         }
865                                 }
866                                 for (PostReply reply : followedSone.get().getReplies()) {
867                                         if (reply.getTime() < now) {
868                                                 markReplyKnown(reply);
869                                         }
870                                 }
871                         }
872                 }
873                 touchConfiguration();
874         }
875
876         /**
877          * Lets the given local Sone unfollow the Sone with the given ID.
878          *
879          * @param sone
880          *            The local Sone that should unfollow another Sone
881          * @param soneId
882          *            The ID of the Sone being unfollowed
883          */
884         public void unfollowSone(Sone sone, String soneId) {
885                 checkNotNull(sone, "sone must not be null");
886                 checkNotNull(soneId, "soneId must not be null");
887                 sone.removeFriend(soneId);
888                 boolean unfollowedSoneStillFollowed = false;
889                 for (Sone localSone : getLocalSones()) {
890                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
891                 }
892                 if (!unfollowedSoneStillFollowed) {
893                         synchronized (soneFollowingTimes) {
894                                 soneFollowingTimes.remove(soneId);
895                         }
896                 }
897                 touchConfiguration();
898         }
899
900         /**
901          * Sets the trust value of the given origin Sone for the target Sone.
902          *
903          * @param origin
904          *            The origin Sone
905          * @param target
906          *            The target Sone
907          * @param trustValue
908          *            The trust value (from {@code -100} to {@code 100})
909          */
910         public void setTrust(Sone origin, Sone target, int trustValue) {
911                 checkNotNull(origin, "origin must not be null");
912                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
913                 checkNotNull(target, "target must not be null");
914                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
915                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
916         }
917
918         /**
919          * Removes any trust assignment for the given target Sone.
920          *
921          * @param origin
922          *            The trust origin
923          * @param target
924          *            The trust target
925          */
926         public void removeTrust(Sone origin, Sone target) {
927                 checkNotNull(origin, "origin must not be null");
928                 checkNotNull(target, "target must not be null");
929                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
930                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
931         }
932
933         /**
934          * Assigns the configured positive trust value for the given target.
935          *
936          * @param origin
937          *            The trust origin
938          * @param target
939          *            The trust target
940          */
941         public void trustSone(Sone origin, Sone target) {
942                 setTrust(origin, target, preferences.getPositiveTrust());
943         }
944
945         /**
946          * Assigns the configured negative trust value for the given target.
947          *
948          * @param origin
949          *            The trust origin
950          * @param target
951          *            The trust target
952          */
953         public void distrustSone(Sone origin, Sone target) {
954                 setTrust(origin, target, preferences.getNegativeTrust());
955         }
956
957         /**
958          * Removes the trust assignment for the given target.
959          *
960          * @param origin
961          *            The trust origin
962          * @param target
963          *            The trust target
964          */
965         public void untrustSone(Sone origin, Sone target) {
966                 removeTrust(origin, target);
967         }
968
969         /**
970          * Updates the stored Sone with the given Sone.
971          *
972          * @param sone
973          *            The updated Sone
974          */
975         public void updateSone(Sone sone) {
976                 updateSone(sone, false);
977         }
978
979         /**
980          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
981          * {@code true}, an older Sone than the current Sone can be given to restore
982          * an old state.
983          *
984          * @param sone
985          *            The Sone to update
986          * @param soneRescueMode
987          *            {@code true} if the stored Sone should be updated regardless
988          *            of the age of the given Sone
989          */
990         public void updateSone(Sone sone, boolean soneRescueMode) {
991                 Optional<Sone> storedSone = getSone(sone.getId());
992                 if (storedSone.isPresent()) {
993                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
994                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
995                                 return;
996                         }
997                         /* find removed posts. */
998                         Collection<Post> existingPosts = database.getPosts(sone.getId());
999                         for (Post oldPost : existingPosts) {
1000                                 if (!sone.getPosts().contains(oldPost)) {
1001                                         eventBus.post(new PostRemovedEvent(oldPost));
1002                                 }
1003                         }
1004                         /* find new posts. */
1005                         for (Post newPost : sone.getPosts()) {
1006                                 if (existingPosts.contains(newPost)) {
1007                                         continue;
1008                                 }
1009                                 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1010                                         newPost.setKnown(true);
1011                                 } else if (!newPost.isKnown()) {
1012                                         eventBus.post(new NewPostFoundEvent(newPost));
1013                                 }
1014                         }
1015                         /* store posts. */
1016                         database.storePosts(sone, sone.getPosts());
1017                         if (!soneRescueMode) {
1018                                 for (PostReply reply : storedSone.get().getReplies()) {
1019                                         if (!sone.getReplies().contains(reply)) {
1020                                                 eventBus.post(new PostReplyRemovedEvent(reply));
1021                                         }
1022                                 }
1023                         }
1024                         Set<PostReply> storedReplies = storedSone.get().getReplies();
1025                         for (PostReply reply : sone.getReplies()) {
1026                                 if (storedReplies.contains(reply)) {
1027                                         continue;
1028                                 }
1029                                 if (reply.getTime() < getSoneFollowingTime(sone)) {
1030                                         reply.setKnown(true);
1031                                 } else if (!reply.isKnown()) {
1032                                         eventBus.post(new NewPostReplyFoundEvent(reply));
1033                                 }
1034                         }
1035                         database.storePostReplies(sone, sone.getReplies());
1036                         synchronized (images) {
1037                                 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1038                                         database.removeAlbum(album);
1039                                         for (Image image : album.getImages()) {
1040                                                 images.remove(image.getId());
1041                                         }
1042                                 }
1043                                 for (Album album : sone.getRootAlbum().getAlbums()) {
1044                                         database.storeAlbum(album);
1045                                         for (Image image : album.getImages()) {
1046                                                 images.put(image.getId(), image);
1047                                         }
1048                                 }
1049                         }
1050                         synchronized (sones) {
1051                                 sone.setOptions(storedSone.get().getOptions());
1052                                 sone.setKnown(storedSone.get().isKnown());
1053                                 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1054                                 if (sone.isLocal()) {
1055                                         soneInserters.get(storedSone.get()).setSone(sone);
1056                                         touchConfiguration();
1057                                 }
1058                                 sones.put(sone.getId(), sone);
1059                         }
1060                 }
1061         }
1062
1063         /**
1064          * Deletes the given Sone. This will remove the Sone from the
1065          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1066          * remove the context from its identity.
1067          *
1068          * @param sone
1069          *            The Sone to delete
1070          */
1071         public void deleteSone(Sone sone) {
1072                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1073                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1074                         return;
1075                 }
1076                 synchronized (sones) {
1077                         if (!getLocalSones().contains(sone)) {
1078                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1079                                 return;
1080                         }
1081                         sones.remove(sone.getId());
1082                         SoneInserter soneInserter = soneInserters.remove(sone);
1083                         soneInserter.stop();
1084                 }
1085                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1086                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1087                 try {
1088                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1089                 } catch (ConfigurationException ce1) {
1090                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1091                 }
1092         }
1093
1094         /**
1095          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1096          * known} before, a {@link MarkSoneKnownEvent} is fired.
1097          *
1098          * @param sone
1099          *            The Sone to mark as known
1100          */
1101         public void markSoneKnown(Sone sone) {
1102                 if (!sone.isKnown()) {
1103                         sone.setKnown(true);
1104                         synchronized (knownSones) {
1105                                 knownSones.add(sone.getId());
1106                         }
1107                         eventBus.post(new MarkSoneKnownEvent(sone));
1108                         touchConfiguration();
1109                 }
1110         }
1111
1112         /**
1113          * Loads and updates the given Sone from the configuration. If any error is
1114          * encountered, loading is aborted and the given Sone is not changed.
1115          *
1116          * @param sone
1117          *            The Sone to load and update
1118          */
1119         public void loadSone(Sone sone) {
1120                 if (!sone.isLocal()) {
1121                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1122                         return;
1123                 }
1124                 logger.info(String.format("Loading local Sone: %s", sone));
1125
1126                 /* initialize options. */
1127                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1128                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1129                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1130                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1131                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1132                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1133
1134                 /* load Sone. */
1135                 String sonePrefix = "Sone/" + sone.getId();
1136                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1137                 if (soneTime == null) {
1138                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1139                         return;
1140                 }
1141                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1142
1143                 /* load profile. */
1144                 Profile profile = new Profile(sone);
1145                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1146                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1147                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1148                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1149                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1150                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1151
1152                 /* load profile fields. */
1153                 while (true) {
1154                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1155                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1156                         if (fieldName == null) {
1157                                 break;
1158                         }
1159                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1160                         profile.addField(fieldName).setValue(fieldValue);
1161                 }
1162
1163                 /* load posts. */
1164                 Set<Post> posts = new HashSet<Post>();
1165                 while (true) {
1166                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1167                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1168                         if (postId == null) {
1169                                 break;
1170                         }
1171                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1172                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1173                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1174                         if ((postTime == 0) || (postText == null)) {
1175                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1176                                 return;
1177                         }
1178                         PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1179                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1180                                 postBuilder.to(postRecipientId);
1181                         }
1182                         posts.add(postBuilder.build());
1183                 }
1184
1185                 /* load replies. */
1186                 Set<PostReply> replies = new HashSet<PostReply>();
1187                 while (true) {
1188                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1189                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1190                         if (replyId == null) {
1191                                 break;
1192                         }
1193                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1194                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1195                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1196                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1197                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1198                                 return;
1199                         }
1200                         PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1201                         replies.add(postReplyBuilder.build());
1202                 }
1203
1204                 /* load post likes. */
1205                 Set<String> likedPostIds = new HashSet<String>();
1206                 while (true) {
1207                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1208                         if (likedPostId == null) {
1209                                 break;
1210                         }
1211                         likedPostIds.add(likedPostId);
1212                 }
1213
1214                 /* load reply likes. */
1215                 Set<String> likedReplyIds = new HashSet<String>();
1216                 while (true) {
1217                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1218                         if (likedReplyId == null) {
1219                                 break;
1220                         }
1221                         likedReplyIds.add(likedReplyId);
1222                 }
1223
1224                 /* load friends. */
1225                 Set<String> friends = new HashSet<String>();
1226                 while (true) {
1227                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1228                         if (friendId == null) {
1229                                 break;
1230                         }
1231                         friends.add(friendId);
1232                 }
1233
1234                 /* load albums. */
1235                 List<Album> topLevelAlbums = new ArrayList<Album>();
1236                 int albumCounter = 0;
1237                 while (true) {
1238                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1239                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1240                         if (albumId == null) {
1241                                 break;
1242                         }
1243                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1244                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1245                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1246                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1247                         if ((albumTitle == null) || (albumDescription == null)) {
1248                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1249                                 return;
1250                         }
1251                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1252                         if (albumParentId != null) {
1253                                 Album parentAlbum = getAlbum(albumParentId, false);
1254                                 if (parentAlbum == null) {
1255                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1256                                         return;
1257                                 }
1258                                 parentAlbum.addAlbum(album);
1259                         } else {
1260                                 if (!topLevelAlbums.contains(album)) {
1261                                         topLevelAlbums.add(album);
1262                                 }
1263                         }
1264                 }
1265
1266                 /* load images. */
1267                 int imageCounter = 0;
1268                 while (true) {
1269                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1270                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1271                         if (imageId == null) {
1272                                 break;
1273                         }
1274                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1275                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1276                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1277                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1278                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1279                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1280                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1281                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1282                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1283                                 return;
1284                         }
1285                         Album album = getAlbum(albumId, false);
1286                         if (album == null) {
1287                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1288                                 return;
1289                         }
1290                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1291                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1292                         album.addImage(image);
1293                 }
1294
1295                 /* load avatar. */
1296                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1297                 if (avatarId != null) {
1298                         profile.setAvatar(getImage(avatarId, false));
1299                 }
1300
1301                 /* load options. */
1302                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1303                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1304                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1305                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1306                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1307                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1308
1309                 /* if we’re still here, Sone was loaded successfully. */
1310                 synchronized (sone) {
1311                         sone.setTime(soneTime);
1312                         sone.setProfile(profile);
1313                         sone.setPosts(posts);
1314                         sone.setReplies(replies);
1315                         sone.setLikePostIds(likedPostIds);
1316                         sone.setLikeReplyIds(likedReplyIds);
1317                         for (String friendId : friends) {
1318                                 followSone(sone, friendId);
1319                         }
1320                         for (Album album : sone.getRootAlbum().getAlbums()) {
1321                                 sone.getRootAlbum().removeAlbum(album);
1322                         }
1323                         for (Album album : topLevelAlbums) {
1324                                 sone.getRootAlbum().addAlbum(album);
1325                         }
1326                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1327                 }
1328                 synchronized (knownSones) {
1329                         for (String friend : friends) {
1330                                 knownSones.add(friend);
1331                         }
1332                 }
1333                 database.storePosts(sone, posts);
1334                 for (Post post : posts) {
1335                         post.setKnown(true);
1336                 }
1337                 database.storePostReplies(sone, replies);
1338                 for (PostReply reply : replies) {
1339                         reply.setKnown(true);
1340                 }
1341
1342                 logger.info(String.format("Sone loaded successfully: %s", sone));
1343         }
1344
1345         /**
1346          * Creates a new post.
1347          *
1348          * @param sone
1349          *            The Sone that creates the post
1350          * @param text
1351          *            The text of the post
1352          * @return The created post
1353          */
1354         public Post createPost(Sone sone, String text) {
1355                 return createPost(sone, System.currentTimeMillis(), text);
1356         }
1357
1358         /**
1359          * Creates a new post.
1360          *
1361          * @param sone
1362          *            The Sone that creates the post
1363          * @param time
1364          *            The time of the post
1365          * @param text
1366          *            The text of the post
1367          * @return The created post
1368          */
1369         public Post createPost(Sone sone, long time, String text) {
1370                 return createPost(sone, null, time, text);
1371         }
1372
1373         /**
1374          * Creates a new post.
1375          *
1376          * @param sone
1377          *            The Sone that creates the post
1378          * @param recipient
1379          *            The recipient Sone, or {@code null} if this post does not have
1380          *            a recipient
1381          * @param text
1382          *            The text of the post
1383          * @return The created post
1384          */
1385         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1386                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1387         }
1388
1389         /**
1390          * Creates a new post.
1391          *
1392          * @param sone
1393          *            The Sone that creates the post
1394          * @param recipient
1395          *            The recipient Sone, or {@code null} if this post does not have
1396          *            a recipient
1397          * @param time
1398          *            The time of the post
1399          * @param text
1400          *            The text of the post
1401          * @return The created post
1402          */
1403         public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1404                 checkNotNull(text, "text must not be null");
1405                 checkArgument(text.trim().length() > 0, "text must not be empty");
1406                 if (!sone.isLocal()) {
1407                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1408                         return null;
1409                 }
1410                 PostBuilder postBuilder = database.newPostBuilder();
1411                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1412                 if (recipient.isPresent()) {
1413                         postBuilder.to(recipient.get().getId());
1414                 }
1415                 final Post post = postBuilder.build();
1416                 database.storePost(post);
1417                 eventBus.post(new NewPostFoundEvent(post));
1418                 sone.addPost(post);
1419                 touchConfiguration();
1420                 localElementTicker.schedule(new Runnable() {
1421
1422                         /**
1423                          * {@inheritDoc}
1424                          */
1425                         @Override
1426                         public void run() {
1427                                 markPostKnown(post);
1428                         }
1429                 }, 10, TimeUnit.SECONDS);
1430                 return post;
1431         }
1432
1433         /**
1434          * Deletes the given post.
1435          *
1436          * @param post
1437          *            The post to delete
1438          */
1439         public void deletePost(Post post) {
1440                 if (!post.getSone().isLocal()) {
1441                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1442                         return;
1443                 }
1444                 database.removePost(post);
1445                 eventBus.post(new PostRemovedEvent(post));
1446                 markPostKnown(post);
1447                 touchConfiguration();
1448         }
1449
1450         /**
1451          * Marks the given post as known, if it is currently not a known post
1452          * (according to {@link Post#isKnown()}).
1453          *
1454          * @param post
1455          *            The post to mark as known
1456          */
1457         public void markPostKnown(Post post) {
1458                 post.setKnown(true);
1459                 eventBus.post(new MarkPostKnownEvent(post));
1460                 touchConfiguration();
1461                 for (PostReply reply : getReplies(post.getId())) {
1462                         markReplyKnown(reply);
1463                 }
1464         }
1465
1466         /**
1467          * Bookmarks the given post.
1468          *
1469          * @param post
1470          *            The post to bookmark
1471          */
1472         public void bookmark(Post post) {
1473                 bookmarkPost(post.getId());
1474         }
1475
1476         /**
1477          * Bookmarks the post with the given ID.
1478          *
1479          * @param id
1480          *            The ID of the post to bookmark
1481          */
1482         public void bookmarkPost(String id) {
1483                 synchronized (bookmarkedPosts) {
1484                         bookmarkedPosts.add(id);
1485                 }
1486         }
1487
1488         /**
1489          * Removes the given post from the bookmarks.
1490          *
1491          * @param post
1492          *            The post to unbookmark
1493          */
1494         public void unbookmark(Post post) {
1495                 unbookmarkPost(post.getId());
1496         }
1497
1498         /**
1499          * Removes the post with the given ID from the bookmarks.
1500          *
1501          * @param id
1502          *            The ID of the post to unbookmark
1503          */
1504         public void unbookmarkPost(String id) {
1505                 synchronized (bookmarkedPosts) {
1506                         bookmarkedPosts.remove(id);
1507                 }
1508         }
1509
1510         /**
1511          * Creates a new reply.
1512          *
1513          * @param sone
1514          *            The Sone that creates the reply
1515          * @param post
1516          *            The post that this reply refers to
1517          * @param text
1518          *            The text of the reply
1519          * @return The created reply
1520          */
1521         public PostReply createReply(Sone sone, Post post, String text) {
1522                 checkNotNull(text, "text must not be null");
1523                 checkArgument(text.trim().length() > 0, "text must not be empty");
1524                 if (!sone.isLocal()) {
1525                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1526                         return null;
1527                 }
1528                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1529                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1530                 final PostReply reply = postReplyBuilder.build();
1531                 database.storePostReply(reply);
1532                 eventBus.post(new NewPostReplyFoundEvent(reply));
1533                 sone.addReply(reply);
1534                 touchConfiguration();
1535                 localElementTicker.schedule(new Runnable() {
1536
1537                         /**
1538                          * {@inheritDoc}
1539                          */
1540                         @Override
1541                         public void run() {
1542                                 markReplyKnown(reply);
1543                         }
1544                 }, 10, TimeUnit.SECONDS);
1545                 return reply;
1546         }
1547
1548         /**
1549          * Deletes the given reply.
1550          *
1551          * @param reply
1552          *            The reply to delete
1553          */
1554         public void deleteReply(PostReply reply) {
1555                 Sone sone = reply.getSone();
1556                 if (!sone.isLocal()) {
1557                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1558                         return;
1559                 }
1560                 database.removePostReply(reply);
1561                 markReplyKnown(reply);
1562                 sone.removeReply(reply);
1563                 touchConfiguration();
1564         }
1565
1566         /**
1567          * Marks the given reply as known, if it is currently not a known reply
1568          * (according to {@link Reply#isKnown()}).
1569          *
1570          * @param reply
1571          *            The reply to mark as known
1572          */
1573         public void markReplyKnown(PostReply reply) {
1574                 boolean previouslyKnown = reply.isKnown();
1575                 reply.setKnown(true);
1576                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1577                 if (!previouslyKnown) {
1578                         touchConfiguration();
1579                 }
1580         }
1581
1582         /**
1583          * Creates a new top-level album for the given Sone.
1584          *
1585          * @param sone
1586          *            The Sone to create the album for
1587          * @return The new album
1588          */
1589         public Album createAlbum(Sone sone) {
1590                 return createAlbum(sone, sone.getRootAlbum());
1591         }
1592
1593         /**
1594          * Creates a new album for the given Sone.
1595          *
1596          * @param sone
1597          *            The Sone to create the album for
1598          * @param parent
1599          *            The parent of the album (may be {@code null} to create a
1600          *            top-level album)
1601          * @return The new album
1602          */
1603         public Album createAlbum(Sone sone, Album parent) {
1604                 AlbumImpl album = new AlbumImpl();
1605                 database.storeAlbum(album);
1606                 album.setSone(sone);
1607                 parent.addAlbum(album);
1608                 return album;
1609         }
1610
1611         /**
1612          * Deletes the given album. The owner of the album has to be a local Sone,
1613          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1614          *
1615          * @param album
1616          *            The album to remove
1617          */
1618         public void deleteAlbum(Album album) {
1619                 checkNotNull(album, "album must not be null");
1620                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1621                 if (!album.isEmpty()) {
1622                         return;
1623                 }
1624                 album.getParent().removeAlbum(album);
1625                 database.removeAlbum(album);
1626                 touchConfiguration();
1627         }
1628
1629         /**
1630          * Creates a new image.
1631          *
1632          * @param sone
1633          *            The Sone creating the image
1634          * @param album
1635          *            The album the image will be inserted into
1636          * @param temporaryImage
1637          *            The temporary image to create the image from
1638          * @return The newly created image
1639          */
1640         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1641                 checkNotNull(sone, "sone must not be null");
1642                 checkNotNull(album, "album must not be null");
1643                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1644                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1645                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1646                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1647                 album.addImage(image);
1648                 synchronized (images) {
1649                         images.put(image.getId(), image);
1650                 }
1651                 imageInserter.insertImage(temporaryImage, image);
1652                 return image;
1653         }
1654
1655         /**
1656          * Deletes the given image. This method will also delete a matching
1657          * temporary image.
1658          *
1659          * @see #deleteTemporaryImage(TemporaryImage)
1660          * @param image
1661          *            The image to delete
1662          */
1663         public void deleteImage(Image image) {
1664                 checkNotNull(image, "image must not be null");
1665                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1666                 deleteTemporaryImage(image.getId());
1667                 image.getAlbum().removeImage(image);
1668                 synchronized (images) {
1669                         images.remove(image.getId());
1670                 }
1671                 touchConfiguration();
1672         }
1673
1674         /**
1675          * Creates a new temporary image.
1676          *
1677          * @param mimeType
1678          *            The MIME type of the temporary image
1679          * @param imageData
1680          *            The encoded data of the image
1681          * @return The temporary image
1682          */
1683         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1684                 TemporaryImage temporaryImage = new TemporaryImage();
1685                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1686                 synchronized (temporaryImages) {
1687                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1688                 }
1689                 return temporaryImage;
1690         }
1691
1692         /**
1693          * Deletes the given temporary image.
1694          *
1695          * @param temporaryImage
1696          *            The temporary image to delete
1697          */
1698         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1699                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1700                 deleteTemporaryImage(temporaryImage.getId());
1701         }
1702
1703         /**
1704          * Deletes the temporary image with the given ID.
1705          *
1706          * @param imageId
1707          *            The ID of the temporary image to delete
1708          */
1709         public void deleteTemporaryImage(String imageId) {
1710                 checkNotNull(imageId, "imageId must not be null");
1711                 synchronized (temporaryImages) {
1712                         temporaryImages.remove(imageId);
1713                 }
1714                 Image image = getImage(imageId, false);
1715                 if (image != null) {
1716                         imageInserter.cancelImageInsert(image);
1717                 }
1718         }
1719
1720         /**
1721          * Notifies the core that the configuration, either of the core or of a
1722          * single local Sone, has changed, and that the configuration should be
1723          * saved.
1724          */
1725         public void touchConfiguration() {
1726                 lastConfigurationUpdate = System.currentTimeMillis();
1727         }
1728
1729         //
1730         // SERVICE METHODS
1731         //
1732
1733         /**
1734          * Starts the core.
1735          */
1736         @Override
1737         public void serviceStart() {
1738                 loadConfiguration();
1739                 updateChecker.start();
1740                 identityManager.start();
1741                 webOfTrustUpdater.init();
1742                 webOfTrustUpdater.start();
1743                 database.start();
1744         }
1745
1746         /**
1747          * {@inheritDoc}
1748          */
1749         @Override
1750         public void serviceRun() {
1751                 long lastSaved = System.currentTimeMillis();
1752                 while (!shouldStop()) {
1753                         sleep(1000);
1754                         long now = System.currentTimeMillis();
1755                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1756                                 for (Sone localSone : getLocalSones()) {
1757                                         saveSone(localSone);
1758                                 }
1759                                 saveConfiguration();
1760                                 lastSaved = now;
1761                         }
1762                 }
1763         }
1764
1765         /**
1766          * Stops the core.
1767          */
1768         @Override
1769         public void serviceStop() {
1770                 localElementTicker.shutdownNow();
1771                 synchronized (sones) {
1772                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1773                                 soneInserter.getValue().stop();
1774                                 saveSone(soneInserter.getKey());
1775                         }
1776                 }
1777                 saveConfiguration();
1778                 database.stop();
1779                 webOfTrustUpdater.stop();
1780                 updateChecker.stop();
1781                 soneDownloader.stop();
1782                 soneDownloaders.shutdown();
1783                 identityManager.stop();
1784         }
1785
1786         //
1787         // PRIVATE METHODS
1788         //
1789
1790         /**
1791          * Saves the given Sone. This will persist all local settings for the given
1792          * Sone, such as the friends list and similar, private options.
1793          *
1794          * @param sone
1795          *            The Sone to save
1796          */
1797         private synchronized void saveSone(Sone sone) {
1798                 if (!sone.isLocal()) {
1799                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1800                         return;
1801                 }
1802                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1803                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1804                         return;
1805                 }
1806
1807                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1808                 try {
1809                         /* save Sone into configuration. */
1810                         String sonePrefix = "Sone/" + sone.getId();
1811                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1812                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1813
1814                         /* save profile. */
1815                         Profile profile = sone.getProfile();
1816                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1817                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1818                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1819                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1820                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1821                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1822                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1823
1824                         /* save profile fields. */
1825                         int fieldCounter = 0;
1826                         for (Field profileField : profile.getFields()) {
1827                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1828                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1829                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1830                         }
1831                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1832
1833                         /* save posts. */
1834                         int postCounter = 0;
1835                         for (Post post : sone.getPosts()) {
1836                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1837                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1838                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1839                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1840                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1841                         }
1842                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1843
1844                         /* save replies. */
1845                         int replyCounter = 0;
1846                         for (PostReply reply : sone.getReplies()) {
1847                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1848                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1849                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1850                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1851                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1852                         }
1853                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1854
1855                         /* save post likes. */
1856                         int postLikeCounter = 0;
1857                         for (String postId : sone.getLikedPostIds()) {
1858                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1859                         }
1860                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1861
1862                         /* save reply likes. */
1863                         int replyLikeCounter = 0;
1864                         for (String replyId : sone.getLikedReplyIds()) {
1865                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1866                         }
1867                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1868
1869                         /* save friends. */
1870                         int friendCounter = 0;
1871                         for (String friendId : sone.getFriends()) {
1872                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1873                         }
1874                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1875
1876                         /* save albums. first, collect in a flat structure, top-level first. */
1877                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1878
1879                         int albumCounter = 0;
1880                         for (Album album : albums) {
1881                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1882                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1883                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1884                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1885                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1886                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1887                         }
1888                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1889
1890                         /* save images. */
1891                         int imageCounter = 0;
1892                         for (Album album : albums) {
1893                                 for (Image image : album.getImages()) {
1894                                         if (!image.isInserted()) {
1895                                                 continue;
1896                                         }
1897                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1898                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1899                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1900                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1901                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1902                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1903                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1904                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1905                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1906                                 }
1907                         }
1908                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1909
1910                         /* save options. */
1911                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1912                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1913                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1914                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1915                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1916                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1917
1918                         configuration.save();
1919
1920                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1921
1922                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1923                 } catch (ConfigurationException ce1) {
1924                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1925                 }
1926         }
1927
1928         /**
1929          * Saves the current options.
1930          */
1931         private void saveConfiguration() {
1932                 synchronized (configuration) {
1933                         if (storingConfiguration) {
1934                                 logger.log(Level.FINE, "Already storing configuration…");
1935                                 return;
1936                         }
1937                         storingConfiguration = true;
1938                 }
1939
1940                 /* store the options first. */
1941                 try {
1942                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1943                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1944                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1945                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1946                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1947                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1948                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1949                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1950                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1951                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1952                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1953                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1954
1955                         /* save known Sones. */
1956                         int soneCounter = 0;
1957                         synchronized (knownSones) {
1958                                 for (String knownSoneId : knownSones) {
1959                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1960                                 }
1961                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1962                         }
1963
1964                         /* save Sone following times. */
1965                         soneCounter = 0;
1966                         synchronized (soneFollowingTimes) {
1967                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1968                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1969                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1970                                         ++soneCounter;
1971                                 }
1972                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1973                         }
1974
1975                         /* save known posts. */
1976                         database.save();
1977
1978                         /* save bookmarked posts. */
1979                         int bookmarkedPostCounter = 0;
1980                         synchronized (bookmarkedPosts) {
1981                                 for (String bookmarkedPostId : bookmarkedPosts) {
1982                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1983                                 }
1984                         }
1985                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1986
1987                         /* now save it. */
1988                         configuration.save();
1989
1990                 } catch (ConfigurationException ce1) {
1991                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1992                 } catch (DatabaseException de1) {
1993                         logger.log(Level.SEVERE, "Could not save database!", de1);
1994                 } finally {
1995                         synchronized (configuration) {
1996                                 storingConfiguration = false;
1997                         }
1998                 }
1999         }
2000
2001         /**
2002          * Loads the configuration.
2003          */
2004         private void loadConfiguration() {
2005                 /* create options. */
2006                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2007
2008                         @Override
2009                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2010                                 SoneInserter.setInsertionDelay(newValue);
2011                         }
2012
2013                 }));
2014                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2015                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2016                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2017                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2018                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2019                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2020                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2021                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2022                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2023
2024                         @Override
2025                         @SuppressWarnings("synthetic-access")
2026                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2027                                 fcpInterface.setActive(newValue);
2028                         }
2029                 }));
2030                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2031
2032                         @Override
2033                         @SuppressWarnings("synthetic-access")
2034                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2035                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2036                         }
2037
2038                 }));
2039
2040                 loadConfigurationValue("InsertionDelay");
2041                 loadConfigurationValue("PostsPerPage");
2042                 loadConfigurationValue("ImagesPerPage");
2043                 loadConfigurationValue("CharactersPerPost");
2044                 loadConfigurationValue("PostCutOffLength");
2045                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2046                 loadConfigurationValue("PositiveTrust");
2047                 loadConfigurationValue("NegativeTrust");
2048                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2049                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2050                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2051
2052                 /* load known Sones. */
2053                 int soneCounter = 0;
2054                 while (true) {
2055                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2056                         if (knownSoneId == null) {
2057                                 break;
2058                         }
2059                         synchronized (knownSones) {
2060                                 knownSones.add(knownSoneId);
2061                         }
2062                 }
2063
2064                 /* load Sone following times. */
2065                 soneCounter = 0;
2066                 while (true) {
2067                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2068                         if (soneId == null) {
2069                                 break;
2070                         }
2071                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2072                         synchronized (soneFollowingTimes) {
2073                                 soneFollowingTimes.put(soneId, time);
2074                         }
2075                         ++soneCounter;
2076                 }
2077
2078                 /* load bookmarked posts. */
2079                 int bookmarkedPostCounter = 0;
2080                 while (true) {
2081                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2082                         if (bookmarkedPostId == null) {
2083                                 break;
2084                         }
2085                         synchronized (bookmarkedPosts) {
2086                                 bookmarkedPosts.add(bookmarkedPostId);
2087                         }
2088                 }
2089
2090         }
2091
2092         /**
2093          * Loads an {@link Integer} configuration value for the option with the
2094          * given name, logging validation failures.
2095          *
2096          * @param optionName
2097          *            The name of the option to load
2098          */
2099         private void loadConfigurationValue(String optionName) {
2100                 try {
2101                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2102                 } catch (IllegalArgumentException iae1) {
2103                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2104                 }
2105         }
2106
2107         /**
2108          * Notifies the core that a new {@link OwnIdentity} was added.
2109          *
2110          * @param ownIdentityAddedEvent
2111          *            The event
2112          */
2113         @Subscribe
2114         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2115                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2116                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2117                 if (ownIdentity.hasContext("Sone")) {
2118                         addLocalSone(ownIdentity);
2119                 }
2120         }
2121
2122         /**
2123          * Notifies the core that an {@link OwnIdentity} was removed.
2124          *
2125          * @param ownIdentityRemovedEvent
2126          *            The event
2127          */
2128         @Subscribe
2129         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2130                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2131                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2132                 trustedIdentities.removeAll(ownIdentity);
2133         }
2134
2135         /**
2136          * Notifies the core that a new {@link Identity} was added.
2137          *
2138          * @param identityAddedEvent
2139          *            The event
2140          */
2141         @Subscribe
2142         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2143                 Identity identity = identityAddedEvent.identity();
2144                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2145                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2146                 addRemoteSone(identity);
2147         }
2148
2149         /**
2150          * Notifies the core that an {@link Identity} was updated.
2151          *
2152          * @param identityUpdatedEvent
2153          *            The event
2154          */
2155         @Subscribe
2156         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2157                 final Identity identity = identityUpdatedEvent.identity();
2158                 soneDownloaders.execute(new Runnable() {
2159
2160                         @Override
2161                         @SuppressWarnings("synthetic-access")
2162                         public void run() {
2163                                 Sone sone = getRemoteSone(identity.getId(), false);
2164                                 if (sone.isLocal()) {
2165                                         return;
2166                                 }
2167                                 sone.setIdentity(identity);
2168                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2169                                 soneDownloader.addSone(sone);
2170                                 soneDownloader.fetchSone(sone);
2171                         }
2172                 });
2173         }
2174
2175         /**
2176          * Notifies the core that an {@link Identity} was removed.
2177          *
2178          * @param identityRemovedEvent
2179          *            The event
2180          */
2181         @Subscribe
2182         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2183                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2184                 Identity identity = identityRemovedEvent.identity();
2185                 trustedIdentities.remove(ownIdentity, identity);
2186                 boolean foundIdentity = false;
2187                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2188                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2189                                 continue;
2190                         }
2191                         if (trustedIdentity.getValue().contains(identity)) {
2192                                 foundIdentity = true;
2193                         }
2194                 }
2195                 if (foundIdentity) {
2196                         /* some local identity still trusts this identity, don’t remove. */
2197                         return;
2198                 }
2199                 Optional<Sone> sone = getSone(identity.getId());
2200                 if (!sone.isPresent()) {
2201                         /* TODO - we don’t have the Sone anymore. should this happen? */
2202                         return;
2203                 }
2204                 database.removePosts(sone.get());
2205                 for (Post post : sone.get().getPosts()) {
2206                         eventBus.post(new PostRemovedEvent(post));
2207                 }
2208                 database.removePostReplies(sone.get());
2209                 for (PostReply reply : sone.get().getReplies()) {
2210                         eventBus.post(new PostReplyRemovedEvent(reply));
2211                 }
2212                 synchronized (sones) {
2213                         sones.remove(identity.getId());
2214                 }
2215                 eventBus.post(new SoneRemovedEvent(sone.get()));
2216         }
2217
2218         /**
2219          * Deletes the temporary image.
2220          *
2221          * @param imageInsertFinishedEvent
2222          *            The event
2223          */
2224         @Subscribe
2225         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2226                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2227                 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2228                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2229                 touchConfiguration();
2230         }
2231
2232 }