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