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