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