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