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