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