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