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