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