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