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