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