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