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