66677deb8fd390c4ecd053b52f44fea1db445886
[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         @Nullable
558         public Image getImage(String imageId) {
559                 return getImage(imageId, true);
560         }
561
562         /**
563          * Returns the image with the given ID, optionally creating it if it does
564          * not exist.
565          *
566          * @param imageId
567          *            The ID of the image
568          * @param create
569          *            {@code true} to create an image if none exists with the given
570          *            ID
571          * @return The image with the given ID, or {@code null} if none exists and
572          *         none was created
573          */
574         @Nullable
575         public Image getImage(String imageId, boolean create) {
576                 Optional<Image> image = database.getImage(imageId);
577                 if (image.isPresent()) {
578                         return image.get();
579                 }
580                 if (!create) {
581                         return null;
582                 }
583                 Image newImage = database.newImageBuilder().withId(imageId).build();
584                 database.storeImage(newImage);
585                 return newImage;
586         }
587
588         /**
589          * Returns the temporary image with the given ID.
590          *
591          * @param imageId
592          *            The ID of the temporary image
593          * @return The temporary image, or {@code null} if there is no temporary
594          *         image with the given ID
595          */
596         public TemporaryImage getTemporaryImage(String imageId) {
597                 synchronized (temporaryImages) {
598                         return temporaryImages.get(imageId);
599                 }
600         }
601
602         //
603         // ACTIONS
604         //
605
606         /**
607          * Locks the given Sone. A locked Sone will not be inserted by
608          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
609          * again.
610          *
611          * @param sone
612          *            The sone to lock
613          */
614         public void lockSone(Sone sone) {
615                 synchronized (lockedSones) {
616                         if (lockedSones.add(sone)) {
617                                 eventBus.post(new SoneLockedEvent(sone));
618                         }
619                 }
620         }
621
622         /**
623          * Unlocks the given Sone.
624          *
625          * @see #lockSone(Sone)
626          * @param sone
627          *            The sone to unlock
628          */
629         public void unlockSone(Sone sone) {
630                 synchronized (lockedSones) {
631                         if (lockedSones.remove(sone)) {
632                                 eventBus.post(new SoneUnlockedEvent(sone));
633                         }
634                 }
635         }
636
637         /**
638          * Adds a local Sone from the given own identity.
639          *
640          * @param ownIdentity
641          *            The own identity to create a Sone from
642          * @return The added (or already existing) Sone
643          */
644         public Sone addLocalSone(OwnIdentity ownIdentity) {
645                 if (ownIdentity == null) {
646                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
647                         return null;
648                 }
649                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
650                 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
651                 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
652                 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
653                 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
654                 sone.setKnown(true);
655                 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
656                 eventBus.register(soneInserter);
657                 synchronized (soneInserters) {
658                         soneInserters.put(sone, soneInserter);
659                 }
660                 loadSone(sone);
661                 database.storeSone(sone);
662                 sone.setStatus(SoneStatus.idle);
663                 soneInserter.start();
664                 return sone;
665         }
666
667         /**
668          * Creates a new Sone for the given own identity.
669          *
670          * @param ownIdentity
671          *            The own identity to create a Sone for
672          * @return The created Sone
673          */
674         public Sone createSone(OwnIdentity ownIdentity) {
675                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
676                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
677                         return null;
678                 }
679                 Sone sone = addLocalSone(ownIdentity);
680
681                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
682                 touchConfiguration();
683                 return sone;
684         }
685
686         /**
687          * Adds the Sone of the given identity.
688          *
689          * @param identity
690          *            The identity whose Sone to add
691          * @return The added or already existing Sone
692          */
693         public Sone addRemoteSone(Identity identity) {
694                 if (identity == null) {
695                         logger.log(Level.WARNING, "Given Identity is null!");
696                         return null;
697                 }
698                 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
699                 long latestEdition = fromNullable(tryParse(property)).or(0L);
700                 Optional<Sone> existingSone = getSone(identity.getId());
701                 if (existingSone.isPresent() && existingSone.get().isLocal()) {
702                         return existingSone.get();
703                 }
704                 boolean newSone = !existingSone.isPresent();
705                 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
706                 sone.setLatestEdition(latestEdition);
707                 if (newSone) {
708                         synchronized (knownSones) {
709                                 newSone = !knownSones.contains(sone.getId());
710                         }
711                         sone.setKnown(!newSone);
712                         if (newSone) {
713                                 eventBus.post(new NewSoneFoundEvent(sone));
714                                 for (Sone localSone : getLocalSones()) {
715                                         if (localSone.getOptions().isAutoFollow()) {
716                                                 followSone(localSone, sone.getId());
717                                         }
718                                 }
719                         }
720                 }
721                 database.storeSone(sone);
722                 soneDownloader.addSone(sone);
723                 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
724                 return sone;
725         }
726
727         /**
728          * Lets the given local Sone follow the Sone with the given ID.
729          *
730          * @param sone
731          *            The local Sone that should follow another Sone
732          * @param soneId
733          *            The ID of the Sone to follow
734          */
735         public void followSone(Sone sone, String soneId) {
736                 checkNotNull(sone, "sone must not be null");
737                 checkNotNull(soneId, "soneId must not be null");
738                 database.addFriend(sone, soneId);
739                 synchronized (soneFollowingTimes) {
740                         if (!soneFollowingTimes.containsKey(soneId)) {
741                                 long now = System.currentTimeMillis();
742                                 soneFollowingTimes.put(soneId, now);
743                                 Optional<Sone> followedSone = getSone(soneId);
744                                 if (!followedSone.isPresent()) {
745                                         return;
746                                 }
747                                 for (Post post : followedSone.get().getPosts()) {
748                                         if (post.getTime() < now) {
749                                                 markPostKnown(post);
750                                         }
751                                 }
752                                 for (PostReply reply : followedSone.get().getReplies()) {
753                                         if (reply.getTime() < now) {
754                                                 markReplyKnown(reply);
755                                         }
756                                 }
757                         }
758                 }
759                 touchConfiguration();
760         }
761
762         /**
763          * Lets the given local Sone unfollow the Sone with the given ID.
764          *
765          * @param sone
766          *            The local Sone that should unfollow another Sone
767          * @param soneId
768          *            The ID of the Sone being unfollowed
769          */
770         public void unfollowSone(Sone sone, String soneId) {
771                 checkNotNull(sone, "sone must not be null");
772                 checkNotNull(soneId, "soneId must not be null");
773                 database.removeFriend(sone, soneId);
774                 boolean unfollowedSoneStillFollowed = false;
775                 for (Sone localSone : getLocalSones()) {
776                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
777                 }
778                 if (!unfollowedSoneStillFollowed) {
779                         synchronized (soneFollowingTimes) {
780                                 soneFollowingTimes.remove(soneId);
781                         }
782                 }
783                 touchConfiguration();
784         }
785
786         /**
787          * Sets the trust value of the given origin Sone for the target Sone.
788          *
789          * @param origin
790          *            The origin Sone
791          * @param target
792          *            The target Sone
793          * @param trustValue
794          *            The trust value (from {@code -100} to {@code 100})
795          */
796         public void setTrust(Sone origin, Sone target, int trustValue) {
797                 checkNotNull(origin, "origin must not be null");
798                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
799                 checkNotNull(target, "target must not be null");
800                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
801                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
802         }
803
804         /**
805          * Removes any trust assignment for the given target Sone.
806          *
807          * @param origin
808          *            The trust origin
809          * @param target
810          *            The trust target
811          */
812         public void removeTrust(Sone origin, Sone target) {
813                 checkNotNull(origin, "origin must not be null");
814                 checkNotNull(target, "target must not be null");
815                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
816                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
817         }
818
819         /**
820          * Assigns the configured positive trust value for the given target.
821          *
822          * @param origin
823          *            The trust origin
824          * @param target
825          *            The trust target
826          */
827         public void trustSone(Sone origin, Sone target) {
828                 setTrust(origin, target, preferences.getPositiveTrust());
829         }
830
831         /**
832          * Assigns the configured negative trust value for the given target.
833          *
834          * @param origin
835          *            The trust origin
836          * @param target
837          *            The trust target
838          */
839         public void distrustSone(Sone origin, Sone target) {
840                 setTrust(origin, target, preferences.getNegativeTrust());
841         }
842
843         /**
844          * Removes the trust assignment for the given target.
845          *
846          * @param origin
847          *            The trust origin
848          * @param target
849          *            The trust target
850          */
851         public void untrustSone(Sone origin, Sone target) {
852                 removeTrust(origin, target);
853         }
854
855         /**
856          * Updates the stored Sone with the given Sone.
857          *
858          * @param sone
859          *            The updated Sone
860          */
861         public void updateSone(Sone sone) {
862                 updateSone(sone, false);
863         }
864
865         /**
866          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
867          * {@code true}, an older Sone than the current Sone can be given to restore
868          * an old state.
869          *
870          * @param sone
871          *            The Sone to update
872          * @param soneRescueMode
873          *            {@code true} if the stored Sone should be updated regardless
874          *            of the age of the given Sone
875          */
876         public void updateSone(final Sone sone, boolean soneRescueMode) {
877                 Optional<Sone> storedSone = getSone(sone.getId());
878                 if (storedSone.isPresent()) {
879                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
880                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
881                                 return;
882                         }
883                         List<Object> events =
884                                         collectEventsForChangesInSone(storedSone.get(), sone);
885                         database.storeSone(sone);
886                         for (Object event : events) {
887                                 eventBus.post(event);
888                         }
889                         sone.setOptions(storedSone.get().getOptions());
890                         sone.setKnown(storedSone.get().isKnown());
891                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
892                         if (sone.isLocal()) {
893                                 touchConfiguration();
894                         }
895                 }
896         }
897
898         private List<Object> collectEventsForChangesInSone(Sone oldSone,
899                         final Sone newSone) {
900                 final List<Object> events = new ArrayList<Object>();
901                 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
902                                 oldSone);
903                 soneChangeDetector.onNewPosts(new PostProcessor() {
904                         @Override
905                         public void processPost(Post post) {
906                                 if (post.getTime() < getSoneFollowingTime(newSone)) {
907                                         post.setKnown(true);
908                                 } else if (!post.isKnown()) {
909                                         events.add(new NewPostFoundEvent(post));
910                                 }
911                         }
912                 });
913                 soneChangeDetector.onRemovedPosts(new PostProcessor() {
914                         @Override
915                         public void processPost(Post post) {
916                                 events.add(new PostRemovedEvent(post));
917                         }
918                 });
919                 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
920                         @Override
921                         public void processPostReply(PostReply postReply) {
922                                 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
923                                         postReply.setKnown(true);
924                                 } else if (!postReply.isKnown()) {
925                                         events.add(new NewPostReplyFoundEvent(postReply));
926                                 }
927                         }
928                 });
929                 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
930                         @Override
931                         public void processPostReply(PostReply postReply) {
932                                 events.add(new PostReplyRemovedEvent(postReply));
933                         }
934                 });
935                 soneChangeDetector.detectChanges(newSone);
936                 return events;
937         }
938
939         /**
940          * Deletes the given Sone. This will remove the Sone from the
941          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
942          * remove the context from its identity.
943          *
944          * @param sone
945          *            The Sone to delete
946          */
947         public void deleteSone(Sone sone) {
948                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
949                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
950                         return;
951                 }
952                 if (!getLocalSones().contains(sone)) {
953                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
954                         return;
955                 }
956                 SoneInserter soneInserter = soneInserters.remove(sone);
957                 soneInserter.stop();
958                 database.removeSone(sone);
959                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
960                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
961                 try {
962                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
963                 } catch (ConfigurationException ce1) {
964                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
965                 }
966         }
967
968         /**
969          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
970          * known} before, a {@link MarkSoneKnownEvent} is fired.
971          *
972          * @param sone
973          *            The Sone to mark as known
974          */
975         public void markSoneKnown(Sone sone) {
976                 if (!sone.isKnown()) {
977                         sone.setKnown(true);
978                         synchronized (knownSones) {
979                                 knownSones.add(sone.getId());
980                         }
981                         eventBus.post(new MarkSoneKnownEvent(sone));
982                         touchConfiguration();
983                 }
984         }
985
986         /**
987          * Loads and updates the given Sone from the configuration. If any error is
988          * encountered, loading is aborted and the given Sone is not changed.
989          *
990          * @param sone
991          *            The Sone to load and update
992          */
993         public void loadSone(Sone sone) {
994                 if (!sone.isLocal()) {
995                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
996                         return;
997                 }
998                 logger.info(String.format("Loading local Sone: %s", sone));
999
1000                 /* load Sone. */
1001                 String sonePrefix = "Sone/" + sone.getId();
1002                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1003                 if (soneTime == null) {
1004                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1005                         return;
1006                 }
1007                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1008
1009                 /* load profile. */
1010                 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1011                 Profile profile = configurationSoneParser.parseProfile();
1012
1013                 /* load posts. */
1014                 Collection<Post> posts;
1015                 try {
1016                         posts = configurationSoneParser.parsePosts(database);
1017                 } catch (InvalidPostFound ipf) {
1018                         logger.log(Level.WARNING, "Invalid post found, aborting load!");
1019                         return;
1020                 }
1021
1022                 /* load replies. */
1023                 Collection<PostReply> replies;
1024                 try {
1025                         replies = configurationSoneParser.parsePostReplies(database);
1026                 } catch (InvalidPostReplyFound iprf) {
1027                         logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1028                         return;
1029                 }
1030
1031                 /* load post likes. */
1032                 Set<String> likedPostIds =
1033                                 configurationSoneParser.parseLikedPostIds();
1034
1035                 /* load reply likes. */
1036                 Set<String> likedReplyIds =
1037                                 configurationSoneParser.parseLikedPostReplyIds();
1038
1039                 /* load albums. */
1040                 List<Album> topLevelAlbums;
1041                 try {
1042                         topLevelAlbums =
1043                                         configurationSoneParser.parseTopLevelAlbums(database);
1044                 } catch (InvalidAlbumFound iaf) {
1045                         logger.log(Level.WARNING, "Invalid album found, aborting load!");
1046                         return;
1047                 } catch (InvalidParentAlbumFound ipaf) {
1048                         logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1049                                         ipaf.getAlbumParentId()));
1050                         return;
1051                 }
1052
1053                 /* load images. */
1054                 try {
1055                         configurationSoneParser.parseImages(database);
1056                 } catch (InvalidImageFound iif) {
1057                         logger.log(WARNING, "Invalid image found, aborting load!");
1058                         return;
1059                 } catch (InvalidParentAlbumFound ipaf) {
1060                         logger.log(Level.WARNING,
1061                                         format("Invalid album image (%s) encountered, aborting load!",
1062                                                         ipaf.getAlbumParentId()));
1063                         return;
1064                 }
1065
1066                 /* load avatar. */
1067                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1068                 if (avatarId != null) {
1069                         final Map<String, Image> images =
1070                                         configurationSoneParser.getImages();
1071                         profile.setAvatar(images.get(avatarId));
1072                 }
1073
1074                 /* load options. */
1075                 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1076                 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1077                 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1078                 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1079                 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1080                 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1081                 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1082
1083                 /* if we’re still here, Sone was loaded successfully. */
1084                 synchronized (sone) {
1085                         sone.setTime(soneTime);
1086                         sone.setProfile(profile);
1087                         sone.setPosts(posts);
1088                         sone.setReplies(replies);
1089                         sone.setLikePostIds(likedPostIds);
1090                         sone.setLikeReplyIds(likedReplyIds);
1091                         for (Album album : sone.getRootAlbum().getAlbums()) {
1092                                 sone.getRootAlbum().removeAlbum(album);
1093                         }
1094                         for (Album album : topLevelAlbums) {
1095                                 sone.getRootAlbum().addAlbum(album);
1096                         }
1097                         synchronized (soneInserters) {
1098                                 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1099                         }
1100                 }
1101                 for (Post post : posts) {
1102                         post.setKnown(true);
1103                 }
1104                 for (PostReply reply : replies) {
1105                         reply.setKnown(true);
1106                 }
1107
1108                 logger.info(String.format("Sone loaded successfully: %s", sone));
1109         }
1110
1111         /**
1112          * Creates a new post.
1113          *
1114          * @param sone
1115          *            The Sone that creates the post
1116          * @param recipient
1117          *            The recipient Sone, or {@code null} if this post does not have
1118          *            a recipient
1119          * @param text
1120          *            The text of the post
1121          * @return The created post
1122          */
1123         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1124                 checkNotNull(text, "text must not be null");
1125                 checkArgument(text.trim().length() > 0, "text must not be empty");
1126                 if (!sone.isLocal()) {
1127                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1128                         return null;
1129                 }
1130                 PostBuilder postBuilder = database.newPostBuilder();
1131                 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1132                 if (recipient.isPresent()) {
1133                         postBuilder.to(recipient.get().getId());
1134                 }
1135                 final Post post = postBuilder.build();
1136                 database.storePost(post);
1137                 eventBus.post(new NewPostFoundEvent(post));
1138                 sone.addPost(post);
1139                 touchConfiguration();
1140                 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1141                 return post;
1142         }
1143
1144         /**
1145          * Deletes the given post.
1146          *
1147          * @param post
1148          *            The post to delete
1149          */
1150         public void deletePost(Post post) {
1151                 if (!post.getSone().isLocal()) {
1152                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1153                         return;
1154                 }
1155                 database.removePost(post);
1156                 eventBus.post(new PostRemovedEvent(post));
1157                 markPostKnown(post);
1158                 touchConfiguration();
1159         }
1160
1161         /**
1162          * Marks the given post as known, if it is currently not a known post
1163          * (according to {@link Post#isKnown()}).
1164          *
1165          * @param post
1166          *            The post to mark as known
1167          */
1168         public void markPostKnown(Post post) {
1169                 post.setKnown(true);
1170                 eventBus.post(new MarkPostKnownEvent(post));
1171                 touchConfiguration();
1172                 for (PostReply reply : getReplies(post.getId())) {
1173                         markReplyKnown(reply);
1174                 }
1175         }
1176
1177         public void bookmarkPost(Post post) {
1178                 database.bookmarkPost(post);
1179         }
1180
1181         /**
1182          * Removes the given post from the bookmarks.
1183          *
1184          * @param post
1185          *            The post to unbookmark
1186          */
1187         public void unbookmarkPost(Post post) {
1188                 database.unbookmarkPost(post);
1189         }
1190
1191         /**
1192          * Creates a new reply.
1193          *
1194          * @param sone
1195          *            The Sone that creates the reply
1196          * @param post
1197          *            The post that this reply refers to
1198          * @param text
1199          *            The text of the reply
1200          * @return The created reply
1201          */
1202         public PostReply createReply(Sone sone, Post post, String text) {
1203                 checkNotNull(text, "text must not be null");
1204                 checkArgument(text.trim().length() > 0, "text must not be empty");
1205                 if (!sone.isLocal()) {
1206                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1207                         return null;
1208                 }
1209                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1210                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1211                 final PostReply reply = postReplyBuilder.build();
1212                 database.storePostReply(reply);
1213                 eventBus.post(new NewPostReplyFoundEvent(reply));
1214                 sone.addReply(reply);
1215                 touchConfiguration();
1216                 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1217                 return reply;
1218         }
1219
1220         /**
1221          * Deletes the given reply.
1222          *
1223          * @param reply
1224          *            The reply to delete
1225          */
1226         public void deleteReply(PostReply reply) {
1227                 Sone sone = reply.getSone();
1228                 if (!sone.isLocal()) {
1229                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1230                         return;
1231                 }
1232                 database.removePostReply(reply);
1233                 markReplyKnown(reply);
1234                 sone.removeReply(reply);
1235                 touchConfiguration();
1236         }
1237
1238         /**
1239          * Marks the given reply as known, if it is currently not a known reply
1240          * (according to {@link Reply#isKnown()}).
1241          *
1242          * @param reply
1243          *            The reply to mark as known
1244          */
1245         public void markReplyKnown(PostReply reply) {
1246                 boolean previouslyKnown = reply.isKnown();
1247                 reply.setKnown(true);
1248                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1249                 if (!previouslyKnown) {
1250                         touchConfiguration();
1251                 }
1252         }
1253
1254         /**
1255          * Creates a new album for the given Sone.
1256          *
1257          * @param sone
1258          *            The Sone to create the album for
1259          * @param parent
1260          *            The parent of the album (may be {@code null} to create a
1261          *            top-level album)
1262          * @return The new album
1263          */
1264         public Album createAlbum(Sone sone, Album parent) {
1265                 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1266                 database.storeAlbum(album);
1267                 parent.addAlbum(album);
1268                 return album;
1269         }
1270
1271         /**
1272          * Deletes the given album. The owner of the album has to be a local Sone,
1273          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1274          *
1275          * @param album
1276          *            The album to remove
1277          */
1278         public void deleteAlbum(Album album) {
1279                 checkNotNull(album, "album must not be null");
1280                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1281                 if (!album.isEmpty()) {
1282                         return;
1283                 }
1284                 album.getParent().removeAlbum(album);
1285                 database.removeAlbum(album);
1286                 touchConfiguration();
1287         }
1288
1289         /**
1290          * Creates a new image.
1291          *
1292          * @param sone
1293          *            The Sone creating the image
1294          * @param album
1295          *            The album the image will be inserted into
1296          * @param temporaryImage
1297          *            The temporary image to create the image from
1298          * @return The newly created image
1299          */
1300         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1301                 checkNotNull(sone, "sone must not be null");
1302                 checkNotNull(album, "album must not be null");
1303                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1304                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1305                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1306                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1307                 album.addImage(image);
1308                 database.storeImage(image);
1309                 imageInserter.insertImage(temporaryImage, image);
1310                 return image;
1311         }
1312
1313         /**
1314          * Deletes the given image. This method will also delete a matching
1315          * temporary image.
1316          *
1317          * @see #deleteTemporaryImage(String)
1318          * @param image
1319          *            The image to delete
1320          */
1321         public void deleteImage(Image image) {
1322                 checkNotNull(image, "image must not be null");
1323                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1324                 deleteTemporaryImage(image.getId());
1325                 image.getAlbum().removeImage(image);
1326                 database.removeImage(image);
1327                 touchConfiguration();
1328         }
1329
1330         /**
1331          * Creates a new temporary image.
1332          *
1333          * @param mimeType
1334          *            The MIME type of the temporary image
1335          * @param imageData
1336          *            The encoded data of the image
1337          * @return The temporary image
1338          */
1339         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1340                 TemporaryImage temporaryImage = new TemporaryImage();
1341                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1342                 synchronized (temporaryImages) {
1343                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1344                 }
1345                 return temporaryImage;
1346         }
1347
1348         /**
1349          * Deletes the temporary image with the given ID.
1350          *
1351          * @param imageId
1352          *            The ID of the temporary image to delete
1353          */
1354         public void deleteTemporaryImage(String imageId) {
1355                 checkNotNull(imageId, "imageId must not be null");
1356                 synchronized (temporaryImages) {
1357                         temporaryImages.remove(imageId);
1358                 }
1359                 Image image = getImage(imageId, false);
1360                 if (image != null) {
1361                         imageInserter.cancelImageInsert(image);
1362                 }
1363         }
1364
1365         /**
1366          * Notifies the core that the configuration, either of the core or of a
1367          * single local Sone, has changed, and that the configuration should be
1368          * saved.
1369          */
1370         public void touchConfiguration() {
1371                 lastConfigurationUpdate = System.currentTimeMillis();
1372         }
1373
1374         //
1375         // SERVICE METHODS
1376         //
1377
1378         /**
1379          * Starts the core.
1380          */
1381         @Override
1382         public void serviceStart() {
1383                 loadConfiguration();
1384                 updateChecker.start();
1385                 identityManager.start();
1386                 webOfTrustUpdater.init();
1387                 webOfTrustUpdater.start();
1388                 database.start();
1389         }
1390
1391         /**
1392          * {@inheritDoc}
1393          */
1394         @Override
1395         public void serviceRun() {
1396                 long lastSaved = System.currentTimeMillis();
1397                 while (!shouldStop()) {
1398                         sleep(1000);
1399                         long now = System.currentTimeMillis();
1400                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1401                                 for (Sone localSone : getLocalSones()) {
1402                                         saveSone(localSone);
1403                                 }
1404                                 saveConfiguration();
1405                                 lastSaved = now;
1406                         }
1407                 }
1408         }
1409
1410         /**
1411          * Stops the core.
1412          */
1413         @Override
1414         public void serviceStop() {
1415                 localElementTicker.shutdownNow();
1416                 synchronized (soneInserters) {
1417                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1418                                 soneInserter.getValue().stop();
1419                                 saveSone(soneInserter.getKey());
1420                         }
1421                 }
1422                 synchronized (soneRescuers) {
1423                         for (SoneRescuer soneRescuer : soneRescuers.values()) {
1424                                 soneRescuer.stop();
1425                         }
1426                 }
1427                 saveConfiguration();
1428                 database.stop();
1429                 webOfTrustUpdater.stop();
1430                 updateChecker.stop();
1431                 soneDownloader.stop();
1432                 soneDownloaders.shutdown();
1433                 identityManager.stop();
1434         }
1435
1436         //
1437         // PRIVATE METHODS
1438         //
1439
1440         /**
1441          * Saves the given Sone. This will persist all local settings for the given
1442          * Sone, such as the friends list and similar, private options.
1443          *
1444          * @param sone
1445          *            The Sone to save
1446          */
1447         private synchronized void saveSone(Sone sone) {
1448                 if (!sone.isLocal()) {
1449                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1450                         return;
1451                 }
1452                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1453                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1454                         return;
1455                 }
1456
1457                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1458                 try {
1459                         /* save Sone into configuration. */
1460                         String sonePrefix = "Sone/" + sone.getId();
1461                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1462                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1463
1464                         /* save profile. */
1465                         Profile profile = sone.getProfile();
1466                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1467                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1468                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1469                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1470                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1471                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1472                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1473
1474                         /* save profile fields. */
1475                         int fieldCounter = 0;
1476                         for (Field profileField : profile.getFields()) {
1477                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1478                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1479                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1480                         }
1481                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1482
1483                         /* save posts. */
1484                         int postCounter = 0;
1485                         for (Post post : sone.getPosts()) {
1486                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1487                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1488                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1489                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1490                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1491                         }
1492                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1493
1494                         /* save replies. */
1495                         int replyCounter = 0;
1496                         for (PostReply reply : sone.getReplies()) {
1497                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1498                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1499                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1500                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1501                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1502                         }
1503                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1504
1505                         /* save post likes. */
1506                         int postLikeCounter = 0;
1507                         for (String postId : sone.getLikedPostIds()) {
1508                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1509                         }
1510                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1511
1512                         /* save reply likes. */
1513                         int replyLikeCounter = 0;
1514                         for (String replyId : sone.getLikedReplyIds()) {
1515                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1516                         }
1517                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1518
1519                         /* save albums. first, collect in a flat structure, top-level first. */
1520                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1521
1522                         int albumCounter = 0;
1523                         for (Album album : albums) {
1524                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1525                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1526                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1527                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1528                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1529                         }
1530                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1531
1532                         /* save images. */
1533                         int imageCounter = 0;
1534                         for (Album album : albums) {
1535                                 for (Image image : album.getImages()) {
1536                                         if (!image.isInserted()) {
1537                                                 continue;
1538                                         }
1539                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1540                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1541                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1542                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1543                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1544                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1545                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1546                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1547                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1548                                 }
1549                         }
1550                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1551
1552                         /* save options. */
1553                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1554                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1555                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1556                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1557                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1558                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1559                         configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1560
1561                         configuration.save();
1562
1563                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1564
1565                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1566                 } catch (ConfigurationException ce1) {
1567                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1568                 }
1569         }
1570
1571         /**
1572          * Saves the current options.
1573          */
1574         private void saveConfiguration() {
1575                 synchronized (configuration) {
1576                         if (storingConfiguration) {
1577                                 logger.log(Level.FINE, "Already storing configuration…");
1578                                 return;
1579                         }
1580                         storingConfiguration = true;
1581                 }
1582
1583                 /* store the options first. */
1584                 try {
1585                         preferences.saveTo(configuration);
1586
1587                         /* save known Sones. */
1588                         int soneCounter = 0;
1589                         synchronized (knownSones) {
1590                                 for (String knownSoneId : knownSones) {
1591                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1592                                 }
1593                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1594                         }
1595
1596                         /* save Sone following times. */
1597                         soneCounter = 0;
1598                         synchronized (soneFollowingTimes) {
1599                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1600                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1601                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1602                                         ++soneCounter;
1603                                 }
1604                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1605                         }
1606
1607                         /* save known posts. */
1608                         database.save();
1609
1610                         /* now save it. */
1611                         configuration.save();
1612
1613                 } catch (ConfigurationException ce1) {
1614                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1615                 } catch (DatabaseException de1) {
1616                         logger.log(Level.SEVERE, "Could not save database!", de1);
1617                 } finally {
1618                         synchronized (configuration) {
1619                                 storingConfiguration = false;
1620                         }
1621                 }
1622         }
1623
1624         /**
1625          * Loads the configuration.
1626          */
1627         private void loadConfiguration() {
1628                 new PreferencesLoader(preferences).loadFrom(configuration);
1629
1630                 /* load known Sones. */
1631                 int soneCounter = 0;
1632                 while (true) {
1633                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1634                         if (knownSoneId == null) {
1635                                 break;
1636                         }
1637                         synchronized (knownSones) {
1638                                 knownSones.add(knownSoneId);
1639                         }
1640                 }
1641
1642                 /* load Sone following times. */
1643                 soneCounter = 0;
1644                 while (true) {
1645                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1646                         if (soneId == null) {
1647                                 break;
1648                         }
1649                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1650                         synchronized (soneFollowingTimes) {
1651                                 soneFollowingTimes.put(soneId, time);
1652                         }
1653                         ++soneCounter;
1654                 }
1655         }
1656
1657         /**
1658          * Notifies the core that a new {@link OwnIdentity} was added.
1659          *
1660          * @param ownIdentityAddedEvent
1661          *            The event
1662          */
1663         @Subscribe
1664         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1665                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1666                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1667                 if (ownIdentity.hasContext("Sone")) {
1668                         addLocalSone(ownIdentity);
1669                 }
1670         }
1671
1672         /**
1673          * Notifies the core that an {@link OwnIdentity} was removed.
1674          *
1675          * @param ownIdentityRemovedEvent
1676          *            The event
1677          */
1678         @Subscribe
1679         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1680                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1681                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1682                 trustedIdentities.removeAll(ownIdentity);
1683         }
1684
1685         /**
1686          * Notifies the core that a new {@link Identity} was added.
1687          *
1688          * @param identityAddedEvent
1689          *            The event
1690          */
1691         @Subscribe
1692         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1693                 Identity identity = identityAddedEvent.identity();
1694                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1695                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1696                 addRemoteSone(identity);
1697         }
1698
1699         /**
1700          * Notifies the core that an {@link Identity} was updated.
1701          *
1702          * @param identityUpdatedEvent
1703          *            The event
1704          */
1705         @Subscribe
1706         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1707                 Identity identity = identityUpdatedEvent.identity();
1708                 final Sone sone = getRemoteSone(identity.getId());
1709                 if (sone.isLocal()) {
1710                         return;
1711                 }
1712                 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1713                 soneDownloader.addSone(sone);
1714                 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1715         }
1716
1717         /**
1718          * Notifies the core that an {@link Identity} was removed.
1719          *
1720          * @param identityRemovedEvent
1721          *            The event
1722          */
1723         @Subscribe
1724         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1725                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1726                 Identity identity = identityRemovedEvent.identity();
1727                 trustedIdentities.remove(ownIdentity, identity);
1728                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1729                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1730                                 continue;
1731                         }
1732                         if (trustedIdentity.getValue().contains(identity)) {
1733                                 return;
1734                         }
1735                 }
1736                 Optional<Sone> sone = getSone(identity.getId());
1737                 if (!sone.isPresent()) {
1738                         /* TODO - we don’t have the Sone anymore. should this happen? */
1739                         return;
1740                 }
1741                 for (PostReply postReply : sone.get().getReplies()) {
1742                         eventBus.post(new PostReplyRemovedEvent(postReply));
1743                 }
1744                 for (Post post : sone.get().getPosts()) {
1745                         eventBus.post(new PostRemovedEvent(post));
1746                 }
1747                 eventBus.post(new SoneRemovedEvent(sone.get()));
1748                 database.removeSone(sone.get());
1749         }
1750
1751         /**
1752          * Deletes the temporary image.
1753          *
1754          * @param imageInsertFinishedEvent
1755          *            The event
1756          */
1757         @Subscribe
1758         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1759                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1760                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1761                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1762                 touchConfiguration();
1763         }
1764
1765         @VisibleForTesting
1766         class MarkPostKnown implements Runnable {
1767
1768                 private final Post post;
1769
1770                 public MarkPostKnown(Post post) {
1771                         this.post = post;
1772                 }
1773
1774                 @Override
1775                 public void run() {
1776                         markPostKnown(post);
1777                 }
1778
1779         }
1780
1781         @VisibleForTesting
1782         class MarkReplyKnown implements Runnable {
1783
1784                 private final PostReply postReply;
1785
1786                 public MarkReplyKnown(PostReply postReply) {
1787                         this.postReply = postReply;
1788                 }
1789
1790                 @Override
1791                 public void run() {
1792                         markReplyKnown(postReply);
1793                 }
1794
1795         }
1796
1797 }