Use logging method that’s present in Java 1.7
[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.getSone().equals(newSone)) {
863                                         post.setKnown(true);
864                                 } else 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.getSone().equals(newSone)) {
881                                         postReply.setKnown(true);
882                                 } else if (postReply.getTime() < database.getFollowingTime(newSone.getId())) {
883                                         postReply.setKnown(true);
884                                 } else if (!postReply.isKnown()) {
885                                         events.add(new NewPostReplyFoundEvent(postReply));
886                                 }
887                         }
888                 });
889                 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
890                         @Override
891                         public void processPostReply(PostReply postReply) {
892                                 events.add(new PostReplyRemovedEvent(postReply));
893                         }
894                 });
895                 soneChangeDetector.detectChanges(newSone);
896                 return events;
897         }
898
899         /**
900          * Deletes the given Sone. This will remove the Sone from the
901          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
902          * remove the context from its identity.
903          *
904          * @param sone
905          *            The Sone to delete
906          */
907         public void deleteSone(Sone sone) {
908                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
909                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
910                         return;
911                 }
912                 if (!getLocalSones().contains(sone)) {
913                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
914                         return;
915                 }
916                 SoneInserter soneInserter = soneInserters.remove(sone);
917                 soneInserter.stop();
918                 database.removeSone(sone);
919                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
920                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
921                 try {
922                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
923                 } catch (ConfigurationException ce1) {
924                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
925                 }
926         }
927
928         /**
929          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
930          * known} before, a {@link MarkSoneKnownEvent} is fired.
931          *
932          * @param sone
933          *            The Sone to mark as known
934          */
935         public void markSoneKnown(Sone sone) {
936                 if (!sone.isKnown()) {
937                         sone.setKnown(true);
938                         synchronized (knownSones) {
939                                 knownSones.add(sone.getId());
940                         }
941                         eventBus.post(new MarkSoneKnownEvent(sone));
942                         touchConfiguration();
943                 }
944         }
945
946         /**
947          * Loads and updates the given Sone from the configuration. If any error is
948          * encountered, loading is aborted and the given Sone is not changed.
949          *
950          * @param sone
951          *            The Sone to load and update
952          */
953         public void loadSone(Sone sone) {
954                 if (!sone.isLocal()) {
955                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
956                         return;
957                 }
958                 logger.info(String.format("Loading local Sone: %s", sone));
959
960                 /* load Sone. */
961                 String sonePrefix = "Sone/" + sone.getId();
962                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
963                 if (soneTime == null) {
964                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
965                         return;
966                 }
967                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
968
969                 /* load profile. */
970                 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
971                 Profile profile = configurationSoneParser.parseProfile();
972
973                 /* load posts. */
974                 Collection<Post> posts;
975                 try {
976                         posts = configurationSoneParser.parsePosts(database);
977                 } catch (InvalidPostFound ipf) {
978                         logger.log(Level.WARNING, "Invalid post found, aborting load!");
979                         return;
980                 }
981
982                 /* load replies. */
983                 Collection<PostReply> replies;
984                 try {
985                         replies = configurationSoneParser.parsePostReplies(database);
986                 } catch (InvalidPostReplyFound iprf) {
987                         logger.log(Level.WARNING, "Invalid reply found, aborting load!");
988                         return;
989                 }
990
991                 /* load post likes. */
992                 Set<String> likedPostIds =
993                                 configurationSoneParser.parseLikedPostIds();
994
995                 /* load reply likes. */
996                 Set<String> likedReplyIds =
997                                 configurationSoneParser.parseLikedPostReplyIds();
998
999                 /* load albums. */
1000                 List<Album> topLevelAlbums;
1001                 try {
1002                         topLevelAlbums =
1003                                         configurationSoneParser.parseTopLevelAlbums(database);
1004                 } catch (InvalidAlbumFound iaf) {
1005                         logger.log(Level.WARNING, "Invalid album found, aborting load!");
1006                         return;
1007                 } catch (InvalidParentAlbumFound ipaf) {
1008                         logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1009                                         ipaf.getAlbumParentId()));
1010                         return;
1011                 }
1012
1013                 /* load images. */
1014                 try {
1015                         configurationSoneParser.parseImages(database);
1016                 } catch (InvalidImageFound iif) {
1017                         logger.log(WARNING, "Invalid image found, aborting load!");
1018                         return;
1019                 } catch (InvalidParentAlbumFound ipaf) {
1020                         logger.log(Level.WARNING,
1021                                         format("Invalid album image (%s) encountered, aborting load!",
1022                                                         ipaf.getAlbumParentId()));
1023                         return;
1024                 }
1025
1026                 /* load avatar. */
1027                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1028                 if (avatarId != null) {
1029                         final Map<String, Image> images =
1030                                         configurationSoneParser.getImages();
1031                         profile.setAvatar(images.get(avatarId));
1032                 }
1033
1034                 /* load options. */
1035                 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1036                 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1037                 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1038                 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1039                 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1040                 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1041                 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1042
1043                 /* if we’re still here, Sone was loaded successfully. */
1044                 synchronized (sone) {
1045                         sone.setTime(soneTime);
1046                         sone.setProfile(profile);
1047                         sone.setPosts(posts);
1048                         sone.setReplies(replies);
1049                         sone.setLikePostIds(likedPostIds);
1050                         sone.setLikeReplyIds(likedReplyIds);
1051                         for (Album album : sone.getRootAlbum().getAlbums()) {
1052                                 sone.getRootAlbum().removeAlbum(album);
1053                         }
1054                         for (Album album : topLevelAlbums) {
1055                                 sone.getRootAlbum().addAlbum(album);
1056                         }
1057                         synchronized (soneInserters) {
1058                                 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1059                         }
1060                 }
1061                 for (Post post : posts) {
1062                         post.setKnown(true);
1063                 }
1064                 for (PostReply reply : replies) {
1065                         reply.setKnown(true);
1066                 }
1067
1068                 logger.info(String.format("Sone loaded successfully: %s", sone));
1069         }
1070
1071         /**
1072          * Creates a new post.
1073          *
1074          * @param sone
1075          *            The Sone that creates the post
1076          * @param recipient
1077          *            The recipient Sone, or {@code null} if this post does not have
1078          *            a recipient
1079          * @param text
1080          *            The text of the post
1081          * @return The created post
1082          */
1083         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1084                 checkNotNull(text, "text must not be null");
1085                 checkArgument(text.trim().length() > 0, "text must not be empty");
1086                 if (!sone.isLocal()) {
1087                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1088                         return null;
1089                 }
1090                 PostBuilder postBuilder = database.newPostBuilder();
1091                 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1092                 if (recipient.isPresent()) {
1093                         postBuilder.to(recipient.get().getId());
1094                 }
1095                 final Post post = postBuilder.build();
1096                 database.storePost(post);
1097                 eventBus.post(new NewPostFoundEvent(post));
1098                 sone.addPost(post);
1099                 touchConfiguration();
1100                 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1101                 return post;
1102         }
1103
1104         /**
1105          * Deletes the given post.
1106          *
1107          * @param post
1108          *            The post to delete
1109          */
1110         public void deletePost(Post post) {
1111                 if (!post.getSone().isLocal()) {
1112                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1113                         return;
1114                 }
1115                 database.removePost(post);
1116                 eventBus.post(new PostRemovedEvent(post));
1117                 markPostKnown(post);
1118                 touchConfiguration();
1119         }
1120
1121         /**
1122          * Marks the given post as known, if it is currently not a known post
1123          * (according to {@link Post#isKnown()}).
1124          *
1125          * @param post
1126          *            The post to mark as known
1127          */
1128         public void markPostKnown(Post post) {
1129                 post.setKnown(true);
1130                 eventBus.post(new MarkPostKnownEvent(post));
1131                 touchConfiguration();
1132                 for (PostReply reply : getReplies(post.getId())) {
1133                         markReplyKnown(reply);
1134                 }
1135         }
1136
1137         public void bookmarkPost(Post post) {
1138                 database.bookmarkPost(post);
1139         }
1140
1141         /**
1142          * Removes the given post from the bookmarks.
1143          *
1144          * @param post
1145          *            The post to unbookmark
1146          */
1147         public void unbookmarkPost(Post post) {
1148                 database.unbookmarkPost(post);
1149         }
1150
1151         /**
1152          * Creates a new reply.
1153          *
1154          * @param sone
1155          *            The Sone that creates the reply
1156          * @param post
1157          *            The post that this reply refers to
1158          * @param text
1159          *            The text of the reply
1160          * @return The created reply
1161          */
1162         public PostReply createReply(Sone sone, Post post, String text) {
1163                 checkNotNull(text, "text must not be null");
1164                 checkArgument(text.trim().length() > 0, "text must not be empty");
1165                 if (!sone.isLocal()) {
1166                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1167                         return null;
1168                 }
1169                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1170                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1171                 final PostReply reply = postReplyBuilder.build();
1172                 database.storePostReply(reply);
1173                 eventBus.post(new NewPostReplyFoundEvent(reply));
1174                 sone.addReply(reply);
1175                 touchConfiguration();
1176                 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1177                 return reply;
1178         }
1179
1180         /**
1181          * Deletes the given reply.
1182          *
1183          * @param reply
1184          *            The reply to delete
1185          */
1186         public void deleteReply(PostReply reply) {
1187                 Sone sone = reply.getSone();
1188                 if (!sone.isLocal()) {
1189                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1190                         return;
1191                 }
1192                 database.removePostReply(reply);
1193                 markReplyKnown(reply);
1194                 sone.removeReply(reply);
1195                 touchConfiguration();
1196         }
1197
1198         /**
1199          * Marks the given reply as known, if it is currently not a known reply
1200          * (according to {@link Reply#isKnown()}).
1201          *
1202          * @param reply
1203          *            The reply to mark as known
1204          */
1205         public void markReplyKnown(PostReply reply) {
1206                 boolean previouslyKnown = reply.isKnown();
1207                 reply.setKnown(true);
1208                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1209                 if (!previouslyKnown) {
1210                         touchConfiguration();
1211                 }
1212         }
1213
1214         /**
1215          * Creates a new album for the given Sone.
1216          *
1217          * @param sone
1218          *            The Sone to create the album for
1219          * @param parent
1220          *            The parent of the album (may be {@code null} to create a
1221          *            top-level album)
1222          * @return The new album
1223          */
1224         public Album createAlbum(Sone sone, Album parent) {
1225                 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1226                 database.storeAlbum(album);
1227                 parent.addAlbum(album);
1228                 return album;
1229         }
1230
1231         /**
1232          * Deletes the given album. The owner of the album has to be a local Sone,
1233          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1234          *
1235          * @param album
1236          *            The album to remove
1237          */
1238         public void deleteAlbum(Album album) {
1239                 checkNotNull(album, "album must not be null");
1240                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1241                 if (!album.isEmpty()) {
1242                         return;
1243                 }
1244                 album.getParent().removeAlbum(album);
1245                 database.removeAlbum(album);
1246                 touchConfiguration();
1247         }
1248
1249         /**
1250          * Creates a new image.
1251          *
1252          * @param sone
1253          *            The Sone creating the image
1254          * @param album
1255          *            The album the image will be inserted into
1256          * @param temporaryImage
1257          *            The temporary image to create the image from
1258          * @return The newly created image
1259          */
1260         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1261                 checkNotNull(sone, "sone must not be null");
1262                 checkNotNull(album, "album must not be null");
1263                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1264                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1265                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1266                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1267                 album.addImage(image);
1268                 database.storeImage(image);
1269                 imageInserter.insertImage(temporaryImage, image);
1270                 return image;
1271         }
1272
1273         /**
1274          * Deletes the given image. This method will also delete a matching
1275          * temporary image.
1276          *
1277          * @see #deleteTemporaryImage(String)
1278          * @param image
1279          *            The image to delete
1280          */
1281         public void deleteImage(Image image) {
1282                 checkNotNull(image, "image must not be null");
1283                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1284                 deleteTemporaryImage(image.getId());
1285                 image.getAlbum().removeImage(image);
1286                 database.removeImage(image);
1287                 touchConfiguration();
1288         }
1289
1290         /**
1291          * Creates a new temporary image.
1292          *
1293          * @param mimeType
1294          *            The MIME type of the temporary image
1295          * @param imageData
1296          *            The encoded data of the image
1297          * @return The temporary image
1298          */
1299         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1300                 TemporaryImage temporaryImage = new TemporaryImage();
1301                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1302                 synchronized (temporaryImages) {
1303                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1304                 }
1305                 return temporaryImage;
1306         }
1307
1308         /**
1309          * Deletes the temporary image with the given ID.
1310          *
1311          * @param imageId
1312          *            The ID of the temporary image to delete
1313          */
1314         public void deleteTemporaryImage(String imageId) {
1315                 checkNotNull(imageId, "imageId must not be null");
1316                 synchronized (temporaryImages) {
1317                         temporaryImages.remove(imageId);
1318                 }
1319                 Image image = getImage(imageId, false);
1320                 if (image != null) {
1321                         imageInserter.cancelImageInsert(image);
1322                 }
1323         }
1324
1325         /**
1326          * Notifies the core that the configuration, either of the core or of a
1327          * single local Sone, has changed, and that the configuration should be
1328          * saved.
1329          */
1330         public void touchConfiguration() {
1331                 lastConfigurationUpdate = System.currentTimeMillis();
1332         }
1333
1334         //
1335         // SERVICE METHODS
1336         //
1337
1338         /**
1339          * Starts the core.
1340          */
1341         @Override
1342         public void serviceStart() {
1343                 loadConfiguration();
1344                 updateChecker.start();
1345                 identityManager.start();
1346                 webOfTrustUpdater.init();
1347                 webOfTrustUpdater.start();
1348                 database.start();
1349         }
1350
1351         /**
1352          * {@inheritDoc}
1353          */
1354         @Override
1355         public void serviceRun() {
1356                 long lastSaved = System.currentTimeMillis();
1357                 while (!shouldStop()) {
1358                         sleep(1000);
1359                         long now = System.currentTimeMillis();
1360                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1361                                 for (Sone localSone : getLocalSones()) {
1362                                         saveSone(localSone);
1363                                 }
1364                                 saveConfiguration();
1365                                 lastSaved = now;
1366                         }
1367                 }
1368         }
1369
1370         /**
1371          * Stops the core.
1372          */
1373         @Override
1374         public void serviceStop() {
1375                 localElementTicker.shutdownNow();
1376                 synchronized (soneInserters) {
1377                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1378                                 soneInserter.getValue().stop();
1379                                 saveSone(soneInserter.getKey());
1380                         }
1381                 }
1382                 synchronized (soneRescuers) {
1383                         for (SoneRescuer soneRescuer : soneRescuers.values()) {
1384                                 soneRescuer.stop();
1385                         }
1386                 }
1387                 saveConfiguration();
1388                 database.stop();
1389                 webOfTrustUpdater.stop();
1390                 updateChecker.stop();
1391                 soneDownloader.stop();
1392                 soneDownloaders.shutdown();
1393                 identityManager.stop();
1394         }
1395
1396         //
1397         // PRIVATE METHODS
1398         //
1399
1400         /**
1401          * Saves the given Sone. This will persist all local settings for the given
1402          * Sone, such as the friends list and similar, private options.
1403          *
1404          * @param sone
1405          *            The Sone to save
1406          */
1407         private synchronized void saveSone(Sone sone) {
1408                 if (!sone.isLocal()) {
1409                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1410                         return;
1411                 }
1412                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1413                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1414                         return;
1415                 }
1416
1417                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1418                 try {
1419                         /* save Sone into configuration. */
1420                         String sonePrefix = "Sone/" + sone.getId();
1421                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1422                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1423
1424                         /* save profile. */
1425                         Profile profile = sone.getProfile();
1426                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1427                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1428                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1429                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1430                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1431                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1432                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1433
1434                         /* save profile fields. */
1435                         int fieldCounter = 0;
1436                         for (Field profileField : profile.getFields()) {
1437                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1438                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1439                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1440                         }
1441                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1442
1443                         /* save posts. */
1444                         int postCounter = 0;
1445                         for (Post post : sone.getPosts()) {
1446                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1447                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1448                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1449                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1450                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1451                         }
1452                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1453
1454                         /* save replies. */
1455                         int replyCounter = 0;
1456                         for (PostReply reply : sone.getReplies()) {
1457                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1458                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1459                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1460                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1461                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1462                         }
1463                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1464
1465                         /* save post likes. */
1466                         int postLikeCounter = 0;
1467                         for (String postId : sone.getLikedPostIds()) {
1468                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1469                         }
1470                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1471
1472                         /* save reply likes. */
1473                         int replyLikeCounter = 0;
1474                         for (String replyId : sone.getLikedReplyIds()) {
1475                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1476                         }
1477                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1478
1479                         /* save albums. first, collect in a flat structure, top-level first. */
1480                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1481
1482                         int albumCounter = 0;
1483                         for (Album album : albums) {
1484                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1485                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1486                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1487                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1488                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1489                         }
1490                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1491
1492                         /* save images. */
1493                         int imageCounter = 0;
1494                         for (Album album : albums) {
1495                                 for (Image image : album.getImages()) {
1496                                         if (!image.isInserted()) {
1497                                                 continue;
1498                                         }
1499                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1500                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1501                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1502                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1503                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1504                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1505                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1506                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1507                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1508                                 }
1509                         }
1510                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1511
1512                         /* save options. */
1513                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1514                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1515                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1516                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1517                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1518                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1519                         configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1520
1521                         configuration.save();
1522
1523                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1524
1525                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1526                 } catch (ConfigurationException ce1) {
1527                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1528                 }
1529         }
1530
1531         /**
1532          * Saves the current options.
1533          */
1534         private void saveConfiguration() {
1535                 synchronized (configuration) {
1536                         if (storingConfiguration) {
1537                                 logger.log(Level.FINE, "Already storing configuration…");
1538                                 return;
1539                         }
1540                         storingConfiguration = true;
1541                 }
1542
1543                 /* store the options first. */
1544                 try {
1545                         preferences.saveTo(configuration);
1546
1547                         /* save known Sones. */
1548                         int soneCounter = 0;
1549                         synchronized (knownSones) {
1550                                 for (String knownSoneId : knownSones) {
1551                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1552                                 }
1553                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1554                         }
1555
1556                         /* save known posts. */
1557                         database.save();
1558
1559                         /* now save it. */
1560                         configuration.save();
1561
1562                 } catch (ConfigurationException ce1) {
1563                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1564                 } catch (DatabaseException de1) {
1565                         logger.log(Level.SEVERE, "Could not save database!", de1);
1566                 } finally {
1567                         synchronized (configuration) {
1568                                 storingConfiguration = false;
1569                         }
1570                 }
1571         }
1572
1573         /**
1574          * Loads the configuration.
1575          */
1576         private void loadConfiguration() {
1577                 new PreferencesLoader(preferences).loadFrom(configuration);
1578
1579                 /* load known Sones. */
1580                 int soneCounter = 0;
1581                 while (true) {
1582                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1583                         if (knownSoneId == null) {
1584                                 break;
1585                         }
1586                         synchronized (knownSones) {
1587                                 knownSones.add(knownSoneId);
1588                         }
1589                 }
1590         }
1591
1592         /**
1593          * Notifies the core that a new {@link OwnIdentity} was added.
1594          *
1595          * @param ownIdentityAddedEvent
1596          *            The event
1597          */
1598         @Subscribe
1599         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1600                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1601                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1602                 if (ownIdentity.hasContext("Sone")) {
1603                         addLocalSone(ownIdentity);
1604                 }
1605         }
1606
1607         /**
1608          * Notifies the core that an {@link OwnIdentity} was removed.
1609          *
1610          * @param ownIdentityRemovedEvent
1611          *            The event
1612          */
1613         @Subscribe
1614         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1615                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1616                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1617                 trustedIdentities.removeAll(ownIdentity);
1618         }
1619
1620         /**
1621          * Notifies the core that a new {@link Identity} was added.
1622          *
1623          * @param identityAddedEvent
1624          *            The event
1625          */
1626         @Subscribe
1627         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1628                 Identity identity = identityAddedEvent.identity();
1629                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1630                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1631                 addRemoteSone(identity);
1632         }
1633
1634         /**
1635          * Notifies the core that an {@link Identity} was updated.
1636          *
1637          * @param identityUpdatedEvent
1638          *            The event
1639          */
1640         @Subscribe
1641         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1642                 Identity identity = identityUpdatedEvent.identity();
1643                 final Sone sone = getRemoteSone(identity.getId());
1644                 if (sone.isLocal()) {
1645                         return;
1646                 }
1647                 String newLatestEdition = identity.getProperty("Sone.LatestEdition");
1648                 if (newLatestEdition != null) {
1649                         Long parsedNewLatestEdition = tryParse(newLatestEdition);
1650                         if (parsedNewLatestEdition != null) {
1651                                 sone.setLatestEdition(parsedNewLatestEdition);
1652                         }
1653                 }
1654                 soneDownloader.addSone(sone);
1655                 soneDownloaders.execute(soneDownloader.fetchSoneAsSskAction(sone));
1656         }
1657
1658         /**
1659          * Notifies the core that an {@link Identity} was removed.
1660          *
1661          * @param identityRemovedEvent
1662          *            The event
1663          */
1664         @Subscribe
1665         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1666                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1667                 Identity identity = identityRemovedEvent.identity();
1668                 trustedIdentities.remove(ownIdentity, identity);
1669                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1670                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1671                                 continue;
1672                         }
1673                         if (trustedIdentity.getValue().contains(identity)) {
1674                                 return;
1675                         }
1676                 }
1677                 Sone sone = getSone(identity.getId());
1678                 if (sone == null) {
1679                         /* TODO - we don’t have the Sone anymore. should this happen? */
1680                         return;
1681                 }
1682                 for (PostReply postReply : sone.getReplies()) {
1683                         eventBus.post(new PostReplyRemovedEvent(postReply));
1684                 }
1685                 for (Post post : sone.getPosts()) {
1686                         eventBus.post(new PostRemovedEvent(post));
1687                 }
1688                 eventBus.post(new SoneRemovedEvent(sone));
1689                 database.removeSone(sone);
1690         }
1691
1692         /**
1693          * Deletes the temporary image.
1694          *
1695          * @param imageInsertFinishedEvent
1696          *            The event
1697          */
1698         @Subscribe
1699         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1700                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1701                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1702                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1703                 touchConfiguration();
1704         }
1705
1706         @VisibleForTesting
1707         class MarkPostKnown implements Runnable {
1708
1709                 private final Post post;
1710
1711                 public MarkPostKnown(Post post) {
1712                         this.post = post;
1713                 }
1714
1715                 @Override
1716                 public void run() {
1717                         markPostKnown(post);
1718                 }
1719
1720         }
1721
1722         @VisibleForTesting
1723         class MarkReplyKnown implements Runnable {
1724
1725                 private final PostReply postReply;
1726
1727                 public MarkReplyKnown(PostReply postReply) {
1728                         this.postReply = postReply;
1729                 }
1730
1731                 @Override
1732                 public void run() {
1733                         markReplyKnown(postReply);
1734                 }
1735
1736         }
1737
1738 }