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